🙌 OpenHands: AI-Driven Development
refactor(canvas): remove bundled VSCode consumer assumptions (#17660)
Graham Neubigdca588a95c9a
diff --git a/.env.sample b/.env.sampleindex 1d67deead8..d0a9640b50 100644--- a/.env.sample+++ b/.env.sample@@ -28,7 +28,8 @@ VITE_MOCK_API="false" # Enable/disable API mocking with MSW# `npm run dev` (scripts/dev-safe.mjs) — isolated local backend via uvx# OH_CANVAS_SAFE_BACKEND_PORT="18000" # Port the spawned agent-server listens on-# OH_CANVAS_SAFE_VSCODE_PORT="18001" # Port forwarded to the embedded VS Code (defaults to backend port + 1)+# OH_CANVAS_ENABLE_VSCODE="false" # Legacy bundled editor is disabled by default; prefer the VS Code Canvas App+# OH_CANVAS_SAFE_VSCODE_PORT="18001" # Legacy editor port, used only when OH_CANVAS_ENABLE_VSCODE=true# OH_CANVAS_SAFE_STATE_DIR="$HOME/.openhands/agent-canvas" # Where conversations and bash events are stored (tmux sockets live under /tmp)# Agent server version selection (uvx) — listed in order of precedence (highest first)diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.tsindex 4444437c49..59a9638bda 100644--- a/__tests__/api/agent-server-conversation-service.test.ts+++ b/__tests__/api/agent-server-conversation-service.test.ts@@ -3,7 +3,6 @@ import {FileClient,ProfilesClient,SettingsClient,- VSCodeClient,} from "@openhands/typescript-client/clients";import { http, HttpResponse } from "msw";import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";@@ -41,8 +40,6 @@ const {mockForkConversation,mockGetEvent,mockSwitchAcpModel,- mockVSCodeGetUrl,- mockVSCodeGetStatus,mockGetSettings,mockGetSettingsForConversation,mockGetProfile,@@ -64,8 +61,6 @@ const {mockForkConversation: vi.fn(),mockGetEvent: vi.fn(),mockSwitchAcpModel: vi.fn(),- mockVSCodeGetUrl: vi.fn(),- mockVSCodeGetStatus: vi.fn(),mockGetSettings: vi.fn(),mockGetSettingsForConversation: vi.fn(),mockGetProfile: vi.fn(),@@ -95,9 +90,6 @@ vi.mock("@openhands/typescript-client/clients", async () => {SettingsClient: vi.fn(function SettingsClientMock() {return mockSettingsClient();}),- VSCodeClient: vi.fn(function VSCodeClientMock() {- return { getUrl: mockVSCodeGetUrl, getStatus: mockVSCodeGetStatus };- }),};});@@ -229,13 +221,10 @@ describe("AgentServerConversationService", () => {mockForkConversation.mockReset();mockGetEvent.mockReset();mockSwitchAcpModel.mockReset();- mockVSCodeGetUrl.mockReset();- mockVSCodeGetStatus.mockReset();vi.mocked(ConversationClient).mockClear();vi.mocked(FileClient).mockClear();vi.mocked(ProfilesClient).mockClear();vi.mocked(SettingsClient).mockClear();- vi.mocked(VSCodeClient).mockClear();mockConversationClient.mockReturnValue({createConversation: async (payload: unknown) => {@@ -318,23 +307,6 @@ describe("AgentServerConversationService", () => {).rejects.toThrow("gone");});- it("preserves disabled editor capability and explicit runtime credentials", async () => {- const status = { enabled: false, running: false };- mockVSCodeGetStatus.mockResolvedValue(status);- await expect(- AgentServerConversationService.getVSCodeStatus(- "https://runtime.example.test/api/conversations/conv-1",- "session-key",- ),- ).resolves.toEqual(status);- expect(VSCodeClient).toHaveBeenCalledWith(- expect.objectContaining({- host: "https://runtime.example.test",- apiKey: "session-key",- }),- );- });-it("renames Cloud conversations through the Cloud resource", async () => {setRegisteredBackends([cloudBackend]);setActiveSelection({ backendId: cloudBackend.id });@@ -1593,31 +1565,6 @@ describe("AgentServerConversationService", () => {);});- it("requests a VS Code URL for the conversation workspace", async () => {- mockHttpGet.mockResolvedValue({- data: [- makeDirectConversation({- workspace: { working_dir: "/workspace/repos/canvas" },- }),- ],- });- mockVSCodeGetUrl.mockResolvedValue("http://localhost:3000/vscode");-- const result = await AgentServerConversationService.getVSCodeUrl(- "conv-1",- "http://runtime.internal:9000",- "runtime-key",- );-- expect(mockVSCodeGetUrl).toHaveBeenCalledWith({- baseUrl: window.location.origin,- workspaceDir: "/workspace/repos/canvas",- });- expect(result).toEqual({- vscode_url: "http://localhost:3000/vscode",- });- });-it("uses the configured working directory when a conversation has no workspace", async () => {mockHttpGet.mockResolvedValue({data: [makeDirectConversation({ workspace: null })],@@ -1638,32 +1585,6 @@ describe("AgentServerConversationService", () => {).resolves.toBe("/workspace/project/agent-canvas");});- it("omits the browser origin when requesting a VS Code URL during SSR", async () => {- mockHttpGet.mockResolvedValue({- data: [makeDirectConversation({ workspace: null })],- });- mockVSCodeGetUrl.mockResolvedValue("http://localhost:3000/vscode");- const browserWindow = window;- Object.defineProperty(globalThis, "window", {- configurable: true,- value: undefined,- });-- try {- await AgentServerConversationService.getVSCodeUrl("conv-1", undefined);- } finally {- Object.defineProperty(globalThis, "window", {- configurable: true,- value: browserWindow,- });- }-- expect(mockVSCodeGetUrl).toHaveBeenCalledWith({- baseUrl: undefined,- workspaceDir: "/workspace/project/agent-canvas",- });- });-it("does not contact a backend for an empty conversation batch", async () => {await expect(AgentServerConversationService.batchGetAppConversations([]),@@ -2641,24 +2562,6 @@ describe("AgentServerConversationService", () => {});});- it("constructs the VS Code client with the supplied runtime coordinates", async () => {- mockHttpGet.mockResolvedValue({ data: [makeDirectConversation()] });- mockVSCodeGetUrl.mockResolvedValue("http://localhost:3000/vscode");-- await AgentServerConversationService.getVSCodeUrl(- "conv-1",- "http://runtime.internal:9000/api/conversations/conv-1",- "runtime-key",- );-- expect(VSCodeClient).toHaveBeenCalledWith({- conversationId: "conv-1",- host: "http://runtime.internal:9000",- apiKey: "runtime-key",- workingDir: "/workspace/project/agent-canvas",- });- });-it.each([["session key",diff --git a/__tests__/api/conversation-service.test.ts b/__tests__/api/conversation-service.test.tsindex 25b58002d6..46ad4f1fe0 100644--- a/__tests__/api/conversation-service.test.ts+++ b/__tests__/api/conversation-service.test.ts@@ -4,18 +4,10 @@ import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-wimport ConversationService from "#/api/conversation-service/conversation-service.api";import { clearAgentServerHomeDirCache } from "#/api/agent-server-home";-const { fileUploadMock, getHomeMock, getVSCodeUrlMock, vscodeClientMock } =- vi.hoisted(() => {- const getVSCodeUrlMock = vi.fn();- return {- fileUploadMock: vi.fn(),- getHomeMock: vi.fn(),- getVSCodeUrlMock,- vscodeClientMock: vi.fn(function VSCodeClientMock() {- return { getUrl: getVSCodeUrlMock };- }),- };- });+const { fileUploadMock, getHomeMock } = vi.hoisted(() => ({+ fileUploadMock: vi.fn(),+ getHomeMock: vi.fn(),+}));vi.mock("@openhands/typescript-client/workspace/remote-workspace", () => ({RemoteWorkspace: vi.fn(function RemoteWorkspaceMock() {@@ -27,7 +19,6 @@ vi.mock("@openhands/typescript-client/clients", () => ({FileClient: vi.fn(function FileClientMock() {return { getHome: getHomeMock };}),- VSCodeClient: vscodeClientMock,}));function makeFile(name: string) {@@ -151,28 +142,4 @@ describe("ConversationService", () => {expect(result.skipped_files).toEqual([]);});});-- describe("getVSCodeUrl", () => {- it("targets the current conversation runtime URL and session key", async () => {- ConversationService.setCurrentConversation({- id: "conv-1",- conversation_url:- "https://runtime.example.com/api/conversations/conv-1",- session_api_key: "runtime-session-key",- workspace: { working_dir: "/workspace/project/conv-1" },- } as never);- getVSCodeUrlMock.mockResolvedValue("https://runtime.example.com/vscode");-- await expect(ConversationService.getVSCodeUrl("conv-1")).resolves.toEqual(- { vscode_url: "https://runtime.example.com/vscode" },- );-- expect(vscodeClientMock).toHaveBeenCalledWith(- expect.objectContaining({- host: "https://runtime.example.com",- apiKey: "runtime-session-key",- }),- );- });- });});diff --git a/__tests__/api/mock-conversation-handlers.test.ts b/__tests__/api/mock-conversation-handlers.test.tsindex ce9022951c..1e74d49db1 100644--- a/__tests__/api/mock-conversation-handlers.test.ts+++ b/__tests__/api/mock-conversation-handlers.test.ts@@ -617,7 +617,6 @@ describe("mock conversation handlers", () => {interrupted,run,agentAnswer,- vscode,skills,pendingMessage,] = await Promise.all([@@ -637,7 +636,6 @@ describe("mock conversation handlers", () => {requestJson<{ response: string }>("/api/conversations/1/ask_agent", {method: "POST",}),- requestJson<{ url: string | null }>("/api/vscode/url"),requestJson<{ skills: unknown[] }>("/api/skills", { method: "POST" }),requestJson<{ id: string; position: number }>("/api/v1/conversations/1/pending-messages",@@ -651,7 +649,6 @@ describe("mock conversation handlers", () => {expect(interrupted.body).toEqual({ success: true });expect(run.body).toEqual({ success: true });expect(agentAnswer.body).toEqual({ response: "Mock agent response" });- expect(vscode.body).toEqual({ url: null });expect(skills.body).toEqual({ skills: [] });expect(pendingMessage.body).toEqual({ id: "mock-pending-id", position: 0 });});diff --git a/__tests__/components/features/conversation-panel/conversation-card.test.tsx b/__tests__/components/features/conversation-panel/conversation-card.test.tsxindex f00d9426a8..5f9d1bd4c0 100644--- a/__tests__/components/features/conversation-panel/conversation-card.test.tsx+++ b/__tests__/components/features/conversation-panel/conversation-card.test.tsx@@ -24,7 +24,6 @@ import {import type { Backend } from "#/api/backend-registry/types";import { ActiveBackendProvider } from "#/contexts/active-backend-context";import { useFreeModelsStore } from "#/stores/free-models-store";-import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";// We'll use the actual i18next implementation but override the translation function@@ -54,10 +53,7 @@ vi.mock("react-i18next", async () => {});vi.mock("#/hooks/use-tracking", () => ({- useTracking: () => ({- trackDownloadVsCodeButtonClicked: vi.fn(),- trackDownloadTrajectoryButtonClicked: vi.fn(),- }),+ useTracking: () => ({}),}));describe("ConversationCard", () => {@@ -415,36 +411,6 @@ describe("ConversationCard", () => {expect(onContextMenuToggle).toHaveBeenCalledWith(false);});- it("closes the context menu when downloading the conversation fails", async () => {- const user = userEvent.setup();- const onContextMenuToggle = vi.fn();- vi.spyOn(- AgentServerConversationService,- "downloadConversation",- ).mockRejectedValue(new Error("HTTP request failed (502 Bad Gateway)"));- renderWithProviders(- <ConversationCard- conversationId="conv-1"- onDelete={onDelete}- title="Conversation 1"- selectedRepository={null}- lastUpdatedAt="2021-10-01T12:00:00Z"- contextMenuOpen- onContextMenuToggle={onContextMenuToggle}- />,- );-- await user.click(- within(screen.getByTestId("context-menu")).getByTestId(- "download-trajectory-button",- ),- );-- await vi.waitFor(() =>- expect(onContextMenuToggle).toHaveBeenCalledWith(false),- );- });-test("clicking the selectedRepository should not trigger the onClick handler", async () => {const user = userEvent.setup();renderWithProviders(diff --git a/__tests__/components/features/conversation/conversation-name.test.tsx b/__tests__/components/features/conversation/conversation-name.test.tsxindex e3dd17c1b9..5c288a2ab5 100644--- a/__tests__/components/features/conversation/conversation-name.test.tsx+++ b/__tests__/components/features/conversation/conversation-name.test.tsx@@ -1,4 +1,4 @@-import { screen, within, waitFor } from "@testing-library/react";+import { screen, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import {afterEach,@@ -91,12 +91,10 @@ vi.mock("react-i18next", async () => {BUTTON$EXPORT_CONVERSATION: "Export Conversation",BUTTON$EXPORT_TRANSCRIPT: "Export…",BUTTON$DOWNLOAD_CONVERSATION_DATA: "Download conversation data",- BUTTON$DOWNLOAD_VIA_VSCODE: "Download via VS Code",BUTTON$SHOW_AGENT_TOOLS_AND_METADATA: "Show Agent Tools",CONVERSATION$SHOW_SKILLS: "Show Skills",BUTTON$DISPLAY_COST: "Display Usage and Cost",- COMMON$CLOSE_CONVERSATION_STOP_RUNTIME:- "Stop Conversation (Runtime)",+ COMMON$CLOSE_CONVERSATION_STOP_RUNTIME: "Stop Conversation (Runtime)",COMMON$STOP_CONVERSATION: "Stop Conversation",COMMON$DELETE_CONVERSATION: "Delete Conversation",CONVERSATION$SHARE_PUBLICLY: "Share Publicly",diff --git a/__tests__/components/features/conversation/conversation-tabs.test.tsx b/__tests__/components/features/conversation/conversation-tabs.test.tsxindex c6d7ec6ab5..f4d73f3620 100644--- a/__tests__/components/features/conversation/conversation-tabs.test.tsx+++ b/__tests__/components/features/conversation/conversation-tabs.test.tsx@@ -60,16 +60,6 @@ vi.mock("#/hooks/use-agent-state", () => ({}),}));-vi.mock("#/hooks/query/use-unified-vscode-url", () => ({- useUnifiedVSCodeUrl: () => ({- data: { url: "http://localhost:8001", error: null },- isLoading: false,- refetch: vi- .fn()- .mockResolvedValue({ data: { url: "http://localhost:8001" } }),- }),-}));-const createWrapper = (conversationId: string) =>function ({ children }: { children: React.ReactNode }) {return (@@ -524,98 +514,6 @@ describe("ConversationTabs localStorage behavior", () => {});});- describe("vscode link visibility by backend kind", () => {- beforeEach(() => {- mockConversationId = REAL_CONVERSATION_ID;- });-- it("should show the vscode link when the active backend is local", () => {- // Arrange- seedActiveBackend({- id: "local-test",- name: "Local Test",- host: "http://localhost:8000",- apiKey: "",- kind: "local",- });-- // Act- render(<ConversationTabs />, {- wrapper: createWrapper(REAL_CONVERSATION_ID),- });-- // Assert — self-hosted backends serve VSCode too; the URL comes from- // the agent server's /api/vscode/url via useUnifiedVSCodeUrl's local- // branch, rather than from cloud `exposed_urls`.- expect(screen.getByTestId("drawer-vscode-link")).toBeInTheDocument();- });-- it("should show the vscode link when the active backend is cloud", () => {- // Arrange- seedActiveBackend({- id: "cloud-test",- name: "Cloud Test",- host: "https://app.example.com",- apiKey: "secret",- kind: "cloud",- });-- // Act- render(<ConversationTabs />, {- wrapper: createWrapper(REAL_CONVERSATION_ID),- });-- // Assert- expect(screen.getByTestId("drawer-vscode-link")).toBeInTheDocument();- });-- it("re-measures the tab row when the vscode button's own width changes", () => {- // The button's width is folded into how many tabs fit inline, and its- // presence is now resolved asynchronously (the hook probes- // /api/vscode/status). It sits inside an `ml-auto shrink-0` wrapper, so- // it appearing or disappearing leaves the row's own box unchanged —- // observing only the row would leave the fit computed against a button- // that is no longer on screen, permanently costing an inline tab.- const observed: Element[] = [];- class RecordingResizeObserver {- observe = (el: Element) => {- observed.push(el);- };-- unobserve = vi.fn();-- disconnect = vi.fn();- }- // Swap only this global back afterwards: vi.unstubAllGlobals() would- // also drop the localStorage/ResizeObserver stubs vitest.setup.ts- // installs in beforeAll, breaking every later test in the file.- const originalResizeObserver = globalThis.ResizeObserver;- globalThis.ResizeObserver =- RecordingResizeObserver as unknown as typeof ResizeObserver;-- try {- seedActiveBackend({- id: "local-test",- name: "Local Test",- host: "http://localhost:8000",- apiKey: "",- kind: "local",- });-- render(<ConversationTabs />, {- wrapper: createWrapper(REAL_CONVERSATION_ID),- });-- const vscodeWrapper =- screen.getByTestId("drawer-vscode-link").parentElement;- expect(vscodeWrapper).not.toBeNull();- expect(observed).toContain(vscodeWrapper);- } finally {- globalThis.ResizeObserver = originalResizeObserver;- }- });- });-describe("ellipsis context menu", () => {beforeEach(() => {mockConversationId = REAL_CONVERSATION_ID;diff --git a/__tests__/hooks/mutation/conversation-mutation-utils.test.ts b/__tests__/hooks/mutation/conversation-mutation-utils.test.tsindex a1f4bb40b7..1191161783 100644--- a/__tests__/hooks/mutation/conversation-mutation-utils.test.ts+++ b/__tests__/hooks/mutation/conversation-mutation-utils.test.ts@@ -410,7 +410,6 @@ describe("conversation cache synchronization", () => {[{ queryKey: ["user", "conversation", CONV_ID] }],[{ queryKey: ["user", "conversations"] }],[{ queryKey: ["v1-batch-get-app-conversations"] }],- [{ queryKey: ["unified", "vscode_url"] }],]);});});diff --git a/__tests__/hooks/use-tracking.test.ts b/__tests__/hooks/use-tracking.test.tsindex d2098218fa..b7f03a8c3d 100644--- a/__tests__/hooks/use-tracking.test.ts+++ b/__tests__/hooks/use-tracking.test.ts@@ -340,17 +340,6 @@ describe("useTracking", () => {});});- describe("trackDownloadVsCodeButtonClicked", () => {- it("captures download_via_vscode_button_clicked with commonProperties", () => {- getTracking().trackDownloadVsCodeButtonClicked();-- expect(captureMock).toHaveBeenCalledWith(- "download_via_vscode_button_clicked",- expect.objectContaining(COMMON),- );- });- });-describe("trackSettingsSaved", () => {it("captures settings_saved with all properties using SCREAMING_SNAKE_CASE keys", () => {getTracking().trackSettingsSaved({diff --git a/__tests__/hooks/use-unified-vscode-url.test.tsx b/__tests__/hooks/use-unified-vscode-url.test.tsxdeleted file mode 100644index 2c68f1962b..0000000000--- a/__tests__/hooks/use-unified-vscode-url.test.tsx+++ /dev/null@@ -1,763 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { act, renderHook, waitFor } from "@testing-library/react";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { I18nextProvider, initReactI18next } from "react-i18next";-import i18n from "i18next";-import React from "react";-import { useUnifiedVSCodeUrl } from "#/hooks/query/use-unified-vscode-url";-import { batchGetCloudSandboxes } from "#/api/cloud/sandbox-service.api";-import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";-import ConversationService from "#/api/conversation-service/conversation-service.api";-import { useActiveBackend } from "#/contexts/active-backend-context";-import { useActiveConversation } from "#/hooks/query/use-active-conversation";-import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";-import type { ResolvedActiveBackend } from "#/api/backend-registry/types";-import type { V1SandboxInfo } from "#/api/cloud/sandbox-service.types";-import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";-import { I18nKey } from "#/i18n/declaration";--const { mockUseConversationId } = vi.hoisted(() => ({- mockUseConversationId: vi.fn(),-}));--vi.mock("react-i18next", async (importOriginal) => ({- ...(await importOriginal<typeof import("react-i18next")>()),- useTranslation: (namespace?: string) => ({- t: (key: string) =>- namespace === "openhands" ? key : `missing-namespace:${key}`,- }),-}));--vi.mock("#/api/cloud/sandbox-service.api");-vi.mock("#/api/conversation-service/agent-server-conversation-service.api");-vi.mock("#/api/conversation-service/conversation-service.api");-vi.mock("#/contexts/active-backend-context");-vi.mock("#/hooks/query/use-active-conversation");-vi.mock("#/hooks/use-runtime-is-ready");-vi.mock("#/hooks/use-conversation-id", () => ({- useOptionalConversationId: () => mockUseConversationId(),- useConversationId: () => mockUseConversationId(),-}));--if (!i18n.isInitialized) {- i18n.use(initReactI18next).init({- lng: "en",- fallbackLng: "en",- ns: ["openhands"],- defaultNS: "openhands",- resources: { en: { openhands: {} } },- interpolation: { escapeValue: false },- returnEmptyString: false,- });-}--const cloudBackend: ResolvedActiveBackend = {- backend: {- id: "cloud-prod",- name: "Production",- host: "https://app.all-hands.dev",- apiKey: "key",- kind: "cloud",- },- orgId: "org-1",-};--const localBackend: ResolvedActiveBackend = {- backend: {- id: "local-1",- name: "Local",- host: "http://localhost:8000",- apiKey: "key",- kind: "local",- },- orgId: null,-};--function makeConversation(- overrides: Partial<AppConversation> = {},-): AppConversation {- return {- id: "conv-123",- sandbox_id: "sandbox-9",- conversation_url: "http://abc.staging-runtime.all-hands.dev/api/conv/1",- session_api_key: "sek",- created_by_user_id: null,- selected_repository: null,- selected_branch: null,- git_provider: null,- title: null,- trigger: null,- pr_number: [],- llm_model: null,- metrics: null,- created_at: "2026-05-12T00:00:00Z",- updated_at: "2026-05-12T00:00:00Z",- execution_status: "running",- sub_conversation_ids: [],- ...overrides,- } as AppConversation;-}--function makeSandbox(overrides: Partial<V1SandboxInfo> = {}): V1SandboxInfo {- return {- id: "sandbox-9",- created_by_user_id: null,- sandbox_spec_id: "spec-1",- status: "RUNNING",- session_api_key: "sek",- exposed_urls: [- {- name: "VSCODE",- url: "https://vscode-abc.staging-runtime.all-hands.dev/?tkn=sek&folder=%2Fworkspace%2Fproject",- },- ],- created_at: "2026-05-12T00:00:00Z",- ...overrides,- };-}--function createQueryHarness() {- const queryClient = new QueryClient({- defaultOptions: { queries: { retry: false, retryDelay: 0 } },- });- const wrapper = ({ children }: { children: React.ReactNode }) => (- <QueryClientProvider client={queryClient}>- <I18nextProvider i18n={i18n}>{children}</I18nextProvider>- </QueryClientProvider>- );-- return { queryClient, wrapper };-}--function createWrapper() {- return createQueryHarness().wrapper;-}--// The local path now gates the URL request on two capability checks the-// archived test predates:-// 1. `getOriginVSCodeBasePath()` — this browser origin must advertise an-// editor route. In jsdom that comes from-// `window.__AGENT_CANVAS_VSCODE_BASE_PATH__`, so we inject it here to-// model a self-hosted deployment that serves the editor.-// 2. `AgentServerConversationService.getVSCodeStatus()` — a 200 probe that-// must report `{ enabled: true, running: true }` before the URL query is-// enabled. Default it to the available state so the existing local-mode-// expectations still exercise the URL resolver.-const VSCODE_BASE_PATH = "/vscode";--beforeEach(() => {- vi.resetAllMocks();- (- window as unknown as Record<string, unknown>- ).__AGENT_CANVAS_VSCODE_BASE_PATH__ = VSCODE_BASE_PATH;- mockUseConversationId.mockReturnValue({ conversationId: "conv-123" });- vi.mocked(useRuntimeIsReady).mockReturnValue(true);- vi.mocked(useActiveConversation).mockReturnValue({- data: makeConversation(),- } as unknown as ReturnType<typeof useActiveConversation>);- vi.mocked(AgentServerConversationService.getVSCodeStatus).mockResolvedValue({- enabled: true,- running: true,- });-});--afterEach(() => {- vi.clearAllMocks();- delete (window as unknown as Record<string, unknown>)- .__AGENT_CANVAS_VSCODE_BASE_PATH__;-});--describe("useUnifiedVSCodeUrl", () => {- it.each(["cloud", "no origin editor", "runtime stopped"])(- "does not fetch a local URL with cached capability when %s",- async (disabledState) => {- vi.mocked(useActiveBackend).mockReturnValue(- disabledState === "cloud" ? cloudBackend : localBackend,- );- vi.mocked(batchGetCloudSandboxes).mockResolvedValue([makeSandbox()]);- if (disabledState === "no origin editor") {- delete (window as unknown as Record<string, unknown>)- .__AGENT_CANVAS_VSCODE_BASE_PATH__;- }- if (disabledState === "runtime stopped") {- vi.mocked(useRuntimeIsReady).mockReturnValue(false);- }- const { queryClient, wrapper } = createQueryHarness();- const conversation = makeConversation();- queryClient.setQueryData(- [- "unified",- "vscode_status",- "local",- "conv-123",- conversation.conversation_url,- conversation.session_api_key,- ],- { enabled: true, running: true },- );- const { unmount } = renderHook(() => useUnifiedVSCodeUrl(), { wrapper });- await act(async () => {- await Promise.resolve();- });- expect(- AgentServerConversationService.getVSCodeStatus,- ).not.toHaveBeenCalled();- expect(- AgentServerConversationService.getVSCodeUrl,- ).not.toHaveBeenCalled();- unmount();- queryClient.clear();- },- );-- it("returns the cloud-computed VSCode URL from sandbox.exposed_urls in cloud mode", async () => {- // Arrange — cloud backend, sandbox returned with a VSCODE entry.- // This is the steady-state happy path: the cloud backend pre-builds the- // public vscode subdomain URL and the GUI must surface it directly- // instead of asking the runtime for /api/vscode/url (which only- // knows its own localhost:8001).- vi.mocked(useActiveBackend).mockReturnValue(cloudBackend);- vi.mocked(batchGetCloudSandboxes).mockResolvedValue([- makeSandbox({- exposed_urls: [- { name: "APP", url: "https://app.example.dev" },- {- name: "VSCODE",- url: "https://vscode-abc.staging-runtime.all-hands.dev/?tkn=sek&folder=%2Fworkspace%2Fproject",- },- ],- }),- ]);-- // Act- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- // Assert- await waitFor(() => expect(result.current.isSuccess).toBe(true));- expect(result.current.data?.url).toBe(- "https://vscode-abc.staging-runtime.all-hands.dev/?tkn=sek&folder=%2Fworkspace%2Fproject",- );- expect(AgentServerConversationService.getVSCodeUrl).not.toHaveBeenCalled();- // Cloud never runs the local capability probe, and the cloud path keeps- // the control visible regardless of exposed_urls.- expect(- AgentServerConversationService.getVSCodeStatus,- ).not.toHaveBeenCalled();- expect(result.current.isUnavailable).toBe(false);- });-- it("returns null url in cloud mode when the sandbox has no VSCODE exposed_url", async () => {- // Arrange — sandbox is reachable but isn't running yet (STARTING /- // PAUSED), so exposed_urls hasn't been populated. The hook must- // surface "no URL" gracefully so the tab shows the empty-state- // copy instead of crashing or serving a localhost fallback.- vi.mocked(useActiveBackend).mockReturnValue(cloudBackend);- vi.mocked(batchGetCloudSandboxes).mockResolvedValue([- makeSandbox({- status: "STARTING",- exposed_urls: null,- }),- ]);-- // Act- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- // Assert- await waitFor(() => expect(result.current.isSuccess).toBe(true));- expect(result.current.data?.url).toBeNull();- expect(result.current.data?.error).toBe(- i18n.t(I18nKey.VSCODE$URL_NOT_AVAILABLE),- );- });-- it("ignores unrelated cloud exposed URLs", async () => {- vi.mocked(useActiveBackend).mockReturnValue(cloudBackend);- vi.mocked(batchGetCloudSandboxes).mockResolvedValue([- makeSandbox({- exposed_urls: [{ name: "APP", url: "https://app.example.dev" }],- }),- ]);-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- await waitFor(() => expect(result.current.isSuccess).toBe(true));- expect(result.current.data).toEqual({- url: null,- error: i18n.t(I18nKey.VSCODE$URL_NOT_AVAILABLE),- });- });-- it("falls through to AgentServerConversationService.getVSCodeUrl in local mode", async () => {- // Arrange — local backend: cloud sandbox lookup must be skipped and- // the existing local resolver must drive the URL. Regression check- // for the cloud/local branch that was added to the hook.- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeUrl).mockResolvedValue({- vscode_url: "http://localhost:8001/?tkn=local-key&folder=workspace",- });-- // Act- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- // Assert- await waitFor(() => expect(result.current.isSuccess).toBe(true));- expect(AgentServerConversationService.getVSCodeUrl).toHaveBeenCalledWith(- "conv-123",- "http://abc.staging-runtime.all-hands.dev/api/conv/1",- "sek",- );- expect(batchGetCloudSandboxes).not.toHaveBeenCalled();- expect(ConversationService.getVSCodeUrl).not.toHaveBeenCalled();- });-- it("allows the VSCode query while the runtime reports an agent error", async () => {- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(useRuntimeIsReady).mockImplementation(- (options) => options?.allowAgentError === true,- );- vi.mocked(AgentServerConversationService.getVSCodeUrl).mockResolvedValue({- vscode_url: "https://vscode.example.dev/?folder=workspace",- });-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- await waitFor(() => expect(result.current.isSuccess).toBe(true));- expect(useRuntimeIsReady).toHaveBeenCalledWith({ allowAgentError: true });- expect(AgentServerConversationService.getVSCodeUrl).toHaveBeenCalledOnce();- });-- it("stores local results under the conversation-specific cache key", async () => {- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeUrl).mockResolvedValue({- vscode_url: "https://vscode.example.dev/?folder=workspace",- });- const { queryClient, wrapper } = createQueryHarness();-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), { wrapper });- await waitFor(() => expect(result.current.isSuccess).toBe(true));-- const cachedQuery = queryClient.getQueryCache().find({- exact: true,- queryKey: [- "unified",- "vscode_url",- "local",- "conv-123",- "http://abc.staging-runtime.all-hands.dev/api/conv/1",- "sek",- ],- });- expect(cachedQuery?.state.data).toEqual({- url: "https://vscode.example.dev/?folder=workspace",- });-- // The capability probe is cached under its own conversation-scoped key so a- // different conversation can't reuse a stale enabled/running answer.- const cachedStatusQuery = queryClient.getQueryCache().find({- exact: true,- queryKey: [- "unified",- "vscode_status",- "local",- "conv-123",- "http://abc.staging-runtime.all-hands.dev/api/conv/1",- "sek",- ],- });- expect(cachedStatusQuery?.state.data).toEqual({- enabled: true,- running: true,- });- });-- it("refreshes stale local URL data when the hook remounts", async () => {- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeUrl)- .mockResolvedValueOnce({- vscode_url: "https://initial.example.dev/?folder=workspace",- })- .mockResolvedValueOnce({- vscode_url: "https://remounted.example.dev/?folder=workspace",- });- const { wrapper } = createQueryHarness();-- const initial = renderHook(() => useUnifiedVSCodeUrl(), { wrapper });- await waitFor(() => expect(initial.result.current.isSuccess).toBe(true));- initial.unmount();-- const remounted = renderHook(() => useUnifiedVSCodeUrl(), { wrapper });- await waitFor(() =>- expect(remounted.result.current.data?.url).toBe(- "https://remounted.example.dev/?folder=workspace",- ),- );- expect(AgentServerConversationService.getVSCodeUrl).toHaveBeenCalledTimes(- 2,- );- // The probe is `refetchOnMount` too, so the remount re-verifies capability- // rather than trusting the previous mount's cached answer.- expect(- AgentServerConversationService.getVSCodeStatus,- ).toHaveBeenCalledTimes(2);- });-- it("falls back to the legacy conversation service when the agent-server request fails", async () => {- const agentServerFailure = new Error("runtime endpoint unavailable");- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeUrl).mockRejectedValue(- agentServerFailure,- );- vi.mocked(ConversationService.getVSCodeUrl).mockResolvedValue({- vscode_url: "https://fallback.example.dev/?folder=workspace",- });-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- await waitFor(() => expect(result.current.isSuccess).toBe(true));- expect(ConversationService.getVSCodeUrl).toHaveBeenCalledWith("conv-123");- expect(result.current.data).toEqual({- url: "https://fallback.example.dev/?folder=workspace",- error: null,- });- });-- it("returns local query failures after both URL services reject", async () => {- const fallbackFailure = new Error("no VS Code endpoint");- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeUrl).mockRejectedValue(- new Error("runtime unavailable"),- );- vi.mocked(ConversationService.getVSCodeUrl).mockRejectedValue(- fallbackFailure,- );-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- await waitFor(() => expect(result.current.isError).toBe(true));- expect(result.current.status).toBe("error");- expect(result.current.error).toBe(fallbackFailure);- expect(result.current.data).toBeUndefined();- });-- it("passes null runtime metadata when active conversation details are unavailable", async () => {- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(useActiveConversation).mockReturnValue({- data: undefined,- } as unknown as ReturnType<typeof useActiveConversation>);- vi.mocked(AgentServerConversationService.getVSCodeUrl).mockResolvedValue({- vscode_url: null,- });-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- await waitFor(() => expect(result.current.isSuccess).toBe(true));- expect(AgentServerConversationService.getVSCodeUrl).toHaveBeenCalledWith(- "conv-123",- null,- null,- );- expect(result.current.data).toEqual({- url: null,- error: i18n.t(I18nKey.VSCODE$URL_NOT_AVAILABLE),- });- });-- it("returns the refreshed local URL", async () => {- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeUrl)- .mockResolvedValueOnce({- vscode_url: "https://initial.example.dev/?folder=workspace",- })- .mockResolvedValueOnce({- vscode_url: "https://refreshed.example.dev/?folder=workspace",- });-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });- await waitFor(() => expect(result.current.isSuccess).toBe(true));-- const refreshed = await result.current.refetch();-- expect(refreshed.data).toEqual({- url: "https://refreshed.example.dev/?folder=workspace",- });- await waitFor(() =>- expect(result.current.data?.url).toBe(- "https://refreshed.example.dev/?folder=workspace",- ),- );- });-- it("maps cloud refetches to refreshed, unavailable, and missing sandbox results", async () => {- vi.mocked(useActiveBackend).mockReturnValue(cloudBackend);- vi.mocked(batchGetCloudSandboxes)- .mockResolvedValueOnce([makeSandbox()])- .mockResolvedValueOnce([- makeSandbox({- exposed_urls: [- { name: "APP", url: "https://app.example.dev" },- { name: "VSCODE", url: "https://refreshed.example.dev" },- ],- }),- ])- .mockResolvedValueOnce([- makeSandbox({- exposed_urls: [{ name: "APP", url: "https://app.example.dev" }],- }),- ])- .mockResolvedValueOnce([- makeSandbox({- exposed_urls: null,- }),- ])- .mockResolvedValueOnce([]);-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });- await waitFor(() => expect(result.current.isSuccess).toBe(true));-- const refreshed = await result.current.refetch();- expect(refreshed.data).toEqual({ url: "https://refreshed.example.dev" });-- const unrelated = await result.current.refetch();- expect(unrelated.data).toEqual({ url: null });-- const unavailable = await result.current.refetch();- expect(unavailable.data).toEqual({ url: null });-- const missing = await result.current.refetch();- expect(missing.data).toBeUndefined();- await waitFor(() => expect(result.current.data?.url).toBeNull());- });-- it("surfaces cloud sandbox lookup failures", async () => {- const failure = new Error("sandbox lookup failed");- vi.mocked(useActiveBackend).mockReturnValue(cloudBackend);- vi.mocked(batchGetCloudSandboxes).mockRejectedValue(failure);-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- await waitFor(() => expect(result.current.isError).toBe(true));- expect(result.current.status).toBe("error");- expect(result.current.error).toBe(failure);- expect(result.current.data).toBeUndefined();- });-- it("does not request a cloud sandbox until the conversation has a sandbox id", () => {- vi.mocked(useActiveBackend).mockReturnValue(cloudBackend);- vi.mocked(useActiveConversation).mockReturnValue({- data: makeConversation({ sandbox_id: null }),- } as unknown as ReturnType<typeof useActiveConversation>);-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- expect(batchGetCloudSandboxes).not.toHaveBeenCalled();- expect(result.current.isLoading).toBe(false);- expect(result.current.data).toBeUndefined();- });-- it("does not request a local URL before the runtime is ready", () => {- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(useRuntimeIsReady).mockReturnValue(false);-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- expect(AgentServerConversationService.getVSCodeUrl).not.toHaveBeenCalled();- expect(result.current.isLoading).toBe(false);- expect(result.current.data).toBeUndefined();- });-- it("reports the missing conversation id when a disabled query is manually refreshed", async () => {- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- mockUseConversationId.mockReturnValue({ conversationId: "" });-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- expect(AgentServerConversationService.getVSCodeUrl).not.toHaveBeenCalled();- expect(result.current.isLoading).toBe(false);- expect(result.current.data).toBeUndefined();-- const refreshed = await result.current.refetch();-- expect(refreshed.data).toBeUndefined();- await waitFor(() => expect(result.current.isError).toBe(true));- expect(result.current.error).toEqual(new Error("No conversation ID"));- expect(AgentServerConversationService.getVSCodeUrl).not.toHaveBeenCalled();- });-- it("hides the control and skips both requests when this origin serves no editor", async () => {- // A public-mode / extra-backend origin advertises no editor route. The- // agent-server might still report one, but this page couldn't reach it, so- // neither the capability probe nor the URL request should fire and the- // control must report itself unavailable rather than loading.- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- delete (window as unknown as Record<string, unknown>)- .__AGENT_CANVAS_VSCODE_BASE_PATH__;-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- expect(- AgentServerConversationService.getVSCodeStatus,- ).not.toHaveBeenCalled();- expect(AgentServerConversationService.getVSCodeUrl).not.toHaveBeenCalled();- expect(result.current.isUnavailable).toBe(true);- expect(result.current.isLoading).toBe(false);- expect(result.current.data).toBeUndefined();- });-- it("hides the control when the capability probe reports the editor disabled", async () => {- // `enabled: false` is the deployment switch. The URL request must never- // fire — that is the whole point of gating on the probe — and the control- // reports itself unavailable instead of erroring.- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeStatus).mockResolvedValue(- {- enabled: false,- running: true,- },- );-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- await waitFor(() => expect(result.current.isUnavailable).toBe(true));- expect(AgentServerConversationService.getVSCodeUrl).not.toHaveBeenCalled();- expect(result.current.isSuccess).toBe(false);- });-- it("hides the control when the editor is enabled but not running", async () => {- // `running: false` alongside `enabled: true` is a terminal failed-start,- // not a startup race, so the URL request is still withheld.- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeStatus).mockResolvedValue(- {- enabled: true,- running: false,- },- );-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- await waitFor(() => expect(result.current.isUnavailable).toBe(true));- expect(AgentServerConversationService.getVSCodeUrl).not.toHaveBeenCalled();- });-- it("keeps the control available when the resolved URL is routed by this origin", async () => {- // The probe cleared the editor and the resolved URL sits under the prefix- // this origin actually serves, so the control is usable.- const routedUrl = `${window.location.origin}/vscode/?tkn=abc&folder=workspace`;- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeUrl).mockResolvedValue({- vscode_url: routedUrl,- });-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- await waitFor(() => expect(result.current.isSuccess).toBe(true));- expect(result.current.data).toEqual({ url: routedUrl, error: null });- expect(result.current.isUnavailable).toBe(false);- });-- it("hides the control when the resolved URL is not routed by this origin", async () => {- // Same-origin but wrong prefix: an extra backend with no prefix of its own- // hands back a URL that would reopen this app instead of an editor. The URL- // resolves successfully yet the control must still hide.- const unroutableUrl = `${window.location.origin}/not-vscode/?tkn=abc`;- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeUrl).mockResolvedValue({- vscode_url: unroutableUrl,- });-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- await waitFor(() => expect(result.current.isSuccess).toBe(true));- expect(result.current.data?.url).toBe(unroutableUrl);- expect(result.current.isUnavailable).toBe(true);- });-- it("marks the control unavailable when the editor reports no URL", async () => {- // The probe says the editor is up, but the resolver returns no URL: there- // is nothing to open, so the control hides rather than offering a no-op.- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeUrl).mockResolvedValue({- vscode_url: null,- });-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- await waitFor(() => expect(result.current.isSuccess).toBe(true));- expect(result.current.data).toEqual({- url: null,- error: i18n.t(I18nKey.VSCODE$URL_NOT_AVAILABLE),- });- expect(result.current.isUnavailable).toBe(true);- });-- it("reports loading while the capability probe is in flight", () => {- // The URL request only starts once the probe clears it, so the control is- // "loading" for the probe as well — otherwise it would look ready while- // there is still nothing to open.- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeUrl).mockResolvedValue({- vscode_url: "https://vscode.example.dev/?folder=workspace",- });-- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });-- expect(result.current.isLoading).toBe(true);- });- it("reports capability-probe failures without treating them as unavailable editors", async () => {- const error = new Error("Unauthorized capability probe");- vi.mocked(useActiveBackend).mockReturnValue(localBackend);- vi.mocked(AgentServerConversationService.getVSCodeStatus).mockRejectedValue(- error,- );- const { result } = renderHook(() => useUnifiedVSCodeUrl(), {- wrapper: createWrapper(),- });- await waitFor(() => expect(result.current.isError).toBe(true));- expect(result.current.error).toBe(error);- expect(result.current.isUnavailable).toBe(false);- expect(AgentServerConversationService.getVSCodeUrl).not.toHaveBeenCalled();- expect(ConversationService.getVSCodeUrl).not.toHaveBeenCalled();- });-});diff --git a/__tests__/scripts/dev-extra-backend.test.ts b/__tests__/scripts/dev-extra-backend.test.tsindex 07f0908709..f25e2691aa 100644--- a/__tests__/scripts/dev-extra-backend.test.ts+++ b/__tests__/scripts/dev-extra-backend.test.ts@@ -44,7 +44,10 @@ describe("buildExtraBackendConfig", () => {}it("defaults to ports 18002/18003 distinct from the bundled instance", () => {- const env = { OH_SESSION_API_KEY_PATH: isolatedKeyPath() };+ const env = {+ OH_CANVAS_ENABLE_VSCODE: "true",+ OH_SESSION_API_KEY_PATH: isolatedKeyPath(),+ };const bundled = buildSafeDevConfig(repoRoot, env);const extra = buildExtraBackendConfig(repoRoot, env);@@ -58,6 +61,7 @@ describe("buildExtraBackendConfig", () => {it("honors OH_CANVAS_EXTRA_BACKEND_PORT and OH_CANVAS_EXTRA_VSCODE_PORT", () => {const config = buildExtraBackendConfig(repoRoot, {+ OH_CANVAS_ENABLE_VSCODE: "true",OH_CANVAS_EXTRA_BACKEND_PORT: "29000",OH_CANVAS_EXTRA_VSCODE_PORT: "29001",OH_SESSION_API_KEY_PATH: isolatedKeyPath(),diff --git a/__tests__/scripts/dev-safe.test.ts b/__tests__/scripts/dev-safe.test.tsindex 228ebe4e78..c9b25a62b8 100644--- a/__tests__/scripts/dev-safe.test.ts+++ b/__tests__/scripts/dev-safe.test.ts@@ -200,6 +200,7 @@ describe("buildSafeDevConfigAsync", () => {// Use a high port so the assertPortsFree check passes even when a real// dev stack is running on the default port (18000).const config = await buildSafeDevConfigAsync(repoRoot, {+ OH_CANVAS_ENABLE_VSCODE: "true",OH_CANVAS_SAFE_BACKEND_PORT: "19800",OH_SESSION_API_KEY_PATH: tempKeyPath(),});@@ -766,6 +767,7 @@ describe("buildSafeDevConfig", () => {const cwd = "/workspace/project/agent-canvas";const config = buildSafeDevConfig(cwd, {+ OH_CANVAS_ENABLE_VSCODE: "true",OH_SESSION_API_KEY_PATH: tempKeyPath(),});@@ -793,6 +795,7 @@ describe("buildSafeDevConfig", () => {const cwd = "/workspace/project/agent-canvas";const config = buildSafeDevConfig(cwd, {+ OH_CANVAS_ENABLE_VSCODE: "true",OH_CANVAS_SAFE_BACKEND_PORT: "19000",OH_CANVAS_SAFE_VSCODE_PORT: "19010",OH_CANVAS_SAFE_STATE_DIR: ".tmp/dev-safe",diff --git a/__tests__/scripts/dev-with-automation.test.ts b/__tests__/scripts/dev-with-automation.test.tsindex 63ec9a355b..06bed5c973 100644--- a/__tests__/scripts/dev-with-automation.test.ts+++ b/__tests__/scripts/dev-with-automation.test.ts@@ -319,6 +319,7 @@ describe("buildConfig", () => {keyDirs.push(dir);return {OH_SESSION_API_KEY_PATH: path.join(dir, "session-api-key.txt"),+ OH_CANVAS_ENABLE_VSCODE: "true",// High ports that are almost certainly free, so assertPortsFree passes.PORT: "19902",OH_CANVAS_SAFE_BACKEND_PORT: "19900",@@ -533,6 +534,7 @@ describe("stack mode routing", () => {keyDirs.push(dir);return {OH_SESSION_API_KEY_PATH: path.join(dir, "session-api-key.txt"),+ OH_CANVAS_ENABLE_VSCODE: "true",PORT: "19802",OH_CANVAS_SAFE_BACKEND_PORT: "19800",OH_CANVAS_SAFE_AUTOMATION_PORT: "19801",diff --git a/__tests__/scripts/docker-vscode-route-sync.test.ts b/__tests__/scripts/docker-vscode-route-sync.test.tsindex 6abcea06f6..27aed3ef70 100644--- a/__tests__/scripts/docker-vscode-route-sync.test.ts+++ b/__tests__/scripts/docker-vscode-route-sync.test.ts@@ -2,12 +2,17 @@//// Drift-detection for the Docker install path's editor route.//-// The VSCode button advertises a URL built by agent-server from-// OH_VSCODE_BASE_PATH, and that URL only resolves because the static server-// carries a route for the same prefix to the same port. Those two facts live in-// separate files (docker/entrypoint.sh, config/defaults.json via the Dockerfile's-// generated defaults.env), so nothing but a test stops them drifting apart and-// leaving a button that points at the canvas shell instead of the editor.+// When editor support is enabled (`OH_CANVAS_ENABLE_VSCODE=true`), the VSCode+// button advertises a URL built by agent-server from OH_VSCODE_BASE_PATH, and+// that URL only resolves because the static server carries a route for the same+// prefix to the same port. Those two facts live in separate files+// (docker/entrypoint.sh, the generated defaults.env), so nothing but a test+// stops them drifting apart and leaving a button that points at the canvas+// shell instead of the editor.+//+// The editor is opt-in: a default stack reserves neither an editor port nor a+// proxy route, so the tests below assert both the enabled wiring and the+// disabled no-op.//// The npm launcher's equivalent wiring is covered in dev-with-automation.test.ts// against the real functions. This file covers the shell/Docker half: the@@ -30,15 +35,15 @@ function read(rel: string): string {}const defaults = JSON.parse(read("config/defaults.json")) as {- ports: { vscode: number; proxy: number };- paths: { vscodeBasePath: string };+ ports: Record<string, unknown>;+ paths: Record<string, unknown>;};const entrypoint = read("docker/entrypoint.sh");const dockerfile = read("docker/Dockerfile");-// Both static-server invocations (the normal one and the --auth-required-// public-mode one started when PUBLIC_MODE_PORT is set) must carry the route;-// the public-mode server is what the auth-mode E2E suite drives.+// The normal static-server invocation and the --auth-required public-mode one+// started when PUBLIC_MODE_PORT is set. The editor route is passed through the+// shared `VSCODE_ROUTE_ARGS` array, so only the normal instance may carry it.function staticServerInvocations(): string[] {return entrypoint.split("node /opt/agent-canvas/static-server.mjs")@@ -47,26 +52,41 @@ function staticServerInvocations(): string[] {}// ── Executing the entrypoint's editor-config block ──────────────────────────-// The block resolves the editor port/prefix from the OH_* variables, this-// image's aliases and the generated defaults.env, then exports the pair to-// agent-server and builds the route string the static servers register. Those-// are two consumers of one setting, so the tests below run the real block and-// compare what each consumer ends up seeing.+// The block resolves the editor port/prefix from the OH_* variables and this+// image's aliases, then exports the pair to agent-server and builds the route+// string the static servers register. Those are two consumers of one setting, so+// the tests below run the real block and compare what each consumer ends up+// seeing. The enabling `if` lives outside the markers, so the harness reproduces+// it to keep the enabled/disabled behavior under test.const BLOCK_START = "# >>> vscode-config";const BLOCK_END = "# <<< vscode-config";--function editorConfigBlock(): string {- const start = entrypoint.indexOf(BLOCK_START);- const end = entrypoint.indexOf(BLOCK_END);+// The canvas mount is resolved outside the editor guard (it has non-editor+// consumers and the script runs under `set -u`), so the harness has to run that+// block too: the collision guard inside the editor block compares against the+// value it produces.+const CANVAS_BLOCK_START = "# >>> canvas-base-path";+const CANVAS_BLOCK_END = "# <<< canvas-base-path";++function markedBlock(startMarker: string, endMarker: string): string {+ const start = entrypoint.indexOf(startMarker);+ const end = entrypoint.indexOf(endMarker);if (start === -1 || end === -1) {throw new Error(- `docker/entrypoint.sh is missing the "${BLOCK_START}"/"${BLOCK_END}" markers; ` +- "the editor-config block can no longer be located, so its behavior is untested.",+ `docker/entrypoint.sh is missing the "${startMarker}"/"${endMarker}" markers; ` ++ "the block can no longer be located, so its behavior is untested.",);}return entrypoint.slice(start, end);}+function canvasBasePathBlock(): string {+ return markedBlock(CANVAS_BLOCK_START, CANVAS_BLOCK_END);+}++function editorConfigBlock(): string {+ return markedBlock(BLOCK_START, BLOCK_END);+}+interface ResolvedEditorConfig {status: number | null;stderr: string;@@ -75,6 +95,8 @@ interface ResolvedEditorConfig {advertisedPort: string;/** What every static-server instance registers. */route: string;+ /** How many editor route args the normal static-server invocation receives. */+ routeArgCount: string;}function resolveEditorConfig(@@ -82,27 +104,49 @@ function resolveEditorConfig(): ResolvedEditorConfig {const script = ["set -uo pipefail",- // Defined near the top of entrypoint.sh, above the extracted block.+ // Defined near the top of entrypoint.sh, above the extracted blocks.`log_error() { printf 'ERROR: %s\\n' "$*" >&2; }`,+ // Runs before the guard in entrypoint.sh, and is what the editor block's+ // collision guard compares against.+ canvasBasePathBlock(),+ // Mirrors the guard wrapping the block in entrypoint.sh.+ `OH_CANVAS_ENABLE_VSCODE="\${OH_CANVAS_ENABLE_VSCODE:-false}"`,+ "VSCODE_ROUTE_ARGS=()",+ `if [ "$OH_CANVAS_ENABLE_VSCODE" = "true" ]; then`,editorConfigBlock(),- `printf '%s\\n%s\\n%s\\n' "$OH_VSCODE_BASE_PATH" "$OH_VSCODE_PORT" "$VSCODE_ROUTE"`,+ ` VSCODE_ROUTE_ARGS=(--route "$VSCODE_ROUTE" --vscode-base-path "$VSCODE_BASE_PATH" --no-referrer-prefix "$VSCODE_BASE_PATH")`,+ "fi",+ `printf '%s\\n%s\\n%s\\n%s\\n' "\${OH_VSCODE_BASE_PATH:-}" "\${OH_VSCODE_PORT:-}" "\${VSCODE_ROUTE:-}" "\${#VSCODE_ROUTE_ARGS[@]}"`,].join("\n");// Deliberately not inheriting the ambient environment: a developer with- // OH_VSCODE_* exported would otherwise change what these tests measure.+ // OH_VSCODE_* exported would otherwise change what these tests measure. The+ // default enables the editor so each case below only states its own override;+ // the disabled behavior has its own test.const res = spawnSync("bash", ["-c", script], {encoding: "utf-8",- env: { PATH: process.env.PATH ?? "", ...env },+ env: {+ PATH: process.env.PATH ?? "",+ OH_CANVAS_ENABLE_VSCODE: "true",+ OH_VSCODE_PORT: "8001",+ ...env,+ },});- const [advertisedBasePath = "", advertisedPort = "", route = ""] = res.stdout- .trim()- .split("\n");+ // Split on the trailing newline only: `trim()` would also eat a leading empty+ // field (an unset advertised prefix), shifting every value up by one.+ const [+ advertisedBasePath = "",+ advertisedPort = "",+ route = "",+ routeArgCount = "",+ ] = res.stdout.replace(/\n$/, "").split("\n");return {status: res.status,stderr: res.stderr,advertisedBasePath,advertisedPort,route,+ routeArgCount,};}@@ -115,20 +159,37 @@ function expectRouteMatchesAdvertised(resolved: ResolvedEditorConfig): void {}describe("docker editor route", () => {- it("centralizes the base path and port in defaults.json", () => {- expect(defaults.paths.vscodeBasePath).toBe("/vscode");- expect(defaults.paths.vscodeBasePath.startsWith("/")).toBe(true);- expect(Number.isInteger(defaults.ports.vscode)).toBe(true);+ it("keeps the editor out of the centralized defaults", () => {+ // Editor provisioning is opt-in, so neither the port nor the prefix is a+ // project-wide default any more: a default stack must not reserve either.+ expect(defaults.ports).not.toHaveProperty("vscode");+ expect(defaults.paths).not.toHaveProperty("vscodeBasePath");});- it("exports both values from defaults.json into the generated defaults.env", () => {- // The container has no jq/python, so the Dockerfile bakes defaults.json- // into a shell-sourceable env file. A value missing here silently falls- // back to the hardcoded default in entrypoint.sh.- expect(dockerfile).toContain(- "'CONFIG_VSCODE_BASE_PATH=' + c.paths.vscodeBasePath",+ it("does not bake editor values into the generated defaults.env", () => {+ // The container has no jq/python, so the Dockerfile bakes defaults.json into+ // a shell-sourceable env file. Editor values are gone from defaults.json, so+ // they must be gone from the generated file too — otherwise a stale entry+ // would silently re-enable the editor for every stack.+ expect(dockerfile).not.toContain("CONFIG_VSCODE_PORT");+ expect(dockerfile).not.toContain("CONFIG_VSCODE_BASE_PATH");+ });++ it("gates the editor wiring on OH_CANVAS_ENABLE_VSCODE", () => {+ // The block resolves the pair and, below the markers, builds the route args.+ // Both have to sit inside the same guard or a disabled stack would still+ // route an editor nobody started.+ const guard = 'if [ "${OH_CANVAS_ENABLE_VSCODE:-false}" = "true" ]; then';+ expect(entrypoint).toContain(guard);+ const guardIndex = entrypoint.indexOf(guard);+ const blockEnd = entrypoint.indexOf(BLOCK_END);+ const argsAssignment = entrypoint.indexOf(+ 'VSCODE_ROUTE_ARGS=(--route "$VSCODE_ROUTE"',);- expect(dockerfile).toContain("'CONFIG_VSCODE_PORT=' + c.ports.vscode");+ expect(blockEnd).toBeGreaterThan(guardIndex);+ // The route args are assigned after the extracted block and before the guard+ // closes, i.e. only on the enabled path.+ expect(argsAssignment).toBeGreaterThan(blockEnd);});it("registers the editor route on the normal static-server instance", () => {@@ -138,12 +199,13 @@ describe("docker editor route", () => {expect(invocations).toHaveLength(2);const [normal] = invocations;- expect(normal).toContain('--route "$VSCODE_ROUTE"');+ // Expanded from the shared array, so the route string cannot be built twice.+ expect(normal).toContain('"${VSCODE_ROUTE_ARGS[@]}"');// The route string is assigned once, beside the exports it is derived// from. Two independently-built route strings are the drift this whole// file exists to prevent.- const assignments = entrypoint.match(/^VSCODE_ROUTE=/gm) ?? [];+ const assignments = entrypoint.match(/^\s+VSCODE_ROUTE=/gm) ?? [];expect(assignments).toHaveLength(1);});@@ -154,7 +216,8 @@ describe("docker editor route", () => {// editor must also advertise it, or the control never renders and the// feature is silently off.const [normal] = staticServerInvocations();- expect(normal).toContain('--vscode-base-path "$VSCODE_BASE_PATH"');+ expect(normal).toContain("VSCODE_ROUTE_ARGS");+ expect(entrypoint).toContain('--vscode-base-path "$VSCODE_BASE_PATH"');});it("keeps the editor off the public-mode (--auth-required) instance", () => {@@ -171,7 +234,7 @@ describe("docker editor route", () => {invocation.includes("--auth-required"),);expect(publicMode).toBeDefined();- expect(publicMode).not.toContain("VSCODE_ROUTE");+ expect(publicMode).not.toContain("VSCODE_ROUTE_ARGS");// And it must not advertise one either. Omitting only the route would// leave the control rendering — the agent-server this instance shares with// the main one still reports the editor as available — and the click would@@ -183,26 +246,22 @@ describe("docker editor route", () => {// The advertised URL carries the connection token as a query parameter and// the workbench loads webviews, previews and extension content from that// document, so a Referer would carry the token to each of them.- const [normal] = staticServerInvocations();- expect(normal).toContain('--no-referrer-prefix "$VSCODE_BASE_PATH"');+ expect(entrypoint).toContain('--no-referrer-prefix "$VSCODE_BASE_PATH"');});it("routes the editor to its own port, not the agent-server", () => {// The editor is a separate process. Pointing the prefix at the// agent-server port would 404 the workbench.expect(entrypoint).toMatch(- /^VSCODE_ROUTE="\$\{VSCODE_BASE_PATH\}=http:\/\/127\.0\.0\.1:\$\{VSCODE_PORT\}"$/m,+ /^\s+VSCODE_ROUTE="\$\{VSCODE_BASE_PATH\}=http:\/\/127\.0\.0\.1:\$\{VSCODE_PORT\}"$/m,);- expect(defaults.ports.vscode).not.toBe(defaults.ports.proxy);});it("does not publish the editor port", () => {// The single-origin shape is the point: the editor is reachable only// through the proxy port's path prefix, so it inherits the canvas's// auth/ingress posture instead of needing a second exposed port.- expect(dockerfile).not.toMatch(- new RegExp(`^\\s*EXPOSE\\s+${defaults.ports.vscode}\\b`, "m"),- );+ expect(dockerfile).not.toMatch(/^\s*EXPOSE\s+8001\b/m);});});@@ -211,60 +270,62 @@ describe("docker editor route", () => {describe.skipIf(process.platform === "win32")("docker editor config resolution",() => {- it("advertises and routes the same pair with no overrides", () => {- const resolved = resolveEditorConfig();- expectRouteMatchesAdvertised(resolved);- // Literal fallbacks used when defaults.env is absent — they must not- // drift from the central config either.- expect(resolved.advertisedBasePath).toBe(defaults.paths.vscodeBasePath);- expect(resolved.advertisedPort).toBe(String(defaults.ports.vscode));- });-- it("takes the defaults baked into defaults.env", () => {+ it("registers no editor route while the editor is disabled", () => {+ // The default. A disabled stack must not allocate a port, advertise a+ // prefix, or hand the static server a route — otherwise it proxies to an+ // editor nobody started.const resolved = resolveEditorConfig({- CONFIG_VSCODE_BASE_PATH: "/editor",- CONFIG_VSCODE_PORT: "9001",+ OH_CANVAS_ENABLE_VSCODE: "false",+ OH_VSCODE_PORT: "",+ OH_VSCODE_BASE_PATH: "",});+ expect(resolved.status).toBe(0);+ expect(resolved.advertisedBasePath).toBe("");+ expect(resolved.advertisedPort).toBe("");+ expect(resolved.route).toBe("");+ expect(resolved.routeArgCount).toBe("0");+ });++ it("advertises and routes the same pair with no overrides", () => {+ const resolved = resolveEditorConfig();expectRouteMatchesAdvertised(resolved);- expect(resolved.advertisedBasePath).toBe("/editor");- expect(resolved.advertisedPort).toBe("9001");+ // The prefix still has a literal fallback (agent-server's own default),+ // and the port comes from the caller now that defaults.json no longer+ // carries one.+ expect(resolved.advertisedBasePath).toBe("/vscode");+ expect(resolved.advertisedPort).toBe("8001");+ expect(resolved.routeArgCount).toBe("6");});- // The regression this block was restructured for: agent-server's own- // documented variables are what a self-hosted deployment is most likely to- // already set, and setting one of them used to move the editor without- // moving the route.it("moves the route when only OH_VSCODE_BASE_PATH is set", () => {- const resolved = resolveEditorConfig({- OH_VSCODE_BASE_PATH: "/editor",- CONFIG_VSCODE_BASE_PATH: "/vscode",- });+ const resolved = resolveEditorConfig({ OH_VSCODE_BASE_PATH: "/editor" });expectRouteMatchesAdvertised(resolved);expect(resolved.advertisedBasePath).toBe("/editor");expect(resolved.route).toContain("/editor=");});it("moves the route when only OH_VSCODE_PORT is set", () => {- const resolved = resolveEditorConfig({- OH_VSCODE_PORT: "9001",- CONFIG_VSCODE_PORT: "8001",- });+ const resolved = resolveEditorConfig({ OH_VSCODE_PORT: "9001" });expectRouteMatchesAdvertised(resolved);expect(resolved.advertisedPort).toBe("9001");expect(resolved.route).toBe("/vscode=http://127.0.0.1:9001");});it("honours this image's aliases too", () => {- const resolved = resolveEditorConfig({+ // VSCODE_PORT / VSCODE_BASE_PATH are this image's aliases for+ // agent-server's own OH_VSCODE_* variables; they resolve to the same pair.+ const aliased = resolveEditorConfig({+ OH_VSCODE_PORT: "",+ OH_VSCODE_BASE_PATH: "",VSCODE_BASE_PATH: "/editor",VSCODE_PORT: "9001",});- expectRouteMatchesAdvertised(resolved);- expect(resolved.advertisedBasePath).toBe("/editor");- expect(resolved.advertisedPort).toBe("9001");+ expectRouteMatchesAdvertised(aliased);+ expect(aliased.advertisedBasePath).toBe("/editor");+ expect(aliased.advertisedPort).toBe("9001");});- it("keeps one effective pair when both names are set and disagree", () => {+ it("prefers agent-server's documented names when both are set", () => {const resolved = resolveEditorConfig({OH_VSCODE_BASE_PATH: "/editor",OH_VSCODE_PORT: "9001",diff --git a/__tests__/scripts/vscode-base-path-opt-in.test.ts b/__tests__/scripts/vscode-base-path-opt-in.test.tsindex 3881001e12..104c3cccda 100644--- a/__tests__/scripts/vscode-base-path-opt-in.test.ts+++ b/__tests__/scripts/vscode-base-path-opt-in.test.ts@@ -86,9 +86,28 @@ describe("editor base path is opt-in", () => {// Not "" or undefined-but-present: agent-server reads the variable's// presence, so an empty string would still put it into prefix-mode.expect(env).not.toHaveProperty("OH_VSCODE_BASE_PATH");- // The port is unconditional — the editor still runs, it is just advertised- // on its own port rather than under a prefix.- expect(env.OH_VSCODE_PORT).toBe(String(config.vscodePort));+ });++ it("omits the editor port until the editor is enabled", () => {+ // The editor is now opt-in as a whole: with no OH_CANVAS_ENABLE_VSCODE the+ // launcher does not allocate a port for it, so nothing is advertised and+ // agent-server does not start one.+ const disabled = buildSafeDevConfig(process.cwd(), {+ OH_SESSION_API_KEY_PATH: path.join(repoRoot, "node_modules", ".test-key"),+ });+ expect(disabled.vscodePort).toBeNull();+ expect(buildAgentServerEnv(disabled)).not.toHaveProperty("OH_VSCODE_PORT");++ // Enabled, the port becomes unconditional — which is what lets the editor+ // be advertised on its own port rather than under a prefix.+ const enabled = buildSafeDevConfig(process.cwd(), {+ OH_SESSION_API_KEY_PATH: path.join(repoRoot, "node_modules", ".test-key"),+ OH_CANVAS_ENABLE_VSCODE: "true",+ });+ expect(enabled.vscodePort).not.toBeNull();+ expect(buildAgentServerEnv(enabled).OH_VSCODE_PORT).toBe(+ String(enabled.vscodePort),+ );});it("sets OH_VSCODE_BASE_PATH to exactly what the caller passed", () => {diff --git a/__tests__/utils/vscode-origin.test.ts b/__tests__/utils/vscode-origin.test.tsdeleted file mode 100644index 3b36e9c4da..0000000000--- a/__tests__/utils/vscode-origin.test.ts+++ /dev/null@@ -1,89 +0,0 @@-import { afterEach, describe, expect, it } from "vitest";-import {- getOriginVSCodeBasePath,- isVSCodeUrlServedByOrigin,-} from "#/utils/vscode-origin";--function setInjected(value: unknown) {- if (value === undefined) {- delete (window as unknown as Record<string, unknown>)- .__AGENT_CANVAS_VSCODE_BASE_PATH__;- return;- }- (- window as unknown as Record<string, unknown>- ).__AGENT_CANVAS_VSCODE_BASE_PATH__ = value;-}--afterEach(() => setInjected(undefined));--describe("getOriginVSCodeBasePath", () => {- it("returns null when nothing advertises an editor", () => {- // The public-mode origin and any deployment predating this flag land here.- // Hiding the control matches the behavior every local backend had before- // the control was made to render at all, so this default cannot regress a- // deployment that used to work.- expect(getOriginVSCodeBasePath()).toBeNull();- });-- it("reads the value static-server injects into the document", () => {- setInjected("/vscode");- expect(getOriginVSCodeBasePath()).toBe("/vscode");- });-- it("normalizes a missing leading slash and a trailing slash", () => {- // The flag is validated at the server, but the value also arrives from- // VITE_VSCODE_BASE_PATH, so normalize rather than trust the shape.- setInjected("vscode/");- expect(getOriginVSCodeBasePath()).toBe("/vscode");- });-- it("treats a blank or non-string value as no editor", () => {- setInjected(" ");- expect(getOriginVSCodeBasePath()).toBeNull();- setInjected(42);- expect(getOriginVSCodeBasePath()).toBeNull();- });-});--describe("isVSCodeUrlServedByOrigin", () => {- const origin = window.location.origin;-- it("accepts a URL under the advertised prefix", () => {- expect(- isVSCodeUrlServedByOrigin(`${origin}/vscode/?tkn=abc`, "/vscode"),- ).toBe(true);- });-- it("accepts the prefix itself with no trailing path", () => {- expect(isVSCodeUrlServedByOrigin(`${origin}/vscode`, "/vscode")).toBe(true);- });-- it("rejects the origin root, which is what an unprefixed backend returns", () => {- // The extra-backend case: agent-server appends nothing, so the "editor"- // URL is the canvas itself. Same origin, wrong destination.- expect(isVSCodeUrlServedByOrigin(`${origin}/?tkn=abc`, "/vscode")).toBe(- false,- );- });-- it("rejects a prefix that merely shares a string prefix", () => {- // `/vscode-other` starts with `/vscode` as a string but is a different- // route; only a full segment boundary counts.- expect(- isVSCodeUrlServedByOrigin(`${origin}/vscode-other/`, "/vscode"),- ).toBe(false);- });-- it("rejects a cross-origin URL", () => {- expect(- isVSCodeUrlServedByOrigin("http://elsewhere.test/vscode/", "/vscode"),- ).toBe(false);- });-- it("rejects when there is no advertised prefix or no URL", () => {- expect(isVSCodeUrlServedByOrigin(`${origin}/vscode/`, null)).toBe(false);- expect(isVSCodeUrlServedByOrigin(null, "/vscode")).toBe(false);- expect(isVSCodeUrlServedByOrigin("not a url", "/vscode")).toBe(false);- });-});diff --git a/__tests__/utils/vscode-url-helper.test.ts b/__tests__/utils/vscode-url-helper.test.tsdeleted file mode 100644index a55b03bbbf..0000000000--- a/__tests__/utils/vscode-url-helper.test.ts+++ /dev/null@@ -1,61 +0,0 @@-import { describe, it, expect, beforeEach, afterEach } from "vitest";-import { transformVSCodeUrl } from "#/utils/vscode-url-helper";--describe("transformVSCodeUrl", () => {- const originalWindowLocation = window.location;-- beforeEach(() => {- // Mock window.location- Object.defineProperty(window, "location", {- value: {- hostname: "example.com",- },- writable: true,- });- });-- afterEach(() => {- // Restore window.location- Object.defineProperty(window, "location", {- value: originalWindowLocation,- writable: true,- });- });-- it("should return null if input is null", () => {- expect(transformVSCodeUrl(null)).toBeNull();- });-- it("should replace localhost with current hostname when they differ", () => {- const input = "http://localhost:8080/?tkn=abc123&folder=/workspace";- const expected = "http://example.com:8080/?tkn=abc123&folder=/workspace";-- expect(transformVSCodeUrl(input)).toBe(expected);- });-- it("should not modify URL if hostname is not localhost", () => {- const input = "http://otherhost:8080/?tkn=abc123&folder=/workspace";-- expect(transformVSCodeUrl(input)).toBe(input);- });-- it("should not modify URL if current hostname is also localhost", () => {- // Change the mocked hostname to localhost- Object.defineProperty(window, "location", {- value: {- hostname: "localhost",- },- writable: true,- });-- const input = "http://localhost:8080/?tkn=abc123&folder=/workspace";-- expect(transformVSCodeUrl(input)).toBe(input);- });-- it("should handle invalid URLs gracefully", () => {- const input = "not-a-valid-url";-- expect(transformVSCodeUrl(input)).toBe(input);- });-});diff --git a/config/defaults.json b/config/defaults.jsonindex ea12dc18c5..07f6df1e11 100644--- a/config/defaults.json+++ b/config/defaults.json@@ -15,18 +15,14 @@"ports": {"agentServer": 18000,"automation": 18001,- "proxy": 8000,- "_vscodeComment": "Port the bundled editor binds to inside the container; agent-server's own default. Only the Docker entrypoint reads this — the npm launchers derive the editor port from the agent-server port so several stacks can run side by side. It is never published: the editor is reached through paths.vscodeBasePath on the proxy port.",- "vscode": 8001+ "proxy": 8000},"paths": {"stateSubdir": "agent-canvas","conversations": "agent-canvas/conversations","bashEvents": "agent-canvas/bash_events","automationDb": "automation/automations.db",- "canvasBasePath": "/canvas",- "_vscodeBasePathComment": "Path prefix the bundled editor is served under, on the same origin as the canvas. Passed to agent-server as OH_VSCODE_BASE_PATH (it launches openvscode-server with --server-base-path and advertises the prefix in /api/vscode/url), and registered as an ingress route to the VSCode port. Keeping one value on both sides is what lets a single-origin deployment reach the editor without publishing a second port. Tradeoff: a path prefix routes but does not isolate, so the editor shares the canvas's browser origin and therefore its localStorage — see docs/SELF_HOSTING.md and OpenHands/OpenHands#16492.",- "vscodeBasePath": "/vscode"+ "canvasBasePath": "/canvas"},"packages": {"agentServer": "openhands-agent-server",diff --git a/docker/Dockerfile b/docker/Dockerfileindex 07c9a2eeea..8868d320b1 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -57,13 +57,11 @@ RUN node -e " \'CONFIG_AGENT_SERVER_PORT=' + c.ports.agentServer, \'CONFIG_AUTOMATION_PORT=' + c.ports.automation, \'CONFIG_PROXY_PORT=' + c.ports.proxy, \- 'CONFIG_VSCODE_PORT=' + c.ports.vscode, \'CONFIG_STATE_SUBDIR=' + c.paths.stateSubdir, \'CONFIG_CONVERSATIONS=' + c.paths.conversations, \'CONFIG_BASH_EVENTS=' + c.paths.bashEvents, \'CONFIG_AUTOMATION_DB=' + c.paths.automationDb, \'CONFIG_CANVAS_BASE_PATH=' + c.paths.canvasBasePath, \- 'CONFIG_VSCODE_BASE_PATH=' + c.paths.vscodeBasePath, \'CONFIG_POSTHOG_API_KEY=' + c.telemetry.posthogApiKey, \'CONFIG_POSTHOG_HOST=' + c.telemetry.posthogHost, \]; \diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex 92209cd092..118c92b711 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -89,85 +89,89 @@ AUTOMATION_PORT="${AUTOMATION_PORT:-${CONFIG_AUTOMATION_PORT:-18001}}"# independently would let `OH_VSCODE_BASE_PATH=/editor` move the editor without# moving the route, leaving the button pointing at a path the proxy never# serves.-# >>> vscode-config: this block is extracted and executed by+VSCODE_ROUTE_ARGS=()+# >>> canvas-base-path: this block is extracted and executed by# >>> __tests__/scripts/docker-vscode-route-sync.test.ts — keep the markers.-# The canvas mount is resolved here rather than alongside the ports above-# because the collision guard below compares the two prefixes: keeping both-# inside the extracted block is what lets that comparison be tested against the-# real defaults instead of only against values a test injects.-AGENT_CANVAS_BASE_PATH="${AGENT_CANVAS_BASE_PATH:-${CONFIG_CANVAS_BASE_PATH:-/canvas}}"-VSCODE_PORT="${OH_VSCODE_PORT:-${VSCODE_PORT:-${CONFIG_VSCODE_PORT:-8001}}}"-VSCODE_BASE_PATH="${OH_VSCODE_BASE_PATH:-${VSCODE_BASE_PATH:-${CONFIG_VSCODE_BASE_PATH:-/vscode}}}"--# Accept "editor", "/editor" and "/editor/" alike: agent-server strips the-# slashes when it builds the advertised URL, the static-server route table-# needs the leading one, so settle on one spelling rather than one per use site.+# Accept "canvas" and "/canvas/" alike: agent-server and both static-server+# instances normalize whatever they are handed, so this settles on one spelling+# for every consumer and keeps the collision guard below comparing the value the+# router will actually use.normalize_base_path() {local p="$1"while [ "${p#/}" != "$p" ]; do p="${p#/}"; donewhile [ "${p%/}" != "$p" ]; do p="${p%/}"; doneprintf '/%s' "$p"}-VSCODE_BASE_PATH="$(normalize_base_path "$VSCODE_BASE_PATH")"-if [ "$VSCODE_BASE_PATH" = "/" ]; then- log_error "VSCODE_BASE_PATH resolved to the site root — that would route the whole origin to the editor instead of the canvas. Set a prefix such as /vscode."- exit 1-fi--# The canvas mount gets the same treatment, for the same reason and with the-# same function. static-server normalizes whatever `--base-path` it is handed-# (`canvas` and `/canvas/` both mount at `/canvas`), so comparing a normalized-# editor prefix against a raw canvas one below would let `AGENT_CANVAS_BASE_PATH=canvas`-# with `OH_VSCODE_BASE_PATH=/canvas` past the collision guard and then land both-# on `/canvas` — where the editor route, registered after the SPA mount, takes-# the application over. Normalizing here rather than at the comparison keeps the-# value passed to `--base-path` further down identical to the one guarded.+# Resolved outside the editor guard on purpose: this value is consumed+# unconditionally further down (the `--base-path` arguments to both static-server+# instances and the reserved-route list) and this script runs under `set -u`, so+# leaving it unresolved aborts the entrypoint with "unbound variable" whenever+# the editor is disabled — the default.+AGENT_CANVAS_BASE_PATH="${AGENT_CANVAS_BASE_PATH:-${CONFIG_CANVAS_BASE_PATH:-/canvas}}"AGENT_CANVAS_BASE_PATH="$(normalize_base_path "$AGENT_CANVAS_BASE_PATH")"--# static-server keys its route table by prefix and the editor route is-# registered last, so a prefix that collides with an earlier route silently-# replaces it rather than failing: OH_VSCODE_BASE_PATH=/api would send every-# API call to the editor port. Reject collisions and anything that is not a-# plain single-segment path — '=' would be mis-split by the --route parser-# (it cuts at the first '='), and whitespace, '?', '#' or '..' have no-# meaningful reading as a route prefix.-VSCODE_PATH_SEGMENT="${VSCODE_BASE_PATH#/}"-case "$VSCODE_PATH_SEGMENT" in- */*)- log_error "VSCODE_BASE_PATH must be a single path segment (got '$VSCODE_BASE_PATH'). Use a prefix such as /vscode."- exit 1- ;;- .|..)- log_error "VSCODE_BASE_PATH must not be a relative path segment (got '$VSCODE_BASE_PATH'). Use a prefix such as /vscode."- exit 1- ;;- *[!A-Za-z0-9._-]*)- log_error "VSCODE_BASE_PATH may only contain letters, digits, '.', '_' and '-' (got '$VSCODE_BASE_PATH'). Use a prefix such as /vscode."- exit 1- ;;-esac-for reserved in /api /sockets /server_info /alive /health /ready /docs /redoc /openapi.json "${AGENT_CANVAS_BASE_PATH:-}"; do- if [ -n "$reserved" ] && [ "$VSCODE_BASE_PATH" = "$reserved" ]; then- log_error "VSCODE_BASE_PATH '$VSCODE_BASE_PATH' collides with an existing route and would take it over. Set a different prefix, such as /vscode."+# <<< canvas-base-path++if [ "${OH_CANVAS_ENABLE_VSCODE:-false}" = "true" ]; then+ # >>> vscode-config: this block is extracted and executed by+ # >>> __tests__/scripts/docker-vscode-route-sync.test.ts — keep the markers.+ VSCODE_PORT="${OH_VSCODE_PORT:-${VSCODE_PORT:-}}"+ VSCODE_BASE_PATH="${OH_VSCODE_BASE_PATH:-${VSCODE_BASE_PATH:-/vscode}}"++ # Accept "editor", "/editor" and "/editor/" alike: agent-server strips the+ # slashes when it builds the advertised URL, the static-server route table+ # needs the leading one, so settle on one spelling rather than one per use site.+ VSCODE_BASE_PATH="$(normalize_base_path "$VSCODE_BASE_PATH")"+ if [ "$VSCODE_BASE_PATH" = "/" ]; then+ log_error "VSCODE_BASE_PATH resolved to the site root — that would route the whole origin to the editor instead of the canvas. Set a prefix such as /vscode."exit 1fi-done-# The port ends up in a proxy target URL, so a non-numeric value fails at the-# first editor request instead of at startup. Catch it here.-case "$VSCODE_PORT" in- ''|*[!0-9]*)- log_error "VSCODE_PORT must be a number (got '$VSCODE_PORT')."- exit 1- ;;-esac+ # static-server keys its route table by prefix and the editor route is+ # registered last, so a prefix that collides with an earlier route silently+ # replaces it rather than failing: OH_VSCODE_BASE_PATH=/api would send every+ # API call to the editor port. Reject collisions and anything that is not a+ # plain single-segment path — '=' would be mis-split by the --route parser+ # (it cuts at the first '='), and whitespace, '?', '#' or '..' have no+ # meaningful reading as a route prefix.+ VSCODE_PATH_SEGMENT="${VSCODE_BASE_PATH#/}"+ case "$VSCODE_PATH_SEGMENT" in+ */*)+ log_error "VSCODE_BASE_PATH must be a single path segment (got '$VSCODE_BASE_PATH'). Use a prefix such as /vscode."+ exit 1+ ;;+ .|..)+ log_error "VSCODE_BASE_PATH must not be a relative path segment (got '$VSCODE_BASE_PATH'). Use a prefix such as /vscode."+ exit 1+ ;;+ *[!A-Za-z0-9._-]*)+ log_error "VSCODE_BASE_PATH may only contain letters, digits, '.', '_' and '-' (got '$VSCODE_BASE_PATH'). Use a prefix such as /vscode."+ exit 1+ ;;+ esac+ for reserved in /api /sockets /server_info /alive /health /ready /docs /redoc /openapi.json "${AGENT_CANVAS_BASE_PATH:-}"; do+ if [ -n "$reserved" ] && [ "$VSCODE_BASE_PATH" = "$reserved" ]; then+ log_error "VSCODE_BASE_PATH '$VSCODE_BASE_PATH' collides with an existing route and would take it over. Set a different prefix, such as /vscode."+ exit 1+ fi+ done-export OH_VSCODE_PORT="$VSCODE_PORT"-export OH_VSCODE_BASE_PATH="$VSCODE_BASE_PATH"-# The single route string every static-server instance registers. Derived from-# the exported pair above so the advertised URL and the route cannot diverge.-VSCODE_ROUTE="${VSCODE_BASE_PATH}=http://127.0.0.1:${VSCODE_PORT}"-# <<< vscode-config+ # The port ends up in a proxy target URL, so a non-numeric value fails at the+ # first editor request instead of at startup. Catch it here.+ case "$VSCODE_PORT" in+ ''|*[!0-9]*)+ log_error "VSCODE_PORT must be a number (got '$VSCODE_PORT')."+ exit 1+ ;;+ esac++ export OH_VSCODE_PORT="$VSCODE_PORT"+ export OH_VSCODE_BASE_PATH="$VSCODE_BASE_PATH"+ # The single route string every static-server instance registers. Derived from+ # the exported pair above so the advertised URL and the route cannot diverge.+ VSCODE_ROUTE="${VSCODE_BASE_PATH}=http://127.0.0.1:${VSCODE_PORT}"+ # <<< vscode-config+ VSCODE_ROUTE_ARGS=(--route "$VSCODE_ROUTE" --vscode-base-path "$VSCODE_BASE_PATH" --no-referrer-prefix "$VSCODE_BASE_PATH")+fi# Persistence paths — keep settings, conversations, bash history under a# single well-known directory that the VOLUME directive exposes.@@ -427,9 +431,7 @@ node /opt/agent-canvas/static-server.mjs \--route "/docs=http://127.0.0.1:${AGENT_SERVER_PORT}" \--route "/redoc=http://127.0.0.1:${AGENT_SERVER_PORT}" \--route "/openapi.json=http://127.0.0.1:${AGENT_SERVER_PORT}" \- --route "$VSCODE_ROUTE" \- --vscode-base-path "$VSCODE_BASE_PATH" \- --no-referrer-prefix "$VSCODE_BASE_PATH" &+ "${VSCODE_ROUTE_ARGS[@]}" &STATIC_PID=$!PIDS+=("$STATIC_PID")diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.mdindex c321a06334..f90fcbdadd 100644--- a/docs/DEVELOPMENT.md+++ b/docs/DEVELOPMENT.md@@ -35,8 +35,10 @@ Both modes still start the ingress proxy; the proxy only routes to the servicesThe dev stack uses `uvx` to run a temporary `agent-server`installation on `127.0.0.1:18000` and points the frontend at it. It isolates-conversation persistence by setting separate `OH_CONVERSATIONS_PATH`,-`OH_BASH_EVENTS_DIR`, and `OH_VSCODE_PORT` values under `.openhands-dev/`, and+conversation persistence by setting separate `OH_CONVERSATIONS_PATH` and+`OH_BASH_EVENTS_DIR` values under `.openhands-dev/`. The legacy bundled editor+is disabled by default; prefer installing the VS Code Canvas App. Set+`OH_CANVAS_ENABLE_VSCODE=true` only when testing legacy compatibility. The stackkeeps its tmux sockets under `~/.openhands/agent-canvas/tmux` (via`TMUX_TMPDIR`), so it does not collide with other local or cloud-backedOpenHands sessions. If `$HOME` is on a filesystem that does not support Unix@@ -212,7 +214,8 @@ client, then Canvas consumption of the client type. See the### Other useful overrides- `OH_CANVAS_SAFE_BACKEND_PORT` — backend port for the isolated server (default `18000`)-- `OH_CANVAS_SAFE_VSCODE_PORT` — VS Code sidecar port (default `backend port + 1`)+- `OH_CANVAS_ENABLE_VSCODE` — enable the legacy bundled editor (`false` by default; prefer the VS Code Canvas App)+- `OH_CANVAS_SAFE_VSCODE_PORT` — legacy editor port used only when `OH_CANVAS_ENABLE_VSCODE=true` (default `backend port + 1`)- `OH_CANVAS_SAFE_STATE_DIR` — base directory for isolated server state- `VITE_WORKING_DIR` — repo root used for new conversations (defaults to the current checkout)diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.mdindex 6adefbc04e..662fc185be 100644--- a/docs/SELF_HOSTING.md+++ b/docs/SELF_HOSTING.md@@ -93,15 +93,12 @@ to reach it from a browser without tunneling, you'll open ports 80 and 443in step 4.> [!NOTE]-> **The bundled editor shares the canvas's browser origin.** OpenVSCode is-> served under a path prefix (`/vscode` by default) on the proxy port rather-> than on a published port of its own — that is what keeps the deployment to a-> single port, but a path prefix routes requests, it does not isolate them.-> Script running anywhere on that origin, including editor content reached-> through an extension or a compromised asset, can read the canvas's-> `localStorage`, which holds the SESSION API key of _every_ backend registered-> in that browser. Tracked in-> [#16492](https://github.com/OpenHands/OpenHands/issues/16492).+> **Editor support is opt-in and default-off.** Prefer installing the VS Code+> Canvas App, which uses the managed App-backend bridge and a separate browser+> origin. `OH_CANVAS_ENABLE_VSCODE=true` enables the legacy bundled editor only+> for compatibility testing. That legacy route shares the Canvas browser origin+> (`/vscode` by default), so it does not provide the App bridge's origin+> isolation. Tracked in [#16492](https://github.com/OpenHands/OpenHands/issues/16492).## 3. Run Agent Canvasdiff --git a/scripts/check-translation-completeness.cjs b/scripts/check-translation-completeness.cjsindex d13df111e6..e8faae9335 100755--- a/scripts/check-translation-completeness.cjs+++ b/scripts/check-translation-completeness.cjs@@ -6,75 +6,73 @@* and that values are actually translated rather than English copied to every language.*/-const fs = require('fs');-const path = require('path');+const fs = require("fs");+const path = require("path");// Keys whose value is intentionally identical in every language (brand names,// protocol/technical terms, placeholder-only format strings). Add a key here// only when the English value is genuinely correct for all languages.const IDENTICAL_VALUE_ALLOWLIST = new Set([- 'ACTION_MESSAGE$ACP_TOOL',- 'API$TAVILY_KEY_EXAMPLE',- 'API$TVLY_KEY_EXAMPLE',- 'AUTOMATIONS$DOWNLOAD_TARBALL',- 'AUTOMATIONS$GIT_SYNC$BRANCH_PLACEHOLDER',- 'AUTOMATIONS$GIT_SYNC$PATH_PLACEHOLDER',- 'AUTOMATIONS$GIT_SYNC$REPO_URL_PLACEHOLDER',- 'BACKEND$CLOUD_TITLE',- 'BACKEND$VERSION_LABEL',- 'BRANDING$OPENHANDS',- 'COMMAND_MENU$SHORTCUT',- 'CONVERSATION$ACP_AGENT_GENERIC',- 'CONVERSATION$BUDGET_USAGE_FORMAT',- 'CONVERSATION$OVERVIEW_DIFF_ADDITIONS',- 'CONVERSATION$OVERVIEW_DIFF_DELETIONS',- 'CONVERSATION$OVERVIEW_GIT',- 'CONVERSATION$OVERVIEW_UNAVAILABLE',- 'CONVERSATION_PANEL$PREVIEW_GIT',- 'FILES$VSCODE',- 'GITHUB$AUTH_SCOPE',- 'LAUNCH$PLUGIN_PATH',- 'LAUNCH$PLUGIN_REF',- 'MCP$MCP_TAB',- 'SCHEMA$LLM$SECTION_LABEL',- 'SCHEMA$LLM$TOP_K$LABEL',- 'SCHEMA$LLM$TOP_P$LABEL',- 'SCHEMA$SECURITY_ANALYZER$CHOICE$LLM',- 'SCHEMA$VERIFICATION$SECURITY_ANALYZER$CHOICE$LLM',- 'SETTINGS$AGENT_SERVER_URL_PLACEHOLDER',- 'SETTINGS$AGENT_TYPE_OPENHANDS',- 'SETTINGS$APP_UPDATE_CARD_TITLE',- 'SETTINGS$AZURE_DEVOPS',- 'SETTINGS$CLOUD_SETTINGS_LINK',- 'SETTINGS$VERSION_DOCKER',- 'SETTINGS$VERSION_NPM_RECOMMENDED',- 'SETTINGS$VERSION_PRODUCT_NAME',- 'SETTINGS$GITHUB',- 'SETTINGS$GITLAB',- 'SETTINGS$MCP_AUTH_MODE_OAUTH',- 'SETTINGS$MCP_DEFAULT_CONFIG',- 'SETTINGS$MCP_HEADERS_PLACEHOLDER',- 'SETTINGS$MCP_OAUTH_CLIENT_ID_PLACEHOLDER',- 'SETTINGS$MCP_OAUTH_CLIENT_SECRET_PLACEHOLDER',- 'SETTINGS$MCP_OAUTH_SCOPES_PLACEHOLDER',- 'SETTINGS$MCP_SERVER_TYPE_SHTTP',- 'SETTINGS$MCP_SERVER_TYPE_SSE',- 'SETTINGS$MCP_SERVER_TYPE_STDIO',- 'SETTINGS$NAV_LLM',- 'SETTINGS$OPENHANDS_API_KEY_HELP_LINK',- 'SETTINGS$SKILLS_PILLS_MORE',- 'SETTINGS$SKILLS_VERSION',- 'SETTINGS$SLACK',- 'SETTINGS$TITLE_GENERATION_PROFILE_OPTION',- 'SETUP$REPOSITORY_PLACEHOLDER',- 'VSCODE$TITLE',- 'WORKSPACE$JUPYTER_TAB_LABEL',+ "ACTION_MESSAGE$ACP_TOOL",+ "API$TAVILY_KEY_EXAMPLE",+ "API$TVLY_KEY_EXAMPLE",+ "AUTOMATIONS$DOWNLOAD_TARBALL",+ "AUTOMATIONS$GIT_SYNC$BRANCH_PLACEHOLDER",+ "AUTOMATIONS$GIT_SYNC$PATH_PLACEHOLDER",+ "AUTOMATIONS$GIT_SYNC$REPO_URL_PLACEHOLDER",+ "BACKEND$CLOUD_TITLE",+ "BACKEND$VERSION_LABEL",+ "BRANDING$OPENHANDS",+ "COMMAND_MENU$SHORTCUT",+ "CONVERSATION$ACP_AGENT_GENERIC",+ "CONVERSATION$BUDGET_USAGE_FORMAT",+ "CONVERSATION$OVERVIEW_DIFF_ADDITIONS",+ "CONVERSATION$OVERVIEW_DIFF_DELETIONS",+ "CONVERSATION$OVERVIEW_GIT",+ "CONVERSATION$OVERVIEW_UNAVAILABLE",+ "CONVERSATION_PANEL$PREVIEW_GIT",+ "GITHUB$AUTH_SCOPE",+ "LAUNCH$PLUGIN_PATH",+ "LAUNCH$PLUGIN_REF",+ "MCP$MCP_TAB",+ "SCHEMA$LLM$SECTION_LABEL",+ "SCHEMA$LLM$TOP_K$LABEL",+ "SCHEMA$LLM$TOP_P$LABEL",+ "SCHEMA$SECURITY_ANALYZER$CHOICE$LLM",+ "SCHEMA$VERIFICATION$SECURITY_ANALYZER$CHOICE$LLM",+ "SETTINGS$AGENT_SERVER_URL_PLACEHOLDER",+ "SETTINGS$AGENT_TYPE_OPENHANDS",+ "SETTINGS$APP_UPDATE_CARD_TITLE",+ "SETTINGS$AZURE_DEVOPS",+ "SETTINGS$CLOUD_SETTINGS_LINK",+ "SETTINGS$VERSION_DOCKER",+ "SETTINGS$VERSION_NPM_RECOMMENDED",+ "SETTINGS$VERSION_PRODUCT_NAME",+ "SETTINGS$GITHUB",+ "SETTINGS$GITLAB",+ "SETTINGS$MCP_AUTH_MODE_OAUTH",+ "SETTINGS$MCP_DEFAULT_CONFIG",+ "SETTINGS$MCP_HEADERS_PLACEHOLDER",+ "SETTINGS$MCP_OAUTH_CLIENT_ID_PLACEHOLDER",+ "SETTINGS$MCP_OAUTH_CLIENT_SECRET_PLACEHOLDER",+ "SETTINGS$MCP_OAUTH_SCOPES_PLACEHOLDER",+ "SETTINGS$MCP_SERVER_TYPE_SHTTP",+ "SETTINGS$MCP_SERVER_TYPE_SSE",+ "SETTINGS$MCP_SERVER_TYPE_STDIO",+ "SETTINGS$NAV_LLM",+ "SETTINGS$OPENHANDS_API_KEY_HELP_LINK",+ "SETTINGS$SKILLS_PILLS_MORE",+ "SETTINGS$SKILLS_VERSION",+ "SETTINGS$SLACK",+ "SETTINGS$TITLE_GENERATION_PROFILE_OPTION",+ "SETUP$REPOSITORY_PLACEHOLDER",+ "WORKSPACE$JUPYTER_TAB_LABEL",]);// Extract the language codes from the AvailableLanguages array in the i18n index filefunction getSupportedLanguageCodes() {- const i18nIndexPath = path.join(__dirname, '../src/i18n/index.ts');- const i18nIndexContent = fs.readFileSync(i18nIndexPath, 'utf8');+ const i18nIndexPath = path.join(__dirname, "../src/i18n/index.ts");+ const i18nIndexContent = fs.readFileSync(i18nIndexPath, "utf8");const languageCodesRegex = /\{ label: "[^"]+", value: "([^"]+)" \}/g;const supportedLanguageCodes = [];@@ -95,7 +93,7 @@ function checkTranslations(translationJson, supportedLanguageCodes) {const untranslatedKeys = {};const nonEnglishLanguageCodes = supportedLanguageCodes.filter(- (langCode) => langCode !== 'en'+ (langCode) => langCode !== "en",);Object.entries(translationJson).forEach(([key, translations]) => {@@ -104,7 +102,7 @@ function checkTranslations(translationJson, supportedLanguageCodes) {// Find missing languages for this keyconst missing = supportedLanguageCodes.filter(- (langCode) => !availableLanguages.includes(langCode)+ (langCode) => !availableLanguages.includes(langCode),);if (missing.length > 0) {@@ -113,7 +111,7 @@ function checkTranslations(translationJson, supportedLanguageCodes) {// Find extra languages for this keyconst extra = availableLanguages.filter(- (langCode) => !supportedLanguageCodes.includes(langCode)+ (langCode) => !supportedLanguageCodes.includes(langCode),);if (extra.length > 0) {@@ -127,7 +125,7 @@ function checkTranslations(translationJson, supportedLanguageCodes) {!IDENTICAL_VALUE_ALLOWLIST.has(key) &&translations.en !== undefined &&nonEnglishLanguageCodes.every(- (langCode) => translations[langCode] === translations.en+ (langCode) => translations[langCode] === translations.en,)) {untranslatedKeys[key] = translations.en;@@ -145,7 +143,10 @@ module.exports = {if (require.main === module) {// Load the translation file- const translationJsonPath = path.join(__dirname, '../src/i18n/translation.json');+ const translationJsonPath = path.join(+ __dirname,+ "../src/i18n/translation.json",+ );const translationJson = require(translationJsonPath);const { missingTranslations, extraLanguages, untranslatedKeys } =@@ -158,44 +159,61 @@ if (require.main === module) {// Generate detailed error message if there are missing translationsif (Object.keys(missingTranslations).length > 0) {- console.error('\x1b[31m%s\x1b[0m', 'ERROR: Missing translations detected');- console.error(`Found ${Object.keys(missingTranslations).length} translation keys with missing languages:`);+ console.error("\x1b[31m%s\x1b[0m", "ERROR: Missing translations detected");+ console.error(+ `Found ${Object.keys(missingTranslations).length} translation keys with missing languages:`,+ );Object.entries(missingTranslations).forEach(([key, langs]) => {- console.error(`- Key "${key}" is missing translations for: ${langs.join(', ')}`);+ console.error(+ `- Key "${key}" is missing translations for: ${langs.join(", ")}`,+ );});- console.error('\nPlease add the missing translations before committing.');+ console.error("\nPlease add the missing translations before committing.");}// Generate detailed error message if there are extra languagesif (Object.keys(extraLanguages).length > 0) {- console.error('\x1b[31m%s\x1b[0m', 'ERROR: Extra languages detected');- console.error(`Found ${Object.keys(extraLanguages).length} translation keys with extra languages not in AvailableLanguages:`);+ console.error("\x1b[31m%s\x1b[0m", "ERROR: Extra languages detected");+ console.error(+ `Found ${Object.keys(extraLanguages).length} translation keys with extra languages not in AvailableLanguages:`,+ );Object.entries(extraLanguages).forEach(([key, langs]) => {- console.error(`- Key "${key}" has translations for unsupported languages: ${langs.join(', ')}`);+ console.error(+ `- Key "${key}" has translations for unsupported languages: ${langs.join(", ")}`,+ );});- console.error('\nPlease remove the extra languages before committing.');+ console.error("\nPlease remove the extra languages before committing.");}// Generate detailed error message if there are untranslated keysif (Object.keys(untranslatedKeys).length > 0) {- console.error('\x1b[31m%s\x1b[0m', 'ERROR: Untranslated keys detected');- console.error(`Found ${Object.keys(untranslatedKeys).length} translation keys where the English value is copied to every language:`);+ console.error("\x1b[31m%s\x1b[0m", "ERROR: Untranslated keys detected");+ console.error(+ `Found ${Object.keys(untranslatedKeys).length} translation keys where the English value is copied to every language:`,+ );Object.entries(untranslatedKeys).forEach(([key, value]) => {- console.error(`- Key "${key}" has the same value ("${value}") for all languages`);+ console.error(+ `- Key "${key}" has the same value ("${value}") for all languages`,+ );});- console.error('\nPlease translate the values before committing. If a value is intentionally identical in every language (brand name, technical term, format string), add the key to IDENTICAL_VALUE_ALLOWLIST in scripts/check-translation-completeness.cjs.');+ console.error(+ "\nPlease translate the values before committing. If a value is intentionally identical in every language (brand name, technical term, format string), add the key to IDENTICAL_VALUE_ALLOWLIST in scripts/check-translation-completeness.cjs.",+ );}// Exit with error code if there are issuesif (hasErrors) {process.exit(1);} else {- console.log('\x1b[32m%s\x1b[0m', 'All translation keys have complete language coverage!');+ console.log(+ "\x1b[32m%s\x1b[0m",+ "All translation keys have complete language coverage!",+ );}}diff --git a/scripts/dev-extra-backend.mjs b/scripts/dev-extra-backend.mjsindex b6588b5781..8b8cc1664a 100644--- a/scripts/dev-extra-backend.mjs+++ b/scripts/dev-extra-backend.mjs@@ -19,7 +19,6 @@ import {} from "./dev-process-utils.mjs";const DEFAULT_EXTRA_BACKEND_PORT = 18002;-const DEFAULT_EXTRA_VSCODE_PORT = 18003;const DEFAULT_WAIT_TIMEOUT_MS = 30_000;function parsePort(value, fallback) {@@ -53,10 +52,10 @@ export function buildExtraBackendConfig(env.OH_CANVAS_EXTRA_BACKEND_PORT,DEFAULT_EXTRA_BACKEND_PORT,);- const vscodePort = parsePort(- env.OH_CANVAS_EXTRA_VSCODE_PORT,- DEFAULT_EXTRA_VSCODE_PORT,- );+ const vscodePort =+ env.OH_CANVAS_ENABLE_VSCODE === "true"+ ? parsePort(env.OH_CANVAS_EXTRA_VSCODE_PORT, backendPort + 1)+ : null;return {...base,diff --git a/scripts/dev-safe.mjs b/scripts/dev-safe.mjsindex 29fe278c89..b61e887513 100644--- a/scripts/dev-safe.mjs+++ b/scripts/dev-safe.mjs@@ -38,11 +38,8 @@ const SHARED_DEFAULTS = JSON.parse();const DEFAULT_BACKEND_PORT = SHARED_DEFAULTS.ports.agentServer;-// Path prefix the bundled editor is served under. The same value has to reach-// agent-server (as OH_VSCODE_BASE_PATH, so openvscode-server is launched with-// --server-base-path and advertises the prefix) and the ingress route table,-// or the advertised URL and the route that serves it disagree.-export const VSCODE_BASE_PATH = SHARED_DEFAULTS.paths.vscodeBasePath;+export const VSCODE_BASE_PATH = "/vscode";+const VSCODE_ENABLED_ENV = "OH_CANVAS_ENABLE_VSCODE";const DEFAULT_VITE_PORT = 3001;const DEFAULT_WAIT_TIMEOUT_MS = 30_000;const DEFAULT_AGENT_SERVER_PACKAGE = SHARED_DEFAULTS.packages.agentServer;@@ -561,7 +558,10 @@ export function buildSafeDevConfig(cwd = process.cwd(), env = process.env) {env.OH_CANVAS_SAFE_BACKEND_PORT,DEFAULT_BACKEND_PORT,);- const vscodePort = parsePort(env.OH_CANVAS_SAFE_VSCODE_PORT, backendPort + 1);+ const vscodePort =+ env[VSCODE_ENABLED_ENV] === "true"+ ? parsePort(env.OH_CANVAS_SAFE_VSCODE_PORT, backendPort + 1)+ : null;return buildConfigFromPorts({ backendPort, vscodePort }, cwd, env);}@@ -594,16 +594,16 @@ export async function buildSafeDevConfigAsync(env.OH_CANVAS_SAFE_BACKEND_PORT,DEFAULT_BACKEND_PORT,);- const preferredVscodePort = parsePort(- env.OH_CANVAS_SAFE_VSCODE_PORT,- preferredBackendPort + 1,- );-- // Fail fast if any required port is already in use.- await assertPortsFree([- { name: "agent-server", port: preferredBackendPort },- { name: "vscode", port: preferredVscodePort },- ]);+ const preferredVscodePort =+ env[VSCODE_ENABLED_ENV] === "true"+ ? parsePort(env.OH_CANVAS_SAFE_VSCODE_PORT, preferredBackendPort + 1)+ : null;++ const requiredPorts = [{ name: "agent-server", port: preferredBackendPort }];+ if (preferredVscodePort) {+ requiredPorts.push({ name: "vscode", port: preferredVscodePort });+ }+ await assertPortsFree(requiredPorts);return buildConfigFromPorts({ backendPort: preferredBackendPort, vscodePort: preferredVscodePort },@@ -616,8 +616,8 @@ export async function buildSafeDevConfigAsync(* @typedef {object} SafeDevConfig* @property {string} cwd* @property {number} backendPort- * @property {number} vscodePort- * @property {string} vscodeBasePath+ * @property {number | null} vscodePort+ * @property {string | null} vscodeBasePath* @property {string} stateDir* @property {string} tmuxTmpDir* @property {string} conversationsPath@@ -676,7 +676,7 @@ function buildConfigFromPorts(ports, cwd, env) {cwd,backendPort,vscodePort,- vscodeBasePath: VSCODE_BASE_PATH,+ vscodeBasePath: vscodePort ? VSCODE_BASE_PATH : null,stateDir,// tmux socket directory. Defaults to <stateDir>/tmux (under// ~/.openhands/agent-canvas), matching where the rest of dev state lives@@ -823,7 +823,7 @@ export function buildAgentServerEnv(config, options = {}) {OH_PERSISTENCE_DIR: path.dirname(config.stateDir),OH_CONVERSATIONS_PATH: config.conversationsPath,OH_BASH_EVENTS_DIR: config.bashEventsDir,- OH_VSCODE_PORT: String(config.vscodePort),+ ...(config.vscodePort ? { OH_VSCODE_PORT: String(config.vscodePort) } : {}),// Serve the editor under a path prefix on the canvas origin rather than on// its own published port. agent-server passes this to openvscode-server as// --server-base-path and includes it in the URL from /api/vscode/url, whichdiff --git a/scripts/dev-static.mjs b/scripts/dev-static.mjsindex cf9163a9d5..8d19d0578a 100644--- a/scripts/dev-static.mjs+++ b/scripts/dev-static.mjs@@ -332,7 +332,9 @@ function startAgentServer(config) {...process.env,OH_CANVAS_SAFE_STATE_DIR: config.stateDir,OH_CANVAS_SAFE_BACKEND_PORT: config.agentServerPort.toString(),- OH_CANVAS_SAFE_VSCODE_PORT: config.vscodePort.toString(),+ ...(config.vscodePort+ ? { OH_CANVAS_SAFE_VSCODE_PORT: config.vscodePort.toString() }+ : {}),});const agentServerEnv = {diff --git a/scripts/dev-with-automation.mjs b/scripts/dev-with-automation.mjsindex d927eb02d5..6e47ccbc8a 100644--- a/scripts/dev-with-automation.mjs+++ b/scripts/dev-with-automation.mjs@@ -460,7 +460,8 @@ async function buildConfig(args, env = process.env) {logStep("ports", "Checking ports...");await assertPortsFree(requiredPorts);- const vscodePort = preferredBackendPort + 1000;+ const vscodePort =+ env.OH_CANVAS_ENABLE_VSCODE === "true" ? preferredBackendPort + 1000 : null;// API key — shared by both agent-server and automation backend.// Both validate it via the `X-Session-API-Key` header.@@ -474,7 +475,9 @@ async function buildConfig(args, env = process.env) {...env,OH_CANVAS_SAFE_STATE_DIR: stateDir,OH_CANVAS_SAFE_BACKEND_PORT: preferredBackendPort.toString(),- OH_CANVAS_SAFE_VSCODE_PORT: vscodePort.toString(),+ ...(vscodePort+ ? { OH_CANVAS_SAFE_VSCODE_PORT: vscodePort.toString() }+ : {}),});const sessionApiKey = safeConfig.sessionApiKey;@@ -948,7 +951,9 @@ function startAgentServer(config) {...process.env,OH_CANVAS_SAFE_STATE_DIR: config.stateDir,OH_CANVAS_SAFE_BACKEND_PORT: config.agentServerPort.toString(),- OH_CANVAS_SAFE_VSCODE_PORT: config.vscodePort.toString(),+ ...(config.vscodePort+ ? { OH_CANVAS_SAFE_VSCODE_PORT: config.vscodePort.toString() }+ : {}),});const agentServerEnv = {diff --git a/src/api/canvas-ui-client-tool.ts b/src/api/canvas-ui-client-tool.tsindex 168c83eab4..6ef5451645 100644--- a/src/api/canvas-ui-client-tool.ts+++ b/src/api/canvas-ui-client-tool.ts@@ -19,7 +19,7 @@ export interface ClientToolSpec {};}-const CANVAS_UI_DESCRIPTION = `The user is interacting with you inside Agent Canvas — a web UI with a chat panel on the left and a tabbed right-side panel (files, terminal, browser, vscode, planner, tasklist). This tool lets you drive that right-side panel so the user sees what you just produced.+const CANVAS_UI_DESCRIPTION = `The user is interacting with you inside Agent Canvas — a web UI with a chat panel on the left and a tabbed right-side panel (files, terminal, browser, planner, tasklist). This tool lets you drive that right-side panel so the user sees what you just produced.They will NOT see the files you wrote, the terminal output, or the browserunless you call this tool to switch the right-side panel to the relevant@@ -76,7 +76,7 @@ export const CANVAS_UI_CLIENT_TOOL: ClientToolSpec = {},tab: {type: "string",- enum: ["files", "browser", "vscode", "terminal", "planner", "tasklist"],+ enum: ["files", "browser", "terminal", "planner", "tasklist"],description: "Tab to open. Required for open_tab; ignored otherwise.",},},diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.tsindex 268c3884cd..4efc9b4a86 100644--- a/src/api/conversation-service/agent-server-conversation-service.api.ts+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts@@ -2,13 +2,11 @@ import {ConversationSortOrder,type ForkConversationRequest,type LLMConfig,- type VSCodeStatusResponse,} from "@openhands/typescript-client";import {ConversationClient,FileClient,ProfilesClient,- VSCodeClient,} from "@openhands/typescript-client/clients";import { v4 as uuidv4 } from "uuid";import { AgentKind, Provider } from "#/types/settings";@@ -44,7 +42,6 @@ import {toAppConversation,toConversationPage,} from "../agent-server-adapter";-import { GetVSCodeUrlResponse } from "../open-hands.types";import {getAgentServerClientOptions,NoBackendAvailableError,@@ -731,56 +728,6 @@ class AgentServerConversationService {return null;}- static async getVSCodeUrl(- conversationId: string,- conversationUrl: string | null | undefined,- sessionApiKey?: string | null,- ): Promise<GetVSCodeUrlResponse> {- // Local-only path. Cloud conversations read the VSCode URL straight- // from the cloud-computed `sandbox.exposed_urls` (see- // `useUnifiedVSCodeUrl` + `useCloudSandbox`); the runtime's own- // `/api/vscode/url` only knows its internal `localhost:8001`, which- // the user's browser can't reach.- const workspaceDir =- await this.resolveConversationWorkingDir(conversationId);- // Local mode: the typescript-client targets the local agent-server- // directly via the conversationUrl override.- const vscodeUrl = await new VSCodeClient(- getAgentServerClientOptions({- conversationId,- conversationUrl,- sessionApiKey,- }),- ).getUrl({- baseUrl:- typeof window !== "undefined" ? window.location.origin : undefined,- workspaceDir,- });-- return { vscode_url: vscodeUrl };- }-- /**- * Read the editor's capability state from the agent-server.- *- * `/api/vscode/status` answers 200 with `enabled: false` when the- * deployment set `enable_vscode: false`, which distinguishes "this- * deployment offers no editor" from a transport, auth, or server- * failure — `/api/vscode/url` answers 503 for the former and so- * cannot be told apart from the latter.- */- static async getVSCodeStatus(- conversationUrl: string | null | undefined,- sessionApiKey?: string | null,- ): Promise<VSCodeStatusResponse> {- return new VSCodeClient(- getAgentServerClientOptions({- conversationUrl,- sessionApiKey,- }),- ).getStatus();- }-static async resolveConversationWorkingDir(conversationId: string,): Promise<string> {diff --git a/src/api/conversation-service/conversation-service.api.ts b/src/api/conversation-service/conversation-service.api.tsindex 3cd6868a2a..4bd95f591e 100644--- a/src/api/conversation-service/conversation-service.api.ts+++ b/src/api/conversation-service/conversation-service.api.ts@@ -1,16 +1,10 @@-import { VSCodeClient } from "@openhands/typescript-client/clients";import { RemoteEventsList } from "@openhands/typescript-client/events/remote-events-list";import { uploadFilesToConversation } from "#/api/conversation-file-upload.api";import {- GetVSCodeUrlResponse,GetTrajectoryResponse,FileUploadSuccessResponse,} from "../open-hands.types";-import { getAgentServerWorkingDir } from "../agent-server-config";-import {- getAgentServerClientOptions,- getAgentServerHttpClientOptions,-} from "../agent-server-client-options";+import { getAgentServerHttpClientOptions } from "../agent-server-client-options";import { AppConversation } from "./agent-server-conversation-service.types";class ConversationService {@@ -38,25 +32,6 @@ class ConversationService {};}- static async getVSCodeUrl(- conversationId: string,- ): Promise<GetVSCodeUrlResponse> {- const workspaceDir =- this.currentConversation?.id === conversationId- ? (this.currentConversation?.workspace?.working_dir ??- getAgentServerWorkingDir())- : getAgentServerWorkingDir();- const vscodeUrl = await new VSCodeClient(- getAgentServerClientOptions(this.getClientOverrides(conversationId)),- ).getUrl({- baseUrl:- typeof window !== "undefined" ? window.location.origin : undefined,- workspaceDir,- });-- return { vscode_url: vscodeUrl };- }-static async getTrajectory(conversationId: string,): Promise<GetTrajectoryResponse> {diff --git a/src/api/open-hands.types.ts b/src/api/open-hands.types.tsindex e9796d6162..08272c18b6 100644--- a/src/api/open-hands.types.ts+++ b/src/api/open-hands.types.ts@@ -40,11 +40,6 @@ export interface Feedback {trajectory: unknown[];}-export interface GetVSCodeUrlResponse {- vscode_url: string | null;- error?: string;-}-export interface GetTrajectoryResponse {trajectory: unknown[] | null;error?: string;diff --git a/src/components/features/conversation-panel/conversation-card/conversation-card-actions.tsx b/src/components/features/conversation-panel/conversation-card/conversation-card-actions.tsxindex 10ed9d24d5..76df0f4373 100644--- a/src/components/features/conversation-panel/conversation-card/conversation-card-actions.tsx+++ b/src/components/features/conversation-panel/conversation-card/conversation-card-actions.tsx@@ -17,11 +17,9 @@ interface ConversationCardActionsProps {onStop?: (event: React.MouseEvent<HTMLButtonElement>) => void;onEdit?: (event: React.MouseEvent<HTMLButtonElement>) => void;onEditTags?: (event: React.MouseEvent<HTMLButtonElement>) => void;- onDownloadViaVSCode?: (event: React.MouseEvent<HTMLButtonElement>) => void;onDownloadConversation?: (event: React.MouseEvent<HTMLButtonElement>) => void;executionStatus?: ExecutionStatus | null;conversationId?: string;- showOptions?: boolean;}export function ConversationCardActions({@@ -33,11 +31,9 @@ export function ConversationCardActions({onStop,onEdit,onEditTags,- onDownloadViaVSCode,onDownloadConversation,executionStatus,conversationId,- showOptions,}: ConversationCardActionsProps) {const { t } = useTranslation("openhands");const isPaused = isExecutionPaused(executionStatus);@@ -121,9 +117,6 @@ export function ConversationCardActions({onStop={isActive ? onStop : undefined}onEdit={onEdit}onEditTags={onEditTags}- onDownloadViaVSCode={- conversationId && showOptions ? onDownloadViaVSCode : undefined- }onDownloadConversation={conversationId ? onDownloadConversation : undefined}diff --git a/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsx b/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsxindex e067fd01ad..6bc4d9e069 100644--- a/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsx+++ b/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsx@@ -27,7 +27,6 @@ interface ConversationCardContextMenuProps {onDisplayCost?: (event: React.MouseEvent<HTMLButtonElement>) => void;onShowAgentTools?: (event: React.MouseEvent<HTMLButtonElement>) => void;onShowSkills?: (event: React.MouseEvent<HTMLButtonElement>) => void;- onDownloadViaVSCode?: (event: React.MouseEvent<HTMLButtonElement>) => void;onDownloadConversation?: (event: React.MouseEvent<HTMLButtonElement>) => void;position?: "top" | "bottom";/**@@ -49,7 +48,6 @@ export function ConversationCardContextMenu({onDisplayCost,onShowAgentTools,onShowSkills,- onDownloadViaVSCode,onDownloadConversation,position = "bottom",floatingStyle,@@ -183,18 +181,6 @@ export function ConversationCardContextMenu({/></ContextMenuListItem>),- onDownloadViaVSCode && (- <ContextMenuListItem- key="download-vscode-button"- testId="download-vscode-button"- onClick={onDownloadViaVSCode}- >- <ConversationNameContextMenuIconText- icon={<DownloadIcon width={16} height={16} />}- text={t(I18nKey.BUTTON$DOWNLOAD_VIA_VSCODE)}- />- </ContextMenuListItem>- ),onDownloadConversation && (<ContextMenuListItemkey="download-trajectory-button"diff --git a/src/components/features/conversation-panel/conversation-card/conversation-card.tsx b/src/components/features/conversation-panel/conversation-card/conversation-card.tsxindex 7410d6a8b1..0460e32241 100644--- a/src/components/features/conversation-panel/conversation-card/conversation-card.tsx+++ b/src/components/features/conversation-panel/conversation-card/conversation-card.tsx@@ -1,11 +1,8 @@import React from "react";import { Pin } from "lucide-react";import { useTranslation } from "react-i18next";-import { useTracking } from "#/hooks/use-tracking";import { cn } from "#/utils/utils";import { I18nKey } from "#/i18n/declaration";-import { transformVSCodeUrl } from "#/utils/vscode-url-helper";-import ConversationService from "#/api/conversation-service/conversation-service.api";import { getDisplayConversationTags } from "#/api/agent-server-adapter";import { ExecutionStatus } from "#/types/agent-server/core/base/common";import { SandboxStatus } from "#/api/conversation-service/agent-server-conversation-service.types";@@ -101,7 +98,6 @@ export function ConversationCard({alwaysShowPinIcon = false,}: ConversationCardProps) {const { t } = useTranslation("openhands");- const { trackDownloadVsCodeButtonClicked } = useTracking();const [titleMode, setTitleMode] = React.useState<"view" | "edit">("view");const { mutateAsync: downloadConversation } = useDownloadConversation();@@ -158,32 +154,6 @@ export function ConversationCard({onContextMenuToggle?.(false);};- const handleDownloadViaVSCode = async (- event: React.MouseEvent<HTMLButtonElement>,- ) => {- event.preventDefault();- event.stopPropagation();- trackDownloadVsCodeButtonClicked();-- // Fetch the VS Code URL from the API- if (conversationId) {- try {- const data = await ConversationService.getVSCodeUrl(conversationId);- if (data.vscode_url) {- const transformedUrl = transformVSCodeUrl(data.vscode_url);- if (transformedUrl) {- window.open(transformedUrl, "_blank");- }- }- // VS Code URL not available- } catch {- // Failed to fetch VS Code URL- }- }-- onContextMenuToggle?.(false);- };-const handleDownloadConversation = async (event: React.MouseEvent<HTMLButtonElement>,) => {@@ -325,11 +295,9 @@ export function ConversationCard({onStop={onStop && handleStop}onEdit={onChangeTitle && handleEdit}onEditTags={onEditTags && handleEditTags}- onDownloadViaVSCode={handleDownloadViaVSCode}onDownloadConversation={handleDownloadConversation}executionStatus={executionStatus}conversationId={conversationId}- showOptions={showOptions}/></div><p@@ -353,11 +321,9 @@ export function ConversationCard({onStop={onStop && handleStop}onEdit={onChangeTitle && handleEdit}onEditTags={onEditTags && handleEditTags}- onDownloadViaVSCode={handleDownloadViaVSCode}onDownloadConversation={handleDownloadConversation}executionStatus={executionStatus}conversationId={conversationId}- showOptions={showOptions}/>) : null}</div>diff --git a/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx b/src/components/features/conversation/conversation-tabs/conversation-tabs.tsxindex b0235efbf5..dccda830ff 100644--- a/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx+++ b/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx@@ -16,7 +16,6 @@ import { cn } from "#/utils/utils";import { useConversationLocalStorageState } from "#/utils/conversation-local-storage";import { CONVERSATION_TAB_LABEL_KEYS } from "./conversation-tab-ids";import { ConversationTabNav } from "./conversation-tab-nav";-import { DrawerVSCodeLink } from "./drawer-vscode-link";import { ChatActionTooltip } from "../../chat/chat-action-tooltip";import { I18nKey } from "#/i18n/declaration";import { useConversationStore } from "#/stores/conversation-store";@@ -24,7 +23,6 @@ import { ConversationTabsContextMenu } from "./conversation-tabs-context-menu";import { useConversationId } from "#/hooks/use-conversation-id";import { useSelectConversationTab } from "#/hooks/use-select-conversation-tab";import { useTaskList } from "#/hooks/use-task-list";-import { useActiveBackend } from "#/contexts/active-backend-context";import { useHandleBuildPlanClick } from "#/hooks/use-handle-build-plan-click";import { useAgentState, usePlanningAgentState } from "#/hooks/use-agent-state";import { AgentState } from "#/types/agent-state";@@ -48,8 +46,6 @@ export function ConversationTabs({useConversationLocalStorageState(conversationId);const { hasTaskList } = useTaskList();- const { backend } = useActiveBackend();-const { handleBuildPlanClick } = useHandleBuildPlanClick();const { curAgentState } = useAgentState();const { isPlanningAgentRunning } = usePlanningAgentState();@@ -180,7 +176,6 @@ export function ConversationTabs({const tabsRowInnerRef = useRef<HTMLDivElement>(null);const measureRowRef = useRef<HTMLDivElement>(null);const menuRef = useRef<HTMLDivElement>(null);- const vscodeButtonRef = useRef<HTMLDivElement>(null);const anchorRef = useRef<HTMLButtonElement>(null);const [inlineTabCount, setInlineTabCount] = useState(visibleTabs.length);@@ -188,8 +183,7 @@ export function ConversationTabs({const rowInner = tabsRowInnerRef.current;const measureRow = measureRowRef.current;const menuEl = menuRef.current;- const vscodeEl = vscodeButtonRef.current;- if (!rowInner || !measureRow || !menuEl || !vscodeEl) return undefined;+ if (!rowInner || !measureRow || !menuEl) return undefined;const measure = () => {const measureButtons = measureRow.querySelectorAll<HTMLButtonElement>(@@ -213,14 +207,13 @@ export function ConversationTabs({}const menuWidth = menuEl.getBoundingClientRect().width;- const vscodeWidth = vscodeEl.getBoundingClientRect().width;const gapCss =getComputedStyle(rowInner).columnGap || getComputedStyle(rowInner).gap;const gapPx = parseFloat(gapCss) || 6;let nextCount = 0;for (let k = tabCount; k >= 0; k -= 1) {- let total = menuWidth + vscodeWidth;+ let total = menuWidth;for (let i = 0; i < k; i += 1) {total += widths[i] ?? 0;}@@ -240,18 +233,11 @@ export function ConversationTabs({if (typeof ResizeObserver === "undefined") return undefined;const ro = new ResizeObserver(measure);ro.observe(rowInner);- // The editor button's presence is resolved asynchronously (the hook probes- // /api/vscode/status), and it sits inside an `ml-auto shrink-0` wrapper, so- // it appearing or disappearing does not change `rowInner`'s own box and- // would not otherwise re-measure. Its width is folded into the fit- // calculation above, so a stale value permanently costs an inline tab.- ro.observe(vscodeEl);return () => ro.disconnect();}, [unpinnedSignature,visibleTabs.length,hasTaskList,- backend.kind,selectedTab,isRightPanelShown,i18n.language,@@ -424,11 +410,6 @@ export function ConversationTabs({</div></div></div>- {/* The ref'd wrapper must stay mounted — the overflow measurement- effect above bails if it's missing. */}- <div ref={vscodeButtonRef} className="ml-auto shrink-0 pr-1">- <DrawerVSCodeLink />- </div></div></div>{isTabActive("planner") && (diff --git a/src/components/features/conversation/conversation-tabs/drawer-vscode-link.tsx b/src/components/features/conversation/conversation-tabs/drawer-vscode-link.tsxdeleted file mode 100644index 12cb652fda..0000000000--- a/src/components/features/conversation/conversation-tabs/drawer-vscode-link.tsx+++ /dev/null@@ -1,59 +0,0 @@-import { ExternalLink } from "lucide-react";-import { useTranslation } from "react-i18next";-import VSCodeIcon from "#/icons/vscode.svg?react";-import { I18nKey } from "#/i18n/declaration";-import { useAgentState } from "#/hooks/use-agent-state";-import { useUnifiedVSCodeUrl } from "#/hooks/query/use-unified-vscode-url";-import { RUNTIME_STARTING_STATES } from "#/types/agent-state";-import { cn } from "#/utils/utils";--export function DrawerVSCodeLink() {- const { t } = useTranslation("openhands");- const { curAgentState } = useAgentState();- const { data, refetch, isLoading, isUnavailable } = useUnifiedVSCodeUrl();- const isRuntimeStarting = RUNTIME_STARTING_STATES.includes(curAgentState);-- const handleClick = async () => {- let vscodeUrl = data?.url;-- if (!vscodeUrl) {- const result = await refetch();- vscodeUrl = result.data?.url ?? null;- }-- if (vscodeUrl) {- window.open(vscodeUrl, "_blank", "noopener,noreferrer");- }- };-- // Backends that report no editor to open — `enable_vscode: false`, a- // configured editor whose process is not running, or no URL reported — get- // no button rather than one that does nothing when clicked.- if (isUnavailable) {- return null;- }-- return (- <button- type="button"- onClick={handleClick}- disabled={isLoading || isRuntimeStarting}- aria-label={t(I18nKey.VSCODE$OPEN)}- title={t(I18nKey.VSCODE$OPEN)}- data-testid="drawer-vscode-link"- className={cn(- "inline-flex items-center gap-1.5 rounded-[7px] border border-border bg-base-secondary px-2 py-1 text-xs",- "text-muted transition-colors hover:enabled:bg-surface-raised hover:enabled:text-contrast",- "cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",- )}- >- <VSCodeIcon className="h-3.75 w-3.75 shrink-0" aria-hidden />- <span>{t(I18nKey.FILES$VSCODE)}</span>- <ExternalLink- className="h-3.5 w-3.5 shrink-0"- aria-hidden- strokeWidth={2}- />- </button>- );-}diff --git a/src/hooks/mutation/conversation-mutation-utils.ts b/src/hooks/mutation/conversation-mutation-utils.tsindex 32d929650b..42eca462d2 100644--- a/src/hooks/mutation/conversation-mutation-utils.ts+++ b/src/hooks/mutation/conversation-mutation-utils.ts@@ -181,5 +181,4 @@ export const invalidateConversationQueries = (queryClient.invalidateQueries({queryKey: ["v1-batch-get-app-conversations"],});- queryClient.invalidateQueries({ queryKey: ["unified", "vscode_url"] });};diff --git a/src/hooks/mutation/use-resume-conversation.ts b/src/hooks/mutation/use-resume-conversation.tsindex c2d74e2ab4..933ea0d9ed 100644--- a/src/hooks/mutation/use-resume-conversation.ts+++ b/src/hooks/mutation/use-resume-conversation.ts@@ -32,7 +32,6 @@ export const useResumeConversation = () => {queryClient.invalidateQueries({queryKey: ["v1-batch-get-app-conversations"],});- queryClient.invalidateQueries({ queryKey: ["unified", "vscode_url"] });},});};diff --git a/src/hooks/query/use-unified-vscode-url.ts b/src/hooks/query/use-unified-vscode-url.tsdeleted file mode 100644index fc9a570d42..0000000000--- a/src/hooks/query/use-unified-vscode-url.ts+++ /dev/null@@ -1,211 +0,0 @@-import { useQuery } from "@tanstack/react-query";-import type { VSCodeStatusResponse } from "@openhands/typescript-client";-import { useTranslation } from "react-i18next";-import { useConversationId } from "#/hooks/use-conversation-id";-import { I18nKey } from "#/i18n/declaration";-import ConversationService from "#/api/conversation-service/conversation-service.api";-import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";-import { transformVSCodeUrl } from "#/utils/vscode-url-helper";-import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";-import { useActiveConversation } from "#/hooks/query/use-active-conversation";-import { useActiveBackend } from "#/contexts/active-backend-context";-import { useCloudSandbox } from "#/hooks/query/use-cloud-sandbox";-import {- getOriginVSCodeBasePath,- isVSCodeUrlServedByOrigin,-} from "#/utils/vscode-origin";--interface VSCodeUrlResult {- url: string | null;-}--const VSCODE_EXPOSED_URL_NAME = "VSCODE";--export const useUnifiedVSCodeUrl = () => {- const { t } = useTranslation("openhands");- const { conversationId } = useConversationId();- const runtimeIsReady = useRuntimeIsReady({ allowAgentError: true });- const { data: conversation } = useActiveConversation();- const active = useActiveBackend();-- const conversationUrl = conversation?.conversation_url ?? null;- const sessionApiKey = conversation?.session_api_key ?? null;- const sandboxId = conversation?.sandbox_id ?? null;- const isCloud = active.backend.kind === "cloud";-- // The origin half of the availability question. The agent-server will- // happily report an editor this page has no route to — see- // `#/utils/vscode-origin`. `null` means this origin serves no editor, in- // which case there is nothing to probe for and nothing to render.- const originBasePath = getOriginVSCodeBasePath();- const originServesEditor = originBasePath !== null;-- // Cloud mode: read VSCode URL from the cloud-computed `exposed_urls` on- // the conversation's sandbox. The runtime's `/api/vscode/url` only- // knows its internal `localhost:8001`, so calling it returned a URL- // the user's browser couldn't reach.- const cloudSandboxQuery = useCloudSandbox(isCloud ? sandboxId : null);-- // Capability probe. `/api/vscode/status` answers 200 with- // `enabled: false` when the deployment set `enable_vscode: false`, so a- // deliberately editor-less deployment is a value here rather than an- // error — unlike `/api/vscode/url`, which answers 503 and is therefore- // indistinguishable from an auth, proxy, or server failure.- //- // Gating the URL request on this means a disabled editor never issues- // the 503 in the first place, so the global error toast needs no- // blanket suppression and genuine failures stay observable.- const statusQuery = useQuery<VSCodeStatusResponse>({- queryKey: [- "unified",- "vscode_status",- "local",- conversationId,- conversationUrl,- sessionApiKey,- ],- queryFn: () =>- AgentServerConversationService.getVSCodeStatus(- conversationUrl,- sessionApiKey,- ),- enabled:- !isCloud && originServesEditor && runtimeIsReady && !!conversationId,- refetchOnMount: true,- });-- // `enabled: false` is the deployment switch. `running: false` alongside- // `enabled: true` means the process failed to start or has died: the- // agent-server awaits `VSCodeService.start()` in its lifespan before it- // serves any request, so this is a terminal state rather than a startup- // window we would be racing.- const editorIsAvailable =- statusQuery.data?.enabled === true && statusQuery.data?.running === true;-- const localQuery = useQuery<VSCodeUrlResult>({- // Include conversation host + key in the cache key so different- // conversations don't share VSCode URL data.- queryKey: [- "unified",- "vscode_url",- "local",- conversationId,- conversationUrl,- sessionApiKey,- ],- queryFn: async () => {- if (!conversationId) throw new Error("No conversation ID");-- const response = await AgentServerConversationService.getVSCodeUrl(- conversationId,- conversationUrl,- sessionApiKey,- ).catch(() => ConversationService.getVSCodeUrl(conversationId));-- return { url: transformVSCodeUrl(response.vscode_url) };- },- enabled:- !isCloud &&- originServesEditor &&- runtimeIsReady &&- !!conversationId &&- editorIsAvailable,- refetchOnMount: true,- retry: 3,- });-- let data: VSCodeUrlResult | undefined;- let isLoading: boolean;- let isError: boolean;- let isSuccess: boolean;- let status: typeof localQuery.status;- let error: unknown;- let refetch: () => Promise<{ data: VSCodeUrlResult | undefined }>;- // True once we know there is nothing to open, so callers can render nothing- // instead of a control whose activation is a no-op.- let isUnavailable: boolean;-- if (isCloud) {- const sandbox = cloudSandboxQuery.data;- const exposedUrl =- sandbox?.exposed_urls?.find((u) => u.name === VSCODE_EXPOSED_URL_NAME)- ?.url ?? null;- data = cloudSandboxQuery.isSuccess- ? { url: transformVSCodeUrl(exposedUrl) }- : undefined;- isLoading = cloudSandboxQuery.isLoading;- isError = cloudSandboxQuery.isError;- isSuccess = cloudSandboxQuery.isSuccess;- status = cloudSandboxQuery.status;- error = cloudSandboxQuery.error;- refetch = async () => {- const result = await cloudSandboxQuery.refetch();- const refreshedUrl =- result.data?.exposed_urls?.find(- (u) => u.name === VSCODE_EXPOSED_URL_NAME,- )?.url ?? null;- return {- data: result.data- ? { url: transformVSCodeUrl(refreshedUrl) }- : undefined,- };- };- // Cloud behavior is deliberately unchanged: a sandbox with no VSCODE- // entry in `exposed_urls` still surfaces the control. Narrowing this- // change to self-hosted keeps its blast radius off the cloud path.- isUnavailable = false;- } else {- data = localQuery.data;- // The URL request only starts once the capability probe has cleared it,- // so the control is "loading" for the probe as well — otherwise it would- // look ready while there is still nothing to open.- isLoading = statusQuery.isLoading || localQuery.isLoading;- isError = statusQuery.isError || localQuery.isError;- isSuccess = localQuery.isSuccess;- status = localQuery.status;- error = statusQuery.error ?? localQuery.error;- refetch = async () => {- // Load-bearing and easy to misread: this fires a real request even when- // the probe failed and left the URL query `enabled: false`. An observer's- // own `refetch()` does not consult `enabled` — only- // `queryClient.refetchQueries` skips disabled queries — so a click after- // a failed probe still retries rather than silently doing nothing.- const result = await localQuery.refetch();- return { data: result.data };- };- // Hide only on an explicit, terminal capability answer:- // - this origin serves no editor at all, so nothing it advertises is- // reachable from this page,- // - the probe succeeded and reports no usable editor (disabled, or- // enabled but not running),- // - the editor is there but reports no URL to open, or- // - the URL resolves somewhere this origin does not route the editor —- // an extra backend with no prefix of its own hands back the canvas- // root, which would open this app again instead of an editor.- // A failed probe is deliberately not "unavailable": transport, auth and- // server faults stay visible as query errors with their normal retry and- // toast, rather than silently removing the control.- isUnavailable =- !originServesEditor ||- (statusQuery.isSuccess && !editorIsAvailable) ||- (isSuccess && !localQuery.data?.url) ||- (isSuccess &&- !isVSCodeUrlServedByOrigin(localQuery.data?.url, originBasePath));- }-- // Derive the i18n'd "URL unavailable" message outside `queryFn` so the- // queryKey doesn't have to include `t`.- const errorMessage =- data && !data.url ? t(I18nKey.VSCODE$URL_NOT_AVAILABLE) : null;-- return {- data: data ? { ...data, error: errorMessage } : undefined,- error,- isLoading,- isError,- isSuccess,- isUnavailable,- status,- refetch,- };-};diff --git a/src/hooks/use-tracking.ts b/src/hooks/use-tracking.tsindex 03a94dc76e..2590ca5b42 100644--- a/src/hooks/use-tracking.ts+++ b/src/hooks/use-tracking.ts@@ -233,10 +233,6 @@ export const useTracking = () => {});};- const trackDownloadVsCodeButtonClicked = () => {- track("download_via_vscode_button_clicked");- };-const trackSettingsSaved = ({llmModel,llmApiKeySet,@@ -475,7 +471,6 @@ export const useTracking = () => {trackAutomationSetupFailed,trackInitialQuerySubmitted,trackUserMessageSent,- trackDownloadVsCodeButtonClicked,trackSettingsSaved,trackMcpConfigUpdated,trackDownloadTrajectoryButtonClicked,diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 70604beefb..98191c341d 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -8414,142 +8414,6 @@"uk": "Недійсний шлях до файлу. Перевірте ім'я файлу та спробуйте ще раз.","ca": "Ruta de fitxer no vàlida. Comproveu el nom del fitxer i torneu-ho a intentar."},- "VSCODE$OPEN": {- "en": "Open in VS Code",- "ja": "VS Codeで開く",- "zh-CN": "在VS Code中打开",- "zh-TW": "在 VS Code 中開啟",- "ko-KR": "VS Code에서 열기",- "de": "In VS Code öffnen",- "no": "Åpne i VS Code",- "it": "Apri in VS Code",- "pt": "Abrir no VS Code",- "es": "Abrir en VS Code",- "ar": "فتح في VS Code",- "fr": "Ouvrir dans VS Code",- "tr": "VS Code'da aç",- "uk": "Відкрити у VS Code",- "ca": "Obre a VS Code"- },- "VSCODE$TITLE": {- "en": "VS Code",- "ja": "VS Code",- "zh-CN": "VS Code",- "zh-TW": "VS Code",- "ko-KR": "VS Code",- "de": "VS Code",- "no": "VS Code",- "it": "VS Code",- "pt": "VS Code",- "es": "VS Code",- "ar": "VS Code",- "fr": "VS Code",- "tr": "VS Code",- "uk": "VS Code",- "ca": "VS Code"- },- "VSCODE$LOADING": {- "en": "Loading VS Code...",- "ja": "VS Codeを読み込み中...",- "zh-CN": "正在加载VS Code...",- "zh-TW": "正在加載VS Code...",- "ko-KR": "VS Code 로딩 중...",- "de": "VS Code wird geladen...",- "no": "Laster VS Code...",- "it": "Caricamento di VS Code...",- "pt": "Carregando VS Code...",- "es": "Cargando VS Code...",- "ar": "جاري تحميل VS Code...",- "fr": "Chargement de VS Code...",- "tr": "VS Code yükleniyor...",- "uk": "Завантажую VS Code...",- "ca": "Carregant VS Code..."- },- "VSCODE$URL_NOT_AVAILABLE": {- "en": "VS Code URL not available",- "ja": "VS Code URLが利用できません",- "zh-CN": "VS Code URL不可用",- "zh-TW": "VS Code URL不可用",- "ko-KR": "VS Code URL을 사용할 수 없습니다",- "de": "VS Code URL nicht verfügbar",- "no": "VS Code URL ikke tilgjengelig",- "it": "URL di VS Code non disponibile",- "pt": "URL do VS Code não disponível",- "es": "URL de VS Code no disponible",- "ar": "رابط VS Code غير متوفر",- "fr": "URL VS Code non disponible",- "tr": "VS Code URL'si mevcut değil",- "uk": "VS Code URL недоступний",- "ca": "URL de VS Code no disponible"- },- "VSCODE$FETCH_ERROR": {- "en": "Failed to fetch VS Code URL",- "ja": "VS Code URLの取得に失敗しました",- "zh-CN": "获取VS Code URL失败",- "zh-TW": "獲取VS Code URL失敗",- "ko-KR": "VS Code URL을 가져오지 못했습니다",- "de": "Fehler beim Abrufen der VS Code URL",- "no": "Kunne ikke hente VS Code URL",- "it": "Impossibile recuperare l'URL di VS Code",- "pt": "Falha ao buscar URL do VS Code",- "es": "Error al obtener la URL de VS Code",- "ar": "فشل في جلب رابط VS Code",- "fr": "Échec de la récupération de l'URL VS Code",- "tr": "VS Code URL'si alınamadı",- "uk": "Не вдалося отримати VS Code URL",- "ca": "No s'ha pogut obtenir la URL de VS Code"- },- "VSCODE$CROSS_ORIGIN_WARNING": {- "en": "The code editor cannot be embedded due to browser security restrictions. Cross-origin cookies are being blocked.",- "ja": "ブラウザのセキュリティ制限により、コードエディタを埋め込むことができません。クロスオリジンCookieがブロックされています。",- "zh-CN": "由于浏览器安全限制,无法嵌入代码编辑器。跨源Cookie被阻止。",- "zh-TW": "由於瀏覽器安全限制,無法嵌入代碼編輯器。跨源Cookie被阻止。",- "ko-KR": "브라우저 보안 제한으로 인해 코드 편집기를 삽입할 수 없습니다. 교차 출처 쿠키가 차단되고 있습니다.",- "de": "Der Code-Editor kann aufgrund von Browser-Sicherheitsbeschränkungen nicht eingebettet werden. Cross-Origin-Cookies werden blockiert.",- "no": "Koderedigereren kan ikke bygges inn på grunn av nettleserens sikkerhetsbegrensninger. Cross-origin cookies blir blokkert.",- "it": "L'editor di codice non può essere incorporato a causa delle restrizioni di sicurezza del browser. I cookie cross-origin vengono bloccati.",- "pt": "O editor de código não pode ser incorporado devido a restrições de segurança do navegador. Cookies de origem cruzada estão sendo bloqueados.",- "es": "El editor de código no se puede incrustar debido a las restricciones de seguridad del navegador. Las cookies de origen cruzado están siendo bloqueadas.",- "ar": "لا يمكن تضمين محرر التعليمات البرمجية بسبب قيود أمان المتصفح. يتم حظر ملفات تعريف الارتباط عبر المصدر.",- "fr": "L'éditeur de code ne peut pas être intégré en raison des restrictions de sécurité du navigateur. Les cookies cross-origin sont bloqués.",- "tr": "Tarayıcı güvenlik kısıtlamaları nedeniyle kod düzenleyici yerleştirilemiyor. Çapraz kaynaklı çerezler engelleniyor.",- "uk": "Редактор коду не може бути вбудований через обмеження безпеки браузера. Блокуються файли cookie з різних джерел.",- "ca": "L'editor de codi no es pot incrustar a causa de les restriccions de seguretat del navegador. Les galetes d'origen creuat estan bloquejades."- },- "VSCODE$URL_PARSE_ERROR": {- "en": "Error parsing URL",- "ja": "URLの解析エラー",- "zh-CN": "URL解析错误",- "zh-TW": "URL解析錯誤",- "ko-KR": "URL 구문 분석 오류",- "de": "Fehler beim Parsen der URL",- "no": "Feil ved parsing av URL",- "it": "Errore durante l'analisi dell'URL",- "pt": "Erro ao analisar URL",- "es": "Error al analizar URL",- "ar": "خطأ في تحليل عنوان URL",- "fr": "Erreur d'analyse de l'URL",- "tr": "URL ayrıştırma hatası",- "uk": "Помилка аналізу URL",- "ca": "Error en analitzar la URL"- },- "VSCODE$OPEN_IN_NEW_TAB": {- "en": "Open in New Tab",- "ja": "新しいタブで開く",- "zh-CN": "在新标签页中打开",- "zh-TW": "在新標籤頁中打開",- "ko-KR": "새 탭에서 열기",- "de": "In neuem Tab öffnen",- "no": "Åpne i ny fane",- "it": "Apri in una nuova scheda",- "pt": "Abrir em nova aba",- "es": "Abrir en nueva pestaña",- "ar": "فتح في علامة تبويب جديدة",- "fr": "Ouvrir dans un nouvel onglet",- "tr": "Yeni Sekmede Aç",- "uk": "Відкрити в новій вкладці",- "ca": "Obre en una pestanya nova"- },"INCREASE_TEST_COVERAGE": {"en": "Increase test coverage","ja": "テストカバレッジを向上",@@ -11678,23 +11542,6 @@"uk": "Редагувати заголовок","ca": "Edita el títol"},- "BUTTON$DOWNLOAD_VIA_VSCODE": {- "en": "Download via VS Code",- "ja": "VS Code経由でダウンロード",- "zh-CN": "通过VS Code下载",- "zh-TW": "透過VS Code下載",- "ko-KR": "VS Code를 통해 다운로드",- "fr": "Télécharger via VS Code",- "es": "Descargar a través de VS Code",- "de": "Über VS Code herunterladen",- "it": "Scarica tramite VS Code",- "pt": "Baixar via VS Code",- "ar": "تحميل عبر VS Code",- "no": "Last ned via VS Code",- "tr": "VS Code ile İndir",- "uk": "Завантажити через VS Code",- "ca": "Descarrega via VS Code"- },"BUTTON$DISPLAY_COST": {"en": "Display Usage and Cost","ja": "使用量とコストを表示",@@ -26264,23 +26111,6 @@"uk": "Відкрити в новому вікні","ca": "Obre en una finestra nova"},- "FILES$VSCODE": {- "en": "VSCode",- "ja": "VSCode",- "zh-CN": "VSCode",- "zh-TW": "VSCode",- "ko-KR": "VSCode",- "no": "VSCode",- "it": "VSCode",- "pt": "VSCode",- "es": "VSCode",- "ar": "VSCode",- "fr": "VSCode",- "tr": "VSCode",- "de": "VSCode",- "uk": "VSCode",- "ca": "VSCode"- },"FILES$REFRESH": {"en": "Refresh files","ja": "ファイルを更新",diff --git a/src/mocks/conversation-handlers.ts b/src/mocks/conversation-handlers.tsindex 5e5e3def1b..744599e3b1 100644--- a/src/mocks/conversation-handlers.ts+++ b/src/mocks/conversation-handlers.ts@@ -477,8 +477,6 @@ export const CONVERSATION_HANDLERS = [HttpResponse.json({ response: "Mock agent response" }),),- http.get("*/api/vscode/url", async () => HttpResponse.json({ url: null })),-http.post("*/api/skills", async () => HttpResponse.json({ skills: [] })),http.post(diff --git a/src/utils/vscode-origin.ts b/src/utils/vscode-origin.tsdeleted file mode 100644index c12a4cab60..0000000000--- a/src/utils/vscode-origin.ts+++ /dev/null@@ -1,109 +0,0 @@-/**- * Whether *this browser origin* can serve the editor, and whether a given- * editor URL is one it will actually route.- *- * Editor availability is not a property of the agent-server process alone. The- * agent-server answers `/api/vscode/status` for whatever conversation you ask- * about, and builds `/api/vscode/url` from the `base_url` the caller sends —- * which is always `window.location.origin`. So a server can truthfully report- * an editor that the page's own origin has no route to. Two supported layouts- * hit that:- *- * - **Public mode** (`docker/entrypoint.sh`, `--auth-required`): a second- * static server on its own port, sharing the same agent-server but- * deliberately without the editor route, because the editor's connection- * token is the session API key (OpenHands/software-agent-sdk#4317) and that- * origin exists to test the *unauthenticated* case.- * - **Extra backends** (`scripts/dev-extra-backend.mjs`): a second- * agent-server registered from a browser whose origin belongs to another- * stack. That origin's editor route, if any, points at the *bundled*- * stack's editor — a different container's workspace.- *- * In both cases a control gated only on the server probe renders and then- * resolves to the canvas SPA or, worse, someone else's workspace. So the- * frontend has to intersect the server's capability with the origin's route- * table, and this module is the origin half of that.- */--const VSCODE_BASE_PATH_WINDOW_KEY = "__AGENT_CANVAS_VSCODE_BASE_PATH__";--/**- * The path prefix this origin serves the editor under, or `null` if it serves- * no editor at all.- *- * Two sources, in order — mirroring `getRawRuntimeServicesInfo` in- * `agent-server-adapter.ts`:- * 1. `VITE_VSCODE_BASE_PATH` — baked in at build time by the dev launchers- * that proxy the editor (`npm run dev`, dev:static).- * 2. `window.__AGENT_CANVAS_VSCODE_BASE_PATH__` — injected into index.html at- * serve time by `scripts/static-server.mjs --vscode-base-path <path>`,- * which refuses to start unless a matching `--route` exists. That is the- * path used by static builds (the Docker image, the published binary),- * where the env var is empty in the prebuilt bundle.- *- * Absent from both means "this origin does not serve the editor" and the- * control is hidden. That is the pre-existing behavior for every local backend,- * so a deployment this cannot detect is no worse off than before.- */-export function getOriginVSCodeBasePath(): string | null {- const envRaw = import.meta.env.VITE_VSCODE_BASE_PATH?.trim();- if (envRaw) return normalizePrefix(envRaw);-- if (typeof window !== "undefined") {- const injected = (window as unknown as Record<string, unknown>)[- VSCODE_BASE_PATH_WINDOW_KEY- ];- if (typeof injected === "string" && injected.trim()) {- return normalizePrefix(injected.trim());- }- }-- return null;-}--function normalizePrefix(value: string): string {- const withLeadingSlash = value.startsWith("/") ? value : `/${value}`;- return withLeadingSlash.length > 1- ? withLeadingSlash.replace(/\/+$/, "")- : withLeadingSlash;-}--/**- * Whether `url` is an editor URL this origin will actually route.- *- * The agent-server appends its own `vscode_base_path` to the origin we send it,- * so the returned URL carries the prefix of the server that answered — not- * necessarily the prefix this origin routes. An extra backend that configures- * no prefix yields `<origin>/?tkn=…`, which is the canvas root: same origin,- * wrong destination. Comparing paths is what separates the two.- */-export function isVSCodeUrlServedByOrigin(- url: string | null | undefined,- basePath: string | null,-): boolean {- if (!url || !basePath) return false;-- let parsed: URL;- try {- parsed = new URL(- url,- typeof window !== "undefined" ? window.location.href : undefined,- );- } catch {- return false;- }-- // A cross-origin URL is somebody else's problem to route, not ours to vouch- // for. The local path always builds on `window.location.origin`, so this only- // fires on a value we did not construct.- if (- typeof window !== "undefined" &&- parsed.origin !== window.location.origin- ) {- return false;- }-- return (- parsed.pathname === basePath || parsed.pathname.startsWith(`${basePath}/`)- );-}diff --git a/src/utils/vscode-url-helper.ts b/src/utils/vscode-url-helper.tsdeleted file mode 100644index 21f32a66a8..0000000000--- a/src/utils/vscode-url-helper.ts+++ /dev/null@@ -1,31 +0,0 @@-/**- * Helper function to transform VS Code URLs- *- * This function checks if a VS Code URL points to localhost and replaces it with- * the current window's hostname if they don't match.- *- * @param vsCodeUrl The original VS Code URL from the backend- * @returns The transformed URL with the correct hostname- */-export function transformVSCodeUrl(vsCodeUrl: string | null): string | null {- if (!vsCodeUrl) return null;-- try {- const url = new URL(vsCodeUrl);-- // Check if the URL points to localhost- if (- url.hostname === "localhost" &&- window.location.hostname !== "localhost"- ) {- // Replace localhost with the current hostname- url.hostname = window.location.hostname;- return url.toString();- }-- return vsCodeUrl;- } catch {- // Silently handle the error and return the original URL- return vsCodeUrl;- }-}