Skip to content

🙌 OpenHands: AI-Driven Development

fix(canvas): respect scoped runtime clients and workspace capabilities (#17387)

Graham Neubigb9d174c9ca36
diff --git a/__tests__/api/agent-server-client-options.test.ts b/__tests__/api/agent-server-client-options.test.ts
new file mode 100644
index 0000000000..f7c351741d
--- /dev/null
+++ b/__tests__/api/agent-server-client-options.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from "vitest";
+import {
+ getAgentServerClientOptions,
+ getAgentServerHttpClientOptions,
+} from "#/api/agent-server-client-options";
+
+const overrides = {
+ host: "http://127.0.0.1:9000",
+ conversationUrl:
+ "http://127.0.0.1:9000/api/conversations/11111111-1111-4111-8111-111111111111",
+};
+
+describe("Docker conversation client context", () => {
+ it("retains conversation context in typed client options", () => {
+ expect(getAgentServerClientOptions(overrides).conversationId).toBe(
+ "11111111-1111-4111-8111-111111111111",
+ );
+ });
+
+ it("retains the same context in HTTP client options", () => {
+ expect(getAgentServerHttpClientOptions(overrides)).toHaveProperty(
+ "conversationId",
+ "11111111-1111-4111-8111-111111111111",
+ );
+ });
+});
+
+describe("explicit conversation context", () => {
+ it("retains explicit ID without a URL and prefers it over URL context", () => {
+ expect(
+ getAgentServerHttpClientOptions({
+ ...overrides,
+ conversationId: "explicit-id",
+ }).conversationId,
+ ).toBe("explicit-id");
+ expect(
+ getAgentServerClientOptions({
+ host: overrides.host,
+ conversationId: "explicit-id",
+ }).conversationId,
+ ).toBe("explicit-id");
+ });
+ it("leaves host discovery unscoped", () => {
+ expect(
+ getAgentServerClientOptions({ host: overrides.host }),
+ ).not.toHaveProperty("conversationId");
+ });
+ it("retains the full ID from a prefixed URL without query or fragment", () => {
+ expect(
+ getAgentServerClientOptions({
+ ...overrides,
+ conversationUrl:
+ "http://localhost/runtime/123/api/conversations/conversation-abc?view=files#tab",
+ }).conversationId,
+ ).toBe("conversation-abc");
+ });
+});
diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.ts
index 89403346e3..4fc4c77441 100644
--- a/__tests__/api/agent-server-conversation-service.test.ts
+++ b/__tests__/api/agent-server-conversation-service.test.ts
@@ -502,9 +502,10 @@ describe("AgentServerConversationService", () => {
workingDir: "/workspace/project/agent-canvas",
});
expect(FileClient).toHaveBeenCalledWith({
+ conversationId: "conv-123",
host: "http://localhost:54928",
apiKey: "test-api-key",
- workingDir: "/workspace/project/agent-canvas",
+ workingDir: "/workspace/project/agent-canvas/conv-123",
});
expect(mockHttpGet).toHaveBeenCalledWith(
"/api/file/download",
@@ -1822,6 +1823,7 @@ describe("AgentServerConversationService", () => {
expect(result.status).toBe("paused");
expect(mockGetConversation).toHaveBeenCalledWith("conv-cloud");
expect(ConversationClient).toHaveBeenLastCalledWith({
+ conversationId: "conv-cloud",
host: "http://runtime.example",
apiKey: "session-key",
workingDir: "/workspace/project/agent-canvas",
@@ -2472,6 +2474,7 @@ describe("AgentServerConversationService", () => {
expect(result.title).toBe("Conversation conv-");
expect(ConversationClient).toHaveBeenLastCalledWith({
+ conversationId: "conv-1",
host: "http://runtime.internal:9000",
apiKey: "runtime-key",
workingDir: "/workspace/project/agent-canvas",
@@ -2489,6 +2492,7 @@ describe("AgentServerConversationService", () => {
);
expect(VSCodeClient).toHaveBeenCalledWith({
+ conversationId: "conv-1",
host: "http://runtime.internal:9000",
apiKey: "runtime-key",
workingDir: "/workspace/project/agent-canvas",
@@ -2614,6 +2618,7 @@ describe("AgentServerConversationService", () => {
expect(result.status).toBe("running");
expect(mockGetConversation).toHaveBeenCalledWith("conv-cloud");
expect(ConversationClient).toHaveBeenLastCalledWith({
+ conversationId: "conv-cloud",
host: "http://runtime.example",
apiKey: "runtime-key",
workingDir: "/workspace/project/agent-canvas",
diff --git a/__tests__/api/agent-server-git-service.test.ts b/__tests__/api/agent-server-git-service.test.ts
index 7bf1650d84..aef6dfee21 100644
--- a/__tests__/api/agent-server-git-service.test.ts
+++ b/__tests__/api/agent-server-git-service.test.ts
@@ -65,6 +65,7 @@ describe("AgentServerGitService", () => {
);
expect(RemoteWorkspace).toHaveBeenCalledWith({
+ conversationId: "123",
host: "http://localhost:3000",
apiKey: "my-session-key",
workingDir: "workspace/project",
@@ -126,6 +127,7 @@ describe("AgentServerGitService", () => {
);
expect(RemoteWorkspace).toHaveBeenCalledWith({
+ conversationId: "123",
host: "http://localhost:3000",
apiKey: "test-api-key",
workingDir: "workspace/project",
diff --git a/__tests__/api/docker-conversation-boundaries.test.ts b/__tests__/api/docker-conversation-boundaries.test.ts
new file mode 100644
index 0000000000..40348081e9
--- /dev/null
+++ b/__tests__/api/docker-conversation-boundaries.test.ts
@@ -0,0 +1,213 @@
+import i18n from "#/i18n";
+import { I18nKey } from "#/i18n/declaration";
+import AgentServerGitService from "#/api/git-service/agent-server-git-service.api";
+import { beforeEach, describe, expect, it } from "vitest";
+import { http, HttpResponse } from "msw";
+import { server } from "#/mocks/node";
+import {
+ setRegisteredBackends,
+ setActiveSelection,
+} from "#/api/backend-registry/active-store";
+import { clearCachedAgentServerInfo } from "#/api/agent-server-compatibility";
+import { clearAgentServerHomeDirCache } from "#/api/agent-server-home";
+import { resolveNewConversationWorkspace } from "#/api/conversation-workspace";
+import GitService from "#/api/git-service/git-service.api";
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import AgentServerRuntimeService from "#/api/runtime-service/agent-server-runtime-service";
+
+const host = "http://localhost:9876";
+const cid = "11111111-1111-4111-8111-111111111111";
+const paths: string[] = [];
+let isolated = true;
+let capabilities = true;
+
+beforeEach(() => {
+ isolated = true;
+ capabilities = true;
+ paths.length = 0;
+ clearCachedAgentServerInfo();
+ clearAgentServerHomeDirCache();
+ setRegisteredBackends([
+ {
+ id: "boundary",
+ name: "Boundary",
+ kind: "local",
+ host,
+ apiKey: "boundary-test-key",
+ },
+ ]);
+ setActiveSelection({ backendId: "boundary" });
+ // Only the HTTP server is substituted; frontend services and SDK clients run unchanged.
+ server.use(
+ http.all(`${host}/*`, ({ request }) => {
+ const url = new URL(request.url);
+ paths.push(url.pathname + url.search);
+ expect(request.headers.get("X-Session-API-Key")).toBe(
+ "boundary-test-key",
+ );
+ if (url.pathname === "/server_info")
+ return HttpResponse.json({
+ version: "1.45.0",
+ uptime: 0,
+ idle_time: 0,
+ capabilities: capabilities ? ["conversation_runtime_routes_v1"] : [],
+ conversation_runtime: isolated ? "docker" : "local",
+ runtime_services: { mode: isolated ? "dev:automation" : "docker" },
+ });
+ if (url.pathname === "/api/file/home")
+ return HttpResponse.json({ home: "/home/agent" });
+ if (url.pathname === "/api/conversations")
+ return HttpResponse.json([
+ {
+ id: cid,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ execution_status: "idle",
+ workspace: { working_dir: "/workspace" },
+ },
+ ]);
+ if (url.pathname.endsWith("/git/changes"))
+ return HttpResponse.json([{ path: "file.txt", status: "M" }]);
+ if (url.pathname.endsWith("/git/diff"))
+ return HttpResponse.json({ original: "before", modified: "after" });
+ if (url.pathname.endsWith("/file/download"))
+ return HttpResponse.text("plan contents");
+ if (url.pathname.endsWith("/bash/execute_bash_command"))
+ return HttpResponse.json({
+ exit_code: 0,
+ stdout: "/workspace",
+ stderr: "",
+ });
+ return HttpResponse.json(
+ { error: "Unexpected endpoint" },
+ { status: 500 },
+ );
+ }),
+ );
+});
+
+describe("conversation runtime boundaries", () => {
+ it("scopes live unified git calls even before conversation URL hydration", async () => {
+ expect(
+ await AgentServerGitService.getGitChanges(cid, null, null, "/workspace"),
+ ).toHaveLength(1);
+ expect(
+ await AgentServerGitService.getGitChangeDiff(cid, null, null, "file.txt"),
+ ).toEqual({ original: "before", modified: "after" });
+ expect(paths).toContain(
+ `/api/conversations/${cid}/git/changes?path=%2Fworkspace`,
+ );
+ expect(paths).toContain(`/api/conversations/${cid}/git/diff?path=file.txt`);
+ });
+
+ it("uses a new isolated workspace without reading host home or hooks", async () => {
+ expect(
+ await resolveNewConversationWorkspace({ conversationId: cid }),
+ ).toEqual({
+ workingDir: "/workspace",
+ hooksProjectDir: null,
+ isolated: true,
+ });
+ expect(paths).toEqual(["/server_info"]);
+ });
+
+ it.each(["/home/user/project", "/workspace", "relative/project"])(
+ "rejects selected host folder %s rather than discarding it",
+ async (workingDir) => {
+ await expect(
+ resolveNewConversationWorkspace({ conversationId: cid, workingDir }),
+ ).rejects.toThrow(i18n.t(I18nKey.HOME$ISOLATED_WORKSPACE_NOTICE));
+ expect(paths).toEqual(["/server_info"]);
+ },
+ );
+
+ it("rejects selected host repository metadata", async () => {
+ await expect(
+ resolveNewConversationWorkspace({
+ conversationId: cid,
+ selectedRepository: "owner/project",
+ }),
+ ).rejects.toThrow(i18n.t(I18nKey.HOME$ISOLATED_WORKSPACE_NOTICE));
+ });
+
+ it("uses the active language for workspace rejection errors", async () => {
+ const originalLanguage = i18n.language;
+ const notice = "Ce backend utilise des espaces de travail isolés.";
+ i18n.addResourceBundle("fr", "openhands", {
+ [I18nKey.HOME$ISOLATED_WORKSPACE_NOTICE]: notice,
+ });
+ try {
+ await i18n.changeLanguage("fr");
+ await expect(
+ resolveNewConversationWorkspace({
+ conversationId: cid,
+ selectedRepository: "owner/project",
+ }),
+ ).rejects.toThrow(notice);
+ } finally {
+ await i18n.changeLanguage(originalLanguage);
+ }
+ });
+
+ it("preserves a Docker child conversation's parent workspace", async () => {
+ expect(
+ await resolveNewConversationWorkspace({
+ conversationId: cid,
+ parentConversationId: "parent",
+ workingDir: "/workspace",
+ }),
+ ).toMatchObject({ workingDir: "/workspace", isolated: true });
+ });
+
+ it("uses host metadata rather than runtime_services deployment mode", async () => {
+ isolated = false;
+ expect(
+ await resolveNewConversationWorkspace({
+ conversationId: cid,
+ workingDir: "/home/user/project",
+ }),
+ ).toEqual({
+ workingDir: "/home/user/project",
+ hooksProjectDir: "/home/user/project",
+ isolated: false,
+ });
+ });
+
+ it("routes legacy git service changes and diff to the conversation", async () => {
+ expect(await GitService.getGitChanges(cid)).toHaveLength(1);
+ expect(await GitService.getGitChangeDiff(cid, "file.txt")).toEqual({
+ original: "before",
+ modified: "after",
+ });
+ expect(paths).toContain(
+ `/api/conversations/${cid}/git/changes?path=%2Fworkspace`,
+ );
+ expect(paths).toContain(`/api/conversations/${cid}/git/diff?path=file.txt`);
+ });
+
+ it("routes plan downloads and runtime bash to the same conversation", async () => {
+ expect(await AgentServerConversationService.readConversationFile(cid)).toBe(
+ "plan contents",
+ );
+ expect(
+ await AgentServerRuntimeService.executeCommand(
+ `${host}/api/conversations/${cid}`,
+ null,
+ "pwd",
+ "/workspace",
+ ),
+ ).toMatchObject({ stdout: "/workspace" });
+ expect(paths).toContain(
+ `/api/conversations/${cid}/file/download?path=%2Fworkspace%2F.agents_tmp%2FPLAN.md`,
+ );
+ expect(paths).toContain(
+ `/api/conversations/${cid}/bash/execute_bash_command`,
+ );
+ });
+
+ it("retains cid for legacy servers without canonical capability", async () => {
+ capabilities = false;
+ await GitService.getGitChangeDiff(cid, "file.txt");
+ expect(paths).toContain(`/api/git/diff?path=file.txt&cid=${cid}`);
+ });
+});
diff --git a/__tests__/api/git-service.test.ts b/__tests__/api/git-service.test.ts
index 311f1bcd81..bfef4645fb 100644
--- a/__tests__/api/git-service.test.ts
+++ b/__tests__/api/git-service.test.ts
@@ -359,6 +359,7 @@ describe("GitService", () => {
],
);
expect(workspaceMocks.clientOptions).toHaveBeenCalledWith({
+ conversationId: "conversation-1",
workingDir: "/workspace/project",
});
expect(workspaceMocks.gitChanges).toHaveBeenCalledWith(
diff --git a/__tests__/api/mock-conversation-handlers.test.ts b/__tests__/api/mock-conversation-handlers.test.ts
index 658ebd3014..ce9022951c 100644
--- a/__tests__/api/mock-conversation-handlers.test.ts
+++ b/__tests__/api/mock-conversation-handlers.test.ts
@@ -58,17 +58,25 @@ describe("mock conversation handlers", () => {
// lets Stryker's per-test mutants actually take effect against these
// handlers. `resetHandlers` (replace, not append) drops the default base
// handlers so a mutated-away route has no unmutated duplicate to fall back
- // to. The git-repository handlers are included for the git-changes case.
+ // to. The git-repository handlers are included for the git-changes case, and
+ // the settings handlers supply `/server_info` — the scoped runtime clients
+ // probe it to negotiate conversation-runtime routes. Without it those probes
+ // hit the 599 catch-all below and the request never reaches the real handler.
beforeEach(async () => {
vi.resetModules();
- const [{ CONVERSATION_HANDLERS }, { GIT_REPOSITORY_HANDLERS }] =
- await Promise.all([
- import("#/mocks/conversation-handlers"),
- import("#/mocks/git-repository-handlers"),
- ]);
+ const [
+ { CONVERSATION_HANDLERS },
+ { GIT_REPOSITORY_HANDLERS },
+ { SETTINGS_HANDLERS },
+ ] = await Promise.all([
+ import("#/mocks/conversation-handlers"),
+ import("#/mocks/git-repository-handlers"),
+ import("#/mocks/settings-handlers"),
+ ]);
server.resetHandlers(
...CONVERSATION_HANDLERS,
...GIT_REPOSITORY_HANDLERS,
+ ...SETTINGS_HANDLERS,
...UNHANDLED_REQUESTS,
);
});
diff --git a/__tests__/components/features/conversation-panel/local-new-conversation-menu.test.tsx b/__tests__/components/features/conversation-panel/local-new-conversation-menu.test.tsx
index d389247cdc..cf7808a61e 100644
--- a/__tests__/components/features/conversation-panel/local-new-conversation-menu.test.tsx
+++ b/__tests__/components/features/conversation-panel/local-new-conversation-menu.test.tsx
@@ -1,3 +1,6 @@
+import { http, HttpResponse } from "msw";
+import { server } from "#/mocks/node";
+import { clearCachedAgentServerInfo } from "#/api/agent-server-compatibility";
import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -98,6 +101,43 @@ const renderMenu = ({
};
describe("LocalNewConversationMenu", () => {
+ it("disables saved host workspaces and explains isolated Docker creation", async () => {
+ clearCachedAgentServerInfo();
+ server.use(
+ http.get("*/server_info", () =>
+ HttpResponse.json({
+ version: "1.45.0",
+ uptime: 0,
+ idle_time: 0,
+ conversation_runtime: "docker",
+ }),
+ ),
+ );
+ const user = userEvent.setup();
+ renderMenu({
+ workspaces: [
+ {
+ id: "host-project",
+ name: "Host project",
+ path: "/home/user/project",
+ },
+ ],
+ });
+ await user.click(screen.getByTestId("new-conversation-button"));
+ await waitFor(() =>
+ expect(screen.getByTestId("launch-workspace")).toBeDisabled(),
+ );
+ expect(screen.getByRole("status")).toHaveTextContent(
+ "HOME$ISOLATED_WORKSPACE_NOTICE",
+ );
+ expect(screen.getByTestId("add-workspaces-button")).toBeDisabled();
+ expect(screen.getByTestId("launch-no-workspace")).toBeEnabled();
+ expect(screen.getByTestId("launch-workspace")).toHaveAttribute(
+ "data-workspace-path",
+ "/home/user/project",
+ );
+ });
+
beforeEach(() => {
mockSearchSubdirectories.mockReset();
mockSearchSubdirectories.mockResolvedValue({
diff --git a/__tests__/components/features/home/home-chat-launcher.test.tsx b/__tests__/components/features/home/home-chat-launcher.test.tsx
index 5c713d8341..a5c0994da0 100644
--- a/__tests__/components/features/home/home-chat-launcher.test.tsx
+++ b/__tests__/components/features/home/home-chat-launcher.test.tsx
@@ -20,9 +20,11 @@ const mockClearAllFiles = vi.fn();
const enqueueHomeTaskPendingMessage = vi.fn();
const mockDisplayErrorToast = vi.fn();
const mockUseLlmConfigured = vi.fn();
+const mockUseConversationWorkspace = vi.fn();
let mockImages: File[] = [];
let mockFiles: File[] = [];
+let mockIsolated = false;
vi.mock("#/utils/send-message-with-attachments", () => ({
sendMessageWithAttachments: (...args: unknown[]) =>
@@ -73,6 +75,10 @@ vi.mock("#/hooks/use-llm-configured", () => ({
useLlmConfigured: () => mockUseLlmConfigured(),
}));
+vi.mock("#/hooks/query/use-conversation-workspace", () => ({
+ useConversationWorkspace: () => mockUseConversationWorkspace(),
+}));
+
vi.mock("#/hooks/use-is-creating-conversation", () => ({
useIsCreatingConversation: () => false,
}));
@@ -316,11 +322,16 @@ describe("HomeChatLauncher", () => {
vi.clearAllMocks();
mockImages = [];
mockFiles = [];
+ mockIsolated = false;
mockUseActiveBackend.mockReturnValue(localBackend);
mockUseLlmConfigured.mockReturnValue({
isConfigured: true,
isLoading: false,
});
+ mockUseConversationWorkspace.mockImplementation(() => ({
+ isolated: mockIsolated,
+ unsupportedMessage: mockIsolated ? "isolated-unsupported" : null,
+ }));
enqueueHomeTaskPendingMessage.mockResolvedValue(undefined);
sendMessageWithAttachments.mockResolvedValue({
text: "hello world",
@@ -427,6 +438,42 @@ describe("HomeChatLauncher", () => {
);
});
+ it("omits a stale host workspace override on an isolated backend", async () => {
+ // A host folder selected while the backend looked like a normal local
+ // backend must not be forwarded once the backend advertises isolation: the
+ // server rejects it and the user sees an error toast for a selection the
+ // launcher already deems unsupported. `isolated` is read per render, so
+ // flipping the mocked value and forcing a re-render models the backend
+ // changing under the user.
+ mockUseConversationWorkspace.mockImplementation(() => ({
+ isolated: mockIsolated,
+ unsupportedMessage: mockIsolated ? "isolated-unsupported" : null,
+ }));
+ const createSpy = vi
+ .spyOn(AgentServerConversationService, "createConversation")
+ .mockResolvedValue(
+ makeConversationResponse({ app_conversation_id: "conv-iso" }),
+ );
+
+ renderLauncher();
+ const user = userEvent.setup();
+
+ await user.click(screen.getByTestId("open-workspace-button"));
+ await user.click(
+ await screen.findByTestId("stub-workspace-dialog-confirm"),
+ );
+
+ mockIsolated = true;
+ await user.click(screen.getByTestId("stub-workspace-mode-new-worktree"));
+ await user.click(screen.getByTestId("stub-chat-submit"));
+
+ await waitFor(() => expect(createSpy).toHaveBeenCalledTimes(1));
+ expect(createSpy).toHaveBeenCalledWith({
+ initialUserMsg: "hello world",
+ metadata: null,
+ });
+ });
+
it("passes the picked workspace path with new-worktree mode when selected", async () => {
const createSpy = vi
.spyOn(AgentServerConversationService, "createConversation")
diff --git a/__tests__/components/features/home/workspace-selection-form.test.tsx b/__tests__/components/features/home/workspace-selection-form.test.tsx
index 21b527417b..1f68be6baf 100644
--- a/__tests__/components/features/home/workspace-selection-form.test.tsx
+++ b/__tests__/components/features/home/workspace-selection-form.test.tsx
@@ -1,3 +1,6 @@
+import { http, HttpResponse } from "msw";
+import { server } from "#/mocks/node";
+import { clearCachedAgentServerInfo } from "#/api/agent-server-compatibility";
import {
fireEvent,
render,
@@ -652,3 +655,42 @@ describe("WorkspaceSelectionForm (server-backed workspaces)", () => {
]);
});
});
+
+describe("isolated workspace selection", () => {
+ it("preserves saved selection but disables confirmation of host folders", async () => {
+ clearCachedAgentServerInfo();
+ sessionStorage.setItem(
+ HOME_SELECTED_WORKSPACE_PATH_KEY,
+ "/home/user/project",
+ );
+ server.use(
+ http.get("*/server_info", () =>
+ HttpResponse.json({
+ version: "1.45.0",
+ uptime: 0,
+ idle_time: 0,
+ conversation_runtime: "docker",
+ }),
+ ),
+ );
+ renderForm({
+ workspaces: [
+ {
+ id: "host-project",
+ name: "Host project",
+ path: "/home/user/project",
+ },
+ ],
+ });
+ await waitFor(() =>
+ expect(screen.getByTestId("workspace-status-message")).toHaveTextContent(
+ "HOME$ISOLATED_WORKSPACE_NOTICE",
+ ),
+ );
+ expect(screen.getByTestId("workspace-dropdown")).toBeDisabled();
+ expect(screen.getByTestId("workspace-launch-button")).toBeDisabled();
+ expect(sessionStorage.getItem(HOME_SELECTED_WORKSPACE_PATH_KEY)).toBe(
+ "/home/user/project",
+ );
+ });
+});
diff --git a/__tests__/hooks/query/use-has-git-commits.test.tsx b/__tests__/hooks/query/use-has-git-commits.test.tsx
index 95a551aa03..9659968926 100644
--- a/__tests__/hooks/query/use-has-git-commits.test.tsx
+++ b/__tests__/hooks/query/use-has-git-commits.test.tsx
@@ -111,6 +111,7 @@ describe("useHasGitCommits", () => {
"git rev-parse --verify HEAD",
"/workspace/project",
10,
+ conversation.id,
);
expect(result.current.hasCommits).toBe(true);
});
diff --git a/__tests__/hooks/query/use-workspace-file-content.test.tsx b/__tests__/hooks/query/use-workspace-file-content.test.tsx
index dcd0e1dd8b..34f77d5dec 100644
--- a/__tests__/hooks/query/use-workspace-file-content.test.tsx
+++ b/__tests__/hooks/query/use-workspace-file-content.test.tsx
@@ -27,7 +27,11 @@ vi.mock("#/hooks/query/use-active-conversation", () => ({
const useRuntimeIsReadyMock = vi.fn();
vi.mock("#/hooks/use-runtime-is-ready", () => ({
- useRuntimeIsReady: () => useRuntimeIsReadyMock(),
+ useRuntimeIsReady: (...args: unknown[]) => useRuntimeIsReadyMock(...args),
+}));
+
+vi.mock("#/hooks/use-agent-state", () => ({
+ useAgentState: () => ({ curAgentState: "error" }),
}));
const getActiveBackendMock = vi.fn();
@@ -108,6 +112,26 @@ describe("useWorkspaceFileContent", () => {
return new TextEncoder().encode(value).buffer as ArrayBuffer;
}
+ it("reads a diagnostic file while the conversation is in Error", async () => {
+ const { useRuntimeIsReady } = await vi.importActual<
+ typeof import("#/hooks/use-runtime-is-ready")
+ >("#/hooks/use-runtime-is-ready");
+ useRuntimeIsReadyMock.mockImplementation(useRuntimeIsReady);
+ useActiveConversationMock.mockReturnValue({
+ data: { id: "conv-1", execution_status: "error" },
+ });
+ fetchMock.mockResolvedValue({
+ ok: true,
+ status: 200,
+ arrayBuffer: () => Promise.resolve(arrayBufferFromString("diagnostic")),
+ });
+ const { result } = renderHook(
+ () => useWorkspaceFileContent("evidence/checkpoint.txt"),
+ { wrapper: makeWrapper() },
+ );
+ await waitFor(() => expect(result.current.data?.text).toBe("diagnostic"));
+ });
+
it("returns a static URL on the workspace fileserver for text content", async () => {
fetchMock.mockResolvedValue({
ok: true,
diff --git a/__tests__/hooks/query/use-workspace-files.test.tsx b/__tests__/hooks/query/use-workspace-files.test.tsx
index b9358811d2..b432e45936 100644
--- a/__tests__/hooks/query/use-workspace-files.test.tsx
+++ b/__tests__/hooks/query/use-workspace-files.test.tsx
@@ -50,7 +50,11 @@ vi.mock("#/hooks/query/use-active-conversation", () => ({
const useRuntimeIsReadyMock = vi.fn();
vi.mock("#/hooks/use-runtime-is-ready", () => ({
- useRuntimeIsReady: () => useRuntimeIsReadyMock(),
+ useRuntimeIsReady: (...args: unknown[]) => useRuntimeIsReadyMock(...args),
+}));
+
+vi.mock("#/hooks/use-agent-state", () => ({
+ useAgentState: () => ({ curAgentState: "error" }),
}));
const useOptionalConversationIdMock = vi.fn();
@@ -110,6 +114,27 @@ describe("useWorkspaceFiles — local backend", () => {
storeBackendKind = "local";
});
+ it("lists diagnostic files while the conversation is in Error", async () => {
+ const { useRuntimeIsReady } = await vi.importActual<
+ typeof import("#/hooks/use-runtime-is-ready")
+ >("#/hooks/use-runtime-is-ready");
+ useRuntimeIsReadyMock.mockImplementation(useRuntimeIsReady);
+ useActiveConversationMock.mockReturnValue({
+ data: { ...conversation, execution_status: "error" },
+ });
+ executeCommandSpy.mockResolvedValue({
+ exit_code: 0,
+ stdout: "./evidence/checkpoint.json\n",
+ stderr: "",
+ });
+ const { result } = renderHook(() => useWorkspaceFiles(), {
+ wrapper: makeWrapper(),
+ });
+ await waitFor(() =>
+ expect(result.current.data).toEqual(["evidence/checkpoint.json"]),
+ );
+ });
+
it("lists files via bash find and does not touch git changes", async () => {
executeCommandSpy.mockResolvedValue({
exit_code: 0,
diff --git a/__tests__/hooks/use-bash-command-runner.integration.test.ts b/__tests__/hooks/use-bash-command-runner.integration.test.ts
new file mode 100644
index 0000000000..9668d5e236
--- /dev/null
+++ b/__tests__/hooks/use-bash-command-runner.integration.test.ts
@@ -0,0 +1,96 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it } from "vitest";
+import { http, HttpResponse, delay } from "msw";
+import { server } from "#/mocks/node";
+import { useBashCommandRunner } from "#/hooks/use-bash-command-runner";
+import {
+ setRegisteredBackends,
+ setActiveSelection,
+} from "#/api/backend-registry/active-store";
+
+const host = "http://localhost:9876";
+const cid = "11111111-1111-4111-8111-111111111111";
+
+beforeEach(() => {
+ setRegisteredBackends([
+ {
+ id: "bash-probe",
+ name: "Probe",
+ kind: "local",
+ host,
+ apiKey: "backend-key",
+ },
+ ]);
+ setActiveSelection({ backendId: "bash-probe" });
+ server.use(
+ http.get(`${host}/server_info`, () =>
+ HttpResponse.json({
+ version: "1.47.0",
+ capabilities: ["conversation_runtime_routes_v1"],
+ conversation_runtime: "docker",
+ }),
+ ),
+ );
+});
+
+describe("useBashCommandRunner", () => {
+ it("scopes commands before URL hydration and correlates concurrent results", async () => {
+ const seen: string[] = [];
+ server.use(
+ http.post(
+ `${host}/api/conversations/${cid}/bash/execute_bash_command`,
+ async ({ request }) => {
+ expect(request.headers.get("X-Session-API-Key")).toBe(
+ "conversation-key",
+ );
+ const body = (await request.json()) as {
+ command: string;
+ cwd: string;
+ timeout: number;
+ };
+ expect(body.cwd).toBe("/workspace");
+ expect(body.timeout).toBe(30);
+ seen.push(body.command);
+ if (body.command === "first") await delay(20);
+ return HttpResponse.json({
+ exit_code: 0,
+ stdout: body.command,
+ stderr: "",
+ });
+ },
+ ),
+ );
+ const { result } = renderHook(() =>
+ useBashCommandRunner(undefined, "conversation-key", true, cid),
+ );
+ const output = await Promise.all([
+ result.current("first", "/workspace", 30),
+ result.current("second", "/workspace", 30),
+ ]);
+ expect(output.map((x) => x.stdout)).toEqual(["first", "second"]);
+ expect(seen).toEqual(["first", "second"]);
+ });
+
+ it("rejects a disabled probe without sending a request", async () => {
+ const { result } = renderHook(() =>
+ useBashCommandRunner(undefined, null, false, cid),
+ );
+ await expect(result.current("pwd", "/workspace", 30)).rejects.toThrow(
+ "disabled",
+ );
+ });
+
+ it("propagates runtime failures without claiming command success", async () => {
+ server.use(
+ http.post(
+ `${host}/api/conversations/${cid}/bash/execute_bash_command`,
+ () =>
+ HttpResponse.json({ detail: "Runtime unavailable" }, { status: 503 }),
+ ),
+ );
+ const { result } = renderHook(() =>
+ useBashCommandRunner(`${host}/api/conversations/${cid}`, null, true),
+ );
+ await expect(result.current("pwd", "/workspace", 30)).rejects.toThrow();
+ });
+});
diff --git a/__tests__/hooks/use-bash-command-runner.test.ts b/__tests__/hooks/use-bash-command-runner.test.ts
deleted file mode 100644
index 368f71db56..0000000000
--- a/__tests__/hooks/use-bash-command-runner.test.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-import { renderHook } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { useBashCommandRunner } from "#/hooks/use-bash-command-runner";
-
-class MockWebSocket {
- static readonly CONNECTING = 0;
- static readonly OPEN = 1;
- static readonly CLOSING = 2;
- static readonly CLOSED = 3;
- static instance: MockWebSocket | null = null;
-
- readonly url: string;
- readonly sent: string[] = [];
- readyState = MockWebSocket.CONNECTING;
- onopen: (() => void) | null = null;
- onmessage: ((event: MessageEvent) => void) | null = null;
- onclose: (() => void) | null = null;
- onerror: (() => void) | null = null;
-
- constructor(url: string) {
- this.url = url;
- MockWebSocket.instance = this;
- }
-
- send(data: string) {
- if (this.readyState !== MockWebSocket.OPEN) {
- throw new DOMException("WebSocket is not open", "InvalidStateError");
- }
- this.sent.push(data);
- }
-
- open() {
- this.readyState = MockWebSocket.OPEN;
- this.onopen?.();
- }
-
- receive(data: unknown) {
- this.onmessage?.(
- new MessageEvent("message", { data: JSON.stringify(data) }),
- );
- }
-
- close() {
- this.readyState = MockWebSocket.CLOSED;
- }
-}
-
-describe("useBashCommandRunner", () => {
- afterEach(() => {
- MockWebSocket.instance = null;
- vi.unstubAllGlobals();
- });
-
- it("sends auth before queued commands without putting the key in the URL", async () => {
- vi.stubGlobal("WebSocket", MockWebSocket);
- const sessionApiKey = `sk-oh-${"b".repeat(64)}`;
- const { result, unmount } = renderHook(() =>
- useBashCommandRunner(
- "https://runtime.example.com/api/conversations/conv-1",
- sessionApiKey,
- true,
- ),
- );
- const socket = MockWebSocket.instance!;
- socket.readyState = MockWebSocket.OPEN;
-
- const command = result.current("pwd", "/workspace", 30);
-
- expect(socket.sent).toEqual([]);
- socket.open();
-
- expect(socket.url).not.toContain(sessionApiKey);
- expect(socket.url).not.toContain("session_api_key");
- expect(socket.sent).toEqual([
- JSON.stringify({ type: "auth", session_api_key: sessionApiKey }),
- JSON.stringify({ command: "pwd", cwd: "/workspace", timeout: 30 }),
- ]);
-
- socket.receive({ kind: "BashCommand", id: "command-1" });
- socket.receive({
- kind: "BashOutput",
- command_id: "command-1",
- stdout: "/workspace\n",
- stderr: "",
- exit_code: 0,
- });
- await expect(command).resolves.toEqual({
- exit_code: 0,
- stdout: "/workspace\n",
- stderr: "",
- });
-
- unmount();
- });
-
- it("sends queued commands without an auth frame when no key is configured", async () => {
- vi.stubGlobal("WebSocket", MockWebSocket);
- const { result, unmount } = renderHook(() =>
- useBashCommandRunner(
- "http://runtime.example.com/api/conversations/conv-1",
- null,
- true,
- ),
- );
- const socket = MockWebSocket.instance!;
- const command = result.current("git status", "/workspace", 10);
-
- expect(socket.sent).toEqual([]);
- socket.open();
- expect(socket.sent).toEqual([
- JSON.stringify({
- command: "git status",
- cwd: "/workspace",
- timeout: 10,
- }),
- ]);
-
- socket.receive({ kind: "BashCommand", id: "command-1" });
- socket.receive({
- kind: "BashOutput",
- command_id: "command-1",
- stdout: "",
- stderr: "",
- exit_code: 0,
- });
- await expect(command).resolves.toEqual({
- exit_code: 0,
- stdout: "",
- stderr: "",
- });
-
- unmount();
- });
-
- it("closes a handshake stuck in CONNECTING at the timeout", () => {
- // Arrange: the server never completes the 101 upgrade. Left alone, this
- // socket would hold the browser's per-host handshake lock and block the
- // conversation's events socket indefinitely.
- vi.stubGlobal("WebSocket", MockWebSocket);
- vi.useFakeTimers();
-
- try {
- const { unmount } = renderHook(() =>
- useBashCommandRunner(
- "http://runtime.example.com/api/conversations/conv-1",
- null,
- true,
- ),
- );
- const socket = MockWebSocket.instance!;
- const closeSpy = vi.spyOn(socket, "close");
-
- // Act/Assert: untouched just before the timeout, closed right at it.
- vi.advanceTimersByTime(9_999);
- expect(closeSpy).not.toHaveBeenCalled();
-
- vi.advanceTimersByTime(1);
- expect(closeSpy).toHaveBeenCalledOnce();
- expect(socket.readyState).toBe(MockWebSocket.CLOSED);
-
- unmount();
- } finally {
- vi.useRealTimers();
- }
- });
-
- it("does not close a socket that finished its handshake in time", () => {
- vi.stubGlobal("WebSocket", MockWebSocket);
- vi.useFakeTimers();
-
- try {
- const { unmount } = renderHook(() =>
- useBashCommandRunner(
- "http://runtime.example.com/api/conversations/conv-1",
- null,
- true,
- ),
- );
- const socket = MockWebSocket.instance!;
- const closeSpy = vi.spyOn(socket, "close");
-
- // Act: the handshake completes, then the watchdog window elapses.
- socket.open();
- vi.advanceTimersByTime(60_000);
-
- // Assert: the cleared watchdog never touched the healthy socket.
- expect(closeSpy).not.toHaveBeenCalled();
- expect(socket.readyState).toBe(MockWebSocket.OPEN);
-
- unmount();
- } finally {
- vi.useRealTimers();
- }
- });
-});
diff --git a/__tests__/hooks/use-bash-command-runner.test.tsx b/__tests__/hooks/use-bash-command-runner.test.tsx
index 0ec2a1b8d1..fb18cc210f 100644
--- a/__tests__/hooks/use-bash-command-runner.test.tsx
+++ b/__tests__/hooks/use-bash-command-runner.test.tsx
@@ -1,443 +1,115 @@
-import { act, renderHook } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { useBashCommandRunner } from "#/hooks/use-bash-command-runner";
-function installControlledWebSocket() {
- class ControlledWebSocket {
- static readonly CONNECTING = 0;
- static readonly OPEN = 1;
- static readonly CLOSING = 2;
- static readonly CLOSED = 3;
-
- readonly sent: string[] = [];
- readonly url: string;
- readyState = ControlledWebSocket.CONNECTING;
- onopen: ((event: Event) => void) | null = null;
- onmessage: ((event: MessageEvent) => void) | null = null;
- onclose: ((event: CloseEvent) => void) | null = null;
- onerror: ((event: Event) => void) | null = null;
- close = vi.fn(() => {
- this.readyState = ControlledWebSocket.CLOSED;
- });
-
- constructor(url: string) {
- this.url = url;
- instances.push(this);
- }
-
- send(data: string) {
- this.sent.push(data);
- }
-
- open() {
- this.readyState = ControlledWebSocket.OPEN;
- this.onopen?.(new Event("open"));
+const { createClient, executeCommand, close } = vi.hoisted(() => ({
+ createClient: vi.fn(),
+ executeCommand: vi.fn(),
+ close: vi.fn(),
+}));
+
+vi.mock("@openhands/typescript-client/clients", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@openhands/typescript-client/clients")
+ >()),
+ BashClient: class {
+ constructor(options: unknown) {
+ createClient(options);
}
- emitRaw(data: string) {
- this.onmessage?.(new MessageEvent("message", { data }));
- }
-
- emit(data: Record<string, unknown>) {
- this.emitRaw(JSON.stringify(data));
- }
-
- fail() {
- this.onerror?.(new Event("error"));
- }
-
- disconnect() {
- this.readyState = ControlledWebSocket.CLOSED;
- this.onclose?.(new CloseEvent("close"));
- }
- }
-
- const instances: ControlledWebSocket[] = [];
- vi.stubGlobal("WebSocket", ControlledWebSocket);
-
- return {
- instances,
- get socket() {
- const socket = instances.at(-1);
- if (!socket) throw new Error("Expected a WebSocket to be created");
- return socket;
- },
- };
-}
-
-const bashCommand = (id: string) => ({
- kind: "BashCommand",
- id,
- timestamp: "2026-07-12T00:00:00.000Z",
- command: "ignored server echo",
-});
-
-const bashOutput = (
- commandId: string,
- output: {
- stdout?: string | null;
- stderr?: string | null;
- exit_code?: number | null;
+ executeCommand = executeCommand;
+ close = close;
},
-) => ({
- kind: "BashOutput",
- id: `output-${commandId}`,
- timestamp: "2026-07-12T00:00:01.000Z",
- command_id: commandId,
- order: 0,
- ...output,
-});
-
-const bashError = (code: string, detail: string) => ({
- kind: "BashError",
- id: `error-${code}`,
- timestamp: "2026-07-12T00:00:01.000Z",
- code,
- detail,
-});
-
-function withSettlementDeadline<T>(promise: Promise<T>): Promise<T> {
- return new Promise((resolve, reject) => {
- const timer = setTimeout(
- () => reject(new Error("Bash command promise did not settle")),
- 250,
- );
- promise.then(
- (value) => {
- clearTimeout(timer);
- resolve(value);
- },
- (error: unknown) => {
- clearTimeout(timer);
- reject(error);
- },
- );
- });
-}
+}));
-afterEach(() => {
- vi.unstubAllGlobals();
+beforeEach(() => {
+ vi.clearAllMocks();
+ executeCommand.mockResolvedValue({ exit_code: 0, stdout: "ok", stderr: "" });
});
-describe("bash command execution over a persistent socket", () => {
- it("stays disconnected when disabled and rejects commands immediately", async () => {
- const sockets = installControlledWebSocket();
+describe("bash command execution through the SDK", () => {
+ it("forwards command options and releases the client after success", async () => {
const { result } = renderHook(() =>
useBashCommandRunner(
- "https://runtime.example.com/api/conversations/conv-1",
+ "http://runtime.example.com/api/conversations/conv-1",
"session-key",
- false,
- ),
- );
-
- await expect(
- withSettlementDeadline(result.current("pwd", "/workspace", 10)),
- ).rejects.toThrow("Bash WebSocket not available");
- expect(sockets.instances).toHaveLength(0);
- });
-
- it("buffers commands when the socket is OPEN but not yet the ready socket", async () => {
- const sockets = installControlledWebSocket();
- const { result } = renderHook(() =>
- useBashCommandRunner("http://runtime.example.com", "session-key", true),
- );
-
- // The socket reports OPEN before the hook's open handler has run, so it is
- // not yet the tracked "ready" socket. Commands must still be buffered
- // rather than sent on a socket the hook has not authenticated.
- act(() => {
- sockets.socket.readyState = 1; // WebSocket.OPEN
- });
- const pending = withSettlementDeadline(
- result.current("pwd", "/workspace", 10),
- );
- expect(sockets.socket.sent).toEqual([]);
-
- // Once the open handler runs, the hook authenticates and flushes the queue.
- act(() => sockets.socket.open());
- expect(sockets.socket.sent.map((payload) => JSON.parse(payload))).toEqual([
- { type: "auth", session_api_key: "session-key" },
- { command: "pwd", cwd: "/workspace", timeout: 10 },
- ]);
-
- act(() => sockets.socket.emit(bashCommand("command-1")));
- act(() =>
- sockets.socket.emit(bashOutput("command-1", { stdout: "ok", exit_code: 0 })),
- );
- await expect(pending).resolves.toEqual({
- exit_code: 0,
- stdout: "ok",
- stderr: "",
- });
-
- // A command issued once the socket is ready is sent immediately rather than
- // buffered.
- const followUp = withSettlementDeadline(
- result.current("ls", "/workspace", 5),
- );
- expect(
- sockets.socket.sent.map((payload) => JSON.parse(payload)).at(-1),
- ).toEqual({ command: "ls", cwd: "/workspace", timeout: 5 });
- act(() => sockets.socket.emit(bashCommand("command-2")));
- act(() =>
- sockets.socket.emit(bashOutput("command-2", { stdout: "", exit_code: 0 })),
- );
- await expect(followUp).resolves.toEqual({
- exit_code: 0,
- stdout: "",
- stderr: "",
- });
- });
-
- it("buffers commands while connecting, correlates them FIFO, and aggregates output chunks", async () => {
- const sockets = installControlledWebSocket();
- const { result } = renderHook(() =>
- useBashCommandRunner(
- "https://runtime.example.com/runtime/18000/api/conversations/conv-1",
- "key with spaces",
true,
),
);
-
- const first = withSettlementDeadline(
- result.current("printf first", "/workspace/one", 11),
- );
- const second = withSettlementDeadline(
- result.current("printf second", "/workspace/two", 22),
- );
- expect(sockets.socket.sent).toEqual([]);
- expect(sockets.socket.url).toBe(
- "wss://runtime.example.com/runtime/18000/sockets/bash-events",
- );
-
- act(() => sockets.socket.open());
- // On open the hook first authenticates over the socket, then flushes the
- // buffered commands in FIFO order.
- expect(sockets.socket.sent.map((payload) => JSON.parse(payload))).toEqual([
- { type: "auth", session_api_key: "key with spaces" },
- { command: "printf first", cwd: "/workspace/one", timeout: 11 },
- { command: "printf second", cwd: "/workspace/two", timeout: 22 },
- ]);
-
- act(() => {
- sockets.socket.emit(bashCommand("command-1"));
- sockets.socket.emit(
- bashOutput("command-1", {
- stdout: "first ",
- stderr: "warn ",
- exit_code: null,
- }),
- );
- sockets.socket.emit(
- bashOutput("command-1", {
- stdout: "result",
- stderr: "again",
- exit_code: 0,
- }),
- );
- sockets.socket.emit(bashCommand("command-2"));
- sockets.socket.emit(
- bashOutput("command-2", {
- stdout: "second result",
- stderr: "",
- exit_code: 7,
- }),
- );
- });
-
- await expect(first).resolves.toEqual({
+ await expect(result.current("pwd", "/workspace", 10)).resolves.toEqual({
exit_code: 0,
- stdout: "first result",
- stderr: "warn again",
- });
- await expect(second).resolves.toEqual({
- exit_code: 7,
- stdout: "second result",
+ stdout: "ok",
stderr: "",
});
- });
- it("ignores malformed, unknown, uncorrelated, and incomplete server frames", async () => {
- const sockets = installControlledWebSocket();
- const { result } = renderHook(() =>
- useBashCommandRunner("http://runtime.example.com", null, true),
- );
- act(() => sockets.socket.open());
-
- const command = withSettlementDeadline(
- result.current("echo safe", "/workspace", 5),
- );
- act(() => {
- sockets.socket.emitRaw("not-json");
- sockets.socket.emit({ kind: "FutureBashEvent" });
- sockets.socket.emit(bashOutput("", { exit_code: 0 }));
- sockets.socket.emit(bashOutput("not-active", { exit_code: 0 }));
- sockets.socket.emit(bashCommand("active-command"));
- sockets.socket.emit({
- kind: "FutureBashEvent",
- command_id: "active-command",
- stdout: "forged",
- stderr: "forged",
- exit_code: 99,
- });
- sockets.socket.emit(bashCommand("unrequested-command"));
- sockets.socket.emit(
- bashOutput("active-command", {
- stdout: "",
- stderr: null,
- exit_code: null,
- }),
- );
+ expect(createClient).toHaveBeenCalledWith(
+ expect.objectContaining({
+ host: "http://runtime.example.com",
+ apiKey: "session-key",
+ conversationId: "conv-1",
+ }),
+ );
+ expect(executeCommand).toHaveBeenCalledWith({
+ command: "pwd",
+ cwd: "/workspace",
+ timeout: 10,
});
-
- expect(
- await Promise.race([command.then(() => "resolved"), "pending"]),
- ).toBe("pending");
-
- act(() => {
- sockets.socket.emit(
- bashOutput("active-command", {
- stdout: null,
- stderr: "",
- exit_code: 0,
- }),
- );
- });
- await expect(command).resolves.toEqual({
- exit_code: 0,
- stdout: "",
- stderr: "",
- });
- });
-
- it("rejects commands waiting for connection when the server reports a bash error", async () => {
- const sockets = installControlledWebSocket();
- const { result } = renderHook(() =>
- useBashCommandRunner("http://runtime.example.com", null, true),
- );
- const command = withSettlementDeadline(
- result.current("pwd", "/workspace", 10),
- );
-
- act(() => sockets.socket.emit(bashError("NOT_READY", "runtime starting")));
-
- await expect(command).rejects.toThrow(
- "Bash error: NOT_READY: runtime starting",
- );
+ expect(close).toHaveBeenCalledOnce();
});
- it("rejects sent commands that have not received their server id on socket error", async () => {
- const sockets = installControlledWebSocket();
+ it("releases the client and propagates execution failures", async () => {
+ const failure = new Error("Runtime unavailable");
+ executeCommand.mockRejectedValueOnce(failure);
const { result } = renderHook(() =>
- useBashCommandRunner("http://runtime.example.com", null, true),
- );
- act(() => sockets.socket.open());
- const command = withSettlementDeadline(
- result.current("pwd", "/workspace", 10),
+ useBashCommandRunner("http://runtime.example.com", "key", true, "conv-1"),
);
- expect(sockets.socket.sent.map((payload) => JSON.parse(payload))).toEqual([
- { command: "pwd", cwd: "/workspace", timeout: 10 },
- ]);
-
- act(() => sockets.socket.fail());
-
- await expect(command).rejects.toThrow("Bash WebSocket error");
- await expect(
- withSettlementDeadline(result.current("pwd", "/workspace", 10)),
- ).rejects.toThrow("Bash WebSocket not available");
+ await expect(result.current("pwd", "/workspace", 10)).rejects.toBe(failure);
+ expect(close).toHaveBeenCalledOnce();
});
- it("rejects active commands when the socket closes", async () => {
- const sockets = installControlledWebSocket();
+ it("rejects disabled commands without creating a client", async () => {
const { result } = renderHook(() =>
- useBashCommandRunner("http://runtime.example.com", null, true),
+ useBashCommandRunner("http://runtime.example.com", "key", false),
);
- act(() => sockets.socket.open());
- const command = withSettlementDeadline(
- result.current("pwd", "/workspace", 10),
+ await expect(result.current("pwd", "/workspace", 10)).rejects.toThrow(
+ "disabled",
);
- act(() => sockets.socket.emit(bashCommand("active-command")));
-
- act(() => sockets.socket.disconnect());
-
- await expect(command).rejects.toThrow("Bash WebSocket closed");
+ expect(createClient).not.toHaveBeenCalled();
});
- it("rejects pending work on unmount without running close handlers twice", async () => {
- const sockets = installControlledWebSocket();
- const { result, unmount } = renderHook(() =>
- useBashCommandRunner("http://runtime.example.com", null, true),
- );
- act(() => sockets.socket.open());
- const command = withSettlementDeadline(
- result.current("pwd", "/workspace", 10),
- );
-
- unmount();
-
- await expect(command).rejects.toThrow("Bash WebSocket unmounted");
- expect(sockets.socket.close).toHaveBeenCalledOnce();
- expect(sockets.socket.onclose).toBeNull();
- expect(sockets.socket.onerror).toBeNull();
- });
-
- it("reconnects with the latest runtime URL, session key, and enabled state", async () => {
- const sockets = installControlledWebSocket();
+ it("uses the latest runtime identity after rerender", async () => {
const { result, rerender } = renderHook(
- ({ url, sessionKey, enabled }) =>
- useBashCommandRunner(url, sessionKey, enabled),
+ ({ host, key, id }) => useBashCommandRunner(host, key, true, id),
{
initialProps: {
- url: "https://runtime-a.example.com/api/conversations/conv-1",
- sessionKey: "key-a",
- enabled: true,
+ host: "http://first.example.com",
+ key: "first",
+ id: "one",
},
},
);
- const firstSocket = sockets.socket;
- const queuedCommand = withSettlementDeadline(
- result.current("pwd", "/workspace", 10),
- );
-
- rerender({
- url: "https://runtime-b.example.com/api/conversations/conv-2",
- sessionKey: "key-b",
- enabled: true,
- });
-
- await expect(queuedCommand).rejects.toThrow("Bash WebSocket unmounted");
- expect(firstSocket.close).toHaveBeenCalledOnce();
- expect(sockets.instances).toHaveLength(2);
- expect(sockets.socket.url).toBe(
- "wss://runtime-b.example.com/sockets/bash-events",
- );
-
- const secondSocket = sockets.socket;
- // The reconnected socket authenticates with the latest session key.
- act(() => secondSocket.open());
- expect(secondSocket.sent.map((payload) => JSON.parse(payload))).toEqual([
- { type: "auth", session_api_key: "key-b" },
- ]);
- rerender({
- url: "https://runtime-b.example.com/api/conversations/conv-2",
- sessionKey: "key-b",
- enabled: false,
- });
- expect(secondSocket.close).toHaveBeenCalledOnce();
- expect(sockets.instances).toHaveLength(2);
+ await result.current("pwd", "/workspace", 10);
+ rerender({ host: "http://second.example.com", key: "second", id: "two" });
+ await result.current("pwd", "/workspace", 10);
+ expect(createClient).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ host: "http://second.example.com",
+ apiKey: "second",
+ conversationId: "two",
+ }),
+ );
+ expect(close).toHaveBeenCalledTimes(2);
});
- it.each([
- { state: 2, label: "closing" },
- { state: 3, label: "closed" },
- ])("rejects commands while the socket is $label", async ({ state }) => {
- const sockets = installControlledWebSocket();
+ it("normalizes absent command output without inventing success", async () => {
+ executeCommand.mockResolvedValueOnce({});
const { result } = renderHook(() =>
- useBashCommandRunner("http://runtime.example.com", null, true),
+ useBashCommandRunner("http://runtime.example.com", "key", true),
);
- sockets.socket.readyState = state;
-
- await expect(
- withSettlementDeadline(result.current("pwd", "/workspace", 10)),
- ).rejects.toThrow("Bash WebSocket not available");
+ await expect(result.current("pwd", "/workspace", 10)).resolves.toEqual({
+ exit_code: -1,
+ stdout: "",
+ stderr: "",
+ });
+ expect(close).toHaveBeenCalledOnce();
});
});
diff --git a/__tests__/hooks/use-runtime-is-ready.test.tsx b/__tests__/hooks/use-runtime-is-ready.test.tsx
index 08b6f6a05b..354f8bef13 100644
--- a/__tests__/hooks/use-runtime-is-ready.test.tsx
+++ b/__tests__/hooks/use-runtime-is-ready.test.tsx
@@ -57,6 +57,43 @@ describe("useRuntimeIsReady", () => {
expect(result.current).toBe(false);
});
+ it.each([ExecutionStatus.ERROR, ExecutionStatus.STUCK])(
+ "allows read-only diagnostics for execution status %s only when requested",
+ (execution_status) => {
+ vi.mocked(useActiveConversation).mockReturnValue(
+ asMockReturnValue<ReturnType<typeof useActiveConversation>>({
+ data: { ...makeConversation(), execution_status },
+ }),
+ );
+ vi.mocked(useAgentState).mockReturnValue({
+ curAgentState: AgentState.ERROR,
+ });
+ const { result } = renderHook(() => ({
+ normal: useRuntimeIsReady(),
+ diagnostics: useRuntimeIsReady({ allowAgentError: true }),
+ }));
+ expect(result.current).toEqual({ normal: false, diagnostics: true });
+ },
+ );
+
+ it("keeps a paused runtime unavailable even for diagnostics", () => {
+ vi.mocked(useActiveConversation).mockReturnValue(
+ asMockReturnValue<ReturnType<typeof useActiveConversation>>({
+ data: {
+ ...makeConversation(),
+ execution_status: ExecutionStatus.PAUSED,
+ },
+ }),
+ );
+ vi.mocked(useAgentState).mockReturnValue({
+ curAgentState: AgentState.ERROR,
+ });
+ const { result } = renderHook(() =>
+ useRuntimeIsReady({ allowAgentError: true }),
+ );
+ expect(result.current).toBe(false);
+ });
+
it("allows runtime-backed tabs to stay ready when the agent errors", () => {
vi.mocked(useAgentState).mockReturnValue({
curAgentState: AgentState.ERROR,
diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.ts
index 23fb3393ae..aff94e4f67 100644
--- a/src/api/agent-server-adapter.ts
+++ b/src/api/agent-server-adapter.ts
@@ -1652,7 +1652,7 @@ export async function buildStartConversationRequestWithEncryptedSettings(options
parentConversationId?: string;
workingDir?: string;
/** Workspace root for the hooks lookup, not the per-conversation `workingDir` (#16907). */
- hooksProjectDir?: string;
+ hooksProjectDir?: string | null;
worktree?: boolean;
agentProfileId?: string;
agentProfileKind?: AgentKind;
@@ -1668,7 +1668,9 @@ export async function buildStartConversationRequestWithEncryptedSettings(options
SettingsService.getSettingsForConversation(),
SecretsService.getSecrets(),
fetchBackendServerInfo(),
- HooksService.loadWorkspaceHooks(options.hooksProjectDir),
+ options.hooksProjectDir === null
+ ? Promise.resolve(null)
+ : HooksService.loadWorkspaceHooks(options.hooksProjectDir),
]);
const { agentSettings, conversationSettings, secretsEncrypted } =
diff --git a/src/api/agent-server-client-options.ts b/src/api/agent-server-client-options.ts
index 6926bdf1bc..c22cf9d50b 100644
--- a/src/api/agent-server-client-options.ts
+++ b/src/api/agent-server-client-options.ts
@@ -4,6 +4,7 @@ import { getEffectiveLocalBackend } from "./backend-registry/active-store";
import type { Backend } from "./backend-registry/types";
export interface AgentServerClientOverrides {
+ conversationId?: string;
host?: string;
apiKey?: string | null;
sessionApiKey?: string | null;
@@ -13,6 +14,7 @@ export interface AgentServerClientOverrides {
}
export interface AgentServerClientOptions {
+ conversationId?: string;
host: string;
apiKey?: string;
workingDir: string;
@@ -60,8 +62,15 @@ export function getAgentServerClientOptions(
const apiKey =
overrides.sessionApiKey ?? overrides.apiKey ?? backend?.apiKey ?? undefined;
+ const conversationId =
+ overrides.conversationId ??
+ overrides.conversationUrl?.match(
+ /\/api\/conversations\/([^/?#]+)(?:[/?#]|$)/,
+ )?.[1];
+
return {
host: resolveHost(overrides, backend),
+ ...(conversationId ? { conversationId } : {}),
...(apiKey ? { apiKey } : {}),
workingDir: overrides.workingDir ?? getAgentServerWorkingDir(),
...(overrides.timeout !== undefined ? { timeout: overrides.timeout } : {}),
@@ -71,9 +80,11 @@ export function getAgentServerClientOptions(
export function getAgentServerHttpClientOptions(
overrides?: AgentServerClientOverrides,
) {
- const { host, apiKey, timeout } = getAgentServerClientOptions(overrides);
+ const { host, apiKey, timeout, conversationId } =
+ getAgentServerClientOptions(overrides);
return {
baseUrl: host,
+ ...(conversationId ? { conversationId } : {}),
...(apiKey ? { apiKey } : {}),
timeout: timeout ?? 60000,
};
diff --git a/src/api/conversation-file-upload.api.ts b/src/api/conversation-file-upload.api.ts
index d07e54db9e..83727d8637 100644
--- a/src/api/conversation-file-upload.api.ts
+++ b/src/api/conversation-file-upload.api.ts
@@ -99,6 +99,7 @@ export async function uploadFilesToConversation(
sessionApiKey,
});
return uploadFilesToRuntime({
+ conversationId,
files,
workingDir,
conversationUrl: cloudRuntime.conversationUrl,
@@ -107,6 +108,7 @@ export async function uploadFilesToConversation(
}
return uploadFilesToRuntime({
+ conversationId,
files,
workingDir,
conversationUrl,
@@ -115,6 +117,7 @@ export async function uploadFilesToConversation(
}
async function uploadFilesToRuntime(options: {
+ conversationId: string;
files: File[];
workingDir: string;
conversationUrl: string | null;
@@ -123,6 +126,7 @@ async function uploadFilesToRuntime(options: {
const { files, workingDir, conversationUrl, sessionApiKey } = options;
const workspace = new RemoteWorkspace(
getAgentServerClientOptions({
+ conversationId: options.conversationId,
conversationUrl,
sessionApiKey,
workingDir,
diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.ts
index a700d9b3ca..7b51709ef4 100644
--- a/src/api/conversation-service/agent-server-conversation-service.api.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts
@@ -13,12 +13,8 @@ import {
import { v4 as uuidv4 } from "uuid";
import { AgentKind, Provider } from "#/types/settings";
import type { ConversationRuntimeContext } from "#/api/conversation-file-upload.api";
-import {
- buildConversationWorkingDirForBackend,
- getAgentServerWorkingDir,
- getWorkspaceRootForBackend,
-} from "../agent-server-config";
-import { resolveAbsoluteAgentServerPath } from "../agent-server-home";
+import { getAgentServerWorkingDir } from "../agent-server-config";
+import { resolveNewConversationWorkspace } from "../conversation-workspace";
import {
getActiveBackend,
getEffectiveLocalBackend,
@@ -490,40 +486,13 @@ class AgentServerConversationService {
profiles,
);
const conversationId = uuidv4();
- // @spec WUP-001 — Send an absolute working_dir to the agent-server.
- // The default is `workspace/project/<hex>` (relative); without
- // resolving it here, `/api/file/upload` later prepends `/` and writes
- // to `/workspace/...` (read-only on macOS and fresh containers). When
- // the user picks an explicit workspace, `workingDirOverride` is
- // already absolute (it comes from `search_subdirs`).
- //
- // Pick the base working dir per-backend:
- // 1. explicit user workspace pick → use it as-is;
- // 2. no pick, backend that served this frontend → the baked default
- // (honors a launcher-baked absolute `VITE_WORKING_DIR`);
- // 3. no pick, any other backend → the backend-relative default.
- // A baked absolute dir is a path on the host that served this frontend,
- // so it is only valid on that backend. Using it for a different backend
- // (e.g. a remote sandbox) makes the agent-server mkdir an unwritable path
- // and the conversation fails at the first prompt (e.g. `Permission
- // denied: '/Users'`). The relative default is anchored per-backend by
- // `resolveAbsoluteAgentServerPath()` via `/api/file/home`. The gate keys
- // on the active backend's host (not its id): the seeded `default-local`
- // entry is mutable, so a user can edit it to point at a remote host while
- // its id stays `default-local`.
- const backendHost = getActiveBackend().backend.host;
- const baseWorkingDir =
- workingDirOverride ??
- buildConversationWorkingDirForBackend(conversationId, backendHost);
- const workingDir = await resolveAbsoluteAgentServerPath(baseWorkingDir);
- // The agent-server checks `<project_dir>/.openhands/hooks.json` literally,
- // so hooks need the workspace root: the per-conversation subdir below it is
- // created only after this request (#16907). An explicit pick is the root.
- const hooksProjectDir = workingDirOverride
- ? workingDir
- : await resolveAbsoluteAgentServerPath(
- getWorkspaceRootForBackend(backendHost),
- );
+ const { workingDir, hooksProjectDir, isolated } =
+ await resolveNewConversationWorkspace({
+ conversationId,
+ workingDir: workingDirOverride,
+ selectedRepository: metadata?.selected_repository,
+ parentConversationId,
+ });
const resolvedWorkspaceMode =
workspaceMode ?? (workingDirOverride ? "local_repo" : "new_worktree");
@@ -541,7 +510,7 @@ class AgentServerConversationService {
parentConversationId,
workingDir,
hooksProjectDir,
- worktree: resolvedWorkspaceMode === "new_worktree",
+ worktree: !isolated && resolvedWorkspaceMode === "new_worktree",
agentProfileId,
agentProfileKind,
titleLlmProfile,
@@ -723,6 +692,7 @@ class AgentServerConversationService {
// directly via the conversationUrl override.
const vscodeUrl = await new VSCodeClient(
getAgentServerClientOptions({
+ conversationId,
conversationUrl,
sessionApiKey,
}),
@@ -836,7 +806,9 @@ class AgentServerConversationService {
filePath ?? `${workingDir}/.agents_tmp/PLAN.md`,
workingDir,
);
- return new FileClient(getAgentServerClientOptions()).downloadTextFile(path);
+ return new FileClient(
+ getAgentServerClientOptions({ conversationId, workingDir }),
+ ).downloadTextFile(path);
}
static async downloadConversation(conversationId: string): Promise<Blob> {
diff --git a/src/api/conversation-service/conversation-service.api.ts b/src/api/conversation-service/conversation-service.api.ts
index c125654019..3cd6868a2a 100644
--- a/src/api/conversation-service/conversation-service.api.ts
+++ b/src/api/conversation-service/conversation-service.api.ts
@@ -26,10 +26,15 @@ class ConversationService {
return this.currentConversation;
}
- private static getClientOverrides() {
+ private static getClientOverrides(conversationId: string) {
return {
- conversationUrl: this.currentConversation?.conversation_url,
- sessionApiKey: this.currentConversation?.session_api_key,
+ conversationId,
+ ...(this.currentConversation?.id === conversationId
+ ? {
+ conversationUrl: this.currentConversation.conversation_url,
+ sessionApiKey: this.currentConversation.session_api_key,
+ }
+ : {}),
};
}
@@ -42,7 +47,7 @@ class ConversationService {
getAgentServerWorkingDir())
: getAgentServerWorkingDir();
const vscodeUrl = await new VSCodeClient(
- getAgentServerClientOptions(this.getClientOverrides()),
+ getAgentServerClientOptions(this.getClientOverrides(conversationId)),
).getUrl({
baseUrl:
typeof window !== "undefined" ? window.location.origin : undefined,
@@ -56,7 +61,7 @@ class ConversationService {
conversationId: string,
): Promise<GetTrajectoryResponse> {
const page = await new RemoteEventsList(
- getAgentServerHttpClientOptions(this.getClientOverrides()),
+ getAgentServerHttpClientOptions(this.getClientOverrides(conversationId)),
conversationId,
).search({ limit: 10000 });
diff --git a/src/api/conversation-workspace.ts b/src/api/conversation-workspace.ts
new file mode 100644
index 0000000000..dcf2f8f738
--- /dev/null
+++ b/src/api/conversation-workspace.ts
@@ -0,0 +1,81 @@
+import i18n from "#/i18n";
+import { I18nKey } from "#/i18n/declaration";
+import { ServerClient } from "@openhands/typescript-client/clients";
+import type { ServerInfo } from "@openhands/typescript-client";
+import {
+ getAgentServerClientOptions,
+ type AgentServerClientOverrides,
+} from "./agent-server-client-options";
+import { getCachedAgentServerInfo } from "./agent-server-compatibility";
+import {
+ buildConversationWorkingDirForBackend,
+ getWorkspaceRootForBackend,
+} from "./agent-server-config";
+import { resolveAbsoluteAgentServerPath } from "./agent-server-home";
+
+const ISOLATED_WORKSPACE_DIR = "/workspace";
+
+export function usesIsolatedWorkspace(
+ info: ServerInfo | null | undefined,
+): boolean {
+ return info?.conversation_runtime === "docker";
+}
+
+export async function getConversationServerInfo(
+ overrides: AgentServerClientOverrides = {},
+): Promise<ServerInfo | null> {
+ const options = getAgentServerClientOptions(overrides);
+ const cached = getCachedAgentServerInfo({ host: options.host });
+ if (cached) return cached;
+ try {
+ return await new ServerClient(options).getServerInfo();
+ } catch {
+ // An unreachable or non-responding agent-server is not fatal: callers
+ // fall back to host-workspace behavior, matching how the rest of the
+ // app treats an unavailable `server_info` (see
+ // `fetchBackendServerInfo`). Only a *successful* probe that reports
+ // `conversation_runtime: "docker"` may isolate the workspace.
+ return null;
+ }
+}
+
+export async function resolveNewConversationWorkspace(options: {
+ conversationId: string;
+ workingDir?: string;
+ selectedRepository?: string | null;
+ parentConversationId?: string;
+}) {
+ const clientOptions = getAgentServerClientOptions();
+ const info = await getConversationServerInfo(clientOptions);
+ if (usesIsolatedWorkspace(info)) {
+ if (
+ options.selectedRepository ||
+ (options.workingDir !== undefined &&
+ !(
+ options.parentConversationId &&
+ options.workingDir === ISOLATED_WORKSPACE_DIR
+ ))
+ ) {
+ throw new Error(i18n.t(I18nKey.HOME$ISOLATED_WORKSPACE_NOTICE));
+ }
+ return {
+ workingDir: ISOLATED_WORKSPACE_DIR,
+ hooksProjectDir: null,
+ isolated: true,
+ };
+ }
+ // @spec WUP-001 — Resolve relative local defaults against the backend home.
+ const base =
+ options.workingDir ??
+ buildConversationWorkingDirForBackend(
+ options.conversationId,
+ clientOptions.host,
+ );
+ const workingDir = await resolveAbsoluteAgentServerPath(base);
+ const hooksProjectDir = options.workingDir
+ ? workingDir
+ : await resolveAbsoluteAgentServerPath(
+ getWorkspaceRootForBackend(clientOptions.host),
+ );
+ return { workingDir, hooksProjectDir, isolated: false };
+}
diff --git a/src/api/git-service/agent-server-git-service.api.ts b/src/api/git-service/agent-server-git-service.api.ts
index 9a63327039..99c0204463 100644
--- a/src/api/git-service/agent-server-git-service.api.ts
+++ b/src/api/git-service/agent-server-git-service.api.ts
@@ -134,7 +134,11 @@ class AgentServerGitService {
// up. `ref: "HEAD"` would go blank after every `git commit` — and the
// cloud-proxy branch above already omits `ref`.
const changes = await new RemoteWorkspace(
- getAgentServerClientOptions({ conversationUrl, sessionApiKey }),
+ getAgentServerClientOptions({
+ conversationId,
+ conversationUrl,
+ sessionApiKey,
+ }),
).gitChanges(path);
if (!Array.isArray(changes)) {
@@ -257,7 +261,11 @@ class AgentServerGitService {
// No `ref` for the same reason as getGitChanges: the base must match
// the one the change list was computed against.
const diff = (await new RemoteWorkspace(
- getAgentServerClientOptions({ conversationUrl, sessionApiKey }),
+ getAgentServerClientOptions({
+ conversationId,
+ conversationUrl,
+ sessionApiKey,
+ }),
).gitDiff(path)) as GitChangeDiff & { diff?: string };
return {
diff --git a/src/api/git-service/git-service.api.ts b/src/api/git-service/git-service.api.ts
index 8208d0f7ee..f6363e1049 100644
--- a/src/api/git-service/git-service.api.ts
+++ b/src/api/git-service/git-service.api.ts
@@ -147,7 +147,7 @@ class GitService {
conversationId,
);
const changes = await new RemoteWorkspace(
- getAgentServerClientOptions({ workingDir }),
+ getAgentServerClientOptions({ workingDir, conversationId }),
).gitChanges(workingDir);
return changes.map((change) => ({
@@ -161,11 +161,11 @@ class GitService {
}
static async getGitChangeDiff(
- _conversationId: string,
+ conversationId: string,
path: string,
): Promise<GitChangeDiff> {
const diff = await new RemoteWorkspace(
- getAgentServerClientOptions(),
+ getAgentServerClientOptions({ conversationId }),
).gitDiff(path);
return {
diff --git a/src/api/runtime-service/agent-server-runtime-service.ts b/src/api/runtime-service/agent-server-runtime-service.ts
index a4a77c476a..e3341a6cfe 100644
--- a/src/api/runtime-service/agent-server-runtime-service.ts
+++ b/src/api/runtime-service/agent-server-runtime-service.ts
@@ -27,6 +27,7 @@ class AgentServerRuntimeService {
command: string,
cwd?: string,
timeout = 30,
+ conversationId?: string,
): Promise<CommandResult> {
const active = getActiveBackend().backend;
@@ -47,7 +48,11 @@ class AgentServerRuntimeService {
// anyway, but passing a ms-mismatched default is a latent footgun if any
// method on the client ever lacks a per-request timeout.
const result = await new RemoteWorkspace(
- getAgentServerClientOptions({ conversationUrl, sessionApiKey }),
+ getAgentServerClientOptions({
+ conversationUrl,
+ sessionApiKey,
+ conversationId,
+ }),
).executeCommand(command, cwd, timeout);
// The SDK already coerces these (`exit_code ?? 0`, `stdout || ''`,
// `stderr || ''`); keep a defensive fallback so a contract drift in the
diff --git a/src/components/features/conversation-panel/local-new-conversation-menu.tsx b/src/components/features/conversation-panel/local-new-conversation-menu.tsx
index 64f6e32eb9..5f309b35d8 100644
--- a/src/components/features/conversation-panel/local-new-conversation-menu.tsx
+++ b/src/components/features/conversation-panel/local-new-conversation-menu.tsx
@@ -1,3 +1,4 @@
+import { useConversationWorkspace } from "#/hooks/query/use-conversation-workspace";
import React from "react";
import { useTranslation } from "react-i18next";
@@ -82,10 +83,11 @@ export function LocalNewConversationMenu({
const { mutate: addWorkspaceParents } = useAddWorkspaceParents();
const { mutate: removeWorkspaceParent } = useRemoveWorkspaceParent();
const { workspaces } = useResolvedWorkspaces();
- const workspacesUnsupportedMessage = getWorkspacesUnsupportedMessage(
- workspacesError,
- t,
- );
+ const { isolated, unsupportedMessage: runtimeWorkspaceMessage } =
+ useConversationWorkspace();
+ const workspacesUnsupportedMessage =
+ runtimeWorkspaceMessage ??
+ getWorkspacesUnsupportedMessage(workspacesError, t);
const [browserOpen, setBrowserOpen] = React.useState(false);
const [manageOpen, setManageOpen] = React.useState(false);
@@ -119,7 +121,7 @@ export function LocalNewConversationMenu({
}, [open, browserOpen, manageOpen]);
const launch = (workingDir?: string) => {
- if (isCreating) return;
+ if (isCreating || (workingDir && workspaceActionsDisabled)) return;
createConversation(
{ workingDir, entryPoint: "sidebar_local_menu" },
{
@@ -208,6 +210,14 @@ export function LocalNewConversationMenu({
)}
style={fixedStyle}
>
+ {workspacesUnsupportedMessage && (
+ <p
+ role="status"
+ className="px-3 py-2 text-xs text-[var(--oh-text-secondary)]"
+ >
+ {workspacesUnsupportedMessage}
+ </p>
+ )}
<ul
className={cn(
"max-h-[40vh] overflow-y-auto sm:max-h-70",
@@ -222,8 +232,12 @@ export function LocalNewConversationMenu({
onClick={() => launch()}
className={itemClass}
>
- <span className="text-muted">
- {t(I18nKey.HOME$NO_WORKSPACE_OPTION)}
+ <span className="text-[var(--oh-muted)]">
+ {t(
+ isolated
+ ? I18nKey.HOME$ISOLATED_WORKSPACE_NEW
+ : I18nKey.HOME$NO_WORKSPACE_OPTION,
+ )}
</span>
</button>
</li>
@@ -231,7 +245,8 @@ export function LocalNewConversationMenu({
<li key={w.id}>
<button
type="button"
- disabled={isCreating}
+ disabled={isCreating || workspaceActionsDisabled}
+ title={workspacesUnsupportedMessage ?? undefined}
data-testid="launch-workspace"
data-workspace-path={w.path}
onClick={() => launch(w.path)}
diff --git a/src/components/features/home/home-chat-launcher.tsx b/src/components/features/home/home-chat-launcher.tsx
index 00a9a97e7a..f84654c1a3 100644
--- a/src/components/features/home/home-chat-launcher.tsx
+++ b/src/components/features/home/home-chat-launcher.tsx
@@ -1,3 +1,4 @@
+import { useConversationWorkspace } from "#/hooks/query/use-conversation-workspace";
import { useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
@@ -73,9 +74,11 @@ export function HomeChatLauncher() {
useConversationStore();
const { handleUpload } = useChatAttachmentUpload();
const { error: workspacesError } = useLocalWorkspaces({ enabled: isLocal });
- const workspacesUnsupportedMessage = isLocal
- ? getWorkspacesUnsupportedMessage(workspacesError, t)
- : null;
+ const { isolated, unsupportedMessage: runtimeWorkspaceMessage } =
+ useConversationWorkspace();
+ const workspacesUnsupportedMessage =
+ runtimeWorkspaceMessage ??
+ (isLocal ? getWorkspacesUnsupportedMessage(workspacesError, t) : null);
const setWorkspaceMode = (mode: WorkspaceMode) => {
setWorkspaceModeState(mode);
@@ -111,7 +114,12 @@ export function HomeChatLauncher() {
query: hasAttachments ? undefined : trimmed || undefined,
entryPoint: "home_chat_launcher",
};
- if (isLocal && pendingWorkspace) {
+ // An isolated backend owns its workspace, so a host selection left over
+ // from a non-isolated session must not be forwarded: the server rejects it
+ // (`HOME$ISOLATED_WORKSPACE_NOTICE`) and the user sees an error toast for a
+ // selection they may not have noticed. Creation proceeds isolated instead;
+ // the launcher still offers an explicit "clear" affordance for the UI.
+ if (isLocal && pendingWorkspace && !isolated) {
variables = {
...variables,
workingDir: pendingWorkspace.path,
@@ -246,6 +254,22 @@ export function HomeChatLauncher() {
/>
</div>
+ {isolated && (
+ <p role="status" className="text-xs text-[var(--oh-text-secondary)]">
+ {pendingWorkspace
+ ? runtimeWorkspaceMessage
+ : t(I18nKey.HOME$ISOLATED_WORKSPACE_NEW)}
+ {pendingWorkspace && (
+ <button
+ type="button"
+ className="ml-2 underline"
+ onClick={() => setPendingWorkspace(null)}
+ >
+ {t(I18nKey.HOME$CLEAR_HOST_WORKSPACE)}
+ </button>
+ )}
+ </p>
+ )}
<div className="flex items-center justify-start gap-2">
{hasSelection ? (
<HomeGitControlBarPreview
diff --git a/src/components/features/home/workspace-selection-form.tsx b/src/components/features/home/workspace-selection-form.tsx
index 5cdf6df0f1..860b60c1f3 100644
--- a/src/components/features/home/workspace-selection-form.tsx
+++ b/src/components/features/home/workspace-selection-form.tsx
@@ -1,3 +1,4 @@
+import { useConversationWorkspace } from "#/hooks/query/use-conversation-workspace";
import React from "react";
import { useTranslation } from "react-i18next";
@@ -84,10 +85,14 @@ export function WorkspaceSelectionForm({
isError: hasWorkspaceError,
error: resolvedWorkspacesError,
} = useResolvedWorkspaces();
- const workspacesUnsupportedMessage = getWorkspacesUnsupportedMessage(
- workspacesError ?? resolvedWorkspacesError,
- t,
- );
+ const { unsupportedMessage: runtimeWorkspaceMessage } =
+ useConversationWorkspace();
+ const workspacesUnsupportedMessage =
+ runtimeWorkspaceMessage ??
+ getWorkspacesUnsupportedMessage(
+ workspacesError ?? resolvedWorkspacesError,
+ t,
+ );
const [selectedWorkspace, setSelectedWorkspace] =
React.useState<LocalWorkspace | null>(null);
const [isBrowserOpen, setIsBrowserOpen] = React.useState(false);
@@ -155,7 +160,7 @@ export function WorkspaceSelectionForm({
(isLoadingWorkspaces && workspaces.length === 0);
const handleLaunch = () => {
- if (!selectedWorkspace) return;
+ if (!selectedWorkspace || workspacesUnsupportedMessage) return;
if (onConfirm) {
onConfirm(selectedWorkspace);
return;
@@ -218,6 +223,7 @@ export function WorkspaceSelectionForm({
variant="primary"
type="button"
isDisabled={
+ Boolean(workspacesUnsupportedMessage) ||
!selectedWorkspace ||
(!onConfirm && isCreatingConversation) ||
isLoadingSettings
diff --git a/src/hooks/query/use-conversation-workspace.ts b/src/hooks/query/use-conversation-workspace.ts
new file mode 100644
index 0000000000..8e0718a6e5
--- /dev/null
+++ b/src/hooks/query/use-conversation-workspace.ts
@@ -0,0 +1,34 @@
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { useQuery } from "@tanstack/react-query";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import {
+ getConversationServerInfo,
+ usesIsolatedWorkspace,
+} from "#/api/conversation-workspace";
+
+export function useConversationWorkspace() {
+ const { t } = useTranslation();
+ const { backend } = useActiveBackend();
+ const query = useQuery({
+ queryKey: [
+ "conversation-workspace",
+ backend.id,
+ backend.host,
+ backend.connectionRevision,
+ ],
+ queryFn: () => getConversationServerInfo(),
+ enabled: backend.kind === "local" && !!backend.host,
+ staleTime: 60_000,
+ retry: false,
+ meta: { disableToast: true },
+ });
+ const isolated =
+ backend.kind === "local" && usesIsolatedWorkspace(query.data);
+ return {
+ isolated,
+ unsupportedMessage: isolated
+ ? t(I18nKey.HOME$ISOLATED_WORKSPACE_NOTICE)
+ : null,
+ };
+}
diff --git a/src/hooks/query/use-has-git-commits.ts b/src/hooks/query/use-has-git-commits.ts
index 0400369a89..9bd45ffa66 100644
--- a/src/hooks/query/use-has-git-commits.ts
+++ b/src/hooks/query/use-has-git-commits.ts
@@ -69,6 +69,7 @@ export function useHasGitCommits(options?: { enabled?: boolean }): {
"git rev-parse --verify HEAD",
workingDir,
10,
+ conversationId,
);
return result.exit_code === 0;
},
diff --git a/src/hooks/query/use-local-git-info.ts b/src/hooks/query/use-local-git-info.ts
index 6e87e4673f..03d311e726 100644
--- a/src/hooks/query/use-local-git-info.ts
+++ b/src/hooks/query/use-local-git-info.ts
@@ -116,13 +116,12 @@ export const useLocalGitInfo = () => {
!hasConversationProvider ||
!hasConversationBranch);
- // Persistent WebSocket connection to the bash-events endpoint. The
- // connection is opened when the query is enabled and closed on unmount or
- // when the conversation changes.
+ // The SDK owns command transport and scopes each probe to its conversation.
const runCommand = useBashCommandRunner(
conversationUrl,
sessionApiKey,
queryEnabled,
+ conversationId,
);
// Keep a ref so queryFn can call the latest runner without capturing it
@@ -153,8 +152,7 @@ export const useLocalGitInfo = () => {
// Re-probe the workspace every 10s so the UI reflects branch/repo
// changes (e.g. `git checkout`, adding a remote) without requiring a
// manual refresh when there is no `selected_repository` recorded on
- // the conversation. Commands now run over the persistent WebSocket
- // connection rather than individual REST calls.
+ // the conversation.
staleTime: 10_000,
refetchInterval: 10_000,
gcTime: 1000 * 60 * 5,
diff --git a/src/hooks/query/use-workspace-file-content.ts b/src/hooks/query/use-workspace-file-content.ts
index 9a0a3d7ccd..c8a5809b35 100644
--- a/src/hooks/query/use-workspace-file-content.ts
+++ b/src/hooks/query/use-workspace-file-content.ts
@@ -141,7 +141,7 @@ function arrayBufferToBase64(buffer: ArrayBuffer): string {
*/
export function useWorkspaceFileContent(relativePath: string | null) {
const { data: conversation } = useActiveConversation();
- const runtimeIsReady = useRuntimeIsReady();
+ 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.
diff --git a/src/hooks/query/use-workspace-files.ts b/src/hooks/query/use-workspace-files.ts
index d43b05cc53..c539b6e791 100644
--- a/src/hooks/query/use-workspace-files.ts
+++ b/src/hooks/query/use-workspace-files.ts
@@ -64,7 +64,7 @@ function normalizePath(path: string): string {
*/
function useLocalWorkspaceFiles(enabled: boolean): WorkspaceFilesResult {
const { data: conversation } = useActiveConversation();
- const runtimeIsReady = useRuntimeIsReady();
+ const runtimeIsReady = useRuntimeIsReady({ allowAgentError: true });
const conversationId = conversation?.id;
const conversationUrl = conversation?.conversation_url;
@@ -86,6 +86,7 @@ function useLocalWorkspaceFiles(enabled: boolean): WorkspaceFilesResult {
buildListCommand(),
workingDir,
30,
+ conversationId,
);
if (result.exit_code !== 0) {
@@ -133,7 +134,7 @@ function useCloudWorkspaceFiles(enabled: boolean): WorkspaceFilesResult {
// disabled — and never fire — whenever that data is null or still loading.
const { conversationId } = useOptionalConversationId();
const { data: conversation } = useActiveConversation();
- const runtimeIsReady = useRuntimeIsReady();
+ const runtimeIsReady = useRuntimeIsReady({ allowAgentError: true });
const selectedRepository = conversation?.selected_repository;
const workingDir = conversation?.workspace?.working_dir?.trim();
diff --git a/src/hooks/query/use-workspace-session.ts b/src/hooks/query/use-workspace-session.ts
index fd5be818a8..1ef614be77 100644
--- a/src/hooks/query/use-workspace-session.ts
+++ b/src/hooks/query/use-workspace-session.ts
@@ -50,7 +50,7 @@ export function useWorkspaceSession(): {
error: Error | null;
} {
const { data: conversation } = useActiveConversation();
- const runtimeIsReady = useRuntimeIsReady();
+ const runtimeIsReady = useRuntimeIsReady({ allowAgentError: true });
const conversationId = conversation?.id;
const conversationUrl = conversation?.conversation_url;
diff --git a/src/hooks/use-bash-command-runner.ts b/src/hooks/use-bash-command-runner.ts
index f4df6b5093..645407889c 100644
--- a/src/hooks/use-bash-command-runner.ts
+++ b/src/hooks/use-bash-command-runner.ts
@@ -1,32 +1,7 @@
-import { useCallback, useEffect, useRef } from "react";
-import type {
- BashCommand,
- BashError,
- BashEvent,
- BashOutput,
-} from "@openhands/typescript-client";
+import { useCallback } from "react";
+import { BashClient } from "@openhands/typescript-client/clients";
import type { CommandResult } from "#/api/runtime-service/agent-server-runtime-service";
-import { sendWebSocketAuth } from "#/utils/websocket-auth";
-import { startHandshakeWatchdog } from "#/utils/websocket-handshake";
-import { buildBashWebSocketUrl } from "#/utils/websocket-url";
-
-interface WaitingCommand {
- command: string;
- cwd: string;
- timeout: number;
- resolve: (result: CommandResult) => void;
- reject: (error: Error) => void;
-}
-
-interface PendingCommand {
- resolve: (result: CommandResult) => void;
- reject: (error: Error) => void;
-}
-
-interface ActiveCommand extends PendingCommand {
- stdout: string[];
- stderr: string[];
-}
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
export type BashCommandRunner = (
command: string,
@@ -34,173 +9,34 @@ export type BashCommandRunner = (
timeout: number,
) => Promise<CommandResult>;
-function isBashCommand(event: BashEvent): event is BashCommand {
- return event.kind === "BashCommand";
-}
-
-function isBashOutput(event: BashEvent): event is BashOutput {
- return event.kind === "BashOutput";
-}
-
-function isBashError(event: BashEvent): event is BashError {
- return event.kind === "BashError";
-}
-
-/**
- * Maintains a persistent WebSocket connection to the agent-server's
- * `/sockets/bash-events` endpoint and exposes a `runCommand` function that
- * executes a bash command and returns a Promise that resolves when the
- * final `BashOutput` (non-null `exit_code`) arrives.
- *
- * Commands are correlated using a FIFO queue: each `BashCommand` echo
- * received from the server is paired with the oldest outstanding request in
- * the queue, and subsequent `BashOutput` events are matched by `command_id`.
- *
- * Commands are buffered until the socket's open handler sends authentication.
- */
+/** Run local Git probes through the SDK's conversation-scoped command API. */
export function useBashCommandRunner(
conversationUrl: string | null | undefined,
sessionApiKey: string | null | undefined,
enabled: boolean,
+ conversationId?: string,
): BashCommandRunner {
- const wsRef = useRef<WebSocket | null>(null);
- const readyWsRef = useRef<WebSocket | null>(null);
- const waitingQueueRef = useRef<WaitingCommand[]>([]);
- // Commands whose request was sent; waiting for the BashCommand echo to get command_id
- const pendingQueueRef = useRef<PendingCommand[]>([]);
- // Commands whose command_id is known; waiting for BashOutput with non-null exit_code
- const activeCommandsRef = useRef<Map<string, ActiveCommand>>(new Map());
-
- useEffect(() => {
- if (!enabled) return;
-
- const wsUrl = buildBashWebSocketUrl(conversationUrl);
- const ws = new WebSocket(wsUrl);
- wsRef.current = ws;
- readyWsRef.current = null;
-
- // Abort a handshake stuck in CONNECTING — a hung bash-events handshake
- // would also block the conversation's events socket (the one the chat
- // needs) until it settles.
- const cancelHandshakeWatchdog = startHandshakeWatchdog(ws);
-
- ws.onopen = () => {
- cancelHandshakeWatchdog();
- sendWebSocketAuth(ws, sessionApiKey);
- readyWsRef.current = ws;
- for (const {
- command,
- cwd,
- timeout,
- resolve,
- reject,
- } of waitingQueueRef.current) {
- pendingQueueRef.current.push({ resolve, reject });
- ws.send(JSON.stringify({ command, cwd, timeout }));
- }
- waitingQueueRef.current = [];
- };
-
- ws.onmessage = (event: MessageEvent) => {
- let data: BashEvent;
+ return useCallback(
+ async (command: string, cwd: string, timeout: number) => {
+ if (!enabled) throw new Error("Bash command runner is disabled");
+ const client = new BashClient(
+ getAgentServerClientOptions({
+ conversationUrl,
+ sessionApiKey,
+ conversationId,
+ }),
+ );
try {
- data = JSON.parse(event.data as string) as BashEvent;
- } catch {
- return; // ignore malformed frames
- }
-
- if (isBashCommand(data)) {
- // Associate the next pending request with the server-assigned command_id
- const pending = pendingQueueRef.current.shift();
- if (pending) {
- activeCommandsRef.current.set(data.id, {
- ...pending,
- stdout: [],
- stderr: [],
- });
- }
- } else if (isBashOutput(data) && data.command_id) {
- const active = activeCommandsRef.current.get(data.command_id);
- if (active) {
- if (data.stdout) active.stdout.push(data.stdout);
- if (data.stderr) active.stderr.push(data.stderr);
- if (data.exit_code != null) {
- activeCommandsRef.current.delete(data.command_id);
- active.resolve({
- exit_code: data.exit_code,
- stdout: active.stdout.join(""),
- stderr: active.stderr.join(""),
- });
- }
- }
- } else if (isBashError(data)) {
- rejectAll(`Bash error: ${data.code}: ${data.detail}`);
+ const output = await client.executeCommand({ command, cwd, timeout });
+ return {
+ exit_code: output.exit_code ?? -1,
+ stdout: output.stdout ?? "",
+ stderr: output.stderr ?? "",
+ };
+ } finally {
+ client.close();
}
- };
-
- function rejectAll(reason: string): void {
- const err = new Error(reason);
- for (const { reject: rej } of waitingQueueRef.current) rej(err);
- waitingQueueRef.current = [];
- for (const p of pendingQueueRef.current) p.reject(err);
- pendingQueueRef.current = [];
- for (const a of activeCommandsRef.current.values()) a.reject(err);
- activeCommandsRef.current.clear();
- }
-
- ws.onclose = () => {
- cancelHandshakeWatchdog();
- wsRef.current = null;
- readyWsRef.current = null;
- rejectAll("Bash WebSocket closed");
- };
-
- ws.onerror = () => {
- wsRef.current = null;
- readyWsRef.current = null;
- rejectAll("Bash WebSocket error");
- };
-
- return () => {
- // The close handler is nulled below, so cancel the watchdog here.
- cancelHandshakeWatchdog();
- // Prevent the close/error handlers from double-rejecting after unmount
- ws.onclose = null;
- ws.onerror = null;
- ws.close();
- wsRef.current = null;
- readyWsRef.current = null;
- rejectAll("Bash WebSocket unmounted");
- };
- }, [enabled, conversationUrl, sessionApiKey]);
-
- const runCommand: BashCommandRunner = useCallback(
- (command: string, cwd: string, timeout: number) =>
- new Promise<CommandResult>((resolve, reject) => {
- const ws = wsRef.current;
- if (
- !ws ||
- ws.readyState === WebSocket.CLOSED ||
- ws.readyState === WebSocket.CLOSING
- ) {
- reject(new Error("Bash WebSocket not available"));
- return;
- }
- if (ws.readyState !== WebSocket.OPEN || readyWsRef.current !== ws) {
- waitingQueueRef.current.push({
- command,
- cwd,
- timeout,
- resolve,
- reject,
- });
- } else {
- pendingQueueRef.current.push({ resolve, reject });
- ws.send(JSON.stringify({ command, cwd, timeout }));
- }
- }),
- [],
+ },
+ [enabled, conversationUrl, sessionApiKey, conversationId],
);
-
- return runCommand;
}
diff --git a/src/hooks/use-runtime-is-ready.ts b/src/hooks/use-runtime-is-ready.ts
index d6bfbde658..f8a0f062c8 100644
--- a/src/hooks/use-runtime-is-ready.ts
+++ b/src/hooks/use-runtime-is-ready.ts
@@ -4,7 +4,7 @@ import {
RUNTIME_STARTING_STATES,
} from "#/types/agent-state";
import { useActiveConversation } from "./query/use-active-conversation";
-import { isExecutionActive } from "#/utils/status";
+import { isExecutionActive, isExecutionErrored } from "#/utils/status";
interface UseRuntimeIsReadyOptions {
allowAgentError?: boolean;
@@ -20,7 +20,9 @@ export const useRuntimeIsReady = ({
: RUNTIME_INACTIVE_STATES;
return (
- isExecutionActive(conversation?.execution_status) &&
+ (isExecutionActive(conversation?.execution_status) ||
+ (allowAgentError &&
+ isExecutionErrored(conversation?.execution_status))) &&
!inactiveStates.includes(curAgentState)
);
};
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 9ad333c8cb..fa4cf54571 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -1,4 +1,38 @@
{
+ "HOME$ISOLATED_WORKSPACE_NEW": {
+ "en": "New isolated workspace",
+ "ja": "新しい分離ワークスペース",
+ "zh-CN": "新建隔离工作区",
+ "zh-TW": "建立隔離工作區",
+ "ko-KR": "새 격리 작업 공간",
+ "no": "Nytt isolert arbeidsområde",
+ "ar": "مساحة عمل معزولة جديدة",
+ "de": "Neuer isolierter Arbeitsbereich",
+ "fr": "Nouvel espace de travail isolé",
+ "it": "Nuovo spazio di lavoro isolato",
+ "pt": "Novo espaço de trabalho isolado",
+ "es": "Nuevo espacio de trabajo aislado",
+ "ca": "Nou espai de treball aïllat",
+ "tr": "Yeni yalıtılmış çalışma alanı",
+ "uk": "Новий ізольований робочий простір"
+ },
+ "HOME$CLEAR_HOST_WORKSPACE": {
+ "en": "Clear host project selection",
+ "ja": "ホストプロジェクトの選択を解除",
+ "zh-CN": "清除主机项目选择",
+ "zh-TW": "清除主機專案選擇",
+ "ko-KR": "호스트 프로젝트 선택 지우기",
+ "no": "Fjern valgt vertsprosjekt",
+ "ar": "مسح اختيار مشروع المضيف",
+ "de": "Host-Projektauswahl aufheben",
+ "fr": "Effacer la sélection du projet hôte",
+ "it": "Cancella la selezione del progetto host",
+ "pt": "Limpar seleção do projeto do host",
+ "es": "Borrar la selección del proyecto del host",
+ "ca": "Esborra la selecció del projecte de l’amfitrió",
+ "tr": "Ana makine proje seçimini temizle",
+ "uk": "Скасувати вибір проєкту хоста"
+ },
"AUTOMATIONS$UNAVAILABLE_AGENT_PROFILE": {
"en": "Unavailable profile ({{id}})",
"ja": "利用できないプロファイル ({{id}})",
@@ -43043,6 +43077,23 @@
"zh-CN": "原始尺寸图片预览",
"zh-TW": "原始尺寸圖片預覽"
},
+ "HOME$ISOLATED_WORKSPACE_NOTICE": {
+ "en": "This backend uses isolated workspaces. Host folders and projects cannot be attached.",
+ "ja": "このバックエンドは分離ワークスペースを使用します。ホストのフォルダーやプロジェクトは接続できません。",
+ "zh-CN": "此后端使用隔离工作区,无法附加主机文件夹或项目。",
+ "zh-TW": "此後端使用隔離工作區,無法附加主機資料夾或專案。",
+ "ko-KR": "이 백엔드는 격리된 작업 공간을 사용합니다. 호스트 폴더와 프로젝트를 연결할 수 없습니다.",
+ "no": "Denne backend-en bruker isolerte arbeidsområder. Mapper og prosjekter på verten kan ikke kobles til.",
+ "ar": "تستخدم هذه الخلفية مساحات عمل معزولة. لا يمكن إرفاق مجلدات المضيف ومشاريعه.",
+ "de": "Dieses Backend verwendet isolierte Arbeitsbereiche. Host-Ordner und -Projekte können nicht angehängt werden.",
+ "fr": "Ce backend utilise des espaces de travail isolés. Les dossiers et projets de l’hôte ne peuvent pas être joints.",
+ "it": "Questo backend usa spazi di lavoro isolati. Non è possibile collegare cartelle e progetti dell’host.",
+ "pt": "Este backend usa espaços de trabalho isolados. Não é possível anexar pastas e projetos do host.",
+ "es": "Este backend usa espacios de trabajo aislados. No se pueden adjuntar carpetas ni proyectos del host.",
+ "ca": "Aquest backend utilitza espais de treball aïllats. No s’hi poden adjuntar carpetes ni projectes de l’amfitrió.",
+ "tr": "Bu arka uç yalıtılmış çalışma alanları kullanır. Ana makine klasörleri ve projeleri eklenemez.",
+ "uk": "Цей сервер використовує ізольовані робочі простори. Папки та проєкти хоста підключити неможливо."
+ },
"SETTINGS$AGENT_PROFILE_SECRETS": {
"en": "Secrets",
"ja": "シークレット",
@@ -43212,5 +43263,73 @@
"ca": "No hi ha espais de treball accessibles. Demana a l’administrador que comprovi els teus permisos.",
"tr": "Erişilebilir çalışma alanı yok. Yöneticinizden erişim izinlerinizi kontrol etmesini isteyin.",
"uk": "Немає доступних робочих просторів. Попросіть адміністратора перевірити ваші права доступу."
+ },
+ "HOME$LETS_START_BUILDING": {
+ "en": "Let's Start Building!",
+ "ja": "開発を始めましょう!",
+ "zh-CN": "让我们开始开发!",
+ "zh-TW": "讓我們開始開發!",
+ "ko-KR": "개발을 시작합시다!",
+ "no": "La oss begynne å bygge!",
+ "it": "Iniziamo a costruire!",
+ "pt": "Vamos começar a construir!",
+ "es": "¡Comencemos a construir!",
+ "ar": "لنبدأ البناء!",
+ "fr": "Commençons à construire !",
+ "tr": "Hadi İnşa Etmeye Başlayalım!",
+ "de": "Lass uns anfangen zu bauen!",
+ "uk": "Почнімо будувати!",
+ "ca": "Comencem a construir!"
+ },
+ "AUTOMATIONS$GIT_SYNC$ENABLE_BLOCKED_ERROR": {
+ "en": "Git Sync must be enabled in the automation backend's environment, and the service restarted, before it can be turned on here.",
+ "ja": "Git 同期を有効にするには、オートメーションバックエンドの環境で有効化し、サービスを再起動する必要があります。",
+ "zh-CN": "必须先在自动化后端的环境中启用 Git 同步并重启服务,才能在此处开启。",
+ "zh-TW": "必須先在自動化後端的環境中啟用 Git 同步並重新啟動服務,才能在此處開啟。",
+ "ko-KR": "여기서 켜려면 먼저 자동화 백엔드 환경에서 Git 동기화를 활성화하고 서비스를 다시 시작해야 합니다.",
+ "no": "Git-synkronisering må aktiveres i automatiserings-backendens miljø, og tjenesten må startes på nytt, før den kan slås på her.",
+ "ar": "يجب تفعيل مزامنة Git في بيئة الخدمة الخلفية للأتمتة وإعادة تشغيل الخدمة قبل تفعيلها هنا.",
+ "de": "Die Git-Synchronisierung muss in der Umgebung des Automatisierungs-Backends aktiviert und der Dienst neu gestartet werden, bevor sie hier eingeschaltet werden kann.",
+ "fr": "La synchronisation Git doit être activée dans l'environnement du backend d'automatisation et le service redémarré avant de pouvoir l'activer ici.",
+ "it": "La sincronizzazione Git deve essere abilitata nell'ambiente del backend di automazione e il servizio riavviato prima di poterla attivare qui.",
+ "pt": "A sincronização do Git precisa ser ativada no ambiente do backend de automação, e o serviço reiniciado, antes de poder ser ligada aqui.",
+ "es": "La sincronización de Git debe habilitarse en el entorno del backend de automatización y reiniciar el servicio antes de poder activarla aquí.",
+ "ca": "La sincronització de Git s'ha d'habilitar a l'entorn del backend d'automatització i cal reiniciar el servei abans de poder activar-la aquí.",
+ "tr": "Git eşitlemesi burada açılabilmesi için önce otomasyon arka ucunun ortamında etkinleştirilmeli ve hizmet yeniden başlatılmalıdır.",
+ "uk": "Щоб увімкнути синхронізацію Git тут, її потрібно спершу активувати в середовищі бекенда автоматизації та перезапустити службу."
+ },
+ "AUTOMATIONS$GIT_SYNC$NOT_LOCAL_TITLE": {
+ "en": "Git Sync isn't available",
+ "ja": "Git同期は利用できません",
+ "zh-CN": "Git 同步不可用",
+ "zh-TW": "Git 同步無法使用",
+ "ko-KR": "Git 동기화를 사용할 수 없습니다",
+ "no": "Git-synkronisering er ikke tilgjengelig",
+ "ar": "مزامنة Git غير متاحة",
+ "de": "Git-Synchronisierung ist nicht verfügbar",
+ "fr": "La synchronisation Git n'est pas disponible",
+ "it": "La sincronizzazione Git non è disponibile",
+ "pt": "A sincronização Git não está disponível",
+ "es": "La sincronización de Git no está disponible",
+ "ca": "La sincronització de Git no està disponible",
+ "tr": "Git Senkronizasyonu kullanılamıyor",
+ "uk": "Git-синхронізація недоступна"
+ },
+ "AUTOMATIONS$GIT_SYNC$NOT_LOCAL_MESSAGE": {
+ "en": "Git Sync is only available when connected to a local OpenHands backend.",
+ "ja": "Git同期はローカルのOpenHandsバックエンドに接続している場合のみ利用できます。",
+ "zh-CN": "只有连接到本地 OpenHands 后端时才能使用 Git 同步。",
+ "zh-TW": "只有連線到本機 OpenHands 後端時才能使用 Git 同步。",
+ "ko-KR": "Git 동기화는 로컬 OpenHands 백엔드에 연결된 경우에만 사용할 수 있습니다.",
+ "no": "Git-synkronisering er kun tilgjengelig når du er koblet til en lokal OpenHands-backend.",
+ "ar": "تتوفر مزامنة Git فقط عند الاتصال بخلفية OpenHands محلية.",
+ "de": "Git-Synchronisierung ist nur verfügbar, wenn eine Verbindung zu einem lokalen OpenHands-Backend besteht.",
+ "fr": "La synchronisation Git n'est disponible que lorsque vous êtes connecté à un backend OpenHands local.",
+ "it": "La sincronizzazione Git è disponibile solo quando sei connesso a un backend OpenHands locale.",
+ "pt": "A sincronização Git só está disponível quando conectado a um backend OpenHands local.",
+ "es": "La sincronización de Git solo está disponible al conectarse a un backend local de OpenHands.",
+ "ca": "La sincronització de Git només està disponible en connectar-se a un backend local d'OpenHands.",
+ "tr": "Git Senkronizasyonu yalnızca yerel bir OpenHands arka ucuna bağlıyken kullanılabilir.",
+ "uk": "Git-синхронізація доступна лише при підключенні до локального бекенду OpenHands."
}
}
diff --git a/src/utils/websocket-url.ts b/src/utils/websocket-url.ts
index 2f060900c6..6abd9cd581 100644
--- a/src/utils/websocket-url.ts
+++ b/src/utils/websocket-url.ts
@@ -78,28 +78,6 @@ function getConversationUrlProtocol(
}
}
-/**
- * Builds the WebSocket URL for the agent-server's bash-events endpoint.
- * The URL is derived from the same host and path prefix as the conversation
- * events socket so it works in both direct-connect and reverse-proxy deployments.
- *
- * @param conversationUrl The conversation URL containing host/port
- * @returns WebSocket URL for the bash-events endpoint
- */
-export function buildBashWebSocketUrl(
- conversationUrl: string | null | undefined,
-): string {
- const baseHost = extractBaseHost(conversationUrl);
- const pathPrefix = extractPathPrefix(conversationUrl);
-
- const pageIsSecure = window.location.protocol === "https:";
- const targetIsSecure =
- getConversationUrlProtocol(conversationUrl) === "https:";
- const protocol = pageIsSecure || targetIsSecure ? "wss:" : "ws:";
-
- return `${protocol}//${baseHost}${pathPrefix}/sockets/bash-events`;
-}
-
/**
* Builds the WebSocket URL for V1 conversations (without query params)
* @param conversationId The conversation ID