Skip to content

🙌 OpenHands: AI-Driven Development

feat(mars): connect Agent Canvas to DigitalOcean Managed Agents (desktop and web) (#17838)

amandhawed77be9cfa46
diff --git a/.env.sample b/.env.sample
index 1d67deead8..87917b496f 100644
--- a/.env.sample
+++ b/.env.sample
@@ -23,6 +23,15 @@ VITE_INSECURE_SKIP_VERIFY="false" # Skip TLS certificate verification for proxie
# VITE_POSTHOG_API_KEY="phc_..."
# VITE_DO_NOT_TRACK="1" # Disable all telemetry, including anonymous install counts
+# DigitalOcean Managed Agents: the Electron desktop app, and the web build when
+# its server runs with MARS_WEB=1. `npm run desktop` does not read this file —
+# export these in the shell that launches it; `npm run dev` does. Defaults come
+# from the `mars` block in config/defaults.json.
+# MARS_WEB="1" # Web build: host the DigitalOcean bridge in the dev/static server
+# MARS_TOKEN="" # Web build: personal access token to sign in with at server start (credentials are otherwise in-memory and lost on restart)
+# DO_OAUTH_CLIENT_ID="" # Desktop only: public client ID of a DigitalOcean OAuth app with redirect URI http://127.0.0.1:53682/callback. Unset = personal access tokens only.
+# MARS_API_BASE_URL="https://api.digitalocean.com" # Point at a staging harness API
+
# Mocking / test helpers
VITE_MOCK_API="false" # Enable/disable API mocking with MSW
diff --git a/.pr/digitalocean-screenshots/do-agents.png b/.pr/digitalocean-screenshots/do-agents.png
new file mode 100644
index 0000000000..ab30532fa0
Binary files /dev/null and b/.pr/digitalocean-screenshots/do-agents.png differ
diff --git a/.pr/digitalocean-screenshots/do-sizes-open.png b/.pr/digitalocean-screenshots/do-sizes-open.png
new file mode 100644
index 0000000000..a9166ad756
Binary files /dev/null and b/.pr/digitalocean-screenshots/do-sizes-open.png differ
diff --git a/AGENTS.md b/AGENTS.md
index 32caa015f7..f12993fd67 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -85,3 +85,7 @@ Use the `e2e-testing` skill for suite selection and E2E-specific requirements.
- Spec files live under `specs/`. Keep spec IDs stable and mark deprecated specs with strikethrough rather than renumbering them.
- Tag implementation code and tests with `// @spec BM-002 — Short title` comments immediately above the relevant block so coverage remains grep-able.
- Follow `.agents/skills/release.md` for release automation. Never hand-edit a release-please branch.
+
+## DigitalOcean Managed Agents
+
+Before changing `scripts/mars-*` / `scripts/tunnel-*`, `src/api/mars/`, the Managed Agents UI (`src/components/features/backends/managed-agents/`) or the MARS hooks, read `src/api/mars/AGENTS.md`.
diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.ts
index 9a179ffef7..5440453461 100644
--- a/__tests__/api/agent-server-conversation-service.test.ts
+++ b/__tests__/api/agent-server-conversation-service.test.ts
@@ -971,6 +971,21 @@ describe("AgentServerConversationService", () => {
);
});
+ it("reports ids the agent-server does not have as not found instead of malformed", async () => {
+ mockHttpGet.mockResolvedValue({
+ data: [null, { id: "conv-present", title: "Present" }],
+ });
+
+ const conversations =
+ await AgentServerConversationService.batchGetAppConversations([
+ "conv-gone",
+ "conv-present",
+ ]);
+
+ expect(conversations[0]).toBeNull();
+ expect(conversations[1]).toMatchObject({ id: "conv-present" });
+ });
+
it("preserves sandbox_status from batchGetAppConversations response", async () => {
mockHttpGet.mockResolvedValue({
data: [
diff --git a/__tests__/api/mars-sandbox-setup.test.ts b/__tests__/api/mars-sandbox-setup.test.ts
new file mode 100644
index 0000000000..361e02e05a
--- /dev/null
+++ b/__tests__/api/mars-sandbox-setup.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const executeCommand = vi.hoisted(() => vi.fn());
+const getSettings = vi.hoisted(() => vi.fn());
+const updateSettings = vi.hoisted(() => vi.fn(async () => ({})));
+const waitForMarsAgentServer = vi.hoisted(() => vi.fn(async () => "1.53.0"));
+
+vi.mock("@openhands/typescript-client/clients", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@openhands/typescript-client/clients")
+ >()),
+ BashClient: vi.fn(function BashClient() {
+ return { executeCommand };
+ }),
+ SettingsClient: vi.fn(function SettingsClient() {
+ return { getSettings, updateSettings };
+ }),
+}));
+vi.mock("#/api/mars/mars-tunnel-backend", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#/api/mars/mars-tunnel-backend")>()),
+ waitForMarsAgentServer,
+}));
+
+import {
+ ENSURE_SECRET_KEY_SCRIPT,
+ MARS_SANDBOX_TOOLS,
+ prepareMarsSandbox,
+} from "#/api/mars/mars-sandbox-setup";
+
+const HOST = "http://127.0.0.1:51000";
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.clearAllMocks();
+});
+
+describe("prepareMarsSandbox", () => {
+ it("waits for the restarted server and moves the terminal off tmux", async () => {
+ // Arrange
+ vi.useFakeTimers();
+ executeCommand.mockResolvedValue({ stdout: "restarting\n" });
+ getSettings.mockResolvedValue({ agent_settings: { tools: null } });
+
+ // Act
+ const done = prepareMarsSandbox(HOST, "sess_1");
+ await vi.runAllTimersAsync();
+ await done;
+
+ // Assert
+ expect(executeCommand).toHaveBeenCalledWith(
+ expect.objectContaining({ command: ENSURE_SECRET_KEY_SCRIPT }),
+ );
+ expect(waitForMarsAgentServer).toHaveBeenCalledWith(HOST, {
+ sessionId: "sess_1",
+ });
+ expect(updateSettings).toHaveBeenCalledWith({
+ agent_settings_diff: { tools: MARS_SANDBOX_TOOLS },
+ });
+ });
+
+ it("leaves a ready sandbox and an explicit tool list alone", async () => {
+ executeCommand.mockResolvedValue({ stdout: "ready\n" });
+ getSettings.mockResolvedValue({
+ agent_settings: { tools: [{ name: "terminal", params: {} }] },
+ });
+
+ await prepareMarsSandbox(HOST, "sess_1");
+
+ expect(waitForMarsAgentServer).not.toHaveBeenCalled();
+ expect(updateSettings).not.toHaveBeenCalled();
+ });
+
+ it("never blocks connecting when the sandbox cannot be prepared", async () => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ executeCommand.mockRejectedValue(new Error("bash endpoint gone"));
+
+ await expect(prepareMarsSandbox(HOST, "sess_1")).resolves.toBeUndefined();
+ expect(updateSettings).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/api/mars-web-bridge.test.ts b/__tests__/api/mars-web-bridge.test.ts
new file mode 100644
index 0000000000..f2794d5525
--- /dev/null
+++ b/__tests__/api/mars-web-bridge.test.ts
@@ -0,0 +1,159 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import {
+ MarsWebBridgeError,
+ createMarsWebBridge,
+ installMarsWebBridge,
+ probeMarsWebBridge,
+} from "#/api/mars/mars-web-bridge";
+
+const sessionApiKey = vi.hoisted(() => ({ value: null as string | null }));
+vi.mock("#/api/agent-server-config", () => ({
+ getAgentServerHeaders: (): Record<string, string> =>
+ sessionApiKey.value ? { "X-Session-API-Key": sessionApiKey.value } : {},
+}));
+
+function jsonResponse(status: number, body: unknown): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ delete window.marsBridge;
+ sessionApiKey.value = null;
+});
+
+describe("createMarsWebBridge", () => {
+ it("turns each bridge call into one POST /mars/rpc/<method> carrying the arguments", async () => {
+ const fetchImpl = vi.fn(async () =>
+ jsonResponse(200, { result: { sessions: [], nextPageToken: null } }),
+ );
+ const bridge = createMarsWebBridge(
+ "",
+ fetchImpl as unknown as typeof fetch,
+ );
+
+ const page = await bridge.listConfigSessions("cfg_1", { pageSize: 5 });
+
+ expect(fetchImpl).toHaveBeenCalledWith("/mars/rpc/listConfigSessions", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ args: ["cfg_1", { pageSize: 5 }] }),
+ });
+ expect(page).toEqual({ sessions: [], nextPageToken: null });
+ });
+
+ it("reads the sandbox size catalog over RPC", async () => {
+ const sizes = [{ slug: "mars-2vcpu-4gb", vcpus: 2, memory_mb: 4096 }];
+ const fetchImpl = vi.fn(async () => jsonResponse(200, { result: sizes }));
+ const bridge = createMarsWebBridge(
+ "",
+ fetchImpl as unknown as typeof fetch,
+ );
+
+ expect(await bridge.listSandboxSizes()).toEqual(sizes);
+ expect(fetchImpl).toHaveBeenCalledWith(
+ "/mars/rpc/listSandboxSizes",
+ expect.objectContaining({ body: JSON.stringify({ args: [] }) }),
+ );
+ });
+
+ it("raises the server's error message and status", async () => {
+ const fetchImpl = vi.fn(async () =>
+ jsonResponse(401, {
+ error: { message: "Sign in to DigitalOcean first.", status: 401 },
+ }),
+ );
+ const bridge = createMarsWebBridge(
+ "",
+ fetchImpl as unknown as typeof fetch,
+ );
+
+ await expect(bridge.listSessions()).rejects.toMatchObject({
+ name: "MarsWebBridgeError",
+ message: "Sign in to DigitalOcean first.",
+ status: 401,
+ });
+ });
+
+ it("sends the page's session key on every call so the server can admit it", async () => {
+ sessionApiKey.value = "sk-page";
+ const fetchImpl = vi.fn(async () => jsonResponse(200, { result: null }));
+ const bridge = createMarsWebBridge(
+ "",
+ fetchImpl as unknown as typeof fetch,
+ );
+
+ await bridge.pauseSession("s1");
+
+ expect(fetchImpl).toHaveBeenCalledWith("/mars/rpc/pauseSession", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-Session-API-Key": "sk-page",
+ },
+ body: JSON.stringify({ args: ["s1"] }),
+ });
+ });
+
+ it("never offers OAuth", async () => {
+ const bridge = createMarsWebBridge("", vi.fn() as unknown as typeof fetch);
+ await expect(bridge.signInWithOAuth()).rejects.toBeInstanceOf(
+ MarsWebBridgeError,
+ );
+ });
+});
+
+describe("probeMarsWebBridge / installMarsWebBridge", () => {
+ it("reports whether the server hosts the bridge", async () => {
+ const ok = vi.fn(async () => jsonResponse(200, { ok: true }));
+ const missing = vi.fn(async () => new Response("", { status: 404 }));
+ // A server that answers every path with index.html is a 200 too.
+ const spa = vi.fn(
+ async () =>
+ new Response("<!doctype html><title>Canvas</title>", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ }),
+ );
+ const down = vi.fn(async () => {
+ throw new TypeError("Failed to fetch");
+ });
+
+ expect(await probeMarsWebBridge("", ok as unknown as typeof fetch)).toBe(
+ true,
+ );
+ expect(
+ await probeMarsWebBridge("", missing as unknown as typeof fetch),
+ ).toBe(false);
+ expect(await probeMarsWebBridge("", spa as unknown as typeof fetch)).toBe(
+ false,
+ );
+ expect(await probeMarsWebBridge("", down as unknown as typeof fetch)).toBe(
+ false,
+ );
+ });
+
+ it("installs window.marsBridge only when the server answers, and leaves an existing bridge alone", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response("", { status: 404 })),
+ );
+ expect(await installMarsWebBridge()).toBe(false);
+ expect(window.marsBridge).toBeUndefined();
+
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => jsonResponse(200, { ok: true })),
+ );
+ expect(await installMarsWebBridge()).toBe(true);
+ expect(window.marsBridge).toBeDefined();
+
+ const electronBridge = window.marsBridge;
+ expect(await installMarsWebBridge()).toBe(false);
+ expect(window.marsBridge).toBe(electronBridge);
+ });
+});
diff --git a/__tests__/components/automations/recommended-automations.test.tsx b/__tests__/components/automations/recommended-automations.test.tsx
index 32411b9c54..298b405b08 100644
--- a/__tests__/components/automations/recommended-automations.test.tsx
+++ b/__tests__/components/automations/recommended-automations.test.tsx
@@ -935,6 +935,56 @@ describe("recommended automations", () => {
await waitFor(() => expect(mockNavigate).toHaveBeenCalledTimes(1));
});
+ it("does not list automations in the rail when no automation service answers", async () => {
+ // Earlier cases unstub globals, including the ResizeObserver the rail needs.
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+
+ unobserve() {}
+
+ disconnect() {}
+ },
+ );
+ // Arrange
+ const checkHealth = vi
+ .spyOn(AutomationService, "checkHealth")
+ .mockResolvedValue({ status: "error" });
+ const getAutomations = vi.spyOn(AutomationService, "getAutomations");
+
+ // Act
+ renderLauncher({ variant: "rail" });
+
+ // Assert
+ await waitFor(() => expect(checkHealth).toHaveBeenCalled());
+ expect(getAutomations).not.toHaveBeenCalled();
+ });
+
+ it("lists automations in the rail once the automation service is healthy", async () => {
+ // Earlier cases unstub globals, including the ResizeObserver the rail needs.
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+
+ unobserve() {}
+
+ disconnect() {}
+ },
+ );
+ vi.spyOn(AutomationService, "checkHealth").mockResolvedValue({
+ status: "ok",
+ });
+ const getAutomations = vi
+ .spyOn(AutomationService, "getAutomations")
+ .mockResolvedValue({ automations: [], total: 0 });
+
+ renderLauncher({ variant: "rail" });
+
+ await waitFor(() => expect(getAutomations).toHaveBeenCalled());
+ });
+
it("shows the recommended automations section on cloud backends", async () => {
setRegisteredBackends([cloudBackend]);
setActiveSelection({ backendId: cloudBackend.id });
@@ -1222,6 +1272,9 @@ describe("recommended automations", () => {
disconnect() {}
},
);
+ vi.spyOn(AutomationService, "checkHealth").mockResolvedValue({
+ status: "ok",
+ });
vi.spyOn(AutomationService, "getAutomations").mockResolvedValue({
automations: [
{
@@ -1245,16 +1298,19 @@ describe("recommended automations", () => {
expect(
screen.queryByTestId("recommended-automations-section"),
).not.toBeInTheDocument();
- expect(
- screen.queryByTestId(
- "recommended-automation-rail-card-github-pr-reviewer",
- ),
- ).not.toBeInTheDocument();
- expect(
- screen.getByTestId(
- "recommended-automation-rail-card-slack-standup-digest",
- ),
- ).toBeInTheDocument();
+ // Installed automations load only after the health check succeeds.
+ await waitFor(() => {
+ expect(
+ screen.getByTestId(
+ "recommended-automation-rail-card-slack-standup-digest",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId(
+ "recommended-automation-rail-card-github-pr-reviewer",
+ ),
+ ).not.toBeInTheDocument();
+ });
});
it("launches the recommendation after the missing MCP is installed", async () => {
diff --git a/__tests__/components/backends/add-backend-modal.test.tsx b/__tests__/components/backends/add-backend-modal.test.tsx
index 4c924bd091..50fd4f6cc8 100644
--- a/__tests__/components/backends/add-backend-modal.test.tsx
+++ b/__tests__/components/backends/add-backend-modal.test.tsx
@@ -121,8 +121,10 @@ describe("AddBackendModal – connection chooser", () => {
expect(
within(tabs[0]).getByTestId("add-backend-option-cloud-logo"),
).toBeInTheDocument();
- expect(tabs[0]).toHaveTextContent("BACKEND$CLOUD_OPTION_DESCRIPTION");
- expect(tabs[1]).toHaveTextContent(
+ expect(tabs[0]).toHaveAccessibleDescription(
+ "BACKEND$CLOUD_OPTION_DESCRIPTION",
+ );
+ expect(tabs[1]).toHaveAccessibleDescription(
"BACKEND$AGENT_SERVER_OPTION_DESCRIPTION",
);
@@ -566,3 +568,246 @@ describe("AddBackendModal – analytics", () => {
expect(backendAddedCalls).toHaveLength(1);
});
});
+
+describe("AddBackendModal – DigitalOcean", () => {
+ const CONNECTION = {
+ id: "conn_1",
+ kind: "pat" as const,
+ label: "My team",
+ teamName: "Acme",
+ expiresAt: null,
+ isExpired: false,
+ };
+
+ function fakeMarsBridge({ signedIn }: { signedIn: boolean }) {
+ let active = signedIn ? CONNECTION : null;
+ const authState = () => ({
+ connections: active ? [active] : [],
+ active,
+ isPersistent: true,
+ canUseOAuth: false,
+ });
+ const configs: { id: string; name: string; agent: string | null }[] = [
+ { id: "cfg_oh", name: "Web agent", agent: "openhands" },
+ { id: "cfg_cc", name: "Claude agent", agent: "claude-code" },
+ { id: "cfg_legacy", name: "cursor-github-test", agent: null },
+ ];
+ const configSessions = [
+ {
+ session_id: "sess_1",
+ name: "fix-login",
+ status: "SESSION_STATUS_READY",
+ config_id: "cfg_oh",
+ },
+ ];
+ const bridge = {
+ getAuthState: vi.fn(async () => authState()),
+ savePat: vi.fn(async () => {
+ active = CONNECTION;
+ return authState();
+ }),
+ listAgentConfigs: vi.fn(async () => ({
+ configs: [...configs],
+ nextPageToken: null,
+ })),
+ listConfigSessions: vi.fn(async (configId: string) => ({
+ sessions: configSessions.filter((s) => s.config_id === configId),
+ nextPageToken: null,
+ })),
+ listSandboxSizes: vi.fn(async () => []),
+ createOpenHandsAgent: vi.fn(async ({ name }: { name: string }) => {
+ const config = { id: "cfg_new", name, agent: "openhands" };
+ configs.push(config);
+ return config;
+ }),
+ createSession: vi.fn(async (configId: string, name: string) => ({
+ session_id: "sess_new",
+ name,
+ status: "SESSION_STATUS_READY",
+ config_id: configId,
+ })),
+ listSessions: vi.fn(async () => ({
+ sessions: [
+ {
+ session_id: "sess_codex",
+ status: "SESSION_STATUS_READY",
+ agent_kind: "AGENT_KIND_CODEX_CLI",
+ },
+ {
+ session_id: "sess_legacy",
+ status: "SESSION_STATUS_READY",
+ config_id: "cfg_legacy",
+ },
+ ],
+ nextPageToken: null,
+ })),
+ openTunnel: vi.fn(async ({ sessionId }: { sessionId: string }) => ({
+ sessionId,
+ status: "connected" as const,
+ remotePort: 8000,
+ localPort: 51001,
+ error: undefined,
+ })),
+ getTunnel: vi.fn(async () => undefined),
+ closeTunnel: vi.fn(async () => {}),
+ };
+ window.marsBridge = bridge as unknown as NonNullable<
+ typeof window.marsBridge
+ >;
+ return bridge;
+ }
+
+ afterEach(() => {
+ delete window.marsBridge;
+ });
+
+ it("opens the provider flow and returns to the catalog without connecting", async () => {
+ // Arrange
+ const bridge = fakeMarsBridge({ signedIn: false });
+ const user = userEvent.setup();
+ renderWithProviders(<AddBackendModal onClose={vi.fn()} />);
+
+ // Act
+ await user.click(screen.getByTestId("add-backend-option-providers"));
+ await user.click(screen.getByTestId("add-backend-provider-digitalocean"));
+ await screen.findByTestId("managed-agents-token");
+ await user.click(screen.getByTestId("add-backend-providers-back"));
+
+ // Assert
+ expect(
+ screen.getByTestId("add-backend-provider-digitalocean"),
+ ).toBeVisible();
+ expect(screen.getByTestId("add-backend-option-providers")).toHaveAttribute(
+ "aria-selected",
+ "true",
+ );
+ expect(screen.queryByTestId("managed-agents-token")).toBeNull();
+ expect(bridge.openTunnel).not.toHaveBeenCalled();
+ });
+
+ it("signs in with a token and lists only the team's OpenHands agents", async () => {
+ // Arrange
+ fakeMarsBridge({ signedIn: false });
+ const user = userEvent.setup();
+ renderWithProviders(<AddBackendModal onClose={vi.fn()} />);
+
+ // Act
+ await user.click(screen.getByTestId("add-backend-option-providers"));
+ await user.click(screen.getByTestId("add-backend-provider-digitalocean"));
+ await user.type(
+ await screen.findByTestId("managed-agents-token"),
+ `dop_v1_${"a".repeat(64)}`,
+ );
+ await user.click(screen.getByTestId("managed-agents-token-submit"));
+
+ // Assert
+ expect(
+ await screen.findByTestId("digitalocean-agent-cfg_oh"),
+ ).toBeInTheDocument();
+ expect(screen.queryByTestId("digitalocean-agent-cfg_cc")).toBeNull();
+ expect(screen.queryByTestId("digitalocean-agent-cfg_legacy")).toBeNull();
+ expect(screen.queryByText("sess_codex")).toBeNull();
+ expect(screen.queryByText("sess_legacy")).toBeNull();
+ });
+
+ it("opening an agent resumes its latest session and closes the modal", async () => {
+ // Arrange
+ const bridge = fakeMarsBridge({ signedIn: true });
+ const onClose = vi.fn();
+ const navigate = vi.fn();
+ renderWithProviders(<AddBackendModal onClose={onClose} />, {
+ currentPath: "/",
+ conversationId: null,
+ isNavigating: false,
+ navigate,
+ });
+
+ // Act
+ await userEvent.click(screen.getByTestId("add-backend-option-providers"));
+ await userEvent.click(
+ screen.getByTestId("add-backend-provider-digitalocean"),
+ );
+ await userEvent.click(
+ await screen.findByTestId("digitalocean-agent-open-cfg_oh"),
+ );
+
+ // Assert
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ expect(bridge.openTunnel).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionId: "sess_1" }),
+ );
+ expect(navigate).toHaveBeenCalledWith(
+ expect.stringContaining("/conversations"),
+ );
+ });
+
+ it("New Agent creates an OpenHands agent and launches its first session", async () => {
+ // Arrange
+ const bridge = fakeMarsBridge({ signedIn: true });
+ const onClose = vi.fn();
+ const user = userEvent.setup();
+ renderWithProviders(<AddBackendModal onClose={onClose} />);
+ await user.click(screen.getByTestId("add-backend-option-providers"));
+ await user.click(screen.getByTestId("add-backend-provider-digitalocean"));
+
+ // Act
+ await user.click(await screen.findByTestId("digitalocean-new-agent"));
+ const nameInput = screen.getByTestId("digitalocean-new-agent-name");
+ await user.clear(nameInput);
+ await user.type(nameInput, "team-agent");
+ await user.click(screen.getByTestId("digitalocean-new-agent-submit"));
+
+ // Assert
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ expect(bridge.createOpenHandsAgent).toHaveBeenCalledWith({
+ name: "team-agent",
+ size: undefined,
+ });
+ expect(bridge.createSession).toHaveBeenCalledWith(
+ "cfg_new",
+ expect.stringMatching(/^team-agent-/),
+ );
+ expect(bridge.openTunnel).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionId: "sess_new" }),
+ );
+ });
+
+ it("expanding an agent lists its sessions and opens the chosen one", async () => {
+ // Arrange
+ const bridge = fakeMarsBridge({ signedIn: true });
+ bridge.listConfigSessions.mockResolvedValue({
+ sessions: [
+ {
+ session_id: "sess_1",
+ name: "fix-login",
+ status: "SESSION_STATUS_READY",
+ config_id: "cfg_oh",
+ },
+ {
+ session_id: "sess_2",
+ name: "refactor-api",
+ status: "SESSION_STATUS_PAUSED",
+ config_id: "cfg_oh",
+ },
+ ],
+ nextPageToken: null,
+ });
+ const onClose = vi.fn();
+ const user = userEvent.setup();
+ renderWithProviders(<AddBackendModal onClose={onClose} />);
+ await user.click(screen.getByTestId("add-backend-option-providers"));
+ await user.click(screen.getByTestId("add-backend-provider-digitalocean"));
+
+ // Act
+ await user.click(
+ await screen.findByTestId("digitalocean-agent-toggle-cfg_oh"),
+ );
+ await user.click(screen.getByTestId("digitalocean-session-sess_2"));
+
+ // Assert
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ expect(bridge.openTunnel).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionId: "sess_2" }),
+ );
+ });
+});
diff --git a/__tests__/components/backends/digitalocean-new-agent-form.test.tsx b/__tests__/components/backends/digitalocean-new-agent-form.test.tsx
new file mode 100644
index 0000000000..b930cd2e46
--- /dev/null
+++ b/__tests__/components/backends/digitalocean-new-agent-form.test.tsx
@@ -0,0 +1,149 @@
+import { screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { renderWithProviders } from "test-utils";
+
+import type { MarsSandboxSize } from "#/api/mars/mars-tunnel-backend";
+import { DigitalOceanNewAgentForm } from "#/components/features/backends/managed-agents/digitalocean-new-agent-form";
+
+// Real English strings with interpolation, so option labels can be asserted.
+vi.mock("react-i18next", async (importOriginal) => {
+ const { default: translations } = await import("#/i18n/translation.json");
+ const english = translations as Record<string, { en: string }>;
+ return {
+ ...(await importOriginal<typeof import("react-i18next")>()),
+ useTranslation: () => ({
+ t: (key: string, params: Record<string, unknown> = {}) =>
+ (english[key]?.en ?? key).replace(/{{(\w+)}}/g, (_, name: string) =>
+ String(params[name]),
+ ),
+ i18n: { language: "en" },
+ }),
+ };
+});
+
+const SIZES: MarsSandboxSize[] = [
+ {
+ slug: "mars-2vcpu-4gb",
+ vcpus: 2,
+ memory_mb: 4096,
+ price_per_hour_usd: 0.036,
+ price_per_month_usd: 24,
+ },
+ {
+ slug: "mars-16vcpu-32gb",
+ vcpus: 16,
+ memory_mb: 32768,
+ price_per_hour_usd: 0.286,
+ price_per_month_usd: 192.5,
+ },
+];
+
+function installBridge(listSandboxSizes: () => Promise<MarsSandboxSize[]>) {
+ const bridge = { listSandboxSizes: vi.fn(listSandboxSizes) };
+ window.marsBridge = bridge as unknown as NonNullable<
+ typeof window.marsBridge
+ >;
+ return bridge;
+}
+
+function renderForm() {
+ const onSubmit = vi.fn();
+ renderWithProviders(
+ <DigitalOceanNewAgentForm
+ isCreating={false}
+ error={null}
+ onSubmit={onSubmit}
+ onCancel={vi.fn()}
+ />,
+ );
+ return { onSubmit };
+}
+
+async function typeName(user: ReturnType<typeof userEvent.setup>) {
+ const nameInput = screen.getByTestId("digitalocean-new-agent-name");
+ await user.clear(nameInput);
+ await user.type(nameInput, "team-agent");
+}
+
+afterEach(() => {
+ delete window.marsBridge;
+});
+
+describe("DigitalOceanNewAgentForm – sandbox size", () => {
+ it("lists DigitalOcean's sizes and submits the chosen slug", async () => {
+ // Arrange
+ installBridge(async () => SIZES);
+ const user = userEvent.setup();
+ const { onSubmit } = renderForm();
+ await typeName(user);
+
+ // Act
+ await user.click(screen.getByRole("combobox"));
+ expect(
+ await screen.findByText("2 vCPU · 4 GB · $24.00/month"),
+ ).toBeInTheDocument();
+ await user.click(
+ await screen.findByText("16 vCPU · 32 GB · $192.50/month"),
+ );
+ await user.click(screen.getByTestId("digitalocean-new-agent-submit"));
+
+ // Assert
+ expect(onSubmit).toHaveBeenCalledWith({
+ name: "team-agent",
+ size: "mars-16vcpu-32gb",
+ });
+ });
+
+ it("omits the price when DigitalOcean does not quote one", async () => {
+ installBridge(async () => [
+ { slug: "mars-4vcpu-8gb", vcpus: 4, memory_mb: 8192 },
+ ]);
+ const user = userEvent.setup();
+ renderForm();
+
+ await user.click(screen.getByRole("combobox"));
+
+ expect(await screen.findByText("4 vCPU · 8 GB")).toBeInTheDocument();
+ });
+
+ it("submits no size when the default is kept", async () => {
+ // Arrange
+ const bridge = installBridge(async () => SIZES);
+ const user = userEvent.setup();
+ const { onSubmit } = renderForm();
+ await typeName(user);
+ await waitFor(() => expect(bridge.listSandboxSizes).toHaveBeenCalled());
+
+ // Act
+ await user.click(screen.getByTestId("digitalocean-new-agent-submit"));
+
+ // Assert
+ expect(screen.getByRole("combobox")).toHaveValue(
+ "Default (DigitalOcean picks)",
+ );
+ expect(onSubmit).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "team-agent", size: undefined }),
+ );
+ });
+
+ it("still creates with the default size when the catalog fails to load", async () => {
+ // Arrange
+ const bridge = installBridge(async () => {
+ throw new Error("403 forbidden");
+ });
+ const user = userEvent.setup();
+ const { onSubmit } = renderForm();
+ await typeName(user);
+ await waitFor(() => expect(bridge.listSandboxSizes).toHaveBeenCalled());
+
+ // Act
+ await user.click(screen.getByTestId("digitalocean-new-agent-submit"));
+
+ // Assert
+ expect(screen.getByTestId("digitalocean-new-agent-submit")).toBeEnabled();
+ expect(onSubmit).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "team-agent", size: undefined }),
+ );
+ });
+});
diff --git a/__tests__/components/backends/manage-backends-modal.test.tsx b/__tests__/components/backends/manage-backends-modal.test.tsx
index c4144fb692..29b82f7142 100644
--- a/__tests__/components/backends/manage-backends-modal.test.tsx
+++ b/__tests__/components/backends/manage-backends-modal.test.tsx
@@ -865,6 +865,145 @@ describe("ManageBackendsModal", () => {
});
});
+describe("ManageBackendsModal — removing a DigitalOcean session backend", () => {
+ const MARS_SESSION_ID = "sess_1";
+
+ function installMarsBridge(destroySession: () => Promise<void>) {
+ const bridge = {
+ destroySession: vi.fn(destroySession),
+ closeTunnel: vi.fn().mockResolvedValue(undefined),
+ };
+ (window as unknown as { marsBridge?: unknown }).marsBridge = bridge;
+ return bridge;
+ }
+
+ function BackendNames() {
+ const { backends } = useActiveBackendContext();
+ return (
+ <span data-testid="backend-names">
+ {backends.map((b) => b.name).join(",")}
+ </span>
+ );
+ }
+
+ async function openRemovalFor(name: string, onClose = vi.fn()) {
+ const user = userEvent.setup();
+ renderWithProviders(
+ <TestSeed
+ onMount={(ctx) => {
+ ctx.addBackend({
+ name,
+ host: "http://127.0.0.1:41234",
+ apiKey: "",
+ kind: "local",
+ marsSessionId: MARS_SESSION_ID,
+ });
+ }}
+ >
+ <BackendNames />
+ <ManageBackendsModal onClose={onClose} />
+ </TestSeed>,
+ );
+ await user.click(
+ await screen.findByTestId(`manage-backends-remove-${name}`),
+ );
+ return user;
+ }
+
+ it("does not close Manage Backends on Escape while a session is being stopped", async () => {
+ // A stop that never settles, so the dialog stays mid-destroy.
+ installMarsBridge(() => new Promise<void>(() => {}));
+ const onClose = vi.fn();
+ const user = await openRemovalFor("DO session", onClose);
+
+ await user.click(await screen.findByTestId("stop-session-button"));
+ await user.keyboard("{Escape}");
+
+ expect(onClose).not.toHaveBeenCalled();
+ expect(
+ screen.getByTestId("mars-backend-removal-modal"),
+ ).toBeInTheDocument();
+ });
+
+ afterEach(() => {
+ delete (window as unknown as { marsBridge?: unknown }).marsBridge;
+ });
+
+ it("explains the session keeps running and only disconnects on 'Disconnect only'", async () => {
+ const bridge = installMarsBridge(() => Promise.resolve());
+ const user = await openRemovalFor("DO session");
+
+ const modal = await screen.findByTestId("mars-backend-removal-modal");
+ expect(modal).toHaveTextContent("BACKEND$REMOVE_MARS_CONFIRMATION");
+ await user.click(within(modal).getByTestId("disconnect-only-button"));
+
+ await waitFor(() =>
+ expect(screen.getByTestId("backend-names")).not.toHaveTextContent(
+ "DO session",
+ ),
+ );
+ expect(bridge.destroySession).not.toHaveBeenCalled();
+ expect(bridge.closeTunnel).toHaveBeenCalledWith(MARS_SESSION_ID);
+ });
+
+ it("destroys the DigitalOcean session before removing the backend on 'Stop session'", async () => {
+ const bridge = installMarsBridge(() => Promise.resolve());
+ const user = await openRemovalFor("DO session");
+
+ await user.click(await screen.findByTestId("stop-session-button"));
+
+ await waitFor(() =>
+ expect(screen.getByTestId("backend-names")).not.toHaveTextContent(
+ "DO session",
+ ),
+ );
+ expect(bridge.destroySession).toHaveBeenCalledWith(MARS_SESSION_ID);
+ expect(
+ screen.queryByTestId("mars-backend-removal-modal"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("keeps the backend and shows the error when DigitalOcean refuses to stop the session", async () => {
+ installMarsBridge(() =>
+ Promise.reject(new Error("Session is locked by a checkpoint.")),
+ );
+ const user = await openRemovalFor("DO session");
+
+ await user.click(await screen.findByTestId("stop-session-button"));
+
+ expect(
+ await screen.findByTestId("mars-backend-removal-error"),
+ ).toHaveTextContent("Session is locked by a checkpoint.");
+ expect(screen.getByTestId("backend-names")).toHaveTextContent("DO session");
+ expect(screen.getByTestId("stop-session-button")).toBeEnabled();
+ });
+
+ it("keeps the generic confirmation for backends that are not DigitalOcean sessions", async () => {
+ const user = userEvent.setup();
+ renderWithProviders(
+ <TestSeed
+ onMount={(ctx) => {
+ ctx.addBackend({
+ name: "Plain",
+ host: "http://localhost:9000",
+ apiKey: "",
+ kind: "local",
+ });
+ }}
+ >
+ <ManageBackendsModal onClose={vi.fn()} />
+ </TestSeed>,
+ );
+
+ await user.click(await screen.findByTestId("manage-backends-remove-Plain"));
+
+ expect(await screen.findByTestId("confirmation-modal")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("mars-backend-removal-modal"),
+ ).not.toBeInTheDocument();
+ });
+});
+
function renderInQueryClient(ui: React.ReactElement) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -920,6 +1059,43 @@ describe("BackendRow", () => {
expect(selectButton).toBeDisabled();
});
+ it("keeps a disconnected DigitalOcean session selectable, since selecting it reconnects", async () => {
+ const onSelect = vi.fn();
+ const marsBackend: Backend = {
+ id: "mars-1",
+ name: "DO session",
+ host: "http://127.0.0.1:41234",
+ apiKey: "",
+ kind: "local",
+ marsSessionId: "sess_1",
+ };
+ renderInQueryClient(
+ <ul>
+ <BackendRow
+ backend={marsBackend}
+ health={{
+ isConnected: false,
+ consecutiveFailures: 3,
+ lastError: "connection refused",
+ disabled: true,
+ }}
+ onSelect={onSelect}
+ onEdit={vi.fn()}
+ onRemove={vi.fn()}
+ />
+ </ul>,
+ );
+
+ const selectButton = within(
+ screen.getByTestId("manage-backends-row-DO session"),
+ )
+ .getByText("DO session")
+ .closest("button")!;
+ expect(selectButton).toBeEnabled();
+ await userEvent.click(selectButton);
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ });
+
it("shows a logged-out cloud status with a log back in button", () => {
const onLogin = vi.fn();
diff --git a/__tests__/components/backends/managed-agents-session-row.test.tsx b/__tests__/components/backends/managed-agents-session-row.test.tsx
new file mode 100644
index 0000000000..5073ebafcd
--- /dev/null
+++ b/__tests__/components/backends/managed-agents-session-row.test.tsx
@@ -0,0 +1,54 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+
+import type { MarsSession } from "#/api/mars/mars-tunnel-backend";
+import { ManagedAgentsSessionRow } from "#/components/features/backends/managed-agents/managed-agents-session-row";
+
+function renderRow(status: string, isConnected = false) {
+ const session = {
+ session_id: "sess_1",
+ name: "agent-abc123",
+ status,
+ } as MarsSession;
+ render(
+ <ul>
+ <ManagedAgentsSessionRow
+ session={session}
+ isConnected={isConnected}
+ connectStage={null}
+ isBusy={false}
+ error={null}
+ onConnect={vi.fn()}
+ onOpen={vi.fn()}
+ onDisconnect={vi.fn()}
+ onPause={vi.fn()}
+ onStop={vi.fn()}
+ />
+ </ul>,
+ );
+}
+
+describe("ManagedAgentsSessionRow", () => {
+ it.each(["SESSION_STATUS_READY", "SESSION_STATUS_PAUSED"])(
+ "puts Stop directly left of Connect for a %s session",
+ (status) => {
+ renderRow(status);
+
+ const stop = screen.getByTestId("managed-agents-stop-sess_1");
+ const connect = screen.getByTestId("managed-agents-connect-sess_1");
+ expect(stop.nextElementSibling).toBe(connect);
+ },
+ );
+
+ it("keeps Open rightmost for a connected session, with Stop just left of it", () => {
+ renderRow("SESSION_STATUS_READY", true);
+
+ const stop = screen.getByTestId("managed-agents-stop-sess_1");
+ const open = screen.getByTestId("managed-agents-open-sess_1");
+ expect(stop.nextElementSibling).toBe(open);
+ expect(open.nextElementSibling).toBeNull();
+ expect(
+ screen.queryByTestId("managed-agents-connect-sess_1"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/__tests__/components/backends/managed-agents-view.test.tsx b/__tests__/components/backends/managed-agents-view.test.tsx
new file mode 100644
index 0000000000..10f127839a
--- /dev/null
+++ b/__tests__/components/backends/managed-agents-view.test.tsx
@@ -0,0 +1,376 @@
+import { screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { renderWithProviders } from "test-utils";
+
+vi.mock("#/services/telemetry", () => ({
+ setTelemetryCloudContext: vi.fn(),
+ setTelemetryIdentity: vi.fn(),
+}));
+
+const validateLocalBackend = vi.hoisted(() =>
+ vi.fn(async (): Promise<string | null> => "1.44.1"),
+);
+vi.mock("#/api/agent-server-compatibility", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/api/agent-server-compatibility")
+ >()),
+ validateLocalBackend,
+}));
+
+const searchConversations = vi.hoisted(() =>
+ vi.fn(async (): Promise<{ items: { id: string }[] }> => ({ items: [] })),
+);
+vi.mock("@openhands/typescript-client/clients", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@openhands/typescript-client/clients")
+ >()),
+ ConversationClient: vi.fn(function ConversationClient() {
+ return { searchConversations };
+ }),
+}));
+
+import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";
+import { __resetHealthStoreForTests } from "#/api/backend-registry/health-store";
+import { BACKENDS_STORAGE_KEY } from "#/api/backend-registry/storage";
+import type { Backend } from "#/api/backend-registry/types";
+import type {
+ MarsAuthState,
+ MarsBridge,
+ MarsSession,
+} from "#/api/mars/mars-tunnel-backend";
+import { ManagedAgentsView } from "#/components/features/backends/managed-agents/managed-agents-view";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
+
+const SIGNED_OUT: MarsAuthState = {
+ connections: [],
+ active: null,
+ isPersistent: true,
+ canUseOAuth: false,
+};
+
+const CONNECTION = {
+ id: "conn_1",
+ kind: "pat" as const,
+ label: "My team",
+ teamName: null,
+ expiresAt: null,
+ isExpired: false,
+};
+
+const SIGNED_IN: MarsAuthState = {
+ ...SIGNED_OUT,
+ connections: [CONNECTION],
+ active: CONNECTION,
+};
+
+const READY_SESSION: MarsSession = {
+ session_id: "sess_ready",
+ name: "fix-login",
+ status: "SESSION_STATUS_READY",
+ config_id: "cfg_1",
+};
+
+function fakeBridge(authState: MarsAuthState) {
+ return {
+ getAuthState: vi.fn(async () => authState),
+ savePat: vi.fn(async () => SIGNED_IN),
+ listAgentConfigs: vi.fn(async () => ({
+ configs: [{ id: "cfg_1", name: "Web agent", agent: "openhands" }],
+ nextPageToken: null,
+ })),
+ listSessions: vi.fn(async () => ({
+ sessions: [READY_SESSION],
+ nextPageToken: null,
+ })),
+ listConfigSessions: vi.fn(async () => ({
+ sessions: [READY_SESSION],
+ nextPageToken: null,
+ })),
+ openTunnel: vi.fn(async ({ sessionId }: { sessionId: string }) => ({
+ sessionId,
+ status: "connected" as const,
+ remotePort: 8000,
+ localPort: 51000,
+ error: undefined,
+ })),
+ closeTunnel: vi.fn(async () => {}),
+ getTunnel: vi.fn(async () => undefined),
+ destroySession: vi.fn(async () => {}),
+ deleteAgentConfig: vi.fn(async () => {}),
+ signOut: vi.fn(async () => SIGNED_OUT),
+ } as unknown as MarsBridge;
+}
+
+function renderView() {
+ const navigate = vi.fn();
+ const onDone = vi.fn();
+ renderWithProviders(
+ <ActiveBackendProvider>
+ <ManagedAgentsView onBack={vi.fn()} onDone={onDone} />
+ </ActiveBackendProvider>,
+ { navigation: { navigate } },
+ );
+ return { navigate, onDone };
+}
+
+beforeEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ __resetHealthStoreForTests();
+ validateLocalBackend.mockResolvedValue("1.44.1");
+ searchConversations.mockResolvedValue({ items: [] });
+});
+
+afterEach(() => {
+ window.localStorage.clear();
+ vi.restoreAllMocks();
+ __resetActiveStoreForTests();
+ __resetHealthStoreForTests();
+ delete window.marsBridge;
+});
+
+describe("ManagedAgentsView", () => {
+ it("asks a signed-out user for a token and shows their agents once it is accepted", async () => {
+ const bridge = fakeBridge(SIGNED_OUT);
+ window.marsBridge = bridge;
+ renderView();
+
+ await userEvent.type(
+ await screen.findByTestId("managed-agents-token"),
+ "dop_v1_token",
+ );
+ vi.mocked(bridge.getAuthState).mockResolvedValue(SIGNED_IN);
+ await userEvent.click(screen.getByTestId("managed-agents-token-submit"));
+
+ expect(bridge.savePat).toHaveBeenCalledWith({ token: "dop_v1_token" });
+ expect(
+ await screen.findByTestId("managed-agents-session-sess_ready"),
+ ).toBeInTheDocument();
+ });
+
+ it("lands in the session's latest conversation after connecting", async () => {
+ window.marsBridge = fakeBridge(SIGNED_IN);
+ searchConversations.mockResolvedValue({ items: [{ id: "conv_42" }] });
+ const { navigate, onDone } = renderView();
+
+ await userEvent.click(
+ await screen.findByTestId("managed-agents-connect-sess_ready"),
+ );
+
+ await waitFor(() => expect(onDone).toHaveBeenCalled());
+ expect(navigate).toHaveBeenCalledWith(
+ expect.stringMatching(/^\/conversations\/conv_42\?/),
+ );
+ });
+
+ it("keeps the agent of a session listed under Other sessions when connecting", async () => {
+ // Arrange: the session is missing from its config's own listing.
+ const bridge = fakeBridge(SIGNED_IN);
+ vi.mocked(bridge.listConfigSessions).mockResolvedValue({
+ sessions: [],
+ nextPageToken: null,
+ });
+ window.marsBridge = bridge;
+ const { onDone } = renderView();
+ expect(
+ await screen.findByTestId("managed-agents-other-sessions"),
+ ).toBeInTheDocument();
+
+ // Act
+ await userEvent.click(
+ screen.getByTestId("managed-agents-connect-sess_ready"),
+ );
+
+ // Assert
+ await waitFor(() => expect(onDone).toHaveBeenCalled());
+ const stored: Backend[] = JSON.parse(
+ window.localStorage.getItem(BACKENDS_STORAGE_KEY) ?? "[]",
+ );
+ // Named after the session alone, so the backend menu shows just that.
+ expect(
+ stored.find((backend) => backend.marsSessionId === "sess_ready"),
+ ).toMatchObject({ marsConfigId: "cfg_1", name: "fix-login" });
+ });
+
+ it("signs out through the bridge and returns to the sign-in form", async () => {
+ const bridge = fakeBridge(SIGNED_IN);
+ window.marsBridge = bridge;
+ renderView();
+
+ vi.mocked(bridge.getAuthState).mockResolvedValue(SIGNED_OUT);
+ await userEvent.click(await screen.findByTestId("managed-agents-sign-out"));
+
+ expect(bridge.signOut).toHaveBeenCalledOnce();
+ expect(
+ await screen.findByTestId("managed-agents-sign-in"),
+ ).toBeInTheDocument();
+ });
+
+ it("blocks other connects and launches while a new session is being created", async () => {
+ // Arrange
+ const bridge = fakeBridge(SIGNED_IN);
+ bridge.createSession = vi.fn(() => new Promise<MarsSession>(() => {}));
+ window.marsBridge = bridge;
+ renderView();
+ const newSession = await screen.findByTestId(
+ "managed-agents-new-session-cfg_1",
+ );
+
+ // Act
+ await userEvent.click(newSession);
+
+ // Assert
+ expect(bridge.createSession).toHaveBeenCalledOnce();
+ expect(newSession).toBeDisabled();
+ expect(
+ screen.getByTestId("managed-agents-connect-sess_ready"),
+ ).toBeDisabled();
+ });
+
+ it("explains a refused tunnel on the session row instead of timing out", async () => {
+ const bridge = fakeBridge(SIGNED_IN);
+ vi.mocked(bridge.getTunnel).mockResolvedValue({
+ sessionId: "sess_ready",
+ status: "connected",
+ remotePort: 8000,
+ localPort: 51000,
+ error: undefined,
+ upstreamFailure: { closeCode: 4001, httpStatus: null, message: "gone" },
+ });
+ window.marsBridge = bridge;
+ validateLocalBackend.mockRejectedValue(new Error("connection reset"));
+ const { navigate } = renderView();
+
+ await userEvent.click(
+ await screen.findByTestId("managed-agents-connect-sess_ready"),
+ );
+
+ expect(
+ await screen.findByTestId("managed-agents-session-error-sess_ready"),
+ ).toHaveTextContent("DO_AGENTS$ERROR_REFUSED");
+ expect(navigate).not.toHaveBeenCalled();
+ });
+
+ it("reports a failed connect after launching on the new session's row, not the agent", async () => {
+ // Arrange
+ const NEW_SESSION: MarsSession = {
+ session_id: "sess_new",
+ name: "new-session",
+ status: "SESSION_STATUS_READY",
+ config_id: "cfg_1",
+ };
+ const bridge = fakeBridge(SIGNED_IN);
+ bridge.createSession = vi.fn(async () => NEW_SESSION);
+ const sessions = { sessions: [READY_SESSION], nextPageToken: null };
+ vi.mocked(bridge.listSessions).mockImplementation(async () => sessions);
+ vi.mocked(bridge.listConfigSessions).mockImplementation(
+ async () => sessions,
+ );
+ vi.mocked(bridge.getTunnel).mockResolvedValue({
+ sessionId: "sess_new",
+ status: "connected",
+ remotePort: 8000,
+ localPort: 51000,
+ error: undefined,
+ upstreamFailure: { closeCode: 4001, httpStatus: null, message: "gone" },
+ });
+ window.marsBridge = bridge;
+ validateLocalBackend.mockRejectedValue(new Error("connection reset"));
+ const { navigate } = renderView();
+ const newSession = await screen.findByTestId(
+ "managed-agents-new-session-cfg_1",
+ );
+ sessions.sessions = [READY_SESSION, NEW_SESSION];
+
+ // Act
+ await userEvent.click(newSession);
+
+ // Assert
+ expect(
+ await screen.findByTestId("managed-agents-session-error-sess_new"),
+ ).toHaveTextContent("DO_AGENTS$ERROR_REFUSED");
+ // Not also on the agent header, where a later connect would not clear it.
+ expect(screen.getAllByText("DO_AGENTS$ERROR_REFUSED")).toHaveLength(1);
+ expect(navigate).not.toHaveBeenCalled();
+ });
+
+ it("stops a session only after the user confirms, then refreshes the list", async () => {
+ const bridge = fakeBridge(SIGNED_IN);
+ window.marsBridge = bridge;
+ renderView();
+
+ await userEvent.click(
+ await screen.findByTestId("managed-agents-stop-sess_ready"),
+ );
+ // Nothing destructive happens before the confirmation.
+ expect(bridge.destroySession).not.toHaveBeenCalled();
+ expect(screen.getByTestId("confirmation-modal")).toHaveTextContent(
+ "DO_AGENTS$STOP_CONFIRM",
+ );
+
+ await userEvent.click(screen.getByTestId("cancel-button"));
+ expect(bridge.destroySession).not.toHaveBeenCalled();
+ expect(screen.queryByTestId("confirmation-modal")).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByTestId("managed-agents-stop-sess_ready"));
+ await userEvent.click(screen.getByTestId("confirm-button"));
+
+ await waitFor(() =>
+ expect(bridge.destroySession).toHaveBeenCalledWith("sess_ready"),
+ );
+ await waitFor(() =>
+ expect(
+ screen.queryByTestId("confirmation-modal"),
+ ).not.toBeInTheDocument(),
+ );
+ // The list is re-read so the stopped session disappears.
+ expect(
+ vi.mocked(bridge.listConfigSessions).mock.calls.length,
+ ).toBeGreaterThan(1);
+ });
+
+ it("offers Delete agent only once the agent has no live session", async () => {
+ const bridge = fakeBridge(SIGNED_IN);
+ window.marsBridge = bridge;
+ renderView();
+
+ const deleteButton = await screen.findByTestId(
+ "managed-agents-delete-agent-cfg_1",
+ );
+ expect(deleteButton).toBeDisabled();
+ expect(deleteButton).toHaveAttribute(
+ "title",
+ "DO_AGENTS$DELETE_AGENT_BLOCKED",
+ );
+ expect(bridge.deleteAgentConfig).not.toHaveBeenCalled();
+ });
+
+ it("deletes an agent with no live sessions after confirmation", async () => {
+ const bridge = fakeBridge(SIGNED_IN);
+ vi.mocked(bridge.listConfigSessions).mockResolvedValue({
+ sessions: [{ ...READY_SESSION, status: "SESSION_STATUS_DESTROYED" }],
+ nextPageToken: null,
+ });
+ vi.mocked(bridge.listSessions).mockResolvedValue({
+ sessions: [],
+ nextPageToken: null,
+ });
+ window.marsBridge = bridge;
+ renderView();
+
+ const deleteButton = await screen.findByTestId(
+ "managed-agents-delete-agent-cfg_1",
+ );
+ await waitFor(() => expect(deleteButton).toBeEnabled());
+ await userEvent.click(deleteButton);
+ expect(screen.getByTestId("confirmation-modal")).toHaveTextContent(
+ "DO_AGENTS$DELETE_AGENT_CONFIRM",
+ );
+ await userEvent.click(screen.getByTestId("confirm-button"));
+
+ await waitFor(() =>
+ expect(bridge.deleteAgentConfig).toHaveBeenCalledWith("cfg_1"),
+ );
+ });
+});
diff --git a/__tests__/components/features/sidebar/mars-session-panel.test.tsx b/__tests__/components/features/sidebar/mars-session-panel.test.tsx
new file mode 100644
index 0000000000..99a44a955f
--- /dev/null
+++ b/__tests__/components/features/sidebar/mars-session-panel.test.tsx
@@ -0,0 +1,205 @@
+import { screen, waitFor, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { renderWithProviders } from "test-utils";
+
+vi.mock("#/services/telemetry", () => ({
+ setTelemetryCloudContext: vi.fn(),
+ setTelemetryIdentity: vi.fn(),
+}));
+
+vi.mock("#/api/agent-server-compatibility", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/api/agent-server-compatibility")
+ >()),
+ validateLocalBackend: vi.fn(async () => "1.44.1"),
+}));
+
+vi.mock("@openhands/typescript-client/clients", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@openhands/typescript-client/clients")
+ >()),
+ ConversationClient: vi.fn(function ConversationClient() {
+ return { searchConversations: vi.fn(async () => ({ items: [] })) };
+ }),
+}));
+
+import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";
+import { __resetHealthStoreForTests } from "#/api/backend-registry/health-store";
+import type { Backend } from "#/api/backend-registry/types";
+import type { MarsBridge, MarsSession } from "#/api/mars/mars-tunnel-backend";
+import { MarsSessionPanel } from "#/components/features/sidebar/mars-session-panel";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
+
+const CONNECTION = {
+ id: "conn_1",
+ kind: "pat" as const,
+ label: "My team",
+ teamName: null,
+ expiresAt: null,
+ isExpired: false,
+};
+
+const CURRENT: MarsSession = {
+ session_id: "sess_current",
+ name: "fix-login",
+ status: "SESSION_STATUS_READY",
+ config_id: "cfg_1",
+};
+
+const SIBLING: MarsSession = {
+ session_id: "sess_sibling",
+ name: "add-billing",
+ status: "SESSION_STATUS_PAUSED",
+ config_id: "cfg_1",
+};
+
+const BACKEND: Backend = {
+ id: "mars-sess_current",
+ name: "Web agent · fix-login",
+ kind: "local",
+ host: "http://127.0.0.1:51000",
+ apiKey: "",
+ marsSessionId: CURRENT.session_id,
+ marsConfigId: "cfg_1",
+};
+
+function fakeBridge() {
+ return {
+ getAuthState: vi.fn(async () => ({
+ connections: [CONNECTION],
+ active: CONNECTION,
+ isPersistent: true,
+ canUseOAuth: false,
+ })),
+ listAgentConfigs: vi.fn(async () => ({
+ configs: [{ id: "cfg_1", name: "Web agent", agent: "openhands" }],
+ nextPageToken: null,
+ })),
+ listSessions: vi.fn(async () => ({ sessions: [], nextPageToken: null })),
+ listConfigSessions: vi.fn(async () => ({
+ sessions: [CURRENT, SIBLING],
+ nextPageToken: null,
+ })),
+ createSession: vi.fn(async () => ({
+ session_id: "sess_new",
+ name: "fresh",
+ status: "SESSION_STATUS_READY",
+ config_id: "cfg_1",
+ })),
+ openTunnel: vi.fn(async ({ sessionId }: { sessionId: string }) => ({
+ sessionId,
+ status: "connected" as const,
+ remotePort: 8000,
+ localPort: 51001,
+ error: undefined,
+ })),
+ closeTunnel: vi.fn(async () => {}),
+ getTunnel: vi.fn(async () => undefined),
+ } as unknown as MarsBridge;
+}
+
+function renderPanel() {
+ const navigate = vi.fn();
+ renderWithProviders(
+ <ActiveBackendProvider>
+ <MarsSessionPanel backend={BACKEND} />
+ </ActiveBackendProvider>,
+ { navigation: { navigate } },
+ );
+ return { navigate };
+}
+
+beforeEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ __resetHealthStoreForTests();
+});
+
+afterEach(() => {
+ window.localStorage.clear();
+ vi.restoreAllMocks();
+ __resetActiveStoreForTests();
+ __resetHealthStoreForTests();
+ delete window.marsBridge;
+});
+
+describe("MarsSessionPanel", () => {
+ it("lists the agent's sessions and opens another one with a click", async () => {
+ const bridge = fakeBridge();
+ window.marsBridge = bridge;
+ const { navigate } = renderPanel();
+
+ const current = await screen.findByTestId("mars-session-sess_current");
+ expect(
+ within(current).getByTestId("mars-session-open-sess_current"),
+ ).toHaveAttribute("aria-current", "true");
+ await userEvent.click(
+ await screen.findByTestId("mars-session-open-sess_sibling"),
+ );
+
+ await waitFor(() => expect(navigate).toHaveBeenCalled());
+ expect(bridge.openTunnel).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionId: "sess_sibling" }),
+ );
+ });
+
+ it("shows no age for a session whose timestamps are unset", async () => {
+ // Arrange: harness-api leaves unset datetimes at the epoch.
+ const bridge = fakeBridge();
+ vi.mocked(bridge.listConfigSessions).mockResolvedValue({
+ sessions: [
+ CURRENT,
+ { ...SIBLING, created_at: "1970-01-01T00:00:00Z", last_event_at: null },
+ ],
+ nextPageToken: null,
+ });
+ window.marsBridge = bridge;
+ renderPanel();
+
+ // Act
+ const sibling = await screen.findByTestId("mars-session-sess_sibling");
+
+ // Assert
+ expect(sibling.querySelector("time")).toBeNull();
+ });
+
+ it("closes the agent menu on Escape and on a click outside it", async () => {
+ window.marsBridge = fakeBridge();
+ renderPanel();
+ const trigger = await screen.findByTestId("mars-session-panel-agent");
+
+ await userEvent.click(trigger);
+ expect(
+ screen.getByTestId("mars-session-panel-agent-menu"),
+ ).toBeInTheDocument();
+ await userEvent.keyboard("{Escape}");
+ expect(
+ screen.queryByTestId("mars-session-panel-agent-menu"),
+ ).not.toBeInTheDocument();
+ expect(trigger).toHaveFocus();
+
+ await userEvent.click(trigger);
+ await userEvent.click(document.body);
+ expect(
+ screen.queryByTestId("mars-session-panel-agent-menu"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("launches a new session for the current agent and connects to it", async () => {
+ const bridge = fakeBridge();
+ window.marsBridge = bridge;
+ const { navigate } = renderPanel();
+
+ await userEvent.click(await screen.findByTestId("mars-session-panel-new"));
+
+ await waitFor(() => expect(navigate).toHaveBeenCalled());
+ expect(bridge.createSession).toHaveBeenCalledWith(
+ "cfg_1",
+ expect.any(String),
+ );
+ expect(bridge.openTunnel).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionId: "sess_new" }),
+ );
+ });
+});
diff --git a/__tests__/components/settings/llm-profiles/llm-settings-local-view.test.tsx b/__tests__/components/settings/llm-profiles/llm-settings-local-view.test.tsx
index 3c016832b7..eddbf044e9 100644
--- a/__tests__/components/settings/llm-profiles/llm-settings-local-view.test.tsx
+++ b/__tests__/components/settings/llm-profiles/llm-settings-local-view.test.tsx
@@ -1045,6 +1045,40 @@ describe("LlmSettingsLocalView", () => {
});
});
+ describe("create mode save", () => {
+ it("saves a new profile with the prefilled default model even though the model was never touched", async () => {
+ // Arrange — the model is prefilled and left alone; only an unrelated
+ // field is edited, so the dirty payload carries no model at all.
+ const user = userEvent.setup();
+ mockSaveMutateAsync.mockResolvedValueOnce({ success: true });
+ renderWithProviders(<LlmSettingsLocalView />);
+ await user.click(screen.getByTestId("add-llm-profile"));
+ await waitFor(() =>
+ expect(screen.getByTestId("profile-name-input")).toHaveValue(
+ "gpt-5.6-sol",
+ ),
+ );
+
+ // Act — go to the All tab (whose dirty payload is temperature only) and save.
+ await user.click(await screen.findByTestId("sdk-section-all-toggle"));
+ const temperatureInput = await screen.findByTestId(
+ "sdk-settings-llm.temperature",
+ );
+ await user.clear(temperatureInput);
+ await user.type(temperatureInput, "0.3");
+ await waitFor(() => {
+ expect(screen.getByTestId("save-profile-btn")).not.toBeDisabled();
+ });
+ await user.click(screen.getByTestId("save-profile-btn"));
+
+ // Assert — the prefilled model rides along instead of a "Model is required" refusal.
+ await waitFor(() => expect(mockSaveMutateAsync).toHaveBeenCalled());
+ const savedLlm = mockSaveMutateAsync.mock.calls[0][0].request.llm;
+ expect(savedLlm.model).toBe("openai/gpt-5.6-sol");
+ expect(savedLlm.temperature).toBe(0.3);
+ });
+ });
+
describe("All tab save", () => {
it("persists a changed minor field without wiping untouched fields", async () => {
// Arrange — a profile with a minor field (temperature) plus fields the
diff --git a/__tests__/hooks/query/use-backends-health.test.tsx b/__tests__/hooks/query/use-backends-health.test.tsx
index 6d9c448bf8..095327efea 100644
--- a/__tests__/hooks/query/use-backends-health.test.tsx
+++ b/__tests__/hooks/query/use-backends-health.test.tsx
@@ -331,6 +331,41 @@ describe("useBackendsHealth", () => {
});
});
+ it("keeps polling ordinary backends but stops re-probing MARS sessions the user is not on", async () => {
+ // Arrange — every probe of a MARS session tunnels into its sandbox, so
+ // polling an idle one would keep it from auto-pausing.
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ getSettingsMock.mockResolvedValue({});
+ const idleMarsBackend: Backend = {
+ id: "mars-idle",
+ name: "Web agent · fix-login",
+ host: "http://127.0.0.1:51000",
+ apiKey: "",
+ kind: "local",
+ marsSessionId: "sess_idle",
+ };
+ const probesOf = (host: string) =>
+ vi
+ .mocked(SettingsClient)
+ .mock.calls.filter(([options]) => options?.host === host).length;
+ renderHook(() => useBackendsHealth([localBackend, idleMarsBackend]), {
+ wrapper,
+ });
+ await waitFor(() => {
+ expect(probesOf(localBackend.host)).toBe(1);
+ expect(probesOf(idleMarsBackend.host)).toBe(1);
+ });
+
+ // Act
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(65_000);
+ });
+
+ // Assert
+ expect(probesOf(localBackend.host)).toBeGreaterThan(1);
+ expect(probesOf(idleMarsBackend.host)).toBe(1);
+ });
+
it("does not probe a backend whose disabled state was persisted before the GUI mounted (refresh case)", async () => {
// Arrange — simulate a prior session that already exhausted retries
// by seeding localStorage before the hook subscribes.
diff --git a/__tests__/hooks/use-mars-sign-in.test.tsx b/__tests__/hooks/use-mars-sign-in.test.tsx
new file mode 100644
index 0000000000..767437b677
--- /dev/null
+++ b/__tests__/hooks/use-mars-sign-in.test.tsx
@@ -0,0 +1,42 @@
+import React from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { MarsBridge } from "#/api/mars/mars-tunnel-backend";
+import { useMarsSignIn } from "#/hooks/use-mars-sign-in";
+
+function wrapper({ children }: { children: React.ReactNode }) {
+ const queryClient = new QueryClient({
+ defaultOptions: { mutations: { retry: false } },
+ });
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+}
+
+afterEach(() => {
+ delete window.marsBridge;
+});
+
+describe("useMarsSignIn", () => {
+ it("drops a failed sign-out's error once a new sign-in starts", async () => {
+ // Arrange
+ window.marsBridge = {
+ signOut: vi.fn(async () => {
+ throw new Error("sign-out failed");
+ }),
+ savePat: vi.fn(() => new Promise(() => {})),
+ } as unknown as MarsBridge;
+ const { result } = renderHook(() => useMarsSignIn(), { wrapper });
+ act(() => result.current.signOut());
+ await waitFor(() => expect(result.current.error).toBe("sign-out failed"));
+
+ // Act
+ act(() => result.current.saveToken("dop_v1_token"));
+
+ // Assert
+ await waitFor(() => expect(result.current.isSavingToken).toBe(true));
+ expect(result.current.error).toBeNull();
+ });
+});
diff --git a/__tests__/hooks/use-mars-tunnel-backend.test.tsx b/__tests__/hooks/use-mars-tunnel-backend.test.tsx
new file mode 100644
index 0000000000..87656f599d
--- /dev/null
+++ b/__tests__/hooks/use-mars-tunnel-backend.test.tsx
@@ -0,0 +1,502 @@
+import React from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("#/services/telemetry", () => ({
+ setTelemetryCloudContext: vi.fn(),
+ setTelemetryIdentity: vi.fn(),
+}));
+
+const validateLocalBackend = vi.hoisted(() =>
+ vi.fn(async (): Promise<string | null> => "1.44.1"),
+);
+vi.mock("#/api/agent-server-compatibility", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/api/agent-server-compatibility")
+ >()),
+ validateLocalBackend,
+}));
+
+const searchConversations = vi.hoisted(() =>
+ vi.fn(async (): Promise<{ items: { id: string }[] }> => ({ items: [] })),
+);
+vi.mock("@openhands/typescript-client/clients", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@openhands/typescript-client/clients")
+ >()),
+ ConversationClient: vi.fn(function ConversationClient() {
+ return { searchConversations };
+ }),
+}));
+
+import { INVALID_BACKEND_API_KEY_ERROR } from "#/api/agent-server-compatibility";
+import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";
+import {
+ __resetHealthStoreForTests,
+ getBackendHealthEntry,
+ recordBackendFailure,
+} from "#/api/backend-registry/health-store";
+import {
+ ACTIVE_BACKEND_STORAGE_KEY,
+ BACKENDS_STORAGE_KEY,
+} from "#/api/backend-registry/storage";
+import {
+ ActiveBackendProvider,
+ useActiveBackendContext,
+} from "#/contexts/active-backend-context";
+import {
+ useMarsTunnelBackend,
+ useRestoreMarsTunnels,
+} from "#/hooks/use-mars-tunnel-backend";
+import type {
+ MarsBridge,
+ MarsTunnelStatus,
+ OpenMarsTunnelParams,
+} from "#/api/mars/mars-tunnel-backend";
+import type { Backend } from "#/api/backend-registry/types";
+
+function makeWrapper(queryClient = new QueryClient()) {
+ function Wrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>
+ <ActiveBackendProvider>{children}</ActiveBackendProvider>
+ </QueryClientProvider>
+ );
+ }
+ return Wrapper;
+}
+
+function useCombined() {
+ return {
+ tunnel: useMarsTunnelBackend(),
+ active: useActiveBackendContext(),
+ };
+}
+
+function tunnelStatus(
+ sessionId: string,
+ localPort: number | undefined,
+ error?: string,
+): MarsTunnelStatus {
+ return {
+ sessionId,
+ status: error ? "error" : "connected",
+ remotePort: 8000,
+ localPort,
+ error,
+ };
+}
+
+const SIGNED_IN = {
+ connections: [{ id: "conn_1", label: "token", isExpired: false }],
+ active: { id: "conn_1", label: "token", isExpired: false },
+ isPersistent: false,
+ canUseOAuth: false,
+};
+const SIGNED_OUT = { ...SIGNED_IN, connections: [], active: null };
+
+function fakeMarsBridge(localPort = 51000, authState: object = SIGNED_IN) {
+ return {
+ getAuthState: vi.fn(async () => authState),
+ openTunnel: vi.fn(async ({ sessionId }: OpenMarsTunnelParams) =>
+ tunnelStatus(sessionId, localPort),
+ ),
+ closeTunnel: vi.fn(async () => {}),
+ getTunnel: vi.fn(async () => undefined),
+ } as unknown as MarsBridge & {
+ getAuthState: ReturnType<typeof vi.fn>;
+ openTunnel: ReturnType<typeof vi.fn>;
+ closeTunnel: ReturnType<typeof vi.fn>;
+ };
+}
+
+const SESSION = { sessionId: "sess_abc", name: "Agent · sess-1" };
+
+beforeEach(() => {
+ window.localStorage.clear();
+ vi.stubEnv("VITE_BACKEND_BASE_URL", "http://localhost:9000");
+ vi.stubEnv("VITE_SESSION_API_KEY", "session-key");
+ __resetActiveStoreForTests();
+ __resetHealthStoreForTests();
+ validateLocalBackend.mockResolvedValue("1.44.1");
+ searchConversations.mockResolvedValue({ items: [] });
+ window.marsBridge = fakeMarsBridge();
+});
+
+afterEach(() => {
+ window.localStorage.clear();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ __resetActiveStoreForTests();
+ __resetHealthStoreForTests();
+ delete window.marsBridge;
+});
+
+describe("useMarsTunnelBackend", () => {
+ it("attach() registers the healthy tunnel as the active local backend for that session", async () => {
+ const { result } = renderHook(useCombined, { wrapper: makeWrapper() });
+
+ await act(async () => {
+ await result.current.tunnel.attach({ ...SESSION, configId: "cfg_1" });
+ });
+
+ expect(window.marsBridge!.openTunnel).toHaveBeenCalledWith({
+ sessionId: "sess_abc",
+ localPort: undefined,
+ });
+ expect(result.current.active.active.backend).toMatchObject({
+ name: "Agent · sess-1",
+ host: "http://127.0.0.1:51000",
+ kind: "local",
+ marsSessionId: "sess_abc",
+ marsConfigId: "cfg_1",
+ });
+ });
+
+ it("attach() re-points the session's existing backend instead of adding a duplicate", async () => {
+ const { result } = renderHook(useCombined, { wrapper: makeWrapper() });
+ await act(async () => {
+ await result.current.tunnel.attach(SESSION);
+ });
+ const countAfterFirst = result.current.active.backends.length;
+ window.marsBridge = fakeMarsBridge(52000);
+
+ await act(async () => {
+ await result.current.tunnel.attach(SESSION);
+ });
+
+ expect(result.current.active.backends).toHaveLength(countAfterFirst);
+ expect(
+ result.current.active.backends.find((b) => b.marsSessionId === "sess_abc")
+ ?.host,
+ ).toBe("http://127.0.0.1:52000");
+ });
+
+ it("attach() re-arms the health of the session's existing backend even when its host is unchanged", async () => {
+ const { result } = renderHook(useCombined, { wrapper: makeWrapper() });
+ let backend: Backend;
+ await act(async () => {
+ ({ backend } = await result.current.tunnel.attach(SESSION));
+ });
+ for (let i = 0; i < 5; i += 1) {
+ recordBackendFailure(backend!.id, new Error("offline"));
+ }
+ expect(getBackendHealthEntry(backend!.id)?.disabled).toBe(true);
+
+ await act(async () => {
+ await result.current.tunnel.attach(SESSION);
+ });
+
+ expect(getBackendHealthEntry(backend!.id)).toBeNull();
+ });
+
+ it("attach() throws and registers nothing when the tunnel fails to open", async () => {
+ window.marsBridge!.openTunnel = vi.fn(async () =>
+ tunnelStatus("sess_abc", undefined, "server rejected tunnel (403)"),
+ );
+ const { result } = renderHook(useCombined, { wrapper: makeWrapper() });
+ const countBefore = result.current.active.backends.length;
+
+ await expect(
+ act(() => result.current.tunnel.attach(SESSION)),
+ ).rejects.toThrow(/403/);
+
+ expect(result.current.active.backends).toHaveLength(countBefore);
+ });
+
+ it("attach() closes the tunnel when the agent-server behind it never answers", async () => {
+ validateLocalBackend.mockRejectedValue(new Error("connection refused"));
+ // Expire the 60s probe budget after the first failed attempt.
+ vi.spyOn(Date, "now")
+ .mockReturnValueOnce(0)
+ .mockReturnValue(Number.MAX_SAFE_INTEGER);
+ const { result } = renderHook(useCombined, { wrapper: makeWrapper() });
+ const countBefore = result.current.active.backends.length;
+
+ await expect(
+ act(() => result.current.tunnel.attach(SESSION)),
+ ).rejects.toThrow(/connection refused/);
+
+ expect(window.marsBridge!.closeTunnel).toHaveBeenCalledWith("sess_abc");
+ expect(result.current.active.backends).toHaveLength(countBefore);
+ });
+
+ it("attach() gives up at once when the agent-server rejects the key", async () => {
+ validateLocalBackend.mockRejectedValue(
+ new Error(INVALID_BACKEND_API_KEY_ERROR),
+ );
+ const { result } = renderHook(useCombined, { wrapper: makeWrapper() });
+
+ await expect(
+ act(() => result.current.tunnel.attach(SESSION)),
+ ).rejects.toThrow(INVALID_BACKEND_API_KEY_ERROR);
+
+ expect(validateLocalBackend).toHaveBeenCalledTimes(1);
+ expect(window.marsBridge!.closeTunnel).toHaveBeenCalledWith("sess_abc");
+ });
+
+ it("attach() reports the session's most recent conversation so the caller can land in it", async () => {
+ searchConversations.mockResolvedValueOnce({
+ items: [{ id: "conv_latest" }],
+ });
+ const { result } = renderHook(useCombined, { wrapper: makeWrapper() });
+
+ let attached: Awaited<ReturnType<typeof result.current.tunnel.attach>>;
+ await act(async () => {
+ attached = await result.current.tunnel.attach(SESSION);
+ });
+
+ expect(attached!.latestConversationId).toBe("conv_latest");
+ });
+
+ it("attach() fails fast with a not-openhands error when the guest port stays closed", async () => {
+ validateLocalBackend.mockRejectedValue(new Error("socket hang up"));
+ window.marsBridge!.getTunnel = vi.fn(async () => ({
+ ...tunnelStatus("sess_abc", 51000),
+ upstreamFailure: { closeCode: 4002, httpStatus: null, message: "" },
+ }));
+ // First failure starts the grace window; the next is past it but still
+ // well inside the 60s probe budget.
+ vi.spyOn(Date, "now")
+ .mockReturnValueOnce(0)
+ .mockReturnValueOnce(0)
+ .mockReturnValue(25_000);
+ const { result } = renderHook(useCombined, { wrapper: makeWrapper() });
+
+ await expect(
+ act(() => result.current.tunnel.attach(SESSION)),
+ ).rejects.toMatchObject({
+ name: "MarsAttachError",
+ reason: "not-openhands",
+ });
+ expect(window.marsBridge!.closeTunnel).toHaveBeenCalledWith("sess_abc");
+ });
+
+ it("detach() closes the tunnel and removes the Backend", async () => {
+ const { result } = renderHook(useCombined, { wrapper: makeWrapper() });
+ let backend: Backend;
+ await act(async () => {
+ ({ backend } = await result.current.tunnel.attach(SESSION));
+ });
+
+ await act(async () => {
+ await result.current.tunnel.detach(backend!);
+ });
+
+ expect(window.marsBridge!.closeTunnel).toHaveBeenCalledWith("sess_abc");
+ expect(
+ result.current.active.backends.find((b) => b.id === backend!.id),
+ ).toBeUndefined();
+ });
+
+ it("detach() closes the tunnel only once, through removing the Backend", async () => {
+ const { result } = renderHook(useCombined, { wrapper: makeWrapper() });
+ let backend: Backend;
+ await act(async () => {
+ ({ backend } = await result.current.tunnel.attach(SESSION));
+ });
+
+ await act(async () => {
+ await result.current.tunnel.detach(backend!);
+ });
+
+ expect(window.marsBridge!.closeTunnel).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("useRestoreMarsTunnels", () => {
+ it("waits for a DigitalOcean sign-in, then reconnects the same session without blocking startup", async () => {
+ // Arrange — after a web-server restart the token is gone (it lives only
+ // in server memory) while the backend record survives in the browser.
+ window.localStorage.setItem(
+ BACKENDS_STORAGE_KEY,
+ JSON.stringify([
+ {
+ id: "mars-1",
+ name: "Agent · sess-1",
+ host: "http://127.0.0.1:51000",
+ apiKey: "",
+ kind: "local",
+ marsSessionId: "sess_abc",
+ },
+ ]),
+ );
+ window.localStorage.setItem(
+ ACTIVE_BACKEND_STORAGE_KEY,
+ JSON.stringify({ backendId: "mars-1", orgId: null }),
+ );
+ __resetActiveStoreForTests();
+ const bridge = fakeMarsBridge(51000, SIGNED_OUT);
+ window.marsBridge = bridge;
+ const queryClient = new QueryClient();
+
+ const { result } = renderHook(() => useRestoreMarsTunnels(), {
+ wrapper: makeWrapper(queryClient),
+ });
+
+ // Signed out: no doomed connect, and the bootstrap is not held up.
+ await waitFor(() => expect(result.current).toBe(false));
+ expect(bridge.openTunnel).not.toHaveBeenCalled();
+
+ // Act — the user signs in again.
+ bridge.getAuthState.mockResolvedValue(SIGNED_IN);
+ await act(() =>
+ queryClient.invalidateQueries({ queryKey: ["mars", "auth-state"] }),
+ );
+
+ // Assert — the existing session is reconnected; no new session needed.
+ await waitFor(() =>
+ expect(bridge.openTunnel).toHaveBeenCalledWith({
+ sessionId: "sess_abc",
+ localPort: 51000,
+ }),
+ );
+ });
+
+ it("re-opens only the active session's tunnel on its previous port and follows a port change", async () => {
+ // Dialing a session counts as activity, so restoring every persisted
+ // session would keep idle sandboxes awake and billing.
+ window.localStorage.setItem(
+ BACKENDS_STORAGE_KEY,
+ JSON.stringify([
+ {
+ id: "mars-idle",
+ name: "Agent · sess-0",
+ host: "http://127.0.0.1:50000",
+ apiKey: "",
+ kind: "local",
+ marsSessionId: "sess_idle",
+ },
+ {
+ id: "mars-1",
+ name: "Agent · sess-1",
+ host: "http://127.0.0.1:51000",
+ apiKey: "",
+ kind: "local",
+ marsSessionId: "sess_abc",
+ },
+ ]),
+ );
+ window.localStorage.setItem(
+ ACTIVE_BACKEND_STORAGE_KEY,
+ JSON.stringify({ backendId: "mars-1", orgId: null }),
+ );
+ __resetActiveStoreForTests();
+ window.marsBridge = fakeMarsBridge(52000);
+
+ const { result } = renderHook(
+ () => {
+ useRestoreMarsTunnels();
+ return useActiveBackendContext();
+ },
+ { wrapper: makeWrapper() },
+ );
+
+ await waitFor(() =>
+ expect(result.current.backends.find((b) => b.id === "mars-1")?.host).toBe(
+ "http://127.0.0.1:52000",
+ ),
+ );
+ expect(window.marsBridge!.openTunnel).toHaveBeenCalledTimes(1);
+ expect(window.marsBridge!.openTunnel).toHaveBeenCalledWith({
+ sessionId: "sess_abc",
+ localPort: 51000,
+ });
+ });
+
+ it("reports the launch restore as pending until the session's agent-server answers", async () => {
+ // Arrange — the active session's sandbox is still booting after launch.
+ window.localStorage.setItem(
+ BACKENDS_STORAGE_KEY,
+ JSON.stringify([
+ {
+ id: "mars-1",
+ name: "Agent · sess-1",
+ host: "http://127.0.0.1:51000",
+ apiKey: "",
+ kind: "local",
+ marsSessionId: "sess_abc",
+ },
+ ]),
+ );
+ window.localStorage.setItem(
+ ACTIVE_BACKEND_STORAGE_KEY,
+ JSON.stringify({ backendId: "mars-1", orgId: null }),
+ );
+ __resetActiveStoreForTests();
+ let bootAgentServer: (version: string) => void = () => {};
+ validateLocalBackend.mockReturnValueOnce(
+ new Promise((resolve) => {
+ bootAgentServer = resolve;
+ }),
+ );
+
+ // Act
+ const { result } = renderHook(() => useRestoreMarsTunnels(), {
+ wrapper: makeWrapper(),
+ });
+ await waitFor(() => expect(validateLocalBackend).toHaveBeenCalled());
+ const pendingWhileBooting = result.current;
+ act(() => bootAgentServer("1.44.1"));
+
+ // Assert
+ expect(pendingWhileBooting).toBe(true);
+ await waitFor(() => expect(result.current).toBe(false));
+ });
+
+ it("does not reconnect a session attach() just connected", async () => {
+ const { result } = renderHook(
+ () => {
+ useRestoreMarsTunnels();
+ return useMarsTunnelBackend();
+ },
+ { wrapper: makeWrapper() },
+ );
+
+ await act(async () => {
+ await result.current.attach(SESSION);
+ });
+
+ expect(window.marsBridge!.openTunnel).toHaveBeenCalledTimes(1);
+ expect(validateLocalBackend).toHaveBeenCalledTimes(1);
+ });
+
+ it("leaves the restored tunnel open when the agent-server behind it does not answer yet", async () => {
+ // A slow cold wake can still recover through the health poll, and the
+ // tunnel may be shared with a concurrent attach().
+ window.localStorage.setItem(
+ BACKENDS_STORAGE_KEY,
+ JSON.stringify([
+ {
+ id: "mars-1",
+ name: "Agent · sess-1",
+ host: "http://127.0.0.1:51000",
+ apiKey: "",
+ kind: "local",
+ marsSessionId: "sess_abc",
+ },
+ ]),
+ );
+ window.localStorage.setItem(
+ ACTIVE_BACKEND_STORAGE_KEY,
+ JSON.stringify({ backendId: "mars-1", orgId: null }),
+ );
+ __resetActiveStoreForTests();
+ // The first probe fails and the clock jumps past the wait's deadline,
+ // whoever else reads Date.now() first (e.g. the sign-in query).
+ let now = 0;
+ vi.spyOn(Date, "now").mockImplementation(() => now);
+ validateLocalBackend.mockImplementation(async () => {
+ now = Number.MAX_SAFE_INTEGER;
+ throw new Error("connection refused");
+ });
+
+ const { result } = renderHook(() => useRestoreMarsTunnels(), {
+ wrapper: makeWrapper(),
+ });
+
+ await waitFor(() => expect(result.current).toBe(false));
+ expect(window.marsBridge!.closeTunnel).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/i18n/mars-session-count.test.ts b/__tests__/i18n/mars-session-count.test.ts
new file mode 100644
index 0000000000..1bf4f1eba0
--- /dev/null
+++ b/__tests__/i18n/mars-session-count.test.ts
@@ -0,0 +1,41 @@
+import i18next from "i18next";
+import { describe, expect, it } from "vitest";
+
+import translations from "#/i18n/translation.json";
+import { SESSION_COUNT_I18N_KEY } from "#/components/features/backends/managed-agents/managed-agents-labels";
+
+type Translations = Record<string, Record<string, string>>;
+
+async function sessionCount(lng: string, count: number) {
+ const resources: Record<string, { translation: Record<string, string> }> = {};
+ for (const [key, byLang] of Object.entries(translations as Translations)) {
+ if (!key.startsWith(SESSION_COUNT_I18N_KEY)) continue;
+ for (const [lang, value] of Object.entries(byLang)) {
+ resources[lang] ??= { translation: {} };
+ resources[lang].translation[key] = value;
+ }
+ }
+ const instance = i18next.createInstance();
+ await instance.init({ lng, fallbackLng: "en", resources });
+ return instance.t(SESSION_COUNT_I18N_KEY, { count });
+}
+
+describe("DO_AGENTS$SESSION_COUNT plurals", () => {
+ it("uses the singular for one session in English", async () => {
+ expect(await sessionCount("en", 1)).toBe("1 session");
+ expect(await sessionCount("en", 2)).toBe("2 sessions");
+ });
+
+ it("never falls back to English for Ukrainian or Arabic plural forms", async () => {
+ expect(await sessionCount("uk", 1)).toBe("1 сесія");
+ expect(await sessionCount("uk", 3)).toBe("3 сесії");
+ expect(await sessionCount("uk", 5)).toBe("5 сесій");
+ expect(await sessionCount("ar", 2)).toBe("2 جلستان");
+ expect(await sessionCount("ar", 3)).toBe("3 جلسات");
+ expect(await sessionCount("ar", 11)).toBe("11 جلسة");
+ });
+
+ it("keeps French zero singular", async () => {
+ expect(await sessionCount("fr", 0)).toBe("0 session");
+ });
+});
diff --git a/__tests__/routes/conversation-backend-switch.test.tsx b/__tests__/routes/conversation-backend-switch.test.tsx
index 33866c1ca7..248b50ab81 100644
--- a/__tests__/routes/conversation-backend-switch.test.tsx
+++ b/__tests__/routes/conversation-backend-switch.test.tsx
@@ -124,18 +124,21 @@ function makeConversation(
};
}
-function renderConversation() {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- });
- return render(
- <MemoryRouter initialEntries={[`/conversations/${CLOUD_CONVERSATION_ID}`]}>
+// Shared by `conversationTree` so a `rerender` keeps the same cache; each
+// `renderConversation` starts a fresh one, like a real remount.
+let queryClient: QueryClient;
+
+function conversationTree(conversationId: string, search = "") {
+ return (
+ <MemoryRouter
+ initialEntries={[`/conversations/${conversationId}${search}`]}
+ >
<QueryClientProvider client={queryClient}>
<ActiveBackendProvider>
<NavigationProvider
value={{
- currentPath: `/conversations/${CLOUD_CONVERSATION_ID}`,
- conversationId: CLOUD_CONVERSATION_ID,
+ currentPath: `/conversations/${conversationId}`,
+ conversationId,
isNavigating: false,
navigate: vi.fn(),
}}
@@ -144,10 +147,17 @@ function renderConversation() {
</NavigationProvider>
</ActiveBackendProvider>
</QueryClientProvider>
- </MemoryRouter>,
+ </MemoryRouter>
);
}
+function renderConversation(search = "") {
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return render(conversationTree(CLOUD_CONVERSATION_ID, search));
+}
+
function makeSharedConversation(id: string): SharedConversation {
return {
id,
@@ -245,6 +255,40 @@ describe("conversation route — backend switch", () => {
expect(screen.queryByTestId("conversation-main")).not.toBeInTheDocument();
});
});
+
+ it("tears down the view when the org changes away from the one the URL pins", async () => {
+ // Arrange — the link pins the conversation to org-a of the cloud backend.
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-a" });
+ renderConversation(`?backend=${cloudBackend.id}&org=org-a`);
+ expect(await screen.findByTestId("conversation-main")).toBeInTheDocument();
+
+ // Act — same backend, another org.
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-b" });
+
+ // Assert
+ await waitFor(() => {
+ expect(screen.queryByTestId("conversation-main")).not.toBeInTheDocument();
+ });
+ });
+
+ it("renders a conversation of the new backend reached without leaving the route", async () => {
+ // Arrange — switching DigitalOcean sessions swaps the backend and goes
+ // straight to that session's conversation, never via /conversations.
+ const LOCAL_CONVERSATION_ID = "conv-local";
+ vi.mocked(
+ AgentServerConversationService.batchGetAppConversations,
+ ).mockImplementation(async (ids) => ids.map((id) => makeConversation(id)));
+ setActiveSelection({ backendId: cloudBackend.id });
+ const { rerender } = renderConversation();
+ await screen.findByTestId("conversation-main");
+
+ // Act
+ setActiveSelection({ backendId: localBackend.id });
+ rerender(conversationTree(LOCAL_CONVERSATION_ID));
+
+ // Assert
+ expect(await screen.findByTestId("conversation-main")).toBeInTheDocument();
+ });
});
describe("conversation route — cloud sandbox resume", () => {
diff --git a/__tests__/scripts/mars-api.test.ts b/__tests__/scripts/mars-api.test.ts
new file mode 100644
index 0000000000..606cabc4f5
--- /dev/null
+++ b/__tests__/scripts/mars-api.test.ts
@@ -0,0 +1,84 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ MarsApiError,
+ buildOpenHandsManifest,
+ createMarsApiClient,
+} from "../../scripts/mars-api.mjs";
+
+const API_URL = "https://api.example.test";
+
+function clientAnswering(body: unknown) {
+ const fetchImpl = vi.fn(
+ async () =>
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ const client = createMarsApiClient({
+ getToken: async () => "token",
+ baseUrl: API_URL,
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ });
+ return { client, fetchImpl };
+}
+
+describe("listSandboxSizes", () => {
+ it("reads the size catalog from the sessions sandbox endpoint", async () => {
+ const sizes = [
+ {
+ slug: "mars-2vcpu-4gb",
+ vcpus: 2,
+ memory_mb: 4096,
+ price_per_hour_usd: 0.036,
+ price_per_month_usd: 24,
+ },
+ ];
+ const { client, fetchImpl } = clientAnswering({ sizes });
+
+ const result = await client.listSandboxSizes();
+
+ expect(result).toEqual(sizes);
+ expect(fetchImpl).toHaveBeenCalledWith(
+ `${API_URL}/v2/agents/sessions/sandbox/sizes`,
+ expect.objectContaining({ method: "GET" }),
+ );
+ });
+
+ it("answers an empty list when the body has no sizes", async () => {
+ const { client } = clientAnswering({});
+
+ expect(await client.listSandboxSizes()).toEqual([]);
+ });
+});
+
+describe("buildOpenHandsManifest", () => {
+ it("writes the sandbox size as a top-level manifest key", () => {
+ expect(buildOpenHandsManifest({ size: "mars-16vcpu-32gb" })).toBe(
+ [
+ "agent: openhands",
+ "template: openhands",
+ "keep_warm: false",
+ "size: mars-16vcpu-32gb",
+ "",
+ ].join("\n"),
+ );
+ });
+
+ it("leaves the size to DigitalOcean when none is given", () => {
+ expect(buildOpenHandsManifest({ size: "" })).not.toMatch(/size:/);
+ expect(buildOpenHandsManifest()).not.toMatch(/size:/);
+ });
+
+ it.each([
+ "mars-2vcpu-4gb\nsecrets:",
+ "Mars-2vcpu",
+ "-leading-dash",
+ "has space",
+ "a".repeat(64),
+ ])("rejects %j as a size so nothing can be injected", (size) => {
+ expect(() => buildOpenHandsManifest({ size })).toThrow(MarsApiError);
+ });
+});
diff --git a/__tests__/scripts/mars-credentials.test.ts b/__tests__/scripts/mars-credentials.test.ts
new file mode 100644
index 0000000000..561bbc6699
--- /dev/null
+++ b/__tests__/scripts/mars-credentials.test.ts
@@ -0,0 +1,187 @@
+// @vitest-environment node
+import { mkdtempSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import {
+ CREDENTIAL_KIND_OAUTH,
+ CREDENTIAL_KIND_PAT,
+ createCredentialStore,
+ isValidPatFormat,
+} from "../../scripts/mars-credentials.mjs";
+
+const STORE_FILENAME = "mars-credentials.json";
+
+/** Stand-in for Electron's safeStorage; reversible, not secure. */
+const fakeSafeStorage = {
+ isEncryptionAvailable: () => true,
+ encryptString: (value: string) => Buffer.from(`enc:${value}`),
+ decryptString: (buffer: Buffer) => buffer.toString().replace(/^enc:/, ""),
+};
+
+function newStore({ safeStorage = fakeSafeStorage } = {}) {
+ const userDataPath = mkdtempSync(join(tmpdir(), "mars-creds-"));
+ return {
+ userDataPath,
+ store: createCredentialStore({ userDataPath, safeStorage }),
+ };
+}
+
+describe("isValidPatFormat", () => {
+ it.each([
+ ["a".repeat(64), true],
+ [`do${"a".repeat(69)}`, true],
+ [`xx${"a".repeat(69)}`, false],
+ ["short", false],
+ ["", false],
+ ])("validates %s as %s the way doctl does", (token, expected) => {
+ expect(isValidPatFormat(token)).toBe(expected);
+ });
+});
+
+describe("createCredentialStore", () => {
+ it("keeps the token out of the metadata it hands to the renderer", () => {
+ const { store } = newStore();
+
+ const metadata = store.save({
+ kind: CREDENTIAL_KIND_PAT,
+ token: "a".repeat(64),
+ label: "Platform team",
+ });
+
+ expect(metadata).not.toHaveProperty("token");
+ expect(JSON.stringify(store.list())).not.toContain("a".repeat(64));
+ expect(store.getActiveToken()).toBe("a".repeat(64));
+ });
+
+ it("holds one credential per team and switches between them", () => {
+ const { store } = newStore();
+
+ const first = store.save({
+ kind: CREDENTIAL_KIND_PAT,
+ token: "1".repeat(64),
+ label: "Team one",
+ });
+ const second = store.save({
+ kind: CREDENTIAL_KIND_OAUTH,
+ token: "2".repeat(64),
+ label: "Team two",
+ });
+
+ expect(store.getActive()?.id).toBe(second?.id);
+
+ store.setActive(first!.id);
+ expect(store.getActiveToken()).toBe("1".repeat(64));
+ });
+
+ it("survives a restart by reading the encrypted file back", () => {
+ const { userDataPath, store } = newStore();
+ store.save({
+ kind: CREDENTIAL_KIND_PAT,
+ token: "3".repeat(64),
+ label: "Persisted",
+ });
+
+ const reopened = createCredentialStore({
+ userDataPath,
+ safeStorage: fakeSafeStorage,
+ });
+
+ expect(reopened.getActiveToken()).toBe("3".repeat(64));
+ expect(reopened.isPersistent).toBe(true);
+ });
+
+ it("treats an expired credential as unusable without deleting it", () => {
+ const { store } = newStore();
+ store.save({
+ kind: CREDENTIAL_KIND_OAUTH,
+ token: "4".repeat(64),
+ label: "Lapsed",
+ expiresAt: new Date(Date.now() - 1000).toISOString(),
+ });
+
+ // Implicit grants cannot be refreshed, so the UI prompts for a fresh
+ // sign-in rather than silently discarding the connection.
+ expect(store.getActive()?.isExpired).toBe(true);
+ expect(store.getActiveToken()).toBeNull();
+ expect(store.list()).toHaveLength(1);
+ });
+
+ it("never writes a plaintext token when the keychain is unavailable", () => {
+ const { userDataPath, store } = newStore({
+ safeStorage: { ...fakeSafeStorage, isEncryptionAvailable: () => false },
+ });
+
+ store.save({
+ kind: CREDENTIAL_KIND_PAT,
+ token: "5".repeat(64),
+ label: "Session only",
+ });
+
+ const onDisk = readFileSync(join(userDataPath, STORE_FILENAME), "utf8");
+ expect(onDisk).not.toContain("5".repeat(64));
+ // Usable for this process, but gone after a restart.
+ expect(store.getActiveToken()).toBe("5".repeat(64));
+ expect(store.isPersistent).toBe(false);
+ });
+
+ it("decrypts each token once, not on every use", () => {
+ let decrypts = 0;
+ const { userDataPath, store } = newStore();
+ store.save({
+ kind: CREDENTIAL_KIND_PAT,
+ token: "8".repeat(64),
+ label: "Cached",
+ });
+ const reopened = createCredentialStore({
+ userDataPath,
+ safeStorage: {
+ ...fakeSafeStorage,
+ decryptString: (buffer: Buffer) => {
+ decrypts += 1;
+ return fakeSafeStorage.decryptString(buffer);
+ },
+ },
+ });
+
+ expect(reopened.getActiveToken()).toBe("8".repeat(64));
+ expect(reopened.getActiveToken()).toBe("8".repeat(64));
+ expect(decrypts).toBe(1);
+
+ reopened.remove(reopened.getActive()!.id);
+ expect(reopened.getActiveToken()).toBeNull();
+ });
+
+ it("keeps everything in memory without a userDataPath", () => {
+ const store = createCredentialStore({
+ userDataPath: null,
+ safeStorage: fakeSafeStorage,
+ });
+
+ store.save({
+ kind: CREDENTIAL_KIND_PAT,
+ token: "9".repeat(64),
+ label: "Web",
+ });
+
+ expect(store.getActiveToken()).toBe("9".repeat(64));
+ expect(store.isPersistent).toBe(false);
+ });
+
+ it("falls back to another connection when the active one is removed", () => {
+ const { store } = newStore();
+ const first = store.save({
+ kind: CREDENTIAL_KIND_PAT,
+ token: "6".repeat(64),
+ label: "Team one",
+ });
+ const second = store.save({
+ kind: CREDENTIAL_KIND_PAT,
+ token: "7".repeat(64),
+ label: "Team two",
+ });
+
+ expect(store.remove(second!.id)?.id).toBe(first?.id);
+ });
+});
diff --git a/__tests__/scripts/mars-oauth.test.ts b/__tests__/scripts/mars-oauth.test.ts
new file mode 100644
index 0000000000..84c9511fa9
--- /dev/null
+++ b/__tests__/scripts/mars-oauth.test.ts
@@ -0,0 +1,151 @@
+// @vitest-environment node
+import { createServer } from "node:net";
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ OAUTH_REDIRECT_PORT,
+ OAUTH_REDIRECT_URI,
+ buildAuthorizeUrl,
+ parseImplicitGrant,
+ signInWithDigitalOcean,
+} from "../../scripts/mars-oauth.mjs";
+
+const STATE = "state-abc";
+
+describe("buildAuthorizeUrl", () => {
+ it("requests the implicit grant against the registered redirect URI", () => {
+ const url = new URL(
+ buildAuthorizeUrl({ clientId: "client-1", state: STATE }),
+ );
+
+ // Authorization-code would require shipping a client_secret in the
+ // desktop binary, which DigitalOcean documents no PKCE alternative for.
+ expect(url.searchParams.get("response_type")).toBe("token");
+ expect(url.searchParams.get("client_id")).toBe("client-1");
+ expect(url.searchParams.get("state")).toBe(STATE);
+ expect(url.searchParams.get("redirect_uri")).toBe(OAUTH_REDIRECT_URI);
+ });
+});
+
+describe("parseImplicitGrant", () => {
+ it("recovers the token from a relayed fragment", () => {
+ const grant = parseImplicitGrant(
+ `access_token=tok-1&token_type=bearer&expires_in=2592000&state=${STATE}`,
+ STATE,
+ );
+
+ expect(grant.accessToken).toBe("tok-1");
+ expect(Date.parse(grant.expiresAt ?? "")).toBeGreaterThan(Date.now());
+ });
+
+ it("rejects a callback whose state does not match the attempt", () => {
+ expect(() =>
+ parseImplicitGrant("access_token=tok-1&state=forged-state", STATE),
+ ).toThrow(/state did not match/i);
+ });
+
+ it("treats a query-only callback with no fragment as a failure", () => {
+ // Browsers never send the fragment to the server, so the bare loopback
+ // request carries no token — without the relay page the flow would
+ // silently hang here instead of reporting anything.
+ expect(() => parseImplicitGrant("", STATE)).toThrow(
+ /did not return an access token/i,
+ );
+ });
+
+ it("surfaces the provider's error description when access is declined", () => {
+ expect(() =>
+ parseImplicitGrant(
+ "error=access_denied&error_description=The+user+denied+access",
+ STATE,
+ ),
+ ).toThrow("The user denied access");
+ });
+});
+
+describe("signInWithDigitalOcean", () => {
+ it("completes when the relay page posts the fragment back", async () => {
+ const openExternal = vi.fn(async (authorizeUrl) => {
+ const state = new URL(authorizeUrl).searchParams.get("state");
+
+ // Stand in for the browser: fetch the callback page, then replay the
+ // fragment to the relay route the way its inline script does.
+ await fetch(OAUTH_REDIRECT_URI);
+ await fetch(`http://127.0.0.1:${OAUTH_REDIRECT_PORT}/callback-token`, {
+ method: "POST",
+ body: `access_token=tok-2&token_type=bearer&expires_in=60&state=${state}`,
+ });
+ });
+
+ const grant = await signInWithDigitalOcean({
+ clientId: "client-1",
+ openExternal,
+ });
+
+ expect(grant.accessToken).toBe("tok-2");
+ expect(openExternal).toHaveBeenCalledOnce();
+ });
+
+ it("cuts off an oversized relay body and still accepts the real one", async () => {
+ let oversized: unknown = null;
+ const openExternal = vi.fn(async (authorizeUrl) => {
+ const state = new URL(authorizeUrl).searchParams.get("state");
+ const relay = `http://127.0.0.1:${OAUTH_REDIRECT_PORT}/callback-token`;
+
+ // The reader drops the connection rather than buffering it all.
+ oversized = await fetch(relay, {
+ method: "POST",
+ body: "x".repeat(64 * 1024),
+ }).catch((error: unknown) => error);
+ await fetch(relay, {
+ method: "POST",
+ body: `access_token=tok-3&token_type=bearer&state=${state}`,
+ });
+ });
+
+ const grant = await signInWithDigitalOcean({
+ clientId: "client-1",
+ openExternal,
+ });
+
+ expect(oversized).toBeInstanceOf(Error);
+ expect(grant.accessToken).toBe("tok-3");
+ });
+
+ it("explains a busy redirect port and leaves no rejection behind", async () => {
+ // Arrange
+ const blocker = createServer();
+ await new Promise<void>((resolve) =>
+ blocker.listen(OAUTH_REDIRECT_PORT, "127.0.0.1", resolve),
+ );
+ const unhandled = vi.fn();
+ process.on("unhandledRejection", unhandled);
+ const openExternal = vi.fn();
+
+ try {
+ // Act
+ const attempt = signInWithDigitalOcean({
+ clientId: "client-1",
+ openExternal,
+ timeoutMs: 20,
+ });
+
+ // Assert
+ await expect(attempt).rejects.toThrow(
+ `Port ${OAUTH_REDIRECT_PORT} is already in use`,
+ );
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ expect(unhandled).not.toHaveBeenCalled();
+ expect(openExternal).not.toHaveBeenCalled();
+ } finally {
+ process.off("unhandledRejection", unhandled);
+ await new Promise((resolve) => blocker.close(resolve));
+ }
+ });
+
+ it("explains that a token is the way forward when no OAuth client is built in", async () => {
+ await expect(
+ signInWithDigitalOcean({ clientId: null, openExternal: vi.fn() }),
+ ).rejects.toThrow(/personal access token/i);
+ });
+});
diff --git a/__tests__/scripts/mars-session.test.ts b/__tests__/scripts/mars-session.test.ts
new file mode 100644
index 0000000000..e997d55375
--- /dev/null
+++ b/__tests__/scripts/mars-session.test.ts
@@ -0,0 +1,170 @@
+// @vitest-environment node
+import { createServer } from "node:http";
+import net from "node:net";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createMarsApiClient } from "../../scripts/mars-api.mjs";
+import { ensureSessionAwake } from "../../scripts/mars-session.mjs";
+
+const sessionId = "sess_abc123";
+const accessToken = "test-token";
+const deviceId = "device-123";
+
+/**
+ * A fake harness-api sessions endpoint. `statusSequence` is popped from the
+ * front on each GET (repeating the last entry once exhausted), so a test can
+ * script e.g. ["SESSION_STATUS_PAUSED", "SESSION_STATUS_READY"] to simulate
+ * the session coming up after a resume call. `hang` leaves every GET
+ * unanswered.
+ */
+function startFakeSessionsApi(
+ statusSequence: string[],
+ { expectToken = accessToken, hang = false } = {},
+) {
+ let resumeCalls = 0;
+ let getCalls = 0;
+
+ const server = createServer((req, res) => {
+ if (
+ req.headers.authorization !== `Bearer ${expectToken}` ||
+ req.headers["x-device-uuid"] !== deviceId
+ ) {
+ res.writeHead(401).end();
+ return;
+ }
+ if (
+ req.method === "GET" &&
+ req.url === `/v2/agents/sessions/${sessionId}`
+ ) {
+ getCalls += 1;
+ if (hang) return;
+ const status =
+ statusSequence[Math.min(getCalls - 1, statusSequence.length - 1)];
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ session: { session_id: sessionId, status } }));
+ return;
+ }
+ if (
+ req.method === "POST" &&
+ req.url === `/v2/agents/sessions/${sessionId}/resume`
+ ) {
+ resumeCalls += 1;
+ res.writeHead(204).end();
+ return;
+ }
+ res.writeHead(404).end();
+ });
+
+ return new Promise<{
+ client: ReturnType<typeof createMarsApiClient>;
+ close: () => void;
+ resumeCalls: () => number;
+ getCalls: () => number;
+ }>((resolve) => {
+ server.listen(0, "127.0.0.1", () => {
+ const { port } = server.address() as net.AddressInfo;
+ resolve({
+ client: createMarsApiClient({
+ baseUrl: `http://127.0.0.1:${port}`,
+ deviceId,
+ getToken: async () => accessToken,
+ }),
+ close: () => {
+ server.closeAllConnections();
+ server.close();
+ },
+ resumeCalls: () => resumeCalls,
+ getCalls: () => getCalls,
+ });
+ });
+ });
+}
+
+describe("ensureSessionAwake", () => {
+ let api: Awaited<ReturnType<typeof startFakeSessionsApi>> | undefined;
+
+ afterEach(() => {
+ api?.close();
+ api = undefined;
+ });
+
+ it("resolves immediately for an already-ready session, without resuming", async () => {
+ api = await startFakeSessionsApi(["SESSION_STATUS_READY"]);
+
+ const session = await ensureSessionAwake({ api: api.client, sessionId });
+
+ expect(session.status).toBe("SESSION_STATUS_READY");
+ expect(api.resumeCalls()).toBe(0);
+ });
+
+ it("resumes a paused session and waits for it to become ready", async () => {
+ api = await startFakeSessionsApi([
+ "SESSION_STATUS_PAUSED",
+ "SESSION_STATUS_PAUSED",
+ "SESSION_STATUS_READY",
+ ]);
+
+ const session = await ensureSessionAwake({
+ api: api.client,
+ sessionId,
+ pollIntervalMs: 10,
+ });
+
+ expect(session.status).toBe("SESSION_STATUS_READY");
+ expect(api.resumeCalls()).toBe(1);
+ expect(api.getCalls()).toBeGreaterThanOrEqual(3);
+ });
+
+ it("rejects immediately for a terminal session", async () => {
+ api = await startFakeSessionsApi(["SESSION_STATUS_FAILED"]);
+
+ await expect(
+ ensureSessionAwake({ api: api.client, sessionId, pollIntervalMs: 10 }),
+ ).rejects.toThrow(/SESSION_STATUS_FAILED/);
+ expect(api.resumeCalls()).toBe(0);
+ });
+
+ it("rejects if the session becomes terminal while resuming", async () => {
+ api = await startFakeSessionsApi([
+ "SESSION_STATUS_PAUSED",
+ "SESSION_STATUS_DESTROYED",
+ ]);
+
+ await expect(
+ ensureSessionAwake({ api: api.client, sessionId, pollIntervalMs: 10 }),
+ ).rejects.toThrow(/became SESSION_STATUS_DESTROYED/);
+ });
+
+ it("times out if the session never becomes ready", async () => {
+ api = await startFakeSessionsApi(["SESSION_STATUS_PAUSED"]);
+
+ await expect(
+ ensureSessionAwake({
+ api: api.client,
+ sessionId,
+ pollIntervalMs: 10,
+ timeoutMs: 50,
+ }),
+ ).rejects.toThrow(/Timed out waiting/);
+ });
+
+ it("times out on schedule even while a request is still hanging", async () => {
+ api = await startFakeSessionsApi(["SESSION_STATUS_READY"], { hang: true });
+ const startedAt = Date.now();
+
+ await expect(
+ ensureSessionAwake({ api: api.client, sessionId, timeoutMs: 50 }),
+ ).rejects.toThrow(/Timed out waiting/);
+ expect(Date.now() - startedAt).toBeLessThan(1_000);
+ });
+
+ it("propagates an HTTP error from the get-session call", async () => {
+ api = await startFakeSessionsApi(["SESSION_STATUS_READY"], {
+ expectToken: "other-token",
+ });
+
+ await expect(
+ ensureSessionAwake({ api: api.client, sessionId }),
+ ).rejects.toMatchObject({ name: "MarsApiError", status: 401 });
+ });
+});
diff --git a/__tests__/scripts/mars-tunnel-bridge.test.ts b/__tests__/scripts/mars-tunnel-bridge.test.ts
new file mode 100644
index 0000000000..923d25dd25
--- /dev/null
+++ b/__tests__/scripts/mars-tunnel-bridge.test.ts
@@ -0,0 +1,534 @@
+// @vitest-environment node
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ MARS_TUNNEL_IPC,
+ createMarsTunnelBridge,
+ readMarsConfig,
+ readMarsDefaults,
+} from "../../scripts/mars-tunnel-bridge.mjs";
+import {
+ CREDENTIAL_KIND_OAUTH,
+ createCredentialStore,
+} from "../../scripts/mars-credentials.mjs";
+import { revokeToken } from "../../scripts/mars-oauth.mjs";
+
+vi.mock("../../scripts/mars-oauth.mjs", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../scripts/mars-oauth.mjs")>()),
+ revokeToken: vi.fn(async () => {}),
+}));
+
+const VALID_PAT = `dop_v1_${"a".repeat(64)}`;
+const OTHER_PAT = `dop_v1_${"b".repeat(64)}`;
+const THIRD_PAT = `dop_v1_${"c".repeat(64)}`;
+
+type AuthState = {
+ connections: { id: string }[];
+ active: { id: string } | null;
+};
+const API_URL = "https://api.example.test";
+
+/** What harness-api answers for a session with no public URL. */
+/** A fake ipcMain that just records handlers so tests can invoke them directly. */
+function fakeIpcMain() {
+ const handlers = new Map<
+ string,
+ (event: unknown, ...args: unknown[]) => unknown
+ >();
+ return {
+ channels: () => [...handlers.keys()],
+ handle: vi.fn(
+ (
+ channel: string,
+ fn: (event: unknown, ...args: unknown[]) => unknown,
+ ) => {
+ handlers.set(channel, fn);
+ },
+ ),
+ invoke: (channel: string, ...args: unknown[]) => {
+ const handler = handlers.get(channel);
+ if (!handler) throw new Error(`no handler registered for ${channel}`);
+ return handler({}, ...args);
+ },
+ };
+}
+
+function fakeRegistry() {
+ return {
+ attach: vi.fn(
+ async (params: { sessionId: string; remotePort: number }) => ({
+ ...params,
+ localPort: 51000,
+ status: "connected" as const,
+ error: undefined,
+ upstreamFailure: null,
+ }),
+ ),
+ detach: vi.fn(async () => {}),
+ detachAll: vi.fn(async () => {}),
+ detachOwnedBy: vi.fn(async () => {}),
+ get: vi.fn(() => undefined),
+ };
+}
+
+function fakeApi() {
+ return {
+ verifyAccess: vi.fn(async () => {}),
+ listSessions: vi.fn(async () => ({ sessions: [], nextPageToken: null })),
+ listAgentConfigs: vi.fn(async () => ({
+ configs: [] as { id: string; name?: string }[],
+ nextPageToken: null,
+ })),
+ getAgentConfig: vi.fn(
+ async (
+ id: string,
+ ): Promise<{ id: string; manifest: unknown } | null> => ({
+ id,
+ manifest: null,
+ }),
+ ),
+ listConfigSessions: vi.fn(async () => ({
+ sessions: [],
+ nextPageToken: null,
+ })),
+ listSandboxSizes: vi.fn(async () => [
+ { slug: "mars-2vcpu-4gb", vcpus: 2, memory_mb: 4096 },
+ ]),
+ createAgentConfig: vi.fn(async (name: string) => ({
+ id: "cfg_new",
+ name,
+ })),
+ createSessionFromConfig: vi.fn(async () => ({
+ session_id: "sess_new",
+ status: "SESSION_STATUS_PROVISIONING",
+ })),
+ pauseSession: vi.fn(async () => {}),
+ resumeSession: vi.fn(async () => {}),
+ destroySession: vi.fn(async () => {}),
+ deleteAgentConfig: vi.fn(async () => {}),
+ getSession: vi.fn(async () => null),
+ };
+}
+
+/**
+ * `realRegistry` keeps the bridge's own tunnel registry, whose listeners bind
+ * loopback without dialing anything until a client connects.
+ */
+function setup({ realRegistry = false } = {}) {
+ const registry = fakeRegistry();
+ const api = fakeApi();
+ const credentials = createCredentialStore({
+ userDataPath: mkdtempSync(join(tmpdir(), "mars-bridge-")),
+ });
+ const ensureAwake = vi.fn(async ({ sessionId }: { sessionId: string }) => ({
+ session_id: sessionId,
+ status: "SESSION_STATUS_READY",
+ }));
+ const bridge = createMarsTunnelBridge({
+ registry: realRegistry ? undefined : registry,
+ api,
+ credentials,
+ ensureAwake,
+ env: { MARS_API_BASE_URL: API_URL },
+ });
+ const ipcMain = fakeIpcMain();
+ bridge.registerIpc(ipcMain);
+ return {
+ registry,
+ api,
+ credentials,
+ ensureAwake,
+ bridge,
+ ipcMain,
+ };
+}
+
+describe("readMarsConfig", () => {
+ it.each([
+ {
+ env: { DO_OAUTH_CLIENT_ID: "env-client" },
+ defaults: { oauthClientId: "shipped-client" },
+ expected: "env-client",
+ },
+ {
+ env: {},
+ defaults: { oauthClientId: "shipped-client" },
+ expected: "shipped-client",
+ },
+ { env: {}, defaults: { oauthClientId: "" }, expected: null },
+ ])(
+ "resolves the OAuth client id with env over shipped defaults ($expected)",
+ ({ env, defaults, expected }) => {
+ expect(readMarsConfig(env, defaults).oauthClientId).toBe(expected);
+ },
+ );
+
+ it("reads the shipped defaults from config/defaults.json", () => {
+ expect(readMarsDefaults()).toHaveProperty("apiBaseUrl");
+ });
+});
+
+describe("createMarsTunnelBridge", () => {
+ it("registers a handler for every MARS channel", () => {
+ const { ipcMain } = setup();
+
+ expect(ipcMain.channels().sort()).toEqual(
+ Object.values(MARS_TUNNEL_IPC).sort(),
+ );
+ });
+
+ it("openTunnel opens the port-forward tunnel bound to the active connection on the pinned guest port", async () => {
+ const { registry, credentials, ipcMain } = setup();
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+
+ const result = await ipcMain.invoke(MARS_TUNNEL_IPC.openTunnel, {
+ sessionId: "sess_a",
+ localPort: 51000,
+ });
+
+ expect(registry.attach).toHaveBeenCalledWith({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: expect.any(Function),
+ apiUrl: API_URL,
+ localPort: 51000,
+ owner: credentials.getActive()?.id,
+ });
+ expect(result).toMatchObject({
+ sessionId: "sess_a",
+ transport: "tunnel",
+ host: "http://127.0.0.1:51000",
+ localPort: 51000,
+ });
+ });
+
+ it("a tunnel keeps its own connection's token after switching, and loses it on sign-out", async () => {
+ // Arrange
+ const { registry, ipcMain } = setup();
+ const first = (await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, {
+ token: VALID_PAT,
+ })) as AuthState;
+ const firstId = first.active!.id;
+ await ipcMain.invoke(MARS_TUNNEL_IPC.openTunnel, { sessionId: "sess_a" });
+ const { getAccessToken } = registry.attach.mock.calls[0][0] as unknown as {
+ getAccessToken: () => string | null;
+ };
+
+ // Act
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: OTHER_PAT });
+ const tokenAfterSwitch = getAccessToken();
+ await ipcMain.invoke(MARS_TUNNEL_IPC.signOut, firstId);
+
+ // Assert
+ expect(tokenAfterSwitch).toBe(VALID_PAT);
+ expect(registry.detachOwnedBy).toHaveBeenCalledWith(firstId);
+ expect(getAccessToken()).toBeNull();
+ });
+
+ it("signOut revokes an OAuth connection's token even when it is not the active one", async () => {
+ // Arrange
+ const { credentials, ipcMain } = setup();
+ const oauth = credentials.save({
+ kind: CREDENTIAL_KIND_OAUTH,
+ token: "oauth-token",
+ label: "OAuth team",
+ });
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+
+ // Act
+ await ipcMain.invoke(MARS_TUNNEL_IPC.signOut, oauth!.id);
+
+ // Assert
+ expect(revokeToken).toHaveBeenCalledWith("oauth-token");
+ });
+
+ it("openTunnel refuses to connect while signed out", async () => {
+ const { registry, ipcMain } = setup();
+
+ expect(() =>
+ ipcMain.invoke(MARS_TUNNEL_IPC.openTunnel, { sessionId: "sess_a" }),
+ ).toThrow(/Sign in to DigitalOcean/);
+ expect(registry.attach).not.toHaveBeenCalled();
+ });
+
+ it("savePat keeps a token only once the API accepts it", async () => {
+ const { api, ipcMain } = setup();
+ api.verifyAccess.mockRejectedValueOnce(new Error("403 mars_preview"));
+
+ await expect(
+ ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT }),
+ ).rejects.toThrow(/mars_preview/);
+ const afterRejection = await ipcMain.invoke(MARS_TUNNEL_IPC.getAuthState);
+ const afterSuccess = await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, {
+ token: VALID_PAT,
+ });
+
+ expect(afterRejection).toMatchObject({ connections: [], active: null });
+ expect(afterSuccess).toMatchObject({
+ connections: [expect.objectContaining({ kind: "pat" })],
+ active: expect.objectContaining({ kind: "pat" }),
+ });
+ });
+
+ it("savePat rejects a malformed token without calling the API", async () => {
+ const { api, ipcMain } = setup();
+
+ await expect(
+ ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: "not-a-token" }),
+ ).rejects.toThrow(/personal access token/);
+ expect(api.verifyAccess).not.toHaveBeenCalled();
+ });
+
+ it("a rejected token leaves the previously active connection active", async () => {
+ const { api, ipcMain } = setup();
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+ const second = (await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, {
+ token: OTHER_PAT,
+ })) as AuthState;
+ api.verifyAccess.mockRejectedValueOnce(new Error("403 mars_preview"));
+
+ await expect(
+ ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: THIRD_PAT }),
+ ).rejects.toThrow(/mars_preview/);
+ const state = (await ipcMain.invoke(
+ MARS_TUNNEL_IPC.getAuthState,
+ )) as AuthState;
+
+ expect(state.connections).toHaveLength(2);
+ expect(state.active?.id).toBe(second.active?.id);
+ });
+
+ it("createSession resolves only once the new session is ready", async () => {
+ const { api, ensureAwake, ipcMain } = setup();
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+
+ const session = await ipcMain.invoke(
+ MARS_TUNNEL_IPC.createSession,
+ "cfg_1",
+ "agent-abc123",
+ );
+
+ expect(api.createSessionFromConfig).toHaveBeenCalledWith(
+ "cfg_1",
+ "agent-abc123",
+ );
+ expect(ensureAwake).toHaveBeenCalledWith(
+ expect.objectContaining({ api, sessionId: "sess_new" }),
+ );
+ expect(session).toMatchObject({ status: "SESSION_STATUS_READY" });
+ });
+
+ it("openTunnel right after createSession does not poll the session again, but does once it was paused", async () => {
+ const { ensureAwake, ipcMain, bridge } = setup({ realRegistry: true });
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+
+ try {
+ await ipcMain.invoke(MARS_TUNNEL_IPC.createSession, "cfg_1", "agent-1");
+ const tunnel = await ipcMain.invoke(MARS_TUNNEL_IPC.openTunnel, {
+ sessionId: "sess_new",
+ });
+ expect(tunnel).toMatchObject({ status: "connected" });
+ expect(ensureAwake).toHaveBeenCalledTimes(1);
+
+ await ipcMain.invoke(MARS_TUNNEL_IPC.pauseSession, "sess_new");
+ await ipcMain.invoke(MARS_TUNNEL_IPC.openTunnel, {
+ sessionId: "sess_new",
+ });
+ expect(ensureAwake).toHaveBeenCalledTimes(2);
+ } finally {
+ await bridge.dispose();
+ }
+ });
+
+ it("reusing a live tunnel right after createSession still checks the session", async () => {
+ // Only the first open after createSession skips the poll: a session
+ // paused outside this app (idle, another client) must still be woken.
+ const { ensureAwake, ipcMain, bridge } = setup({ realRegistry: true });
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+
+ try {
+ await ipcMain.invoke(MARS_TUNNEL_IPC.createSession, "cfg_1", "agent-1");
+ await ipcMain.invoke(MARS_TUNNEL_IPC.openTunnel, {
+ sessionId: "sess_new",
+ });
+ await ipcMain.invoke(MARS_TUNNEL_IPC.openTunnel, {
+ sessionId: "sess_new",
+ });
+ expect(ensureAwake).toHaveBeenCalledTimes(2);
+ } finally {
+ await bridge.dispose();
+ }
+ });
+
+ it("openTunnel after closeTunnel polls the session again", async () => {
+ const { ensureAwake, ipcMain, bridge } = setup({ realRegistry: true });
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+
+ try {
+ await ipcMain.invoke(MARS_TUNNEL_IPC.createSession, "cfg_1", "agent-1");
+ await ipcMain.invoke(MARS_TUNNEL_IPC.closeTunnel, "sess_new");
+ await ipcMain.invoke(MARS_TUNNEL_IPC.openTunnel, {
+ sessionId: "sess_new",
+ });
+ expect(ensureAwake).toHaveBeenCalledTimes(2);
+ } finally {
+ await bridge.dispose();
+ }
+ });
+
+ it("createOpenHandsAgent creates a config from the OpenHands manifest and lists it without re-reading", async () => {
+ // Arrange
+ const { api, ipcMain } = setup();
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+ api.listAgentConfigs.mockResolvedValue({
+ configs: [{ id: "cfg_new", name: "my-agent" }],
+ nextPageToken: null,
+ });
+
+ // Act — a renderer passing an LLM key gets no secret into the manifest.
+ const created = await ipcMain.invoke(MARS_TUNNEL_IPC.createOpenHandsAgent, {
+ name: " my-agent ",
+ llmApiKey: "sk-test",
+ });
+ const page = await ipcMain.invoke(MARS_TUNNEL_IPC.listAgentConfigs);
+
+ // Assert
+ expect(api.createAgentConfig).toHaveBeenCalledWith(
+ "my-agent",
+ ["agent: openhands", "template: openhands", "keep_warm: false", ""].join(
+ "\n",
+ ),
+ );
+ expect(created).toMatchObject({ id: "cfg_new", agent: "openhands" });
+ expect(page).toMatchObject({
+ configs: [{ id: "cfg_new", agent: "openhands" }],
+ });
+ expect(api.getAgentConfig).not.toHaveBeenCalled();
+ });
+
+ it("createOpenHandsAgent writes the chosen sandbox size into the manifest", async () => {
+ const { api, ipcMain } = setup();
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+
+ await ipcMain.invoke(MARS_TUNNEL_IPC.createOpenHandsAgent, {
+ name: "my-agent",
+ size: "mars-16vcpu-32gb",
+ });
+
+ expect(api.createAgentConfig).toHaveBeenCalledWith(
+ "my-agent",
+ expect.stringMatching(/^size: mars-16vcpu-32gb$/m),
+ );
+ });
+
+ it("createOpenHandsAgent refuses a size that is not a slug", async () => {
+ const { api, ipcMain } = setup();
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+
+ await expect(
+ ipcMain.invoke(MARS_TUNNEL_IPC.createOpenHandsAgent, {
+ name: "my-agent",
+ size: "x\nkeep_warm: true",
+ }),
+ ).rejects.toMatchObject({ status: 400 });
+ expect(api.createAgentConfig).not.toHaveBeenCalled();
+ });
+
+ it("listSandboxSizes needs a signed-in connection", async () => {
+ const { api, ipcMain } = setup();
+
+ await expect(
+ ipcMain.invoke(MARS_TUNNEL_IPC.listSandboxSizes),
+ ).rejects.toThrow(/Sign in to DigitalOcean/);
+ expect(api.listSandboxSizes).not.toHaveBeenCalled();
+
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+ expect(await ipcMain.invoke(MARS_TUNNEL_IPC.listSandboxSizes)).toEqual([
+ { slug: "mars-2vcpu-4gb", vcpus: 2, memory_mb: 4096 },
+ ]);
+ });
+
+ it("listAgentConfigs names each config's agent from its manifest, reading each once", async () => {
+ const { api, ipcMain } = setup();
+ api.listAgentConfigs.mockResolvedValue({
+ configs: [{ id: "cfg_flat" }, { id: "cfg_spec" }],
+ nextPageToken: null,
+ });
+ api.getAgentConfig.mockImplementation(async (id: string) => ({
+ id,
+ manifest:
+ id === "cfg_flat"
+ ? { agent: "openhands", template: "openhands" }
+ : { kind: "Agent", spec: { agent: "Claude-Code" } },
+ }));
+
+ await ipcMain.invoke(MARS_TUNNEL_IPC.listAgentConfigs);
+ const page = await ipcMain.invoke(MARS_TUNNEL_IPC.listAgentConfigs);
+
+ expect(page).toMatchObject({
+ configs: [
+ { id: "cfg_flat", agent: "openhands" },
+ { id: "cfg_spec", agent: "claude-code" },
+ ],
+ });
+ expect(api.getAgentConfig).toHaveBeenCalledTimes(2);
+ });
+
+ it("dispose() tears down every tunnel", async () => {
+ const { registry, bridge, ipcMain } = setup();
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+ await ipcMain.invoke(MARS_TUNNEL_IPC.openTunnel, { sessionId: "sess_a" });
+
+ await bridge.dispose();
+
+ expect(registry.detachAll).toHaveBeenCalledTimes(1);
+ });
+
+ it("destroySession asks harness-api first and drops the live connection only once it agreed", async () => {
+ const { registry, api, ipcMain } = setup();
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+ await ipcMain.invoke(MARS_TUNNEL_IPC.openTunnel, { sessionId: "sess_1" });
+
+ await ipcMain.invoke(MARS_TUNNEL_IPC.destroySession, "sess_1");
+
+ expect(registry.detach).toHaveBeenCalledWith("sess_1");
+ expect(api.destroySession).toHaveBeenCalledWith("sess_1");
+ expect(api.destroySession.mock.invocationCallOrder[0]).toBeLessThan(
+ registry.detach.mock.invocationCallOrder[0],
+ );
+ });
+
+ it("deleteAgentConfig deletes the config and forgets its cached agent", async () => {
+ const { api, ipcMain } = setup();
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+ api.listAgentConfigs.mockResolvedValue({
+ configs: [{ id: "cfg_1" }],
+ nextPageToken: null,
+ });
+ await ipcMain.invoke(MARS_TUNNEL_IPC.listAgentConfigs);
+
+ await ipcMain.invoke(MARS_TUNNEL_IPC.deleteAgentConfig, "cfg_1");
+ await ipcMain.invoke(MARS_TUNNEL_IPC.listAgentConfigs);
+
+ expect(api.deleteAgentConfig).toHaveBeenCalledWith("cfg_1");
+ expect(api.getAgentConfig).toHaveBeenCalledTimes(2);
+ });
+
+ it("destroySession keeps the connection when harness-api refuses (409/423)", async () => {
+ const { registry, api, ipcMain } = setup();
+ api.destroySession.mockRejectedValueOnce(
+ Object.assign(new Error("a checkpoint is in progress"), { status: 409 }),
+ );
+ await ipcMain.invoke(MARS_TUNNEL_IPC.savePat, { token: VALID_PAT });
+ await ipcMain.invoke(MARS_TUNNEL_IPC.openTunnel, { sessionId: "sess_1" });
+
+ await expect(
+ ipcMain.invoke(MARS_TUNNEL_IPC.destroySession, "sess_1"),
+ ).rejects.toMatchObject({ status: 409 });
+
+ expect(registry.detach).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/scripts/mars-web-bridge.test.ts b/__tests__/scripts/mars-web-bridge.test.ts
new file mode 100644
index 0000000000..4fbaf77e09
--- /dev/null
+++ b/__tests__/scripts/mars-web-bridge.test.ts
@@ -0,0 +1,692 @@
+// @vitest-environment node
+import {
+ createServer,
+ request as httpRequest,
+ type IncomingMessage,
+ type Server,
+} from "node:http";
+import net from "node:net";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import WebSocket, { WebSocketServer } from "ws";
+
+import { server as mswServer } from "#/mocks/node";
+
+import { MARS_TUNNEL_IPC } from "../../scripts/mars-tunnel-bridge.mjs";
+import {
+ RPC_METHODS,
+ createMarsWebBridge,
+ isMarsWebEnabled,
+ mountMarsWebBridge,
+ rewriteAgentServerUrls,
+} from "../../scripts/mars-web-bridge.mjs";
+
+const SESSION_ID = "sess_a";
+
+// The proxy (httpxy) streams a request body once its upstream socket
+// connects, which MSW's interceptor never signals for a request it bypasses.
+// Everything here talks to real loopback servers, so take MSW out of the way.
+beforeAll(() => mswServer.close());
+afterAll(() => mswServer.listen({ onUnhandledRequest: "bypass" }));
+
+function listen(server: Server): Promise<string> {
+ return new Promise((resolve) => {
+ server.listen(0, "127.0.0.1", () => {
+ const { port } = server.address() as net.AddressInfo;
+ resolve(`http://127.0.0.1:${port}`);
+ });
+ });
+}
+
+function closeServer(server: Server): void {
+ server.closeAllConnections();
+ server.close();
+}
+
+/**
+ * Stands in for the Agent Server behind a tunnel listener: records what it was
+ * sent, answers JSON with its own origin in `conversation_url`, and echoes on
+ * its WebSocket.
+ */
+const UPSTREAM_CONVERSATION_PATH = "/mars-upstream/conversation";
+const UPSTREAM_ECHO_PATH = "/mars-upstream/echo";
+
+async function startFakeAgentServer() {
+ const seen: { http: IncomingMessage[]; ws: IncomingMessage[] } = {
+ http: [],
+ ws: [],
+ };
+ let origin = "";
+ let largeBody = "{}";
+ const state = { delayUpgradeMs: 0 };
+ const server = createServer((req, res) => {
+ seen.http.push(req);
+ if (req.url === UPSTREAM_CONVERSATION_PATH) {
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(
+ JSON.stringify({
+ id: "c1",
+ conversation_url: `${origin}/api/conversations/c1`,
+ nested: { url: `${origin}/api/conversations/c1/events` },
+ unrelated: `${origin}/api/other`,
+ }),
+ );
+ return;
+ }
+ if (req.url === "/mars-upstream/large") {
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(largeBody);
+ return;
+ }
+ if (req.url === "/mars-upstream/reset") {
+ req.socket.destroy();
+ return;
+ }
+ if (req.url === UPSTREAM_ECHO_PATH && req.method === "POST") {
+ const chunks: Buffer[] = [];
+ req.on("data", (c) => chunks.push(c));
+ req.on("end", () => {
+ res.writeHead(200, { "Content-Type": "text/plain" });
+ res.end(Buffer.concat(chunks));
+ });
+ return;
+ }
+ res.writeHead(404).end();
+ });
+ const wss = new WebSocketServer({ noServer: true });
+ server.on("upgrade", (req, socket, head) => {
+ seen.ws.push(req);
+ const accept = () =>
+ wss.handleUpgrade(req, socket, head, (ws) => {
+ ws.on("message", (data, isBinary) =>
+ ws.send(`echo:${data.toString()}`, { binary: isBinary }),
+ );
+ });
+ if (state.delayUpgradeMs > 0) setTimeout(accept, state.delayUpgradeMs);
+ else accept();
+ });
+ origin = await listen(server);
+ return {
+ origin,
+ seen,
+ setLargeBody: (body: string) => {
+ largeBody = body;
+ },
+ set delayUpgradeMs(ms: number) {
+ state.delayUpgradeMs = ms;
+ },
+ openSockets: () =>
+ [...wss.clients].filter((c) => c.readyState === WebSocket.OPEN).length,
+ close: () => closeServer(server),
+ };
+}
+
+/**
+ * The tunnel bridge, minus harness-api: openTunnel "connects" a session to the
+ * fake agent server's port, and getTunnel reports it the way the registry
+ * does (no `host`), until closeTunnel or signOut drops it.
+ */
+function fakeBridge(upstreamOrigin: string) {
+ const localPort = Number(new URL(upstreamOrigin).port);
+ const tunnels = new Map<string, { status: string; localPort: number }>();
+ return {
+ getAuthState: vi.fn(() => ({
+ connections: [],
+ active: null,
+ isPersistent: false,
+ canUseOAuth: true,
+ })),
+ savePat: vi.fn(async () => ({})),
+ signOut: vi.fn(async () => {
+ tunnels.clear();
+ }),
+ openTunnel: vi.fn(async ({ sessionId }: { sessionId: string }) => {
+ tunnels.set(sessionId, { status: "connected", localPort });
+ return {
+ sessionId,
+ status: "connected",
+ transport: "tunnel",
+ host: upstreamOrigin,
+ remotePort: 8000,
+ localPort,
+ error: undefined,
+ upstreamFailure: null,
+ };
+ }),
+ closeTunnel: vi.fn(async (sessionId: string) => {
+ tunnels.delete(sessionId);
+ }),
+ destroySession: vi.fn(async () => {}),
+ deleteAgentConfig: vi.fn(async () => {}),
+ listSandboxSizes: vi.fn(async () => [
+ { slug: "mars-2vcpu-4gb", vcpus: 2, memory_mb: 4096 },
+ ]),
+ getTunnel: vi.fn((sessionId: string) => {
+ const tunnel = tunnels.get(sessionId);
+ return tunnel && { sessionId, remotePort: 8000, ...tunnel };
+ }),
+ dispose: vi.fn(async () => {}),
+ };
+}
+
+async function startWebServer(marsWeb: ReturnType<typeof createMarsWebBridge>) {
+ const server = createServer((req, res) => {
+ if (marsWeb.handleHttp(req, res)) return;
+ res.writeHead(404).end("fallthrough");
+ });
+ server.on("upgrade", (req, socket, head) => {
+ if (marsWeb.handleUpgrade(req, socket, head)) return;
+ socket.destroy();
+ });
+ const origin = await listen(server);
+ return { origin, close: () => closeServer(server) };
+}
+
+async function rpc(
+ origin: string,
+ method: string,
+ args: unknown[] = [],
+ init: RequestInit = {},
+) {
+ const response = await fetch(`${origin}/mars/rpc/${method}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...(init.headers ?? {}) },
+ body: JSON.stringify({ args }),
+ ...init,
+ });
+ return { status: response.status, body: await response.json() };
+}
+
+describe("rewriteAgentServerUrls", () => {
+ it("re-points conversation_url at the proxy prefix, whatever host or prefix the upstream used, and leaves other strings alone", () => {
+ const base = "http://localhost:8000/mars/sessions/sess_a";
+ expect(
+ rewriteAgentServerUrls(
+ {
+ conversation_url:
+ "https://ing-1.nyc3.sandbox.ondigitalocean.com/api/conversations/c1",
+ items: [
+ {
+ conversation_url:
+ "http://host/runtime/55313/api/conversations/c1",
+ },
+ ],
+ // A URL that merely appears in content must not be touched.
+ message: "see http://10.0.0.5:8000/api/conversations/c1/events",
+ list: ["http://h/api/conversations", "http://h/api/other"],
+ n: 3,
+ },
+ base,
+ ),
+ ).toEqual({
+ conversation_url: `${base}/api/conversations/c1`,
+ items: [{ conversation_url: `${base}/api/conversations/c1` }],
+ message: "see http://10.0.0.5:8000/api/conversations/c1/events",
+ list: ["http://h/api/conversations", "http://h/api/other"],
+ n: 3,
+ });
+ });
+});
+
+describe("RPC_METHODS", () => {
+ it("is a subset of the desktop IPC surface and leaves OAuth out", () => {
+ for (const method of RPC_METHODS) {
+ expect(Object.keys(MARS_TUNNEL_IPC)).toContain(method);
+ }
+ expect(RPC_METHODS.has("signInWithOAuth")).toBe(false);
+ });
+});
+
+describe("createMarsWebBridge", () => {
+ let upstream: Awaited<ReturnType<typeof startFakeAgentServer>>;
+ let bridge: ReturnType<typeof fakeBridge>;
+ let marsWeb: ReturnType<typeof createMarsWebBridge>;
+ let web: Awaited<ReturnType<typeof startWebServer>>;
+
+ beforeEach(async () => {
+ upstream = await startFakeAgentServer();
+ bridge = fakeBridge(upstream.origin);
+ marsWeb = createMarsWebBridge({
+ bridge: bridge as never,
+ env: {},
+ log: () => {},
+ });
+ web = await startWebServer(marsWeb);
+ });
+
+ afterEach(async () => {
+ await marsWeb.dispose();
+ web.close();
+ upstream.close();
+ });
+
+ it("answers the health probe and ignores non-MARS paths", async () => {
+ expect(await (await fetch(`${web.origin}/mars/health`)).json()).toEqual({
+ ok: true,
+ authRequired: false,
+ });
+ expect((await fetch(`${web.origin}/elsewhere`)).status).toBe(404);
+ expect(await (await fetch(`${web.origin}/elsewhere`)).text()).toBe(
+ "fallthrough",
+ );
+ });
+
+ it("refuses cross-origin requests before touching the bridge", async () => {
+ const { status } = await rpc(web.origin, "getAuthState", [], {
+ headers: { Origin: "https://evil.example" },
+ });
+ expect(status).toBe(403);
+ expect(bridge.getAuthState).not.toHaveBeenCalled();
+ });
+
+ it("exposes the bridge over POST /mars/rpc and never offers OAuth", async () => {
+ const same = await rpc(web.origin, "getAuthState", [], {
+ headers: { Origin: web.origin },
+ });
+ expect(same.status).toBe(200);
+ expect(same.body.result).toMatchObject({ canUseOAuth: false });
+
+ expect((await rpc(web.origin, "signInWithOAuth")).status).toBe(404);
+ expect((await rpc(web.origin, "nope")).status).toBe(404);
+
+ // Destructive session management rides the same allowlisted surface.
+ expect((await rpc(web.origin, "destroySession", ["sess_1"])).status).toBe(
+ 200,
+ );
+ expect(bridge.destroySession).toHaveBeenCalledWith("sess_1");
+ expect((await rpc(web.origin, "deleteAgentConfig", ["cfg_1"])).status).toBe(
+ 200,
+ );
+ expect(bridge.deleteAgentConfig).toHaveBeenCalledWith("cfg_1");
+ expect((await fetch(`${web.origin}/mars/rpc/getAuthState`)).status).toBe(
+ 405,
+ );
+ });
+
+ it("exposes the sandbox size catalog over RPC", async () => {
+ const { status, body } = await rpc(web.origin, "listSandboxSizes");
+
+ expect(status).toBe(200);
+ expect(body.result).toEqual([
+ { slug: "mars-2vcpu-4gb", vcpus: 2, memory_mb: 4096 },
+ ]);
+ expect(bridge.listSandboxSizes).toHaveBeenCalledTimes(1);
+ });
+
+ it("surfaces bridge errors with their status", async () => {
+ bridge.savePat.mockRejectedValueOnce(
+ Object.assign(new Error("Sign in to DigitalOcean first."), {
+ status: 401,
+ }),
+ );
+ const { status, body } = await rpc(web.origin, "savePat", [{ token: "x" }]);
+ expect(status).toBe(401);
+ expect(body.error).toMatchObject({ message: /Sign in/, status: 401 });
+ });
+
+ it("openTunnel answers with the proxied host, not the upstream", async () => {
+ const { body } = await rpc(web.origin, "openTunnel", [
+ { sessionId: SESSION_ID },
+ ]);
+ expect(bridge.openTunnel).toHaveBeenCalledWith({ sessionId: SESSION_ID });
+ expect(body.result).toMatchObject({
+ transport: "tunnel",
+ host: `${web.origin}/mars/sessions/${SESSION_ID}`,
+ });
+ });
+
+ it("proxies HTTP to the connected upstream with agent-server URLs rewritten and no credentials of its own", async () => {
+ await rpc(web.origin, "openTunnel", [{ sessionId: SESSION_ID }]);
+
+ const response = await fetch(
+ `${web.origin}/mars/sessions/${SESSION_ID}${UPSTREAM_CONVERSATION_PATH}`,
+ );
+ const body = await response.json();
+
+ expect(response.status).toBe(200);
+ const seen = upstream.seen.http[0];
+ expect(seen.url).toBe(UPSTREAM_CONVERSATION_PATH);
+ expect(seen.headers.authorization).toBeUndefined();
+ expect(seen.headers.host).toBe(new URL(upstream.origin).host);
+ expect(seen.headers["accept-encoding"]).toBe("identity");
+ expect(seen.headers["x-forwarded-for"]).toBeUndefined();
+ const proxyBase = `${web.origin}/mars/sessions/${SESSION_ID}`;
+ expect(body).toEqual({
+ id: "c1",
+ conversation_url: `${proxyBase}/api/conversations/c1`,
+ // Only the URL fields the renderer follows are rewritten; a URL under
+ // any other key is content and passes through.
+ nested: { url: `${upstream.origin}/api/conversations/c1/events` },
+ unrelated: `${upstream.origin}/api/other`,
+ });
+ });
+
+ it("forwards request bodies and passes non-JSON responses through", async () => {
+ await rpc(web.origin, "openTunnel", [{ sessionId: SESSION_ID }]);
+
+ const response = await fetch(
+ `${web.origin}/mars/sessions/${SESSION_ID}${UPSTREAM_ECHO_PATH}`,
+ {
+ method: "POST",
+ body: "payload",
+ },
+ );
+
+ expect(await response.text()).toBe("payload");
+ });
+
+ it("answers an upstream failure with a JSON 502", async () => {
+ await rpc(web.origin, "openTunnel", [{ sessionId: SESSION_ID }]);
+
+ const response = await fetch(
+ `${web.origin}/mars/sessions/${SESSION_ID}/mars-upstream/reset`,
+ );
+
+ expect(response.status).toBe(502);
+ expect(response.headers.get("content-type")).toBe("application/json");
+ expect(await response.json()).toEqual({
+ error: { message: expect.stringMatching(/^upstream request failed: /) },
+ });
+ });
+
+ it("stops proxying a session once the bridge dropped its tunnel on sign-out", async () => {
+ await rpc(web.origin, "openTunnel", [{ sessionId: SESSION_ID }]);
+ const url = `${web.origin}/mars/sessions/${SESSION_ID}${UPSTREAM_CONVERSATION_PATH}`;
+ expect((await fetch(url)).status).toBe(200);
+
+ await rpc(web.origin, "signOut");
+
+ expect((await fetch(url)).status).toBe(409);
+ });
+
+ it("answers 409 for a session that is not connected, and after closeTunnel", async () => {
+ expect(
+ (
+ await fetch(
+ `${web.origin}/mars/sessions/sess_x${UPSTREAM_CONVERSATION_PATH}`,
+ )
+ ).status,
+ ).toBe(409);
+
+ await rpc(web.origin, "openTunnel", [{ sessionId: SESSION_ID }]);
+ await rpc(web.origin, "closeTunnel", [SESSION_ID]);
+ expect(
+ (
+ await fetch(
+ `${web.origin}/mars/sessions/${SESSION_ID}${UPSTREAM_CONVERSATION_PATH}`,
+ )
+ ).status,
+ ).toBe(409);
+ expect(bridge.closeTunnel).toHaveBeenCalledWith(SESSION_ID);
+ });
+
+ it("proxies the WebSocket and relays both ways", async () => {
+ await rpc(web.origin, "openTunnel", [{ sessionId: SESSION_ID }]);
+ const wsUrl = `${web.origin.replace("http:", "ws:")}/mars/sessions/${SESSION_ID}/sockets/session/c1?after_seq=0`;
+ const client = new WebSocket(wsUrl);
+ const messages: string[] = [];
+ client.on("message", (data) => messages.push(data.toString()));
+ await new Promise<void>((resolve, reject) => {
+ client.once("open", () => resolve());
+ client.once("error", reject);
+ });
+
+ client.send("hello");
+ await vi.waitFor(() => expect(messages).toEqual(["echo:hello"]));
+
+ const seen = upstream.seen.ws[0];
+ expect(seen.url).toBe("/sockets/session/c1?after_seq=0");
+ expect(seen.headers.authorization).toBeUndefined();
+ client.close();
+ });
+
+ it("refuses a WebSocket to a session that is not connected", async () => {
+ const client = new WebSocket(
+ `${web.origin.replace("http:", "ws:")}/mars/sessions/sess_x/sockets/session/c1`,
+ );
+ const outcome = await new Promise<string>((resolve) => {
+ client.once("unexpected-response", (_req, res) =>
+ resolve(`status ${res.statusCode}`),
+ );
+ client.once("error", (error) => resolve(`error ${error.message}`));
+ });
+ expect(outcome).toMatch(/409|Unexpected server response: 409/);
+ });
+
+ it("answers 400 to a session path that cannot be decoded instead of crashing", async () => {
+ expect((await fetch(`${web.origin}/mars/sessions/%E0/`)).status).toBe(400);
+ // The server is still alive afterwards.
+ expect((await fetch(`${web.origin}/mars/health`)).status).toBe(200);
+ });
+
+ it("refuses a request from a foreign Host on a loopback bind (DNS rebinding)", async () => {
+ // fetch() will not send a custom Host, so go through node:http.
+ const { port } = new URL(web.origin);
+ const status = await new Promise<number>((resolve, reject) => {
+ httpRequest(
+ {
+ host: "127.0.0.1",
+ port,
+ path: "/mars/health",
+ headers: { Host: "evil.example:80" },
+ },
+ (res) => {
+ res.resume();
+ resolve(res.statusCode ?? 0);
+ },
+ )
+ .on("error", reject)
+ .end();
+ });
+ expect(status).toBe(403);
+ });
+
+ it("streams a JSON body past the rewrite limit through untouched instead of truncating it", async () => {
+ const big = "x".repeat(9 * 1024 * 1024);
+ upstream.setLargeBody(JSON.stringify({ blob: big }));
+ await rpc(web.origin, "openTunnel", [{ sessionId: SESSION_ID }]);
+
+ const response = await fetch(
+ `${web.origin}/mars/sessions/${SESSION_ID}/mars-upstream/large`,
+ );
+ const text = await response.text();
+ expect(response.status).toBe(200);
+ expect(text.length).toBe(big.length + '{"blob":""}'.length);
+ expect(JSON.parse(text).blob.length).toBe(big.length);
+ });
+
+ it("terminates an upstream WebSocket the browser abandoned before the handshake finished", async () => {
+ upstream.delayUpgradeMs = 150;
+ await rpc(web.origin, "openTunnel", [{ sessionId: SESSION_ID }]);
+
+ const ws = new WebSocket(
+ `${web.origin.replace("http", "ws")}/mars/sessions/${SESSION_ID}/mars-upstream/socket`,
+ );
+ ws.on("error", () => {});
+ await new Promise((r) => setTimeout(r, 30));
+ ws.terminate();
+ await new Promise((r) => setTimeout(r, 300));
+
+ expect(upstream.openSockets()).toBe(0);
+ });
+
+ it("dispose() closes both ends of proxied WebSockets and disposes the bridge", async () => {
+ await rpc(web.origin, "openTunnel", [{ sessionId: SESSION_ID }]);
+ const client = new WebSocket(
+ `${web.origin.replace("http:", "ws:")}/mars/sessions/${SESSION_ID}/mars-upstream/socket`,
+ );
+ client.on("error", () => {});
+ await new Promise((resolve) => client.once("open", resolve));
+ expect(upstream.openSockets()).toBe(1);
+ const closed = new Promise((resolve) => client.once("close", resolve));
+
+ await marsWeb.dispose();
+
+ await closed;
+ // The fake bridge's dispose() closes no tunnel, so only the proxy's own
+ // teardown can have closed the upstream end.
+ await vi.waitFor(() => expect(upstream.openSockets()).toBe(0));
+ expect(bridge.dispose).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("createMarsWebBridge with a session key", () => {
+ const KEY = "sk-test-key";
+ let upstream: Awaited<ReturnType<typeof startFakeAgentServer>>;
+ let bridge: ReturnType<typeof fakeBridge>;
+ let marsWeb: ReturnType<typeof createMarsWebBridge>;
+ let web: Awaited<ReturnType<typeof startWebServer>>;
+
+ beforeEach(async () => {
+ upstream = await startFakeAgentServer();
+ bridge = fakeBridge(upstream.origin);
+ marsWeb = createMarsWebBridge({
+ bridge: bridge as never,
+ env: {},
+ key: KEY,
+ log: () => {},
+ });
+ web = await startWebServer(marsWeb);
+ });
+
+ afterEach(async () => {
+ await marsWeb.dispose();
+ web.close();
+ upstream.close();
+ });
+
+ it("requires the key on RPC and proxy routes, hands out a cookie for it, and keeps health open", async () => {
+ expect(await (await fetch(`${web.origin}/mars/health`)).json()).toEqual({
+ ok: true,
+ authRequired: true,
+ });
+ expect((await rpc(web.origin, "getAuthState")).status).toBe(401);
+ expect(
+ (
+ await rpc(web.origin, "getAuthState", [], {
+ headers: { "X-Session-API-Key": "wrong" },
+ })
+ ).status,
+ ).toBe(401);
+
+ const response = await fetch(`${web.origin}/mars/rpc/getAuthState`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", "X-Session-API-Key": KEY },
+ body: JSON.stringify({ args: [] }),
+ });
+ expect(response.status).toBe(200);
+ const cookie = response.headers.get("set-cookie") ?? "";
+ expect(cookie).toMatch(
+ /^mars_web_auth=[0-9a-f]{64}; HttpOnly; SameSite=Strict; Path=\/mars$/,
+ );
+
+ // The cookie alone is enough afterwards (what a browser does on its own).
+ const cookiePair = cookie.split(";")[0];
+ expect(
+ (
+ await rpc(web.origin, "getAuthState", [], {
+ headers: { Cookie: cookiePair },
+ })
+ ).status,
+ ).toBe(200);
+ });
+
+ it("neither the key header nor the cookie reaches the session host", async () => {
+ await rpc(web.origin, "openTunnel", [{ sessionId: SESSION_ID }], {
+ headers: { "X-Session-API-Key": KEY },
+ });
+ const response = await fetch(
+ `${web.origin}/mars/sessions/${SESSION_ID}/mars-upstream/conversation`,
+ { headers: { "X-Session-API-Key": KEY, Cookie: "canvas=1" } },
+ );
+ expect(response.status).toBe(200);
+ const forwarded = upstream.seen.http.at(-1)!.headers;
+ expect(forwarded.authorization).toBeUndefined();
+ expect(forwarded["x-session-api-key"]).toBeUndefined();
+ expect(forwarded.cookie).toBeUndefined();
+ });
+
+ it("neither the key header nor the cookie reaches the session host on the WebSocket upgrade", async () => {
+ await rpc(web.origin, "openTunnel", [{ sessionId: SESSION_ID }], {
+ headers: { "X-Session-API-Key": KEY },
+ });
+ const ws = new WebSocket(
+ `${web.origin.replace("http", "ws")}/mars/sessions/${SESSION_ID}/mars-upstream/socket`,
+ { headers: { "X-Session-API-Key": KEY, Cookie: "canvas=1" } },
+ );
+ await new Promise<void>((resolve, reject) => {
+ ws.on("open", () => resolve());
+ ws.on("error", reject);
+ });
+ ws.close();
+
+ const forwarded = upstream.seen.ws.at(-1)!.headers;
+ expect(forwarded["x-session-api-key"]).toBeUndefined();
+ expect(forwarded.cookie).toBeUndefined();
+ });
+
+ it("authenticates the WebSocket upgrade by cookie", async () => {
+ const first = await fetch(`${web.origin}/mars/rpc/openTunnel`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", "X-Session-API-Key": KEY },
+ body: JSON.stringify({ args: [{ sessionId: SESSION_ID }] }),
+ });
+ const cookiePair = (first.headers.get("set-cookie") ?? "").split(";")[0];
+ const wsUrl = `${web.origin.replace("http", "ws")}/mars/sessions/${SESSION_ID}/mars-upstream/socket`;
+
+ const refused = new WebSocket(wsUrl);
+ const refusedStatus = await new Promise<number>((resolve) => {
+ refused.on("unexpected-response", (_r, res) =>
+ resolve(res.statusCode ?? 0),
+ );
+ refused.on("error", () => {});
+ });
+ expect(refusedStatus).toBe(401);
+
+ const ws = new WebSocket(wsUrl, { headers: { Cookie: cookiePair } });
+ await new Promise<void>((resolve, reject) => {
+ ws.on("open", () => resolve());
+ ws.on("error", reject);
+ });
+ ws.close();
+ });
+});
+
+describe("mountMarsWebBridge", () => {
+ it("is off unless MARS_WEB=1", () => {
+ expect(isMarsWebEnabled({})).toBe(false);
+ expect(isMarsWebEnabled({ MARS_WEB: "0" })).toBe(false);
+ expect(isMarsWebEnabled({ MARS_WEB: "1" })).toBe(true);
+ expect(
+ mountMarsWebBridge({ env: {}, host: "127.0.0.1", log: () => {} }),
+ ).toBeNull();
+ });
+
+ it("refuses a non-loopback bind without a key, and mounts with one", async () => {
+ const logs: string[] = [];
+ expect(
+ mountMarsWebBridge({
+ env: { MARS_WEB: "1" },
+ host: "0.0.0.0",
+ log: (m) => logs.push(m),
+ }),
+ ).toBeNull();
+ expect(logs[0]).toMatch(/not loopback/);
+
+ const mounted = mountMarsWebBridge({
+ env: { MARS_WEB: "1", MARS_WEB_KEY: "k" },
+ host: "0.0.0.0",
+ log: () => {},
+ });
+ expect(mounted).not.toBeNull();
+ await mounted!.dispose();
+ });
+});
diff --git a/__tests__/scripts/tunnel-client.test.ts b/__tests__/scripts/tunnel-client.test.ts
new file mode 100644
index 0000000000..9aabc367b2
--- /dev/null
+++ b/__tests__/scripts/tunnel-client.test.ts
@@ -0,0 +1,350 @@
+// @vitest-environment node
+import { createServer } from "node:http";
+import net from "node:net";
+import { WebSocketServer } from "ws";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { startPortForwardTunnel } from "../../scripts/tunnel-client.mjs";
+
+const sessionId = "sess_abc123";
+const remotePort = 8000;
+const expectedPath = `/v2/agents/sessions/${sessionId}/port-forward/${remotePort}`;
+
+/**
+ * A local stand-in for MARS's port-forward endpoint: rejects the wrong path
+ * or a bad bearer token at the HTTP-upgrade level (matching harness-api's
+ * real behavior), otherwise upgrades and echoes back whatever it receives —
+ * enough to prove bytes really flow both ways through the tunnel.
+ */
+function startFakeHarness({ expectToken = "test-token" } = {}) {
+ const pings: number[] = [];
+ const httpServer = createServer((_req, res) => {
+ res.writeHead(404).end("not found\n");
+ });
+ const wss = new WebSocketServer({ noServer: true });
+
+ httpServer.on("upgrade", (req, socket, head) => {
+ if (req.url !== expectedPath) {
+ socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
+ socket.destroy();
+ return;
+ }
+ if (req.headers.authorization !== `Bearer ${expectToken}`) {
+ const body = JSON.stringify({ message: "invalid token" });
+ socket.write(
+ `HTTP/1.1 403 Forbidden\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`,
+ );
+ socket.destroy();
+ return;
+ }
+ wss.handleUpgrade(req, socket, head, (ws) => {
+ ws.on("ping", () => pings.push(Date.now()));
+ ws.on("message", (data) =>
+ ws.send(Buffer.concat([Buffer.from("echo:"), data as Buffer])),
+ );
+ });
+ });
+
+ return new Promise<{ port: number; pings: number[]; close: () => void }>(
+ (resolve) => {
+ httpServer.listen(0, "127.0.0.1", () => {
+ const { port } = httpServer.address() as net.AddressInfo;
+ resolve({
+ port,
+ pings,
+ close: () => {
+ wss.close();
+ httpServer.close();
+ },
+ });
+ });
+ },
+ );
+}
+
+describe("startPortForwardTunnel", () => {
+ let harness: { port: number; close: () => void } | undefined;
+ let tunnel: Awaited<ReturnType<typeof startPortForwardTunnel>> | undefined;
+
+ afterEach(() => {
+ tunnel?.stop();
+ tunnel = undefined;
+ harness?.close();
+ harness = undefined;
+ });
+
+ it("rejects when sessionId is missing", async () => {
+ await expect(
+ // @ts-expect-error deliberately omitting a required field to test runtime validation
+ startPortForwardTunnel({ remotePort, accessToken: "test-token" }),
+ ).rejects.toThrow(/sessionId/);
+ });
+
+ it("rejects when accessToken is missing", async () => {
+ await expect(
+ startPortForwardTunnel({ sessionId, remotePort }),
+ ).rejects.toThrow(/accessToken/);
+ });
+
+ it("rejects an out-of-range remote port", async () => {
+ await expect(
+ startPortForwardTunnel({
+ sessionId,
+ remotePort: 70000,
+ accessToken: "test-token",
+ }),
+ ).rejects.toThrow(/Invalid remote port/);
+ });
+
+ it("bridges a local TCP connection through to the guest and back", async () => {
+ harness = await startFakeHarness({ expectToken: "test-token" });
+
+ tunnel = await startPortForwardTunnel({
+ sessionId,
+ remotePort,
+ accessToken: "test-token",
+ apiUrl: `http://127.0.0.1:${harness.port}`,
+ });
+
+ expect(tunnel.sessionId).toBe(sessionId);
+ expect(tunnel.remotePort).toBe(remotePort);
+ expect(tunnel.localPort).toBeGreaterThan(0);
+
+ const response = await new Promise<Buffer>((resolve, reject) => {
+ const socket = net.connect(
+ { port: tunnel!.localPort, host: "127.0.0.1" },
+ () => socket.write("hello-mars"),
+ );
+ socket.once("data", (data: Buffer) => {
+ socket.end();
+ resolve(data);
+ });
+ socket.once("error", reject);
+ });
+
+ expect(response.toString()).toBe("echo:hello-mars");
+ });
+
+ it("relays a large payload intact under backpressure in both directions", async () => {
+ // A raw byte-for-byte echo (no "echo:" prefix) so the received buffer can
+ // be compared directly against what was sent.
+ const wss = new WebSocketServer({ noServer: true });
+ const rawHarness = createServer((_req, res) => res.writeHead(404).end());
+ rawHarness.on("upgrade", (req, socket, head) => {
+ wss.handleUpgrade(req, socket, head, (ws) => {
+ ws.on("message", (data) => ws.send(data as Buffer));
+ });
+ });
+ const rawPort = await new Promise<number>((resolve) => {
+ rawHarness.listen(0, "127.0.0.1", () =>
+ resolve((rawHarness.address() as net.AddressInfo).port),
+ );
+ });
+ harness = {
+ port: rawPort,
+ close: () => {
+ wss.close();
+ rawHarness.close();
+ },
+ };
+
+ tunnel = await startPortForwardTunnel({
+ sessionId,
+ remotePort,
+ accessToken: "test-token",
+ apiUrl: `http://127.0.0.1:${harness.port}`,
+ });
+
+ // Several MB, well beyond a single TCP read chunk, so the tunnel's
+ // localSocket "data" handler fires many times — if pause()/resume()
+ // ever got mismatched (paused but never resumed), this would hang and
+ // the test would time out rather than silently pass.
+ const payload = Buffer.alloc(4 * 1024 * 1024);
+ for (let i = 0; i < payload.length; i += 1) payload[i] = i % 256;
+
+ const received = await new Promise<Buffer>((resolve, reject) => {
+ const socket = net.connect({
+ port: tunnel!.localPort,
+ host: "127.0.0.1",
+ });
+ const chunks: Buffer[] = [];
+ let total = 0;
+ socket.on("connect", () => socket.end(payload));
+ socket.on("data", (chunk: Buffer) => {
+ chunks.push(chunk);
+ total += chunk.length;
+ if (total >= payload.length) {
+ socket.end();
+ resolve(Buffer.concat(chunks));
+ }
+ });
+ socket.once("error", reject);
+ });
+
+ expect(received.equals(payload)).toBe(true);
+ }, 15_000);
+
+ it("surfaces the server's rejection message for a bad token", async () => {
+ harness = await startFakeHarness({ expectToken: "test-token" });
+
+ const logs: string[] = [];
+ tunnel = await startPortForwardTunnel({
+ sessionId,
+ remotePort,
+ accessToken: "wrong-token",
+ apiUrl: `http://127.0.0.1:${harness.port}`,
+ log: (message) => logs.push(message),
+ });
+
+ await new Promise<void>((resolve, reject) => {
+ const socket = net.connect(
+ { port: tunnel!.localPort, host: "127.0.0.1" },
+ () => socket.write("x"),
+ );
+ socket.once("close", () => resolve());
+ socket.once("error", () => resolve());
+ setTimeout(
+ () => reject(new Error("timed out waiting for rejection")),
+ 5_000,
+ );
+ });
+
+ expect(logs.join("\n")).toMatch(
+ /server rejected tunnel \(403.*invalid token/,
+ );
+ expect(tunnel.getLastUpstreamFailure()).toMatchObject({ httpStatus: 403 });
+ });
+
+ it("reads the token on every connection, refusing one once it is gone", async () => {
+ harness = await startFakeHarness({ expectToken: "test-token" });
+ let currentToken: string | null = "test-token";
+ tunnel = await startPortForwardTunnel({
+ sessionId,
+ remotePort,
+ getAccessToken: () => currentToken,
+ apiUrl: `http://127.0.0.1:${harness.port}`,
+ log: () => {},
+ });
+ const exchange = () =>
+ new Promise<string>((resolve) => {
+ const socket = net.connect(
+ { port: tunnel!.localPort, host: "127.0.0.1" },
+ () => socket.write("ping"),
+ );
+ socket.once("data", (data: Buffer) => {
+ socket.destroy();
+ resolve(data.toString());
+ });
+ socket.once("close", () => resolve(""));
+ socket.once("error", () => resolve(""));
+ });
+
+ const beforeSignOut = await exchange();
+ currentToken = null;
+ const afterSignOut = await exchange();
+
+ expect(beforeSignOut).toBe("echo:ping");
+ expect(afterSignOut).toBe("");
+ expect(tunnel.getLastUpstreamFailure()).toMatchObject({ httpStatus: 401 });
+ });
+
+ it("records a guest-port close code so callers can explain the failure", async () => {
+ const wss = new WebSocketServer({ noServer: true });
+ const closingHarness = createServer((_req, res) =>
+ res.writeHead(404).end(),
+ );
+ closingHarness.on("upgrade", (req, socket, head) => {
+ wss.handleUpgrade(req, socket, head, (ws) =>
+ ws.close(4002, "guest dial failed"),
+ );
+ });
+ const port = await new Promise<number>((resolve) => {
+ closingHarness.listen(0, "127.0.0.1", () =>
+ resolve((closingHarness.address() as net.AddressInfo).port),
+ );
+ });
+ harness = {
+ port,
+ close: () => {
+ wss.close();
+ closingHarness.close();
+ },
+ };
+ tunnel = await startPortForwardTunnel({
+ sessionId,
+ remotePort,
+ accessToken: "test-token",
+ apiUrl: `http://127.0.0.1:${port}`,
+ log: () => {},
+ });
+
+ await new Promise<void>((resolve) => {
+ const socket = net.connect({
+ port: tunnel!.localPort,
+ host: "127.0.0.1",
+ });
+ socket.once("close", () => resolve());
+ socket.once("error", () => resolve());
+ });
+
+ expect(tunnel.getLastUpstreamFailure()).toEqual({
+ closeCode: 4002,
+ httpStatus: null,
+ message: "guest dial failed",
+ });
+ });
+
+ it("pings an open upstream socket so an idle tunnel is not reaped", async () => {
+ const fake = await startFakeHarness({ expectToken: "test-token" });
+ harness = fake;
+ tunnel = await startPortForwardTunnel({
+ sessionId,
+ remotePort,
+ accessToken: "test-token",
+ apiUrl: `http://127.0.0.1:${fake.port}`,
+ pingIntervalMs: 20,
+ });
+
+ const socket = net.connect({ port: tunnel.localPort, host: "127.0.0.1" });
+ socket.on("error", () => {});
+ await new Promise((resolve) => socket.once("connect", resolve));
+
+ await vi.waitFor(() => expect(fake.pings.length).toBeGreaterThan(0), {
+ timeout: 1_000,
+ });
+ socket.destroy();
+ });
+
+ it("closes active connections and stops accepting new ones on stop()", async () => {
+ harness = await startFakeHarness({ expectToken: "test-token" });
+
+ tunnel = await startPortForwardTunnel({
+ sessionId,
+ remotePort,
+ accessToken: "test-token",
+ apiUrl: `http://127.0.0.1:${harness.port}`,
+ });
+ const { localPort } = tunnel;
+
+ const socket = net.connect({ port: localPort, host: "127.0.0.1" });
+ // stop() destroys the connection abruptly (RST) rather than a graceful
+ // FIN, so the client side sees ECONNRESET, not a clean end.
+ socket.on("error", () => {});
+ await new Promise((resolve) => socket.once("connect", resolve));
+
+ const closed = new Promise((resolve) => socket.once("close", resolve));
+ tunnel.stop();
+ await closed;
+
+ await expect(
+ new Promise((resolve, reject) => {
+ const retry = net.connect({ port: localPort, host: "127.0.0.1" });
+ retry.once("connect", () => {
+ retry.end();
+ resolve(undefined);
+ });
+ retry.once("error", reject);
+ }),
+ ).rejects.toThrow();
+ });
+});
diff --git a/__tests__/scripts/tunnel-registry.test.ts b/__tests__/scripts/tunnel-registry.test.ts
new file mode 100644
index 0000000000..845a7ab34d
--- /dev/null
+++ b/__tests__/scripts/tunnel-registry.test.ts
@@ -0,0 +1,502 @@
+// @vitest-environment node
+import { createServer } from "node:http";
+import net from "node:net";
+import { WebSocketServer } from "ws";
+import { describe, expect, it, vi } from "vitest";
+
+import { createTunnelRegistry } from "../../scripts/tunnel-registry.mjs";
+import { startPortForwardTunnel } from "../../scripts/tunnel-client.mjs";
+
+/** A stub ensureAwake that resolves immediately, for tests only exercising tunnel logic. */
+const noopEnsureAwake = async () => ({ status: "SESSION_STATUS_READY" });
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (err: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+/** A stub startTunnel that hands out an incrementing fake port per call. */
+function fakeStartTunnel() {
+ let nextPort = 40000;
+ const calls: unknown[] = [];
+ const fn = vi.fn(async (options) => {
+ calls.push(options);
+ return {
+ sessionId: options.sessionId,
+ remotePort: options.remotePort,
+ localPort: nextPort++,
+ getLastUpstreamFailure: () => null,
+ stop: vi.fn(),
+ };
+ });
+ return { fn, calls };
+}
+
+describe("createTunnelRegistry", () => {
+ it("attaches a session and reports it connected", async () => {
+ const { fn } = fakeStartTunnel();
+ const registry = createTunnelRegistry({
+ startTunnel: fn,
+ ensureAwake: noopEnsureAwake,
+ });
+
+ const result = await registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "token",
+ });
+
+ expect(result).toMatchObject({ sessionId: "sess_a", status: "connected" });
+ expect(result.localPort).toBeGreaterThan(0);
+ expect(fn).toHaveBeenCalledTimes(1);
+ });
+
+ it("reuses an existing tunnel instead of opening a duplicate", async () => {
+ const { fn } = fakeStartTunnel();
+ const registry = createTunnelRegistry({
+ startTunnel: fn,
+ ensureAwake: noopEnsureAwake,
+ });
+
+ const first = await registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ });
+ const second = await registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ });
+
+ expect(second.localPort).toBe(first.localPort);
+ expect(fn).toHaveBeenCalledTimes(1);
+ });
+
+ it("dedupes concurrent attach() calls for the same session into one tunnel", async () => {
+ const gate = deferred<void>();
+ const fn = vi.fn(async (options) => {
+ await gate.promise;
+ return {
+ sessionId: options.sessionId,
+ remotePort: options.remotePort,
+ localPort: 41000,
+ getLastUpstreamFailure: () => null,
+ stop: vi.fn(),
+ };
+ });
+ const registry = createTunnelRegistry({
+ startTunnel: fn,
+ ensureAwake: noopEnsureAwake,
+ });
+
+ const attempt1 = registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ });
+ const attempt2 = registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ });
+ gate.resolve();
+
+ const [r1, r2] = await Promise.all([attempt1, attempt2]);
+ expect(fn).toHaveBeenCalledTimes(1);
+ expect(r1.localPort).toBe(r2.localPort);
+ });
+
+ it("gives independent sessions independent, non-colliding ports", async () => {
+ const { fn } = fakeStartTunnel();
+ const registry = createTunnelRegistry({
+ startTunnel: fn,
+ ensureAwake: noopEnsureAwake,
+ });
+
+ const [a, b] = await Promise.all([
+ registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ }),
+ registry.attach({
+ sessionId: "sess_b",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ }),
+ ]);
+
+ expect(a.localPort).not.toBe(b.localPort);
+ expect(fn).toHaveBeenCalledTimes(2);
+ expect(registry.get("sess_a")).toMatchObject({ status: "connected" });
+ expect(registry.get("sess_b")).toMatchObject({ status: "connected" });
+ });
+
+ it("detach() tears down only the targeted session", async () => {
+ const { fn } = fakeStartTunnel();
+ const registry = createTunnelRegistry({
+ startTunnel: fn,
+ ensureAwake: noopEnsureAwake,
+ });
+
+ await registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ });
+ await registry.attach({
+ sessionId: "sess_b",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ });
+
+ await registry.detach("sess_a");
+
+ expect(registry.get("sess_a")).toBeUndefined();
+ expect(registry.get("sess_b")).toMatchObject({ status: "connected" });
+ const aTunnel = await fn.mock.results[0].value;
+ expect(aTunnel.stop).toHaveBeenCalledTimes(1);
+ });
+
+ it("detachAll() tears down every session", async () => {
+ const { fn } = fakeStartTunnel();
+ const registry = createTunnelRegistry({
+ startTunnel: fn,
+ ensureAwake: noopEnsureAwake,
+ });
+
+ await registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ });
+ await registry.attach({
+ sessionId: "sess_b",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ });
+
+ await registry.detachAll();
+
+ expect(registry.get("sess_a")).toBeUndefined();
+ expect(registry.get("sess_b")).toBeUndefined();
+ for (const result of fn.mock.results) {
+ const tunnel = await result.value;
+ expect(tunnel.stop).toHaveBeenCalledTimes(1);
+ }
+ });
+
+ it("surfaces a failed attach() without affecting other sessions, and allows retry", async () => {
+ let badAttempts = 0;
+ const fn = vi.fn(async (options) => {
+ if (options.sessionId === "sess_bad") {
+ badAttempts += 1;
+ if (badAttempts === 1) {
+ throw new Error(
+ "server rejected tunnel (403 Forbidden): invalid token",
+ );
+ }
+ }
+ return {
+ sessionId: options.sessionId,
+ remotePort: options.remotePort,
+ localPort: 42000,
+ getLastUpstreamFailure: () => null,
+ stop: vi.fn(),
+ };
+ });
+ const registry = createTunnelRegistry({
+ startTunnel: fn,
+ ensureAwake: noopEnsureAwake,
+ });
+
+ await registry.attach({
+ sessionId: "sess_ok",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ });
+ await expect(
+ registry.attach({
+ sessionId: "sess_bad",
+ remotePort: 8000,
+ getAccessToken: () => "wrong",
+ }),
+ ).rejects.toThrow(/invalid token/);
+
+ expect(registry.get("sess_ok")).toMatchObject({ status: "connected" });
+ expect(registry.get("sess_bad")).toMatchObject({
+ status: "error",
+ error: expect.stringMatching(/invalid token/),
+ });
+
+ // Retrying (e.g. after the user fixes their token) opens a fresh attempt.
+ const retried = await registry.attach({
+ sessionId: "sess_bad",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ });
+ expect(retried.status).toBe("connected");
+ });
+
+ it("wakes the session again when reusing a connected tunnel", async () => {
+ const ensureAwake = vi.fn(noopEnsureAwake);
+ const { fn } = fakeStartTunnel();
+ const registry = createTunnelRegistry({ startTunnel: fn, ensureAwake });
+ const params = {
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ };
+
+ await registry.attach(params);
+ await registry.attach(params);
+
+ expect(ensureAwake).toHaveBeenCalledTimes(2);
+ expect(fn).toHaveBeenCalledTimes(1);
+ });
+
+ it("falls back to an OS-picked port when the requested one is taken", async () => {
+ const { fn } = fakeStartTunnel();
+ fn.mockImplementationOnce(async () => {
+ throw Object.assign(new Error("listen EADDRINUSE"), {
+ code: "EADDRINUSE",
+ });
+ });
+ const registry = createTunnelRegistry({
+ startTunnel: fn,
+ ensureAwake: noopEnsureAwake,
+ });
+
+ const result = await registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ localPort: 51000,
+ });
+
+ expect(fn).toHaveBeenLastCalledWith(
+ expect.objectContaining({ localPort: 0 }),
+ );
+ expect(result).toMatchObject({ status: "connected", localPort: 40000 });
+ });
+
+ it("detachOwnedBy() tears down only that owner's tunnels", async () => {
+ const { fn } = fakeStartTunnel();
+ const registry = createTunnelRegistry({
+ startTunnel: fn,
+ ensureAwake: noopEnsureAwake,
+ });
+ await registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ owner: "conn_a",
+ });
+ await registry.attach({
+ sessionId: "sess_b",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ owner: "conn_b",
+ });
+
+ await registry.detachOwnedBy("conn_a");
+
+ expect(registry.get("sess_a")).toBeUndefined();
+ expect(registry.get("sess_b")).toMatchObject({ status: "connected" });
+ });
+
+ it("requires an ensureAwake to wake sessions with", () => {
+ // @ts-expect-error deliberately omitting a required field to test runtime validation
+ expect(() => createTunnelRegistry({})).toThrow(/ensureAwake/);
+ });
+
+ it("rejects when sessionId is missing", async () => {
+ const { fn } = fakeStartTunnel();
+ const registry = createTunnelRegistry({
+ startTunnel: fn,
+ ensureAwake: noopEnsureAwake,
+ });
+ await expect(
+ // @ts-expect-error deliberately omitting a required field to test runtime validation
+ registry.attach({ remotePort: 8000, getAccessToken: () => "t" }),
+ ).rejects.toThrow(/sessionId/);
+ });
+
+ it("waits for the session to be awake before dialing the tunnel", async () => {
+ const order: string[] = [];
+ const ensureAwake = vi.fn(async () => {
+ order.push("ensureAwake");
+ return { status: "SESSION_STATUS_READY" };
+ });
+ const { fn } = fakeStartTunnel();
+ fn.mockImplementation(async (options) => {
+ order.push("startTunnel");
+ return {
+ sessionId: options.sessionId,
+ remotePort: options.remotePort,
+ localPort: 43000,
+ getLastUpstreamFailure: () => null,
+ stop: vi.fn(),
+ };
+ });
+ const registry = createTunnelRegistry({ startTunnel: fn, ensureAwake });
+
+ await registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ });
+
+ expect(order).toEqual(["ensureAwake", "startTunnel"]);
+ expect(ensureAwake).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionId: "sess_a" }),
+ );
+ });
+
+ it("surfaces a failure to wake the session without ever dialing the tunnel", async () => {
+ const ensureAwake = vi.fn(async () => {
+ throw new Error(
+ "Session sess_a is SESSION_STATUS_FAILED and cannot be connected to.",
+ );
+ });
+ const { fn } = fakeStartTunnel();
+ const registry = createTunnelRegistry({ startTunnel: fn, ensureAwake });
+
+ await expect(
+ registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "t",
+ }),
+ ).rejects.toThrow(/SESSION_STATUS_FAILED/);
+
+ expect(fn).not.toHaveBeenCalled();
+ expect(registry.get("sess_a")).toMatchObject({
+ status: "error",
+ error: expect.stringMatching(/SESSION_STATUS_FAILED/),
+ });
+ });
+});
+
+/**
+ * End-to-end: the real startPortForwardTunnel, against two independent fake
+ * harness-api servers standing in for two concurrently attached MARS
+ * sessions, proving the registry's dedup/port-allocation logic holds up
+ * against the real tunnel client, not just a stub.
+ */
+describe("createTunnelRegistry (real tunnel client)", () => {
+ function startFakeHarness(
+ sessionId: string,
+ remotePort: number,
+ expectToken: string,
+ ) {
+ const expectedPath = `/v2/agents/sessions/${sessionId}/port-forward/${remotePort}`;
+ const sessionPath = `/v2/agents/sessions/${sessionId}`;
+ const httpServer = createServer((req, res) => {
+ // Also serves the plain REST session-status endpoint ensureSessionAwake
+ // hits before the tunnel is dialed — always READY here, so this test
+ // stays focused on the tunnel/registry path rather than resume logic
+ // (covered separately in mars-session.test.ts).
+ if (req.method === "GET" && req.url === sessionPath) {
+ res.writeHead(200, { "Content-Type": "application/json" });
+ res.end(
+ JSON.stringify({
+ session: { session_id: sessionId, status: "SESSION_STATUS_READY" },
+ }),
+ );
+ return;
+ }
+ res.writeHead(404).end();
+ });
+ const wss = new WebSocketServer({ noServer: true });
+
+ httpServer.on("upgrade", (req, socket, head) => {
+ if (
+ req.url !== expectedPath ||
+ req.headers.authorization !== `Bearer ${expectToken}`
+ ) {
+ socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
+ socket.destroy();
+ return;
+ }
+ wss.handleUpgrade(req, socket, head, (ws) => {
+ ws.on("message", (data) =>
+ ws.send(
+ Buffer.concat([Buffer.from(`echo:${sessionId}:`), data as Buffer]),
+ ),
+ );
+ });
+ });
+
+ return new Promise<{ port: number; close: () => void }>((resolve) => {
+ httpServer.listen(0, "127.0.0.1", () => {
+ const { port } = httpServer.address() as net.AddressInfo;
+ resolve({
+ port,
+ close: () => {
+ wss.close();
+ httpServer.close();
+ },
+ });
+ });
+ });
+ }
+
+ it("bridges two concurrently attached sessions to their own independent guests", async () => {
+ const harnessA = await startFakeHarness("sess_a", 8000, "token-a");
+ const harnessB = await startFakeHarness("sess_b", 8000, "token-b");
+ const registry = createTunnelRegistry({
+ startTunnel: startPortForwardTunnel,
+ ensureAwake: noopEnsureAwake,
+ });
+
+ try {
+ const [a, b] = await Promise.all([
+ registry.attach({
+ sessionId: "sess_a",
+ remotePort: 8000,
+ getAccessToken: () => "token-a",
+ apiUrl: `http://127.0.0.1:${harnessA.port}`,
+ }),
+ registry.attach({
+ sessionId: "sess_b",
+ remotePort: 8000,
+ getAccessToken: () => "token-b",
+ apiUrl: `http://127.0.0.1:${harnessB.port}`,
+ }),
+ ]);
+
+ expect(a.localPort).not.toBe(b.localPort);
+
+ const send = (port: number, payload: string) =>
+ new Promise<Buffer>((resolve, reject) => {
+ const socket = net.connect({ port, host: "127.0.0.1" }, () =>
+ socket.write(payload),
+ );
+ socket.once("data", (data: Buffer) => {
+ socket.end();
+ resolve(data);
+ });
+ socket.once("error", reject);
+ });
+
+ const [respA, respB] = await Promise.all([
+ send(a.localPort!, "hi-a"),
+ send(b.localPort!, "hi-b"),
+ ]);
+
+ expect(respA.toString()).toBe("echo:sess_a:hi-a");
+ expect(respB.toString()).toBe("echo:sess_b:hi-b");
+ } finally {
+ await registry.detachAll();
+ harnessA.close();
+ harnessB.close();
+ }
+ });
+});
diff --git a/config/defaults.json b/config/defaults.json
index 45489379ec..0bab9dba13 100644
--- a/config/defaults.json
+++ b/config/defaults.json
@@ -34,6 +34,11 @@
"tools": "openhands-tools",
"workspace": "openhands-workspace"
},
+ "mars": {
+ "_comment": "DigitalOcean Managed Agents: the Electron desktop app, and the web build when its server runs with MARS_WEB=1. apiBaseUrl is the harness API both use. oauthClientId (desktop only; the web build offers personal access tokens only) is the public client ID of the DigitalOcean OAuth app registered with redirect URI http://127.0.0.1:53682/callback; implicit grant needs no secret. Leave empty to offer personal access tokens only. Overridden at runtime by DO_OAUTH_CLIENT_ID / MARS_API_BASE_URL. Read by scripts/mars-tunnel-bridge.mjs.",
+ "apiBaseUrl": "https://api.digitalocean.com",
+ "oauthClientId": ""
+ },
"telemetry": {
"posthogApiKey": "phc_kBtz5nKmxVRRQ7HtPwr2QX9eMC5j65zE86QKocVNwb4U",
"posthogHost": "https://us.i.posthog.com"
diff --git a/electron-builder.config.mjs b/electron-builder.config.mjs
index 2327d5ae78..7b06e259ce 100644
--- a/electron-builder.config.mjs
+++ b/electron-builder.config.mjs
@@ -72,15 +72,20 @@ import { fileURLToPath } from "node:url";
const ELECTRON_ARCH = process.env.ELECTRON_ARCH;
const isUniversal = ELECTRON_ARCH === "universal";
-// npm packages the packaged app's child-process scripts import at runtime:
+// npm packages imported at runtime by code that isn't bundled through Vite
+// (main.mjs itself, and the child-process scripts it spawns):
// scripts/static-server.mjs → sirv
// scripts/proxy-utils.mjs → httpxy (imported by ingress.mjs)
+// scripts/tunnel-client.mjs → ws (imported directly by main.mjs,
+// not spawned — the MARS
+// port-forward tunnel client)
// Their dependency closure is copied back into Resources/app/node_modules
-// after the strip below. If a spawned script gains a new bare import, add
-// the package here — a missing one crashes that service in the installed
-// app with ERR_MODULE_NOT_FOUND (invisible under Finder, where stdout goes
-// to /dev/null) and the splash times out waiting for port 8000.
-const RUNTIME_PACKAGES = ["sirv", "httpxy"];
+// after the strip below. If a spawned script (or main.mjs itself) gains a
+// new bare import, add the package here — a missing one crashes that
+// service in the installed app with ERR_MODULE_NOT_FOUND (invisible under
+// Finder, where stdout goes to /dev/null) and the splash times out waiting
+// for port 8000.
+const RUNTIME_PACKAGES = ["sirv", "httpxy", "ws"];
const repoRoot = dirname(fileURLToPath(import.meta.url));
diff --git a/electron/main.mjs b/electron/main.mjs
index ab7f1f6a01..0d93dd9e80 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -46,6 +46,7 @@ import {
ipcMain,
nativeImage,
nativeTheme,
+ safeStorage,
shell,
} from "electron";
import { chmodSync, existsSync } from "node:fs";
@@ -313,6 +314,8 @@ async function waitForAgentServer(
let loadingWin = null;
let mainWin = null;
+/** MARS session bridge (port-forward tunnels, MARSOHS-1429) — created in app.whenReady(). */
+let marsTunnelBridge = null;
// Collapsed splash size — loading.html's .container height must match. The
// expanded height reveals the startup-log console below it ("Show details").
@@ -395,6 +398,7 @@ function createMainWindow() {
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
+ // Desktop-shell state and the MARS tunnel bridge (see preload-main.cjs).
preload: join(__dirname, "preload-main.cjs"),
},
});
@@ -715,6 +719,19 @@ app.whenReady().then(async () => {
injectBundledUv();
injectBundledNode();
+ // Registered before the window loads so the renderer's first paint can
+ // already reach the bridge (MARSOHS-1429). Independent of the agent-server
+ // stack below — MARS sessions don't need the bundled backend to be up.
+ const { createMarsTunnelBridge } = await import(
+ pathToFileURL(join(scriptsDir, "mars-tunnel-bridge.mjs")).href
+ );
+ marsTunnelBridge = createMarsTunnelBridge({
+ userDataPath: app.getPath("userData"),
+ safeStorage,
+ openExternal: (url) => shell.openExternal(url),
+ });
+ marsTunnelBridge.registerIpc(ipcMain);
+
if (!uvxAvailable()) {
dialog.showErrorBox(
"Missing prerequisite: uv",
@@ -762,7 +779,10 @@ app.whenReady().then(async () => {
const errorTail = recentServiceErrors.length
? `\n\nRecent service errors:\n${recentServiceErrors.join("\n")}`
: "";
- dialog.showErrorBox("OpenHands Agent Canvas failed to start", summary + errorTail);
+ dialog.showErrorBox(
+ "OpenHands Agent Canvas failed to start",
+ summary + errorTail,
+ );
app.quit();
}
});
@@ -799,6 +819,14 @@ app.on("before-quit", (event) => {
cleanupStarted = true;
event.preventDefault();
+ // MARS connections are in-process state (tunnel listeners to close; no OS
+ // subprocess to signal and wait on), so this
+ // doesn't need the SIGTERM-based cleanup path below — just tear them down
+ // directly. Best-effort: quitting must not hang on it.
+ void marsTunnelBridge?.dispose().catch((err) => {
+ console.warn("[desktop] Failed to close MARS connections:", err);
+ });
+
console.log("[desktop] Stopping backend services…");
if (process.platform === "win32") {
// Run the cleanup handler in-process (see header note). emit() returns
diff --git a/electron/preload-main.cjs b/electron/preload-main.cjs
index 16dab85c19..cdeeb26812 100644
--- a/electron/preload-main.cjs
+++ b/electron/preload-main.cjs
@@ -6,6 +6,13 @@
* to reserve room for the macOS traffic lights and mark a drag region — see
* src/utils/desktop-shell.ts.
*
+ * It also exposes the MARS bridge (`window.marsBridge`). Page JavaScript never
+ * gets direct network access to harness-api or the bearer token; every call is
+ * a request to the main process, which holds the credentials and the tunnels
+ * (see scripts/mars-tunnel-bridge.mjs). Its channel names mirror
+ * MARS_TUNNEL_IPC there, duplicated as literals because this preload cannot
+ * import that ESM module.
+ *
* CommonJS on purpose: sandboxed preload scripts cannot use ESM.
*/
const { contextBridge, ipcRenderer } = require("electron");
@@ -36,3 +43,50 @@ contextBridge.exposeInMainWorld("desktopShell", {
return () => listeners.delete(cb);
},
});
+
+contextBridge.exposeInMainWorld("marsBridge", {
+ /** Stored connections plus whether OAuth is configured in this build. */
+ getAuthState: () => ipcRenderer.invoke("mars:getAuthState"),
+ /** Opens the system browser; resolves once the grant comes back. */
+ signInWithOAuth: () => ipcRenderer.invoke("mars:signInWithOAuth"),
+ savePat: (payload) => ipcRenderer.invoke("mars:savePat", payload),
+ setActiveConnection: (id) =>
+ ipcRenderer.invoke("mars:setActiveConnection", id),
+ signOut: (id) => ipcRenderer.invoke("mars:signOut", id),
+
+ listSessions: (options) => ipcRenderer.invoke("mars:listSessions", options),
+ /** Durable agent definitions; one config has many sessions. */
+ listAgentConfigs: (options) =>
+ ipcRenderer.invoke("mars:listAgentConfigs", options),
+ listConfigSessions: (configId, options) =>
+ ipcRenderer.invoke("mars:listConfigSessions", configId, options),
+ /** Sandbox sizes a new agent may pick, smallest first. */
+ listSandboxSizes: () => ipcRenderer.invoke("mars:listSandboxSizes"),
+ /** `{name, size?}`; the main process owns the OpenHands manifest. */
+ createOpenHandsAgent: (payload) =>
+ ipcRenderer.invoke("mars:createOpenHandsAgent", payload),
+ /** Resolves once the new session is READY. */
+ createSession: (configId, name) =>
+ ipcRenderer.invoke("mars:createSession", configId, name),
+ pauseSession: (sessionId) =>
+ ipcRenderer.invoke("mars:pauseSession", sessionId),
+ resumeSession: (sessionId) =>
+ ipcRenderer.invoke("mars:resumeSession", sessionId),
+ /** Ends the session and its sandbox for good; drops any live connection first. */
+ destroySession: (sessionId) =>
+ ipcRenderer.invoke("mars:destroySession", sessionId),
+ /** Soft-deletes the agent; the renderer only offers it when no session is live. */
+ deleteAgentConfig: (configId) =>
+ ipcRenderer.invoke("mars:deleteAgentConfig", configId),
+
+ /**
+ * Connects to a session's agent-server over a port-forward tunnel and
+ * resolves once it is reachable: `{sessionId, status, transport, host, remotePort,
+ * localPort, error}`. `host` is the base URL to register as the backend.
+ */
+ openTunnel: (params) => ipcRenderer.invoke("mars:openTunnel", params),
+ /** Forgets the connection for one session (and closes its tunnel, if any). */
+ closeTunnel: (sessionId) => ipcRenderer.invoke("mars:closeTunnel", sessionId),
+ /** Reads a session's current connection status without changing it. */
+ getTunnel: (sessionId) => ipcRenderer.invoke("mars:getTunnel", sessionId),
+});
diff --git a/package-lock.json b/package-lock.json
index 181c316244..fb12e6d1d4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -59,6 +59,7 @@
"vite": "8.0.16",
"winston": "3.19.0",
"winston-daily-rotate-file": "5.0.0",
+ "ws": "8.21.0",
"zustand": "5.0.14"
},
"bin": {
@@ -84,6 +85,7 @@
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"@types/react-syntax-highlighter": "15.5.13",
+ "@types/ws": "8.18.1",
"@typescript-eslint/eslint-plugin": "8.67.0",
"@typescript-eslint/parser": "8.67.0",
"@vercel/react-router": "1.3.3",
@@ -8317,6 +8319,16 @@
"integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
"license": "MIT"
},
+ "node_modules/@types/ws": {
+ "version": "8.18.1",
+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.67.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.67.0.tgz",
diff --git a/package.json b/package.json
index 85f63781bf..90176f7410 100644
--- a/package.json
+++ b/package.json
@@ -69,6 +69,7 @@
"vite": "8.0.16",
"winston": "3.19.0",
"winston-daily-rotate-file": "5.0.0",
+ "ws": "8.21.0",
"zustand": "5.0.14"
},
"scripts": {
@@ -146,6 +147,7 @@
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"@types/react-syntax-highlighter": "15.5.13",
+ "@types/ws": "8.18.1",
"@typescript-eslint/eslint-plugin": "8.67.0",
"@typescript-eslint/parser": "8.67.0",
"@vercel/react-router": "1.3.3",
diff --git a/scripts/check-translation-completeness.cjs b/scripts/check-translation-completeness.cjs
index ff4c48b137..dc367fe563 100755
--- a/scripts/check-translation-completeness.cjs
+++ b/scripts/check-translation-completeness.cjs
@@ -35,6 +35,7 @@ const IDENTICAL_VALUE_ALLOWLIST = new Set([
'CONVERSATION$OVERVIEW_GIT',
'CONVERSATION$OVERVIEW_UNAVAILABLE',
'CONVERSATION_PANEL$PREVIEW_GIT',
+ 'DO_AGENTS$BADGE',
'FILES$VSCODE',
'GITHUB$AUTH_SCOPE',
'LAUNCH$PLUGIN_PATH',
diff --git a/scripts/dev-with-automation.mjs b/scripts/dev-with-automation.mjs
index 01133e7220..90ec8cdb8e 100644
--- a/scripts/dev-with-automation.mjs
+++ b/scripts/dev-with-automation.mjs
@@ -1153,6 +1153,9 @@ function startIngress(config) {
{
cwd: projectRoot,
color: c.yellow,
+ // The MARS web bridge (opt-in, MARS_WEB=1) guards /mars/* with the
+ // stack's session key, the same one the page already holds.
+ env: config.sessionApiKey ? { MARS_WEB_KEY: config.sessionApiKey } : {},
},
);
}
diff --git a/scripts/http-body.mjs b/scripts/http-body.mjs
new file mode 100644
index 0000000000..e167f0ee51
--- /dev/null
+++ b/scripts/http-body.mjs
@@ -0,0 +1,35 @@
+/**
+ * Request-body reading with no dependencies beyond Node itself, so Electron
+ * main (via mars-oauth.mjs) can use it without loading the proxy's npm
+ * packages.
+ */
+
+/**
+ * Read a request body of at most `limit` bytes. Rejects, and destroys the
+ * request, once it grows past the limit; rejects rather than hanging when
+ * the client goes away mid-body.
+ *
+ * @param {import("node:http").IncomingMessage} req
+ * @param {number} limit
+ * @returns {Promise<Buffer>}
+ */
+export function readRequestBody(req, limit) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ let size = 0;
+ req.on("data", (chunk) => {
+ size += chunk.length;
+ if (size > limit) {
+ reject(new Error("request body too large"));
+ req.destroy();
+ return;
+ }
+ chunks.push(chunk);
+ });
+ req.on("end", () => resolve(Buffer.concat(chunks)));
+ req.on("error", reject);
+ req.on("close", () => {
+ if (!req.complete) reject(new Error("request aborted"));
+ });
+ });
+}
diff --git a/scripts/ingress.mjs b/scripts/ingress.mjs
index 0924c5f581..9ab45dee92 100644
--- a/scripts/ingress.mjs
+++ b/scripts/ingress.mjs
@@ -26,6 +26,7 @@ import process from "node:process";
import { pathToFileURL } from "node:url";
import { DEFAULT_BIND_HOST, resolveBindHost } from "./bind-host.mjs";
+import { mountMarsWebBridge } from "./mars-web-bridge.mjs";
import {
createProxyHandlers,
createRouter,
@@ -174,11 +175,16 @@ export function startIngress(config) {
const route = createRouter(config.routes, config.defaultBackend);
const proxy = createProxyHandlers({ label: `ingress:${config.port}` });
const uninstallDiagnostics = proxy.installDiagnostics();
+ // DigitalOcean Managed Agents for the browser: with MARS_WEB=1 this server
+ // hosts the MARS bridge and proxies to sessions' tunnel listeners, behind
+ // the session key (MARS_WEB_KEY; dev-with-automation passes the stack's key).
+ const marsWeb = mountMarsWebBridge({ host: config.host });
const noReferrerPrefixes = config.noReferrerPrefixes ?? [];
const server = createServer((req, res) => {
const url = req.url ?? "/";
+ if (marsWeb?.handleHttp(req, res)) return;
const backend = route(url);
if (!backend) {
@@ -208,6 +214,7 @@ export function startIngress(config) {
// Handle WebSocket upgrades
server.on("upgrade", (req, socket, head) => {
+ if (marsWeb?.handleUpgrade(req, socket, head)) return;
const backend = route(req.url ?? "/");
if (!backend) {
@@ -231,6 +238,9 @@ export function startIngress(config) {
}
});
server.on("close", uninstallDiagnostics);
+ server.on("close", () => {
+ void marsWeb?.dispose().catch(() => {});
+ });
server.listen(config.port, config.host || DEFAULT_BIND_HOST, () => {
console.log("");
diff --git a/scripts/mars-api.mjs b/scripts/mars-api.mjs
new file mode 100644
index 0000000000..fbf81e1a43
--- /dev/null
+++ b/scripts/mars-api.mjs
@@ -0,0 +1,334 @@
+/**
+ * REST client for DigitalOcean MARS ("hosted agents") sessions.
+ *
+ * Runs in the Electron main process, never the renderer: harness-api emits no
+ * CORS headers, so a browser origin cannot call these endpoints at all, and
+ * the bearer token must not cross the context bridge.
+ *
+ * Endpoint shapes are those served by harness-api's hand-rolled gorilla/mux
+ * router (NOT grpc-gateway), so paths and the response envelopes below are the
+ * contract — list wraps in `sessions`, single reads wrap in `session`, and
+ * every error is `{error: {code, message}}`.
+ */
+
+export const DEFAULT_MARS_API_BASE_URL = "https://api.digitalocean.com";
+
+/**
+ * Port the guest's `openhands-agent-server` listens on inside the sandbox.
+ * Within harness-api's allowed forwarding range (1024-65535).
+ */
+export const AGENT_SERVER_GUEST_PORT = 8000;
+
+export const SESSIONS_PATH = "/v2/agents/sessions";
+const CONFIGS_PATH = "/v2/agents/configs";
+const CONFIG_SESSIONS_SUBPATH = "/sessions";
+const DEVICE_ID_HEADER = "X-Device-UUID";
+const DEFAULT_TIMEOUT_MS = 15_000;
+/**
+ * Creating a session allocates a sandbox before responding, so it routinely
+ * outlasts the read timeout that every other call is sized for.
+ */
+const CREATE_SESSION_TIMEOUT_MS = 60_000;
+
+/** Terminal states — a session in one of these can never serve a tunnel. */
+const TERMINAL_STATUSES = new Set([
+ "SESSION_STATUS_DESTROYING",
+ "SESSION_STATUS_DESTROYED",
+ "SESSION_STATUS_FAILED",
+]);
+
+export const SESSION_STATUS_READY = "SESSION_STATUS_READY";
+export const SESSION_STATUS_PAUSED = "SESSION_STATUS_PAUSED";
+
+export function isTerminalSessionStatus(status) {
+ return TERMINAL_STATUSES.has(status);
+}
+
+export const OPENHANDS_AGENT = "openhands";
+const OPENHANDS_TEMPLATE = "openhands";
+/** Shape of a sandbox size slug, e.g. `mars-2vcpu-4gb`. */
+const SANDBOX_SIZE_SLUG = /^[a-z0-9][a-z0-9-]{0,62}$/;
+
+/**
+ * Flat agents.yaml for an OpenHands agent. `template` must stay explicit:
+ * harness-api has no agent kind that derives an OpenHands sandbox template,
+ * so omitting it would boot a sandbox with no agent-server on :8000. No LLM
+ * key goes here: the agent's LLM is configured in the session's own
+ * agent-server (Settings → LLM) once connected.
+ *
+ * `size` is a sandbox size slug from `listSandboxSizes()`. It lives in the
+ * manifest because sessions created from a config cannot carry one; omitted,
+ * DigitalOcean picks its default. It is checked against the slug shape so a
+ * renderer-supplied value can never inject YAML.
+ *
+ * @param {{ size?: string }} [options]
+ * @returns {string}
+ */
+export function buildOpenHandsManifest({ size } = {}) {
+ const lines = [
+ `agent: ${OPENHANDS_AGENT}`,
+ `template: ${OPENHANDS_TEMPLATE}`,
+ // The openhands adapter defaults to keep_warm, which bills until the
+ // session is destroyed and makes harness-api refuse every pause.
+ "keep_warm: false",
+ ];
+ if (size !== undefined && size !== null && size !== "") {
+ if (typeof size !== "string" || !SANDBOX_SIZE_SLUG.test(size)) {
+ throw new MarsApiError("Unknown sandbox size.", { status: 400 });
+ }
+ lines.push(`size: ${size}`);
+ }
+ return `${lines.join("\n")}\n`;
+}
+
+/**
+ * The coding agent a config's manifest runs (`agent: openhands`), lowercased.
+ * Manifests are written either flat or as `{apiVersion, kind, spec}`, and
+ * `agent` may be a bare name or an object naming it; null when absent.
+ *
+ * @param {unknown} manifest
+ * @returns {string | null}
+ */
+export function readManifestAgent(manifest) {
+ if (!manifest || typeof manifest !== "object") return null;
+ const agent = manifest.agent ?? manifest.spec?.agent;
+ const name =
+ typeof agent === "string" ? agent : (agent?.name ?? agent?.kind ?? null);
+ return typeof name === "string" && name.trim()
+ ? name.trim().toLowerCase()
+ : null;
+}
+
+export class MarsApiError extends Error {
+ constructor(message, { status = null, cause = null } = {}) {
+ super(message);
+ this.name = "MarsApiError";
+ this.status = status;
+ if (cause) this.cause = cause;
+ }
+}
+
+function trimTrailingSlash(value) {
+ return value.replace(/\/+$/, "");
+}
+
+/**
+ * Build a fully-qualified MARS URL. Any path prefix on `baseUrl` is preserved
+ * so non-production edges (`https://host/edge`) keep routing correctly, which
+ * mirrors how doctl derives its endpoints from `--api-url`.
+ */
+export function buildMarsUrl(baseUrl, path, query = {}) {
+ const url = new URL(`${trimTrailingSlash(baseUrl)}${path}`);
+ for (const [key, value] of Object.entries(query)) {
+ if (value !== undefined && value !== null && value !== "") {
+ url.searchParams.set(key, String(value));
+ }
+ }
+ return url.toString();
+}
+
+/**
+ * Pull the human-readable message out of harness-api's error envelope. Falls
+ * back to the status line so a proxy/edge error page (which is not JSON) still
+ * produces something actionable rather than "undefined".
+ */
+async function readErrorMessage(response) {
+ try {
+ const body = await response.json();
+ const message = body?.error?.message;
+ if (typeof message === "string" && message) return message;
+ } catch {
+ // Non-JSON body (edge HTML, empty 502) — fall through to the status line.
+ }
+ return `${response.status} ${response.statusText}`.trim();
+}
+
+/**
+ * @param {object} options
+ * @param {() => Promise<string | null>} options.getToken Resolves the bearer
+ * token at call time so a rotated or re-authenticated credential is picked
+ * up without rebuilding the client.
+ * @param {string} [options.baseUrl]
+ * @param {string | null} [options.deviceId]
+ * @param {typeof globalThis.fetch} [options.fetchImpl] Injectable for tests.
+ */
+export function createMarsApiClient({
+ getToken,
+ baseUrl = DEFAULT_MARS_API_BASE_URL,
+ deviceId = null,
+ fetchImpl = globalThis.fetch,
+}) {
+ async function request(
+ method,
+ path,
+ { query, timeoutMs, body, signal } = {},
+ ) {
+ const token = await getToken();
+ if (!token) {
+ throw new MarsApiError("Not signed in to DigitalOcean.", { status: 401 });
+ }
+
+ const headers = { Authorization: `Bearer ${token}` };
+ if (deviceId) headers[DEVICE_ID_HEADER] = deviceId;
+ if (body !== undefined) headers["Content-Type"] = "application/json";
+
+ const timeout = AbortSignal.timeout(timeoutMs ?? DEFAULT_TIMEOUT_MS);
+ let response;
+ try {
+ response = await fetchImpl(buildMarsUrl(baseUrl, path, query), {
+ method,
+ headers,
+ body: body === undefined ? undefined : JSON.stringify(body),
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
+ });
+ } catch (error) {
+ throw new MarsApiError(
+ `Could not reach DigitalOcean: ${error instanceof Error ? error.message : String(error)}`,
+ { cause: error },
+ );
+ }
+
+ if (!response.ok) {
+ throw new MarsApiError(await readErrorMessage(response), {
+ status: response.status,
+ });
+ }
+
+ // 204 on pause/resume/delete — no body to parse.
+ if (response.status === 204) return null;
+ return response.json();
+ }
+
+ return {
+ /** `{sessions, next_page_token}`; results are always team-scoped. */
+ async listSessions({ pageSize, pageToken, status } = {}) {
+ const body = await request("GET", SESSIONS_PATH, {
+ query: { page_size: pageSize, page_token: pageToken, status },
+ });
+ return {
+ sessions: Array.isArray(body?.sessions) ? body.sessions : [],
+ nextPageToken: body?.next_page_token || null,
+ };
+ },
+
+ /** @param {{ signal?: AbortSignal }} [options] */
+ async getSession(sessionId, { signal } = {}) {
+ const body = await request("GET", `${SESSIONS_PATH}/${sessionId}`, {
+ signal,
+ });
+ return body?.session ?? null;
+ },
+
+ /**
+ * Agent Configs are the durable agent definitions (one config, many
+ * sessions). List items are the lightweight `AgentConfigSummary`
+ * projection, so they carry no manifest body.
+ */
+ async listAgentConfigs({ pageSize, pageToken } = {}) {
+ const body = await request("GET", CONFIGS_PATH, {
+ query: { page_size: pageSize, page_token: pageToken },
+ });
+ return {
+ configs: Array.isArray(body?.configs) ? body.configs : [],
+ nextPageToken: body?.next_page_token || null,
+ };
+ },
+
+ /**
+ * Create an immutable Agent Config. Secret values travel inside the
+ * manifest (`secrets.<NAME>.value`), are extracted server-side, and are
+ * never returned.
+ */
+ async createAgentConfig(name, manifestYaml) {
+ const body = await request("POST", CONFIGS_PATH, {
+ body: { name, manifest_yaml: manifestYaml },
+ });
+ return body?.config ?? null;
+ },
+
+ /** Full config, including the parsed `manifest` the list omits. */
+ async getAgentConfig(configId) {
+ const body = await request("GET", `${CONFIGS_PATH}/${configId}`);
+ return body?.config ?? null;
+ },
+
+ /**
+ * Sessions belonging to one config. Same Session shape and pagination as
+ * `listSessions`; a config that exists but has no sessions is an empty
+ * 200, so an empty list here does NOT mean the config is gone.
+ */
+ async listConfigSessions(configId, { pageSize, pageToken, status } = {}) {
+ const body = await request(
+ "GET",
+ `${CONFIGS_PATH}/${configId}${CONFIG_SESSIONS_SUBPATH}`,
+ { query: { page_size: pageSize, page_token: pageToken, status } },
+ );
+ return {
+ sessions: Array.isArray(body?.sessions) ? body.sessions : [],
+ nextPageToken: body?.next_page_token || null,
+ };
+ },
+
+ /**
+ * Sandbox sizes a manifest's `size` may name, smallest first. Each is
+ * `{slug, vcpus, memory_mb, price_per_hour_usd, price_per_month_usd}`.
+ */
+ async listSandboxSizes() {
+ const body = await request("GET", `${SESSIONS_PATH}/sandbox/sizes`);
+ return body?.sizes ?? [];
+ },
+
+ /**
+ * Launch a new session from an existing Agent Config. The config already
+ * holds the manifest and its resolved credentials, so this carries no
+ * spec of its own — which is what makes "run this agent" a single call.
+ * The new session starts PROVISIONING, not READY.
+ */
+ async createSessionFromConfig(configId, name) {
+ const body = await request("POST", SESSIONS_PATH, {
+ body: { name, config_id: configId },
+ timeoutMs: CREATE_SESSION_TIMEOUT_MS,
+ });
+ return body?.session ?? null;
+ },
+
+ async pauseSession(sessionId) {
+ await request("POST", `${SESSIONS_PATH}/${sessionId}/pause`);
+ },
+
+ /** @param {{ signal?: AbortSignal }} [options] */
+ async resumeSession(sessionId, { signal } = {}) {
+ await request("POST", `${SESSIONS_PATH}/${sessionId}/resume`, {
+ signal,
+ });
+ },
+
+ /**
+ * End a session for good: harness-api tears down its sandbox and
+ * checkpoints. 204 on success; 409 while a checkpoint, fork or rollback
+ * holds the session (retry later); 423 for a staff-locked session.
+ */
+ async destroySession(sessionId) {
+ await request("DELETE", `${SESSIONS_PATH}/${sessionId}`);
+ },
+
+ /**
+ * Soft-delete an Agent Config. harness-api does not check for live
+ * sessions, so the caller guards that; existing sessions keep running
+ * but no new ones can be created from the config.
+ */
+ async deleteAgentConfig(configId) {
+ await request("DELETE", `${CONFIGS_PATH}/${configId}`);
+ },
+
+ /**
+ * Cheapest authenticated call that proves the token is valid AND that the
+ * caller actually has MARS access. A well-formed token can still be
+ * refused by the `mars_preview` / `mars_access_ric1` feature flippers, so
+ * validating the string shape alone would report success too early.
+ */
+ async verifyAccess() {
+ await request("GET", SESSIONS_PATH, { query: { page_size: 1 } });
+ },
+ };
+}
diff --git a/scripts/mars-credentials.mjs b/scripts/mars-credentials.mjs
new file mode 100644
index 0000000000..f2a96b304f
--- /dev/null
+++ b/scripts/mars-credentials.mjs
@@ -0,0 +1,238 @@
+/**
+ * Encrypted store for DigitalOcean credentials used by the MARS backend.
+ *
+ * Holds *multiple* named connections rather than a single token. An OAuth
+ * access token is pinned to one team (`team_uuid` in the grant) and MARS
+ * sessions are team-scoped, so working across teams means holding one
+ * credential per team and switching between them.
+ *
+ * Only the token is encrypted; the surrounding metadata stays readable so the
+ * UI can label connections without a decrypt round-trip. Nothing here is ever
+ * handed to the renderer except through `toMetadata`, which omits the token.
+ */
+
+import { randomUUID } from "node:crypto";
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+const STORE_FILENAME = "mars-credentials.json";
+const STORE_VERSION = 1;
+
+export const CREDENTIAL_KIND_OAUTH = "oauth";
+export const CREDENTIAL_KIND_PAT = "pat";
+
+const LEGACY_PAT_LENGTH = 64;
+const V1_PAT_LENGTH = 71;
+const V1_PAT_PREFIX = "do";
+
+/**
+ * Shape check matching the one `doctl` performs before storing a token: 64
+ * characters for legacy tokens, or 71 beginning with `do` for v1 tokens.
+ *
+ * This is a fast typo guard only. It cannot tell whether the token is valid or
+ * whether the account has MARS access, so callers must still verify it against
+ * the API before treating the connection as usable.
+ */
+export function isValidPatFormat(token) {
+ const trimmed = token?.trim() ?? "";
+ if (trimmed.length === LEGACY_PAT_LENGTH) return true;
+ return trimmed.length === V1_PAT_LENGTH && trimmed.startsWith(V1_PAT_PREFIX);
+}
+
+function emptyState() {
+ return {
+ version: STORE_VERSION,
+ deviceId: randomUUID(),
+ activeConnectionId: null,
+ connections: [],
+ };
+}
+
+/** Public shape of a connection: everything except the secret. */
+function toMetadata(connection) {
+ if (!connection) return null;
+ return {
+ id: connection.id,
+ kind: connection.kind,
+ label: connection.label,
+ teamName: connection.teamName ?? null,
+ expiresAt: connection.expiresAt ?? null,
+ isExpired: isExpired(connection),
+ };
+}
+
+function isExpired(connection) {
+ if (!connection?.expiresAt) return false;
+ return Date.parse(connection.expiresAt) <= Date.now();
+}
+
+/**
+ * @param {object} options
+ * @param {string | null} [options.userDataPath] Where the store file lives;
+ * null keeps everything in memory for this process (the web bridge).
+ * @param {Pick<import("electron").SafeStorage, "isEncryptionAvailable" | "encryptString" | "decryptString"> | null} [options.safeStorage]
+ * Omitted in tests, which exercise the unencrypted in-memory path.
+ */
+export function createCredentialStore({
+ userDataPath = null,
+ safeStorage = null,
+} = {}) {
+ const filePath = userDataPath
+ ? path.join(userDataPath, STORE_FILENAME)
+ : null;
+
+ // When the OS keychain is unavailable (common on bare Linux desktops),
+ // credentials live only for this process rather than being written to disk
+ // in the clear.
+ const canEncrypt = Boolean(
+ filePath && safeStorage?.isEncryptionAvailable?.(),
+ );
+ /**
+ * Plaintext token per connection id. The only copy when nothing is
+ * encrypted; otherwise a cache, so the keychain is not hit on every dial.
+ * Ids are never reused, so remove() is the only invalidation needed.
+ */
+ const memoryTokens = new Map();
+
+ let state = load();
+
+ function load() {
+ if (!filePath) return emptyState();
+ try {
+ const parsed = JSON.parse(readFileSync(filePath, "utf8"));
+ if (parsed?.version !== STORE_VERSION) return emptyState();
+ return {
+ ...emptyState(),
+ ...parsed,
+ connections: Array.isArray(parsed.connections)
+ ? parsed.connections
+ : [],
+ };
+ } catch {
+ // Missing or corrupt store — start clean rather than blocking sign-in.
+ return emptyState();
+ }
+ }
+
+ function persist() {
+ if (!filePath) return;
+ mkdirSync(path.dirname(filePath), { recursive: true });
+ const serializable = {
+ ...state,
+ connections: state.connections.map((connection) => ({
+ ...connection,
+ // Session-only credentials must not leave a token behind on disk.
+ token: canEncrypt ? connection.token : null,
+ })),
+ };
+ writeFileSync(filePath, JSON.stringify(serializable, null, 2), {
+ mode: 0o600,
+ });
+ }
+
+ function encrypt(token) {
+ if (!canEncrypt) return null;
+ return safeStorage.encryptString(token).toString("base64");
+ }
+
+ function decrypt(connection) {
+ const cached = memoryTokens.get(connection.id);
+ if (cached !== undefined) return cached;
+ if (!canEncrypt || !connection.token) return null;
+ try {
+ const token = safeStorage.decryptString(
+ Buffer.from(connection.token, "base64"),
+ );
+ memoryTokens.set(connection.id, token);
+ return token;
+ } catch {
+ // Keychain rotated or the profile moved between machines.
+ return null;
+ }
+ }
+
+ function find(id) {
+ return state.connections.find((connection) => connection.id === id) ?? null;
+ }
+
+ return {
+ /** True when tokens survive a restart. Surfaced so the UI can warn. */
+ get isPersistent() {
+ return canEncrypt;
+ },
+
+ /** Stable per-install id, sent as `X-Device-UUID` the way doctl does. */
+ get deviceId() {
+ return state.deviceId;
+ },
+
+ list() {
+ return state.connections.map(toMetadata);
+ },
+
+ getActive() {
+ return toMetadata(find(state.activeConnectionId));
+ },
+
+ getActiveToken() {
+ return this.getToken(state.activeConnectionId);
+ },
+
+ /** Token of one connection, or null once it is removed or expired. */
+ getToken(id) {
+ const connection = find(id);
+ if (!connection || isExpired(connection)) return null;
+ return decrypt(connection);
+ },
+
+ /**
+ * @param {object} input
+ * @param {string} input.kind
+ * @param {string} input.token
+ * @param {string | null} [input.expiresAt]
+ * @param {string} input.label
+ * @param {string | null} [input.teamName]
+ */
+ save({ kind, token, expiresAt = null, label, teamName = null }) {
+ const id = randomUUID();
+ const connection = {
+ id,
+ kind,
+ label,
+ teamName,
+ expiresAt,
+ token: encrypt(token),
+ };
+ memoryTokens.set(id, token);
+
+ state.connections = [...state.connections, connection];
+ state.activeConnectionId = id;
+ persist();
+ return toMetadata(connection);
+ },
+
+ setActive(id) {
+ if (!find(id)) return null;
+ state.activeConnectionId = id;
+ persist();
+ return this.getActive();
+ },
+
+ remove(id) {
+ memoryTokens.delete(id);
+ state.connections = state.connections.filter(
+ (connection) => connection.id !== id,
+ );
+ if (state.activeConnectionId === id) {
+ state.activeConnectionId = state.connections[0]?.id ?? null;
+ }
+ persist();
+ return this.getActive();
+ },
+
+ /** Test seam: drop cached state and re-read from disk. */
+ reload() {
+ state = load();
+ },
+ };
+}
diff --git a/scripts/mars-oauth.mjs b/scripts/mars-oauth.mjs
new file mode 100644
index 0000000000..2404302ca9
--- /dev/null
+++ b/scripts/mars-oauth.mjs
@@ -0,0 +1,256 @@
+/**
+ * DigitalOcean OAuth sign-in for the MARS backend.
+ *
+ * Uses the **implicit** grant (`response_type=token`), which DigitalOcean
+ * documents as the flow for "client-side applications such as mobile or
+ * desktop clients where the client secret should not be stored on the user's
+ * device". DigitalOcean documents no PKCE support, so the authorization-code
+ * grant would require shipping a `client_secret` inside a distributed desktop
+ * binary — which is not a secret at all. The tradeoff is that implicit issues
+ * no refresh token, so the 30-day expiry is handled by re-authenticating.
+ */
+
+import { createServer } from "node:http";
+import { randomUUID } from "node:crypto";
+
+import { readRequestBody } from "./http-body.mjs";
+
+const AUTHORIZE_URL = "https://cloud.digitalocean.com/v1/oauth/authorize";
+const REVOKE_URL = "https://cloud.digitalocean.com/v1/oauth/revoke";
+
+/**
+ * DigitalOcean matches `redirect_uri` against the value registered with the
+ * OAuth application, so the loopback port cannot be OS-assigned — it has to be
+ * a fixed, registered port. (rclone pins 53682 for the same reason.)
+ */
+export const OAUTH_REDIRECT_PORT = 53682;
+export const OAUTH_REDIRECT_URI = `http://127.0.0.1:${OAUTH_REDIRECT_PORT}/callback`;
+
+/** Permissions the edge enforces on `/v2/agents/*` for MARS. */
+export const OAUTH_SCOPES = [
+ "agent_harness_session:read",
+ "agent_harness_session:operate",
+].join(" ");
+
+const CALLBACK_PATH = "/callback";
+const RELAY_PATH = "/callback-token";
+const SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000;
+/** The relayed fragment is a token plus a few params; anything larger is not one. */
+const RELAY_BODY_LIMIT_BYTES = 16 * 1024;
+
+/**
+ * Served at the redirect URI.
+ *
+ * The implicit grant returns the token in the URL *fragment*, and browsers
+ * never transmit fragments to the server — so the loopback request that lands
+ * here carries no token at all. This page exists purely to read
+ * `location.hash` in the browser and POST it back on a second request.
+ * Without it the flow appears to hang forever.
+ */
+const RELAY_PAGE = `<!doctype html>
+<html lang="en">
+<head><meta charset="utf-8"><title>Signing in…</title>
+<style>
+ body { font-family: ui-sans-serif, system-ui, sans-serif; background: #0b0e14;
+ color: #e6e6e6; display: grid; place-items: center; height: 100vh; margin: 0; }
+ .card { text-align: center; max-width: 26rem; padding: 2rem; }
+ h1 { font-size: 1.1rem; font-weight: 600; }
+ p { color: #9aa0aa; font-size: .9rem; line-height: 1.5; }
+</style>
+</head>
+<body>
+ <div class="card">
+ <h1 id="title">Finishing sign-in…</h1>
+ <p id="detail">You can close this tab in a moment.</p>
+ </div>
+ <script>
+ (function () {
+ var fragment = window.location.hash.replace(/^#/, "");
+ fetch(${JSON.stringify(RELAY_PATH)}, {
+ method: "POST",
+ headers: { "Content-Type": "text/plain" },
+ body: fragment,
+ }).then(function () {
+ document.getElementById("title").textContent = "Signed in to DigitalOcean";
+ document.getElementById("detail").textContent = "You can close this tab and return to OpenHands.";
+ }).catch(function () {
+ document.getElementById("title").textContent = "Sign-in could not be completed";
+ document.getElementById("detail").textContent = "Return to OpenHands and try again, or use a personal access token.";
+ });
+ })();
+ </script>
+</body>
+</html>`;
+
+/**
+ * @param {object} options
+ * @param {string} options.clientId
+ * @param {string} options.state
+ * @param {string} [options.redirectUri]
+ * @param {string} [options.scope]
+ */
+export function buildAuthorizeUrl({ clientId, state, redirectUri, scope }) {
+ const url = new URL(AUTHORIZE_URL);
+ url.searchParams.set("client_id", clientId);
+ url.searchParams.set("redirect_uri", redirectUri ?? OAUTH_REDIRECT_URI);
+ url.searchParams.set("response_type", "token");
+ url.searchParams.set("scope", scope ?? OAUTH_SCOPES);
+ url.searchParams.set("state", state);
+ url.searchParams.set("prompt", "select_account");
+ return url.toString();
+}
+
+/**
+ * Parse the relayed fragment into a grant. Also handles the error form
+ * DigitalOcean redirects with when the user declines or is not signed in.
+ *
+ * @param {string | null | undefined} fragment
+ * @param {string} expectedState
+ */
+export function parseImplicitGrant(fragment, expectedState) {
+ const params = new URLSearchParams(fragment ?? "");
+
+ const error = params.get("error");
+ if (error) {
+ throw new Error(params.get("error_description") || error);
+ }
+
+ const accessToken = params.get("access_token");
+ if (!accessToken) {
+ throw new Error("DigitalOcean did not return an access token.");
+ }
+
+ // Guards against a forged callback: a third party that can reach the
+ // loopback port cannot know the state we generated for this attempt.
+ if (params.get("state") !== expectedState) {
+ throw new Error("Sign-in state did not match; aborting for safety.");
+ }
+
+ const expiresIn = Number.parseInt(params.get("expires_in") ?? "", 10);
+ return {
+ accessToken,
+ tokenType: params.get("token_type") ?? "bearer",
+ expiresAt: Number.isFinite(expiresIn)
+ ? new Date(Date.now() + expiresIn * 1000).toISOString()
+ : null,
+ };
+}
+
+/**
+ * Run the full sign-in: open the system browser, wait for the relayed grant.
+ *
+ * The system browser is used rather than an in-app `BrowserWindow` so the user
+ * authorizes in the session they are already signed into and can see the real
+ * URL they are authenticating against.
+ *
+ * @param {object} options
+ * @param {string | null | undefined} options.clientId
+ * @param {(url: string) => Promise<void>} options.openExternal
+ * @param {number} [options.timeoutMs]
+ */
+export async function signInWithDigitalOcean({
+ clientId,
+ openExternal,
+ timeoutMs = SIGN_IN_TIMEOUT_MS,
+}) {
+ if (!clientId) {
+ throw new Error(
+ "No DigitalOcean OAuth client is configured in this build. Use a personal access token instead.",
+ );
+ }
+
+ const state = randomUUID();
+ const server = createServer();
+
+ const grant = new Promise((resolve, reject) => {
+ server.on("request", async (req, res) => {
+ const { pathname } = new URL(req.url, OAUTH_REDIRECT_URI);
+
+ if (req.method === "GET" && pathname === CALLBACK_PATH) {
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
+ res.end(RELAY_PAGE);
+ return;
+ }
+
+ if (req.method === "POST" && pathname === RELAY_PATH) {
+ let fragment;
+ try {
+ fragment = (
+ await readRequestBody(req, RELAY_BODY_LIMIT_BYTES)
+ ).toString("utf8");
+ } catch {
+ res.writeHead(400).end();
+ return;
+ }
+ try {
+ const parsed = parseImplicitGrant(fragment, state);
+ res.writeHead(204).end();
+ resolve(parsed);
+ } catch (error) {
+ res.writeHead(400).end();
+ reject(error);
+ }
+ return;
+ }
+
+ res.writeHead(404).end();
+ });
+ });
+
+ // One handler for listen and runtime errors; racing it everywhere keeps the
+ // EADDRINUSE explanation from being shadowed by the raw listen error.
+ const failed = new Promise((_, reject) => {
+ server.on("error", (error) => {
+ reject(
+ error.code === "EADDRINUSE"
+ ? new Error(
+ `Port ${OAUTH_REDIRECT_PORT} is already in use, so DigitalOcean cannot redirect back. Close whatever is using it, or sign in with a personal access token instead.`,
+ )
+ : error,
+ );
+ });
+ });
+
+ let timer;
+ const timeout = new Promise((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error("Timed out waiting for DigitalOcean sign-in.")),
+ timeoutMs,
+ );
+ timer.unref?.();
+ });
+
+ try {
+ await Promise.race([
+ new Promise((resolve) =>
+ server.listen(OAUTH_REDIRECT_PORT, "127.0.0.1", resolve),
+ ),
+ failed,
+ ]);
+
+ await openExternal(buildAuthorizeUrl({ clientId, state }));
+ return await Promise.race([grant, failed, timeout]);
+ } finally {
+ clearTimeout(timer);
+ server.close();
+ }
+}
+
+/**
+ * Invalidate an access token server-side. Best-effort: a failed revoke must
+ * not prevent the local credential from being forgotten.
+ */
+export async function revokeToken(token, fetchImpl = globalThis.fetch) {
+ try {
+ await fetchImpl(REVOKE_URL, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ body: new URLSearchParams({ token }).toString(),
+ });
+ } catch {
+ // Network failure on sign-out; the local record is still removed.
+ }
+}
diff --git a/scripts/mars-session.mjs b/scripts/mars-session.mjs
new file mode 100644
index 0000000000..6fff550f12
--- /dev/null
+++ b/scripts/mars-session.mjs
@@ -0,0 +1,94 @@
+/**
+ * MARS session lifecycle helper: resume a paused session before its tunnel
+ * is dialed.
+ *
+ * MARS auto-pauses idle sessions (HARNESS_IDLE_PAUSE_TIMEOUT), and — per
+ * openhands-canvas-dataplane-design.md's "Inherited risk" section — an open
+ * but quiet port-forward tunnel does not currently count as activity, so a
+ * long-lived chat session WILL hit this, not just as an edge case. Mirrors
+ * doctl's ensureSessionAwakeForPortForward (agent_port_forward.go), which
+ * resumes a paused session before opening a tunnel the same way `launch`/
+ * `attach` already do.
+ *
+ * Built on mars-api.mjs's client so these calls carry the same auth, device
+ * id, and per-request timeout as every other MARS request.
+ */
+
+import { setTimeout as sleep } from "node:timers/promises";
+import {
+ SESSION_STATUS_PAUSED,
+ SESSION_STATUS_READY,
+ isTerminalSessionStatus,
+} from "./mars-api.mjs";
+
+const DEFAULT_POLL_INTERVAL_MS = 2_000;
+const DEFAULT_TIMEOUT_MS = 120_000;
+
+async function readSession(api, sessionId, signal) {
+ const session = await api.getSession(sessionId, { signal });
+ if (!session) {
+ throw new Error(`DigitalOcean returned no session ${sessionId}.`);
+ }
+ return session;
+}
+
+async function waitUntilReady(api, sessionId, pollIntervalMs, signal) {
+ let session = await readSession(api, sessionId, signal);
+ if (isTerminalSessionStatus(session.status)) {
+ throw new Error(
+ `Session ${sessionId} is ${session.status} and cannot be connected to.`,
+ );
+ }
+ if (session.status === SESSION_STATUS_READY) {
+ return session;
+ }
+ if (session.status === SESSION_STATUS_PAUSED) {
+ await api.resumeSession(sessionId, { signal });
+ }
+
+ for (;;) {
+ await sleep(pollIntervalMs, undefined, { signal });
+ session = await readSession(api, sessionId, signal);
+ if (session.status === SESSION_STATUS_READY) {
+ return session;
+ }
+ if (isTerminalSessionStatus(session.status)) {
+ throw new Error(
+ `Session ${sessionId} became ${session.status} while resuming.`,
+ );
+ }
+ }
+}
+
+/**
+ * Resolve once the session is SESSION_STATUS_READY, resuming it first if
+ * it's paused. Throws if the session is (or becomes) terminal, or if it
+ * doesn't reach ready within timeoutMs. The deadline bounds the whole wait,
+ * including any request still in flight when it passes.
+ *
+ * @param {object} options
+ * @param {Pick<ReturnType<typeof import("./mars-api.mjs").createMarsApiClient>, "getSession" | "resumeSession">} options.api
+ * @param {string} options.sessionId
+ * @param {number} [options.pollIntervalMs]
+ * @param {number} [options.timeoutMs]
+ * @returns {Promise<{status: string, [key: string]: any}>} the session, once ready
+ */
+export async function ensureSessionAwake({
+ api,
+ sessionId,
+ pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+}) {
+ const deadline = AbortSignal.timeout(timeoutMs);
+ try {
+ return await waitUntilReady(api, sessionId, pollIntervalMs, deadline);
+ } catch (error) {
+ if (deadline.aborted) {
+ throw new Error(
+ `Timed out waiting for session ${sessionId} to become ready.`,
+ { cause: error },
+ );
+ }
+ throw error;
+ }
+}
diff --git a/scripts/mars-tunnel-bridge.mjs b/scripts/mars-tunnel-bridge.mjs
new file mode 100644
index 0000000000..1141b51912
--- /dev/null
+++ b/scripts/mars-tunnel-bridge.mjs
@@ -0,0 +1,426 @@
+/**
+ * Main-process service behind the DigitalOcean Managed Agents screen.
+ *
+ * Wires the MARS REST client, the port-forward tunnel registry
+ * (scripts/tunnel-registry.mjs, MARSOHS-1428/1429) and the DigitalOcean
+ * credential store into Electron's IPC layer. Channel names mirror the
+ * teammate fork's `window.marsBridge` surface so the two integrations stay
+ * easy to reconcile.
+ *
+ * Connecting to a session opens a port-forward tunnel: a loopback listener
+ * this process holds, relayed over harness-api's port-forward WebSocket to
+ * the agent server inside the sandbox. The renderer registers the listener
+ * as an ordinary local backend.
+ *
+ * Tokens never cross the context bridge: the renderer asks to connect by
+ * session id alone, and this process sources the bearer token from the
+ * stored connection for every dial. harness-api sends no CORS headers, so
+ * every MARS control-plane call has to happen here anyway.
+ */
+
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { createTunnelRegistry } from "./tunnel-registry.mjs";
+import { ensureSessionAwake } from "./mars-session.mjs";
+import {
+ AGENT_SERVER_GUEST_PORT,
+ DEFAULT_MARS_API_BASE_URL,
+ MarsApiError,
+ OPENHANDS_AGENT,
+ buildOpenHandsManifest,
+ createMarsApiClient,
+ readManifestAgent,
+} from "./mars-api.mjs";
+import {
+ CREDENTIAL_KIND_OAUTH,
+ CREDENTIAL_KIND_PAT,
+ createCredentialStore,
+ isValidPatFormat,
+} from "./mars-credentials.mjs";
+import { revokeToken, signInWithDigitalOcean } from "./mars-oauth.mjs";
+
+export const MARS_TUNNEL_IPC = {
+ openTunnel: "mars:openTunnel",
+ closeTunnel: "mars:closeTunnel",
+ getTunnel: "mars:getTunnel",
+ getAuthState: "mars:getAuthState",
+ signInWithOAuth: "mars:signInWithOAuth",
+ savePat: "mars:savePat",
+ setActiveConnection: "mars:setActiveConnection",
+ signOut: "mars:signOut",
+ listSessions: "mars:listSessions",
+ listAgentConfigs: "mars:listAgentConfigs",
+ listConfigSessions: "mars:listConfigSessions",
+ listSandboxSizes: "mars:listSandboxSizes",
+ createOpenHandsAgent: "mars:createOpenHandsAgent",
+ createSession: "mars:createSession",
+ pauseSession: "mars:pauseSession",
+ resumeSession: "mars:resumeSession",
+ destroySession: "mars:destroySession",
+ deleteAgentConfig: "mars:deleteAgentConfig",
+};
+
+/**
+ * Provisioning a brand-new sandbox is slower than waking a paused one, so the
+ * create path gets a longer budget than ensureSessionAwake's wake default.
+ */
+const CREATE_SESSION_READY_TIMEOUT_MS = 300_000;
+
+/**
+ * createSession has just waited for READY, so the openTunnel that follows
+ * within this window skips one getSession round-trip. Only that first open
+ * uses it: any later one — including reusing a live tunnel — asks again, so
+ * a session paused in the meantime (idle, or from another client) is woken.
+ */
+const READY_FRESH_MS = 10_000;
+
+export function buildTunnelHost(localPort) {
+ return `http://127.0.0.1:${localPort}`;
+}
+
+/**
+ * Shipped MARS defaults from `config/defaults.json`. The packaged app copies
+ * `config/` beside `scripts/`, so the same relative path works in dev and in
+ * the installed bundle. A missing file only costs the OAuth button.
+ *
+ * @returns {{ apiBaseUrl?: string, oauthClientId?: string }}
+ */
+export function readMarsDefaults() {
+ try {
+ const defaultsPath = fileURLToPath(
+ new URL("../config/defaults.json", import.meta.url),
+ );
+ return JSON.parse(readFileSync(defaultsPath, "utf-8")).mars ?? {};
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * Env wins over shipped defaults so staging or a private OAuth app can be
+ * used without rebuilding.
+ *
+ * @param {Record<string, string | undefined>} [env]
+ * @param {{ apiBaseUrl?: string, oauthClientId?: string }} [defaults]
+ */
+export function readMarsConfig(
+ env = process.env,
+ defaults = readMarsDefaults(),
+) {
+ return {
+ apiBaseUrl:
+ env.MARS_API_BASE_URL || defaults.apiBaseUrl || DEFAULT_MARS_API_BASE_URL,
+ oauthClientId: env.DO_OAUTH_CLIENT_ID || defaults.oauthClientId || null,
+ };
+}
+
+/**
+ * @param {object} [options]
+ * @param {ReturnType<typeof createTunnelRegistry>} [options.registry] Override for tests
+ * @param {ReturnType<typeof createCredentialStore>} [options.credentials] Override for tests
+ * @param {ReturnType<typeof createMarsApiClient>} [options.api] Override for tests
+ * @param {string} [options.userDataPath] Where the credential store lives
+ * @param {import("electron").SafeStorage | null} [options.safeStorage]
+ * @param {(url: string) => Promise<void>} [options.openExternal] Opens the OAuth page
+ * @param {typeof ensureSessionAwake} [options.ensureAwake] Override for tests
+ * @param {Record<string, string | undefined>} [options.env]
+ */
+export function createMarsTunnelBridge({
+ registry: registryOverride,
+ credentials,
+ api,
+ userDataPath,
+ safeStorage = null,
+ openExternal = async () => {},
+ ensureAwake = ensureSessionAwake,
+ env = process.env,
+} = {}) {
+ const config = readMarsConfig(env);
+ const store =
+ credentials ?? createCredentialStore({ userDataPath, safeStorage });
+ /** @param {() => string | null} getToken */
+ const clientFor = (getToken) =>
+ createMarsApiClient({
+ baseUrl: config.apiBaseUrl,
+ deviceId: store.deviceId,
+ getToken: async () => getToken(),
+ });
+ const client = api ?? clientFor(() => store.getActiveToken());
+
+ /** When createSession saw each session READY; see READY_FRESH_MS. */
+ const readyAt = new Map();
+ async function wake(options) {
+ const session = await ensureAwake(options);
+ readyAt.set(options.sessionId, Date.now());
+ return session;
+ }
+
+ const registry =
+ registryOverride ??
+ createTunnelRegistry({
+ ensureAwake: async ({ sessionId, getAccessToken }) => {
+ // Consumed by the first open after createSession, never refreshed.
+ const at = readyAt.get(sessionId);
+ readyAt.delete(sessionId);
+ if (at !== undefined && Date.now() - at < READY_FRESH_MS) return;
+ await ensureAwake({ api: clientFor(getAccessToken), sessionId });
+ },
+ });
+
+ /** Configs are immutable, so a config's agent never needs re-reading. */
+ const agentByConfigId = new Map();
+
+ /**
+ * Connect over the port-forward tunnel. `host` is what the renderer
+ * registers as the backend's base URL: the loopback listener this process
+ * holds for the session.
+ */
+ async function connectSession({ sessionId, localPort, connectionId }) {
+ const getAccessToken = () => store.getToken(connectionId);
+ // The guest port is fixed here rather than accepted over IPC so the
+ // renderer cannot dial arbitrary ports inside the sandbox.
+ let tunnel;
+ try {
+ tunnel = await registry.attach({
+ sessionId,
+ remotePort: AGENT_SERVER_GUEST_PORT,
+ getAccessToken,
+ apiUrl: config.apiBaseUrl,
+ localPort,
+ owner: connectionId,
+ });
+ } catch (error) {
+ // A failed dial may mean the session is no longer READY; ask again.
+ readyAt.delete(sessionId);
+ throw error;
+ }
+ return {
+ ...tunnel,
+ transport: "tunnel",
+ host:
+ tunnel.localPort === undefined
+ ? undefined
+ : buildTunnelHost(tunnel.localPort),
+ };
+ }
+
+ /**
+ * The list projection has no manifest, so each config's agent is read from
+ * its full record. A failed read leaves `agent` null (unknown) and is
+ * retried on the next list rather than cached.
+ */
+ async function withManifestAgent(config) {
+ if (!agentByConfigId.has(config.id)) {
+ try {
+ const full = await client.getAgentConfig(config.id);
+ agentByConfigId.set(config.id, readManifestAgent(full?.manifest));
+ } catch {
+ return { ...config, agent: null };
+ }
+ }
+ return { ...config, agent: agentByConfigId.get(config.id) };
+ }
+
+ function authState() {
+ return {
+ connections: store.list(),
+ active: store.getActive(),
+ isPersistent: store.isPersistent,
+ canUseOAuth: Boolean(config.oauthClientId),
+ };
+ }
+
+ function requireActiveConnectionId() {
+ const id = store.getActive()?.id;
+ if (!id || !store.getToken(id)) {
+ throw new MarsApiError("Sign in to DigitalOcean first.", { status: 401 });
+ }
+ return id;
+ }
+
+ /**
+ * A well-formed token can still be refused by the MARS feature flippers, so
+ * a new credential only sticks once a real API call has accepted it. A
+ * rejected one leaves the previously active connection active.
+ */
+ async function saveVerified(connection) {
+ const previousId = store.getActive()?.id ?? null;
+ const saved = store.save(connection);
+ try {
+ await client.verifyAccess();
+ } catch (error) {
+ store.remove(saved.id);
+ if (previousId) store.setActive(previousId);
+ throw error;
+ }
+ return authState();
+ }
+
+ return {
+ registry,
+
+ getAuthState: authState,
+
+ async signInWithOAuth() {
+ const grant = await signInWithDigitalOcean({
+ clientId: config.oauthClientId,
+ openExternal,
+ });
+ return saveVerified({
+ kind: CREDENTIAL_KIND_OAUTH,
+ token: grant.accessToken,
+ expiresAt: grant.expiresAt,
+ label: "DigitalOcean",
+ });
+ },
+
+ async savePat({ token, label } = {}) {
+ const trimmed = token?.trim() ?? "";
+ if (!isValidPatFormat(trimmed)) {
+ throw new Error(
+ "That does not look like a DigitalOcean personal access token.",
+ );
+ }
+ return saveVerified({
+ kind: CREDENTIAL_KIND_PAT,
+ token: trimmed,
+ label: label?.trim() || "DigitalOcean token",
+ });
+ },
+
+ /**
+ * Open tunnels are left alone: each keeps dialing with the connection
+ * that opened it, since its session belongs to that connection's team.
+ */
+ setActiveConnection(id) {
+ store.setActive(id);
+ return authState();
+ },
+
+ async signOut(id) {
+ const target = id ?? store.getActive()?.id;
+ if (!target) return authState();
+ await registry.detachOwnedBy(target);
+ readyAt.clear();
+ const kind = store.list().find((c) => c.id === target)?.kind;
+ if (kind === CREDENTIAL_KIND_OAUTH) {
+ const token = store.getToken(target);
+ if (token) await revokeToken(token);
+ }
+ store.remove(target);
+ return authState();
+ },
+
+ listSessions: (options) => client.listSessions(options ?? {}),
+ async listAgentConfigs(options) {
+ const page = await client.listAgentConfigs(options ?? {});
+ return {
+ ...page,
+ configs: await Promise.all(page.configs.map(withManifestAgent)),
+ };
+ },
+ listConfigSessions: (configId, options) =>
+ client.listConfigSessions(configId, options ?? {}),
+ async listSandboxSizes() {
+ requireActiveConnectionId();
+ return client.listSandboxSizes();
+ },
+ pauseSession(sessionId) {
+ readyAt.delete(sessionId);
+ return client.pauseSession(sessionId);
+ },
+ resumeSession: (sessionId) => client.resumeSession(sessionId),
+
+ /**
+ * Destroy first, then drop the live connection: harness-api can refuse
+ * (409 while a checkpoint/fork/rollback holds the session, 423 locked),
+ * and then the session is still running and the user must keep their
+ * connection to it. Only a session that is really gone is detached.
+ */
+ async destroySession(sessionId) {
+ await client.destroySession(sessionId);
+ readyAt.delete(sessionId);
+ await registry.detach(sessionId);
+ },
+ async deleteAgentConfig(configId) {
+ await client.deleteAgentConfig(configId);
+ agentByConfigId.delete(configId);
+ },
+
+ /**
+ * Create an OpenHands Agent Config. The manifest is built here rather
+ * than accepted over IPC so the renderer can only ever create OpenHands
+ * agents; it contributes just the name and an optional sandbox size slug
+ * (validated by the manifest builder).
+ */
+ async createOpenHandsAgent({ name, size } = {}) {
+ const trimmedName = name?.trim() ?? "";
+ if (!trimmedName) {
+ throw new MarsApiError("Give the agent a name.", { status: 400 });
+ }
+ const created = await client.createAgentConfig(
+ trimmedName,
+ buildOpenHandsManifest({ size: size || undefined }),
+ );
+ if (!created?.id) {
+ throw new MarsApiError("DigitalOcean returned no agent.");
+ }
+ agentByConfigId.set(created.id, OPENHANDS_AGENT);
+ return {
+ id: created.id,
+ name: created.name ?? trimmedName,
+ created_by: created.created_by ?? null,
+ updated_at: created.updated_at ?? null,
+ agent: OPENHANDS_AGENT,
+ };
+ },
+
+ /**
+ * Launch a session from an agent config and resolve only once it is
+ * READY, so the caller can tunnel to it directly. A created session
+ * starts PROVISIONING, which ensureSessionAwake already polls through.
+ */
+ async createSession(configId, name) {
+ const session = await client.createSessionFromConfig(configId, name);
+ const sessionId = session?.session_id;
+ if (!sessionId) {
+ throw new MarsApiError("DigitalOcean returned no session.");
+ }
+ return wake({
+ api: client,
+ sessionId,
+ timeoutMs: CREATE_SESSION_READY_TIMEOUT_MS,
+ });
+ },
+
+ /**
+ * Connect to a session's agent-server over a port-forward tunnel. The
+ * connection is bound to the active credential: tunnel dials read that
+ * credential's current token and are cut off when it signs out.
+ */
+ openTunnel({ sessionId, localPort } = {}) {
+ const connectionId = requireActiveConnectionId();
+ return connectSession({ sessionId, localPort, connectionId });
+ },
+
+ closeTunnel(sessionId) {
+ readyAt.delete(sessionId);
+ return registry.detach(sessionId);
+ },
+ getTunnel(sessionId) {
+ return registry.get(sessionId);
+ },
+
+ /** @param {import("electron").IpcMain} ipcMain */
+ registerIpc(ipcMain) {
+ for (const [method, channel] of Object.entries(MARS_TUNNEL_IPC)) {
+ ipcMain.handle(channel, (_event, ...args) => this[method](...args));
+ }
+ },
+
+ /** Tear down every tunnel — on quit. */
+ dispose() {
+ return registry.detachAll();
+ },
+ };
+}
diff --git a/scripts/mars-web-bridge.mjs b/scripts/mars-web-bridge.mjs
new file mode 100644
index 0000000000..b35243437e
--- /dev/null
+++ b/scripts/mars-web-bridge.mjs
@@ -0,0 +1,535 @@
+/**
+ * MARS for the web build: the Agent Canvas server stands in for Electron's
+ * main process.
+ *
+ * In the desktop app the renderer reaches a DigitalOcean session through
+ * `window.marsBridge` (electron/preload-main.cjs → scripts/mars-tunnel-bridge.mjs),
+ * which holds a port-forward tunnel to the session in the Electron main
+ * process. A browser can do neither: harness-api sends no CORS headers, the
+ * tunnel needs a Node process, and the token must never reach the page. So
+ * the server that already fronts the web build (scripts/ingress.mjs,
+ * scripts/static-server.mjs) hosts the same bridge — holding the tunnel
+ * itself — and exposes it same-origin:
+ *
+ * POST /mars/rpc/<method> — the MarsBridge surface over JSON; the
+ * renderer's fetch-backed bridge
+ * (src/api/mars/mars-web-bridge.ts) calls
+ * this exactly as the preload calls IPC.
+ * ANY /mars/sessions/<id>/... — reverse proxy (HTTP + WebSocket) to that
+ * session's tunnel listener on loopback
+ * (the tunnel pings its own upstream
+ * socket, see tunnel-client.mjs).
+ * GET /mars/health — lets the renderer detect this server.
+ *
+ * `openTunnel` therefore answers with `host` = `<origin>/mars/sessions/<id>`,
+ * a path-prefixed backend the renderer already supports (see
+ * src/utils/websocket-url.ts `extractPathPrefix`). The agent-server writes
+ * its own origin into `conversation_url`, which the renderer uses to open
+ * the event WebSocket, so proxied JSON has those URLs rewritten to the prefix.
+ *
+ * Trust model. These routes hold the DigitalOcean token and can destroy
+ * sessions, so they are off unless `MARS_WEB=1`, and when on they want the
+ * server's session key on every request: the renderer sends it as
+ * `X-Session-API-Key` on `/mars/rpc/*` (the same key it already sends the
+ * agent-server), and a request that presents it gets an `HttpOnly;
+ * SameSite=Strict; Path=/mars` cookie back, which the browser then attaches
+ * on its own to the proxied REST calls and to the WebSocket upgrade — the
+ * one request a browser cannot put a header on. The key is `MARS_WEB_KEY`,
+ * else the server's `--session-api-key`; with neither, the bridge mounts
+ * only on a loopback bind (dev), where a `Host` check keeps a DNS-rebound
+ * page from reaching it (cookies are host-scoped, so with a key in play
+ * rebinding cannot carry one). Cross-origin requests are refused outright;
+ * JSON POSTs preflight and this server sends no CORS headers. Credentials
+ * are in-memory only (no OS keychain here, nothing written to disk);
+ * `MARS_TOKEN` seeds one at startup.
+ */
+
+import { randomBytes, timingSafeEqual } from "node:crypto";
+
+import { DEFAULT_BIND_HOST, isLoopbackBind } from "./bind-host.mjs";
+import { readRequestBody } from "./http-body.mjs";
+import {
+ buildTunnelHost,
+ createMarsTunnelBridge,
+} from "./mars-tunnel-bridge.mjs";
+import { createProxyHandlers, rewriteJsonResponse } from "./proxy-utils.mjs";
+
+export const MARS_WEB_PREFIX = "/mars";
+const HEALTH_PATH = `${MARS_WEB_PREFIX}/health`;
+const RPC_PREFIX = `${MARS_WEB_PREFIX}/rpc/`;
+const SESSIONS_PREFIX = `${MARS_WEB_PREFIX}/sessions/`;
+
+const RPC_BODY_LIMIT_BYTES = 64 * 1024;
+/** Past this a JSON body streams through untouched rather than being rewritten. */
+const JSON_REWRITE_LIMIT_BYTES = 8 * 1024 * 1024;
+/** The session key on HTTP requests; same header the agent-server takes. */
+const AUTH_HEADER = "x-session-api-key";
+/** Issued to a request that presented the key; carries auth to WebSocket upgrades. */
+const AUTH_COOKIE = "mars_web_auth";
+/** Response fields whose agent-server URL the renderer follows. */
+const URL_FIELDS = new Set(["conversation_url"]);
+
+/**
+ * Bridge methods a browser may call — an explicit allow-list, so a method
+ * added to the desktop IPC surface is not exposed here until listed. OAuth is
+ * left out: its implicit-grant flow needs a loopback redirect in a trusted
+ * process.
+ */
+export const RPC_METHODS = new Set([
+ "getAuthState",
+ "savePat",
+ "setActiveConnection",
+ "signOut",
+ "listSessions",
+ "listAgentConfigs",
+ "listConfigSessions",
+ "listSandboxSizes",
+ "createOpenHandsAgent",
+ "createSession",
+ "pauseSession",
+ "resumeSession",
+ "destroySession",
+ "deleteAgentConfig",
+ "openTunnel",
+ "closeTunnel",
+ "getTunnel",
+]);
+
+/** Request headers that belong to the canvas origin, never to the session host. */
+const CANVAS_ONLY_HEADERS = ["cookie", AUTH_HEADER, "origin", "referer"];
+
+/** Off unless asked for: these routes hold the DO token and can destroy sessions. */
+export function isMarsWebEnabled(env = process.env) {
+ return env.MARS_WEB === "1";
+}
+
+/**
+ * The key `/mars/*` requires, or null when none is configured. Explicit
+ * `MARS_WEB_KEY` wins so a deployment can decouple it from the agent-server
+ * key; otherwise the server's own `--session-api-key` is reused, which is
+ * what the renderer already holds.
+ */
+export function resolveMarsWebKey({
+ env = process.env,
+ sessionApiKey = null,
+} = {}) {
+ const explicit = env.MARS_WEB_KEY?.trim();
+ if (explicit) return explicit;
+ const own = typeof sessionApiKey === "string" ? sessionApiKey.trim() : "";
+ return own || null;
+}
+
+/**
+ * Mount the bridge for a server, or return null when it must not be: not
+ * opted in, or no key on a non-loopback bind (the routes would be open to
+ * the LAN with the DO token behind them).
+ */
+export function mountMarsWebBridge({
+ env = process.env,
+ host = DEFAULT_BIND_HOST,
+ sessionApiKey = null,
+ log = (message) => console.warn(`[mars-web] ${message}`),
+} = {}) {
+ if (!isMarsWebEnabled(env)) return null;
+ const key = resolveMarsWebKey({ env, sessionApiKey });
+ if (!key && !isLoopbackBind(host)) {
+ log(
+ `MARS_WEB=1 but no key and bind host ${host} is not loopback; refusing to mount /mars/* (set MARS_WEB_KEY or --session-api-key).`,
+ );
+ return null;
+ }
+ if (!key) log("no key configured; /mars/* is open to local callers only");
+ return createMarsWebBridge({ env, host, key });
+}
+
+function safeEqual(a, b) {
+ const x = Buffer.from(a);
+ const y = Buffer.from(b);
+ return x.length === y.length && timingSafeEqual(x, y);
+}
+
+function readCookie(req, name) {
+ const header = req.headers.cookie;
+ if (!header) return null;
+ for (const part of header.split(";")) {
+ const eq = part.indexOf("=");
+ if (eq === -1) continue;
+ if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
+ }
+ return null;
+}
+
+/** Hostname of the request's `Host` header, without port or brackets. */
+function requestHostname(req) {
+ const host = req.headers.host ?? "";
+ try {
+ return new URL(`http://${host}`).hostname.replace(/^\[|\]$/g, "");
+ } catch {
+ return "";
+ }
+}
+
+/** `http://host[:port]` of the request as the browser sees it. */
+function requestOrigin(req) {
+ const proto =
+ req.headers["x-forwarded-proto"]?.split(",")[0].trim() || "http";
+ return `${proto}://${req.headers.host}`;
+}
+
+function sessionProxyBase(req, sessionId) {
+ return `${requestOrigin(req)}${SESSIONS_PREFIX}${encodeURIComponent(sessionId)}`;
+}
+
+/**
+ * A page on another origin cannot be allowed to drive the bridge or read
+ * through the proxy. Same-origin requests either carry a matching Origin or
+ * none at all (plain navigations, same-origin GETs).
+ */
+function isCrossOrigin(req) {
+ const origin = req.headers.origin;
+ if (!origin) return false;
+ try {
+ return new URL(origin).host !== req.headers.host;
+ } catch {
+ return true;
+ }
+}
+
+/**
+ * On a loopback bind the only legitimate `Host` values are loopback names;
+ * a DNS-rebound page arrives with its own hostname in both `Host` and
+ * `Origin`, so the origin check alone would pass it.
+ */
+function isForeignHost(req, bindHost) {
+ if (!isLoopbackBind(bindHost)) return false;
+ const hostname = requestHostname(req);
+ return !(isLoopbackBind(hostname) || hostname.endsWith(".localhost"));
+}
+
+function writeJson(res, status, body) {
+ const payload = JSON.stringify(body);
+ res.writeHead(status, {
+ "Content-Type": "application/json",
+ "Content-Length": Buffer.byteLength(payload),
+ "Cache-Control": "no-store",
+ });
+ res.end(payload);
+}
+
+async function readJsonBody(req, limit) {
+ const body = await readRequestBody(req, limit);
+ if (body.length === 0) return {};
+ try {
+ return JSON.parse(body.toString("utf8"));
+ } catch {
+ throw new Error("request body is not valid JSON");
+ }
+}
+
+const CONVERSATION_URL_RE =
+ /^https?:\/\/[^/?#]+(?:\/[^?#]*?)?(?=\/api\/conversations(?:[/?#]|$))/;
+
+/**
+ * Point the agent-server URL fields of a response at the proxy prefix. The
+ * agent-server builds `conversation_url` from its own view of the request,
+ * whatever host that is, and the renderer opens the event WebSocket at that
+ * host — so without this the page would try to reach the guest directly. Only the fields in URL_FIELDS are touched, so a
+ * URL that merely appears inside a message or event is left alone. Matches
+ * any origin + prefix in front of `/api/conversations`, so it does not
+ * depend on what the upstream thinks its hostname is.
+ */
+export function rewriteAgentServerUrls(value, proxyBase, field = null) {
+ if (typeof value === "string") {
+ return field !== null && URL_FIELDS.has(field)
+ ? value.replace(CONVERSATION_URL_RE, proxyBase)
+ : value;
+ }
+ if (Array.isArray(value)) {
+ return value.map((item) => rewriteAgentServerUrls(item, proxyBase, field));
+ }
+ if (value && typeof value === "object") {
+ const out = {};
+ for (const [key, item] of Object.entries(value)) {
+ out[key] = rewriteAgentServerUrls(item, proxyBase, key);
+ }
+ return out;
+ }
+ return value;
+}
+
+/** Thrown by parseSessionPath for a path that cannot be decoded. */
+class BadSessionPath extends Error {}
+
+function parseSessionPath(url) {
+ if (!url.startsWith(SESSIONS_PREFIX)) return null;
+ const rest = url.slice(SESSIONS_PREFIX.length);
+ const slash = rest.indexOf("/");
+ const queryStart = rest.search(/[?#]/);
+ const idEnd =
+ slash === -1 ? (queryStart === -1 ? rest.length : queryStart) : slash;
+ let sessionId;
+ try {
+ sessionId = decodeURIComponent(rest.slice(0, idEnd));
+ } catch {
+ // A malformed escape must be a 400, not an exception out of the
+ // request handler that takes the whole server down.
+ throw new BadSessionPath("malformed session id in path");
+ }
+ if (!sessionId) return null;
+ const tail = rest.slice(idEnd);
+ return { sessionId, path: tail.startsWith("/") ? tail : `/${tail}` };
+}
+
+/** Rewrite the request to what the session host should see. */
+function toUpstreamRequest(req, path) {
+ for (const name of CANVAS_ONLY_HEADERS) delete req.headers[name];
+ req.url = path;
+}
+
+/**
+ * @param {object} [options]
+ * @param {ReturnType<typeof createMarsTunnelBridge>} [options.bridge] Override for tests
+ * @param {Record<string, string | undefined>} [options.env]
+ * @param {string} [options.host] The server's bind host; loopback gets the Host check
+ * @param {string | null} [options.key] Session key every request must present; null = open (loopback dev only — see mountMarsWebBridge)
+ * @param {(message: string, error?: unknown) => void} [options.log]
+ */
+export function createMarsWebBridge({
+ bridge: bridgeOverride,
+ env = process.env,
+ host = DEFAULT_BIND_HOST,
+ key = null,
+ log = (message, error) => console.warn(`[mars-web] ${message}`, error ?? ""),
+} = {}) {
+ // No userDataPath: credentials stay in this process's memory.
+ const bridge =
+ bridgeOverride ?? createMarsTunnelBridge({ userDataPath: null, env });
+
+ /** Both ends of proxied WebSockets, so dispose() can close them. */
+ const sockets = new Set();
+ function track(socket) {
+ sockets.add(socket);
+ socket.once("close", () => sockets.delete(socket));
+ }
+ // Its own proxy rather than the hosting server's: agent-server calls can
+ // stay silent far longer than a static backend's timeout, the session host
+ // has no use for X-Forwarded-* from the canvas, and errors answer in the
+ // same JSON shape as the rest of /mars/*.
+ const proxy = createProxyHandlers({
+ label: "mars-web",
+ timeout: 0,
+ proxyTimeout: 0,
+ xfwd: false,
+ errorBody: (message) => ({
+ contentType: "application/json",
+ body: JSON.stringify({
+ error: { message: `upstream request failed: ${message}` },
+ }),
+ }),
+ onProxySocket: track,
+ });
+ /** Per-process cookie value handed to requests that presented the key. */
+ const cookieToken = randomBytes(32).toString("hex");
+
+ /**
+ * Whether the request may use the bridge. With no key configured every
+ * same-host request may. Otherwise it must carry the key (HTTP) or the
+ * cookie a keyed request earned (HTTP or WebSocket upgrade). Returns
+ * `"issue"` when the key was presented so the response can set the cookie.
+ */
+ function authorize(req) {
+ if (!key) return "ok";
+ const presented = req.headers[AUTH_HEADER];
+ if (typeof presented === "string" && safeEqual(presented, key)) {
+ return "issue";
+ }
+ const cookie = readCookie(req, AUTH_COOKIE);
+ if (cookie && safeEqual(cookie, cookieToken)) return "ok";
+ return "deny";
+ }
+
+ function cookieHeader() {
+ return `${AUTH_COOKIE}=${cookieToken}; HttpOnly; SameSite=Strict; Path=${MARS_WEB_PREFIX}`;
+ }
+
+ if (env.MARS_TOKEN) {
+ bridge
+ .savePat({ token: env.MARS_TOKEN, label: "MARS_TOKEN" })
+ .catch((error) => log("MARS_TOKEN was not accepted", error));
+ }
+
+ /**
+ * Methods that differ from the bridge's own, called with the request
+ * first; every other RPC_METHODS entry is `bridge[method](...args)`.
+ */
+ const overrides = {
+ getAuthState() {
+ // The web build takes personal access tokens only.
+ return { ...bridge.getAuthState(), canUseOAuth: false };
+ },
+ async openTunnel(req, params) {
+ const status = await bridge.openTunnel(params);
+ return status?.host
+ ? { ...status, host: sessionProxyBase(req, status.sessionId) }
+ : status;
+ },
+ };
+
+ async function handleRpc(req, res, method) {
+ if (req.method !== "POST") {
+ writeJson(res, 405, { error: { message: "use POST" } });
+ return;
+ }
+ if (!RPC_METHODS.has(method)) {
+ writeJson(res, 404, { error: { message: `unknown method ${method}` } });
+ return;
+ }
+ let args;
+ try {
+ const body = await readJsonBody(req, RPC_BODY_LIMIT_BYTES);
+ args = Array.isArray(body.args) ? body.args : [];
+ } catch (error) {
+ writeJson(res, 400, { error: { message: error.message } });
+ return;
+ }
+ try {
+ const result = Object.hasOwn(overrides, method)
+ ? await overrides[method](req, ...args)
+ : await bridge[method](...args);
+ writeJson(res, 200, { result: result ?? null });
+ } catch (error) {
+ const status =
+ typeof error?.status === "number" && error.status >= 400
+ ? error.status
+ : 500;
+ writeJson(res, status, {
+ error: { message: error?.message ?? String(error), status },
+ });
+ }
+ }
+
+ /**
+ * The session's tunnel listener, read from the bridge on every request so
+ * a tunnel it dropped (closeTunnel, destroySession, sign-out) is never
+ * proxied to after its port was freed.
+ */
+ function upstreamFor(sessionId) {
+ const tunnel = bridge.getTunnel(sessionId);
+ return tunnel?.status === "connected" && tunnel.localPort !== undefined
+ ? buildTunnelHost(tunnel.localPort)
+ : null;
+ }
+
+ function proxyHttp(req, res, { sessionId, path }) {
+ const target = upstreamFor(sessionId);
+ if (!target) {
+ writeJson(res, 409, {
+ error: { message: `session ${sessionId} is not connected` },
+ });
+ return;
+ }
+ const proxyBase = sessionProxyBase(req, sessionId);
+ toUpstreamRequest(req, path);
+ proxy.proxyHttp(req, res, target, {
+ // Responses are read as UTF-8 for the URL rewrite; a compressed body
+ // would have to be inflated first.
+ headers: { "accept-encoding": "identity" },
+ onResponse: rewriteJsonResponse(
+ (body) => rewriteAgentServerUrls(body, proxyBase),
+ { limit: JSON_REWRITE_LIMIT_BYTES },
+ ),
+ });
+ }
+
+ function proxyWebSocket(req, socket, head, { sessionId, path }) {
+ const target = upstreamFor(sessionId);
+ if (!target) {
+ socket.end("HTTP/1.1 409 Conflict\r\n\r\n");
+ return;
+ }
+ toUpstreamRequest(req, path);
+ track(socket);
+ proxy.proxyWebSocket(req, socket, head, target);
+ }
+
+ return {
+ /** The bridge in use, for the caller's own dispose() or tests. */
+ bridge,
+
+ /** @returns {boolean} true when the request was a MARS request and handled */
+ handleHttp(req, res) {
+ const url = req.url ?? "/";
+ if (!url.startsWith(`${MARS_WEB_PREFIX}/`)) return false;
+ if (isCrossOrigin(req) || isForeignHost(req, host)) {
+ writeJson(res, 403, {
+ error: { message: "cross-origin request refused" },
+ });
+ return true;
+ }
+ const pathOnly = url.split(/[?#]/)[0];
+ if (pathOnly === HEALTH_PATH) {
+ // Unauthenticated on purpose: it only says the bridge is here.
+ writeJson(res, 200, { ok: true, authRequired: key !== null });
+ return true;
+ }
+ const auth = authorize(req);
+ if (auth === "deny") {
+ writeJson(res, 401, { error: { message: "session key required" } });
+ return true;
+ }
+ if (auth === "issue") res.setHeader("Set-Cookie", cookieHeader());
+ if (pathOnly.startsWith(RPC_PREFIX)) {
+ void handleRpc(req, res, pathOnly.slice(RPC_PREFIX.length));
+ return true;
+ }
+ let session;
+ try {
+ session = parseSessionPath(url);
+ } catch (error) {
+ if (!(error instanceof BadSessionPath)) throw error;
+ writeJson(res, 400, { error: { message: error.message } });
+ return true;
+ }
+ if (session) {
+ proxyHttp(req, res, session);
+ return true;
+ }
+ writeJson(res, 404, { error: { message: "not found" } });
+ return true;
+ },
+
+ /** @returns {boolean} true when the upgrade was a MARS request and handled */
+ handleUpgrade(req, socket, head) {
+ const url = req.url ?? "/";
+ if (!url.startsWith(`${MARS_WEB_PREFIX}/`)) return false;
+ if (isCrossOrigin(req) || isForeignHost(req, host)) {
+ socket.end("HTTP/1.1 403 Forbidden\r\n\r\n");
+ return true;
+ }
+ if (authorize(req) === "deny") {
+ socket.end("HTTP/1.1 401 Unauthorized\r\n\r\n");
+ return true;
+ }
+ let session;
+ try {
+ session = parseSessionPath(url);
+ } catch (error) {
+ if (!(error instanceof BadSessionPath)) throw error;
+ socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
+ return true;
+ }
+ if (!session) {
+ socket.end("HTTP/1.1 404 Not Found\r\n\r\n");
+ return true;
+ }
+ proxyWebSocket(req, socket, head, session);
+ return true;
+ },
+
+ async dispose() {
+ for (const socket of sockets) socket.destroy();
+ sockets.clear();
+ await bridge.dispose();
+ },
+ };
+}
diff --git a/scripts/proxy-utils.mjs b/scripts/proxy-utils.mjs
index 4d81dd870f..8c6a145b06 100644
--- a/scripts/proxy-utils.mjs
+++ b/scripts/proxy-utils.mjs
@@ -45,7 +45,8 @@ function parseBackendUrl(backendUrl) {
}
return {
hostname: url.hostname,
- port: Number.parseInt(url.port, 10) || (url.protocol === "https:" ? 443 : 80),
+ port:
+ Number.parseInt(url.port, 10) || (url.protocol === "https:" ? 443 : 80),
protocol: url.protocol,
};
}
@@ -184,6 +185,66 @@ export function proxyServerInfoRequest(
req.pipe(proxyReq, { end: true });
}
+/**
+ * An `onResponse` for createProxyHandlers' proxyHttp that rewrites a JSON
+ * body through `transform` — buffered, re-serialized, and sent with a fixed
+ * Content-Length, as proxyServerInfoRequest does. Any other response, an
+ * encoded one, and a JSON body past `limit` bytes stream through untouched
+ * (what was buffered first, then the rest), never truncated into broken
+ * JSON.
+ *
+ * @param {(body: unknown) => unknown} transform
+ * @param {{ limit: number }} options
+ */
+export function rewriteJsonResponse(transform, { limit }) {
+ return (proxyRes, req, res) => {
+ const status = proxyRes.statusCode ?? 502;
+ const headers = { ...proxyRes.headers };
+ const encoding = headers["content-encoding"];
+ const isJson = /\bapplication\/json\b/i.test(headers["content-type"] ?? "");
+ if (
+ !isJson ||
+ req.method === "HEAD" ||
+ (encoding && encoding !== "identity")
+ ) {
+ res.writeHead(status, headers);
+ proxyRes.pipe(res);
+ return;
+ }
+ const chunks = [];
+ let size = 0;
+ let streaming = false;
+ proxyRes.on("data", (chunk) => {
+ if (streaming) return;
+ size += chunk.length;
+ if (size <= limit) {
+ chunks.push(chunk);
+ return;
+ }
+ streaming = true;
+ res.writeHead(status, headers);
+ for (const buffered of chunks.splice(0)) res.write(buffered);
+ res.write(chunk);
+ proxyRes.pipe(res);
+ });
+ proxyRes.on("end", () => {
+ if (streaming) return;
+ let body = Buffer.concat(chunks);
+ try {
+ body = Buffer.from(
+ JSON.stringify(transform(JSON.parse(body.toString("utf8")))),
+ );
+ } catch {
+ // Not JSON after all; pass it through as received.
+ }
+ delete headers["transfer-encoding"];
+ headers["content-length"] = String(body.length);
+ res.writeHead(status, headers);
+ res.end(body);
+ });
+ };
+}
+
function once(fn) {
let called = false;
return (...args) => {
@@ -193,28 +254,51 @@ function once(fn) {
};
}
-function writeProxyError(res, message) {
+function textErrorBody(message) {
+ return {
+ contentType: "text/plain; charset=utf-8",
+ body: `Bad Gateway: ${message}`,
+ };
+}
+
+function writeProxyError(res, message, errorBody) {
if (res.destroyed) return;
if (!res.headersSent) {
- res.writeHead(502, { "Content-Type": "text/plain; charset=utf-8" });
- res.end(`Bad Gateway: ${message}`);
+ const { contentType, body } = errorBody(message);
+ res.writeHead(502, { "Content-Type": contentType });
+ res.end(body);
return;
}
res.destroy();
}
+/**
+ * @param {object} [options]
+ * @param {string} [options.label] Prefix for log lines and metrics
+ * @param {number} [options.timeout] Client socket idle timeout in ms; 0 = none
+ * @param {number} [options.proxyTimeout] Upstream response timeout in ms; 0 = none
+ * @param {boolean} [options.xfwd] Add X-Forwarded-* headers upstream
+ * @param {(message: string) => { contentType: string, body: string }} [options.errorBody]
+ * The 502 written when the upstream fails before a response started
+ * @param {(proxySocket: import("node:net").Socket) => void} [options.onProxySocket]
+ * Called with each upstream socket of an established WebSocket proxy
+ */
export function createProxyHandlers({
label = "proxy",
timeout = DEFAULT_PROXY_TIMEOUT_MS,
proxyTimeout = DEFAULT_PROXY_TIMEOUT_MS,
+ xfwd = true,
+ errorBody = textErrorBody,
+ onProxySocket,
} = {}) {
const proxy = createProxyServer({
ws: true,
changeOrigin: true,
- xfwd: true,
+ xfwd,
timeout,
proxyTimeout,
});
+ if (onProxySocket) proxy.on("proxySocket", onProxySocket);
const metrics = {
activeHttpRequests: 0,
activeWebSockets: 0,
@@ -223,6 +307,12 @@ export function createProxyHandlers({
totalErrors: 0,
};
+ /** Per-request `onResponse` handlers; see proxyHttp. */
+ const responseHandlers = new WeakMap();
+ proxy.on("proxyRes", (proxyRes, req, res) => {
+ responseHandlers.get(req)?.(proxyRes, req, res);
+ });
+
proxy.on("error", (err, _req, resOrSocket, target) => {
metrics.totalErrors += 1;
const targetText = target ? ` -> ${target}` : "";
@@ -230,13 +320,23 @@ export function createProxyHandlers({
console.error(`[${label}] Proxy error${targetText}: ${err.message}`);
}
if (resOrSocket && typeof resOrSocket.writeHead === "function") {
- writeProxyError(resOrSocket, err.message);
+ writeProxyError(resOrSocket, err.message, errorBody);
} else if (resOrSocket && typeof resOrSocket.destroy === "function") {
resOrSocket.destroy();
}
});
- function proxyHttp(req, res, target) {
+ /**
+ * @param {import("node:http").IncomingMessage} req
+ * @param {import("node:http").ServerResponse} res
+ * @param {string} target
+ * @param {object} [options]
+ * @param {Record<string, string>} [options.headers] Set on the upstream request
+ * @param {(proxyRes: import("node:http").IncomingMessage, req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => void} [options.onResponse]
+ * Writes the response itself instead of it being piped through (e.g.
+ * rewriteJsonResponse).
+ */
+ function proxyHttp(req, res, target, { headers, onResponse } = {}) {
metrics.activeHttpRequests += 1;
metrics.totalHttpRequests += 1;
const finish = once(() => {
@@ -254,12 +354,21 @@ export function createProxyHandlers({
err,
);
}
- writeProxyError(res, err instanceof Error ? err.message : String(err));
+ writeProxyError(
+ res,
+ err instanceof Error ? err.message : String(err),
+ errorBody,
+ );
finish();
};
+ const options = { target, headers };
+ if (onResponse) {
+ responseHandlers.set(req, onResponse);
+ options.selfHandleResponse = true;
+ }
try {
- proxy.web(req, res, { target }).catch(handleProxyError);
+ proxy.web(req, res, options).catch(handleProxyError);
} catch (err) {
handleProxyError(err);
}
diff --git a/scripts/static-server.mjs b/scripts/static-server.mjs
index 289047c790..3cb21ab929 100644
--- a/scripts/static-server.mjs
+++ b/scripts/static-server.mjs
@@ -35,6 +35,7 @@ import { pathToFileURL } from "node:url";
import sirv from "sirv";
import { applySessionKeyPolicy, DEFAULT_BIND_HOST } from "./bind-host.mjs";
+import { mountMarsWebBridge } from "./mars-web-bridge.mjs";
import {
createProxyHandlers,
createRouter,
@@ -679,9 +680,18 @@ export function startStaticServer(config) {
const staticMiddleware = createStaticMiddleware(dirAbs);
const uninstallDiagnostics = proxy.installDiagnostics();
+ // DigitalOcean Managed Agents for the browser: with MARS_WEB=1 this server
+ // hosts the MARS bridge and proxies to sessions' tunnel listeners, behind
+ // the session key (see mars-web-bridge.mjs). The key is the one this server
+ // already injects; a LAN bind with no key refuses to mount.
+ const marsWeb = mountMarsWebBridge({
+ host: config.host,
+ sessionApiKey: policy.sessionApiKey,
+ });
const server = createServer((req, res) => {
const url = req.url ?? "/";
+ if (marsWeb?.handleHttp(req, res)) return;
const backend = route(url);
if (backend) {
// The editor is advertised as `<origin><prefix>/?tkn=<token>`, and that
@@ -720,6 +730,7 @@ export function startStaticServer(config) {
});
server.on("upgrade", (req, socket, head) => {
+ if (marsWeb?.handleUpgrade(req, socket, head)) return;
const backend = route(req.url ?? "/");
if (backend) {
proxy.proxyWebSocket(req, socket, head, backend);
@@ -728,6 +739,9 @@ export function startStaticServer(config) {
socket.destroy();
});
server.on("close", uninstallDiagnostics);
+ server.on("close", () => {
+ void marsWeb?.dispose().catch(() => {});
+ });
return new Promise((resolveListen) => {
server.listen(config.port, config.host, () => {
diff --git a/scripts/tunnel-client.mjs b/scripts/tunnel-client.mjs
new file mode 100644
index 0000000000..f1056bc31a
--- /dev/null
+++ b/scripts/tunnel-client.mjs
@@ -0,0 +1,274 @@
+/**
+ * MARS port-forward tunnel client (MARSOHS-1427).
+ *
+ * Runs directly inside Canvas's Electron main process and plays the same
+ * role `doctl agents port-forward` plays at the terminal today: given a
+ * session id and a remote port inside that session's sandbox, it dials
+ * MARS's port-forward WebSocket tunnel and exposes the result as an
+ * ordinary local TCP listener that pipes bytes bidirectionally. Anything
+ * that connects to that local port gets a plain, single-hop connection to
+ * whatever is listening on the guest port.
+ *
+ * v1 implementation: plain JS, no subprocess. Node's `net` module provides
+ * the local TCP listener (the same tool `doctl`'s Go implementation and an
+ * earlier Python port both used their own language's equivalent of); the
+ * `ws` package provides the WebSocket client. Node's *built-in* `WebSocket`
+ * global is not usable here — it deliberately mirrors the browser spec,
+ * which does not allow attaching custom headers to a WebSocket handshake,
+ * and this tunnel needs to attach `Authorization: Bearer <token>`. `ws`
+ * isn't spec-constrained that way and supports it directly.
+ *
+ * This replaced an earlier prototype that ran the same logic as a spawned
+ * Python subprocess (`uv run tools/mars_tunnel.py`). That version worked,
+ * but running the tunnel logic in-process here removes an entire layer
+ * that existed only to bridge two different languages: no subprocess to
+ * spawn and supervise, no hand-rolled stdout readiness protocol, no
+ * dependency on `uv` resolving a package at startup. See git history for
+ * the Python version if it's ever useful for comparison.
+ *
+ * Multi-session note: this module starts one local listener per call, for
+ * one (session, remote port) pair. Building a `session_id -> tunnel`
+ * registry on top of this (port allocation, reuse, targeted teardown,
+ * reconnect detection) is a separate, follow-on ticket — out of scope here.
+ */
+
+import { createServer } from "node:net";
+import WebSocket from "ws";
+
+import {
+ DEFAULT_MARS_API_BASE_URL,
+ SESSIONS_PATH,
+ buildMarsUrl,
+} from "./mars-api.mjs";
+
+const REJECTION_BODY_MAX = 300;
+
+/**
+ * Keep an idle upstream socket warm so intermediaries between here and
+ * harness-api do not reap it.
+ */
+export const TUNNEL_PING_INTERVAL_MS = 30_000;
+
+/**
+ * Application close codes harness-api uses on the port-forward socket.
+ * 4001 is terminal (the session is gone or the caller may not reach it);
+ * 4002 means the sandbox woke but nothing accepted the connection on the
+ * guest port; 4011 is a transient upstream failure.
+ */
+export const TUNNEL_CLOSE_SESSION_UNAVAILABLE = 4001;
+export const TUNNEL_CLOSE_GUEST_DIAL_FAILED = 4002;
+export const TUNNEL_CLOSE_UPSTREAM_ERROR = 4011;
+
+const RECORDED_CLOSE_CODES = new Set([
+ TUNNEL_CLOSE_SESSION_UNAVAILABLE,
+ TUNNEL_CLOSE_GUEST_DIAL_FAILED,
+ TUNNEL_CLOSE_UPSTREAM_ERROR,
+]);
+
+function buildTunnelWsUrl(apiUrl, sessionId, remotePort) {
+ const url = new URL(
+ buildMarsUrl(
+ apiUrl,
+ `${SESSIONS_PATH}/${sessionId}/port-forward/${remotePort}`,
+ ),
+ );
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
+ throw new Error(`Unsupported API URL scheme: ${url.protocol}`);
+ }
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
+ return url.toString();
+}
+
+/**
+ * Dial the MARS port-forward tunnel for one session/port pair and resolve
+ * once the local listener is bound and accepting connections.
+ *
+ * @param {object} options
+ * @param {string} options.sessionId MARS session id
+ * @param {number} options.remotePort Port inside the guest sandbox
+ * @param {string} [options.accessToken] Bearer token for the tunnel
+ * @param {() => string | null} [options.getAccessToken] Read on every local
+ * connection instead of `accessToken`, so a rotated or revoked credential
+ * takes effect on the next dial. Returning null refuses the connection.
+ * @param {string} [options.apiUrl] harness-api base URL (http(s)://...); translated to ws(s)://
+ * @param {number} [options.localPort] Local port to listen on (0 lets the OS pick one)
+ * @param {string} [options.address] Local bind address
+ * @param {(message: string) => void} [options.log]
+ * @param {number} [options.pingIntervalMs] Keepalive ping period for each upstream socket
+ * @param {typeof WebSocket} [options.WebSocketImpl] Override for tests
+ * @returns {Promise<{sessionId: string, remotePort: number, localPort: number, getLastUpstreamFailure: () => UpstreamFailure | null, stop: () => void}>}
+ */
+export async function startPortForwardTunnel({
+ sessionId,
+ remotePort,
+ accessToken,
+ getAccessToken,
+ apiUrl = DEFAULT_MARS_API_BASE_URL,
+ localPort = 0,
+ address = "127.0.0.1",
+ log = (message) => console.error(`[mars-tunnel] ${message}`),
+ pingIntervalMs = TUNNEL_PING_INTERVAL_MS,
+ WebSocketImpl = WebSocket,
+} = {}) {
+ if (!sessionId) {
+ throw new Error("sessionId is required");
+ }
+ if (!Number.isInteger(remotePort) || remotePort <= 0 || remotePort > 65535) {
+ throw new Error(`Invalid remote port: ${remotePort}`);
+ }
+ if (!accessToken && typeof getAccessToken !== "function") {
+ throw new Error("accessToken is required");
+ }
+ const readToken = getAccessToken ?? (() => accessToken);
+
+ const wsUrl = buildTunnelWsUrl(apiUrl, sessionId, remotePort);
+ const activeSockets = new Set();
+ /**
+ * Each local connection is its own upstream dial, so a failure never
+ * reaches whoever is reading the local socket — they only see it close.
+ * Keeping the most recent one lets callers explain why.
+ *
+ * @typedef {{ closeCode: number | null, httpStatus: number | null, message: string }} UpstreamFailure
+ * @type {UpstreamFailure | null}
+ */
+ let lastUpstreamFailure = null;
+
+ function bridgeConnection(localSocket) {
+ activeSockets.add(localSocket);
+ localSocket.once("close", () => activeSockets.delete(localSocket));
+
+ const token = readToken();
+ if (!token) {
+ lastUpstreamFailure = {
+ closeCode: null,
+ httpStatus: 401,
+ message: "Not signed in to DigitalOcean.",
+ };
+ localSocket.end();
+ return;
+ }
+
+ const ws = new WebSocketImpl(wsUrl, {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+ let rejected = false;
+
+ // Fires when the server answers the handshake with a non-101 status
+ // (e.g. a rejected/invalid token) — doctl's equivalent is
+ // serverRejection() reading the same kind of response.
+ ws.on("unexpected-response", (_req, res) => {
+ rejected = true;
+ let body = "";
+ res.on("data", (chunk) => {
+ body += chunk.toString();
+ });
+ res.on("end", () => {
+ const message = body.trim().slice(0, REJECTION_BODY_MAX);
+ lastUpstreamFailure = {
+ closeCode: null,
+ httpStatus: res.statusCode ?? null,
+ message,
+ };
+ log(
+ `server rejected tunnel (${res.statusCode} ${res.statusMessage}): ${message}`,
+ );
+ localSocket.end();
+ });
+ });
+
+ // Flow control: one in-flight chunk at a time per direction (pause the
+ // source until the sink reports it drained), so a fast producer and a
+ // slow consumer on either side can't make this process buffer an
+ // unbounded amount of the stream in memory.
+ let keepalive = null;
+ ws.on("open", () => {
+ lastUpstreamFailure = null;
+ keepalive = setInterval(() => {
+ if (ws.readyState === WebSocketImpl.OPEN) ws.ping();
+ }, pingIntervalMs);
+ localSocket.on("data", (chunk) => {
+ localSocket.pause();
+ ws.send(chunk, (err) => {
+ if (err) {
+ log(`local->ws send failed: ${err.message}`);
+ return;
+ }
+ localSocket.resume();
+ });
+ });
+
+ ws.on("message", (data) => {
+ if (!localSocket.write(data)) {
+ ws.pause();
+ localSocket.once("drain", () => ws.resume());
+ }
+ });
+ });
+
+ ws.on("close", (code, reason) => {
+ clearInterval(keepalive);
+ if (RECORDED_CLOSE_CODES.has(code)) {
+ lastUpstreamFailure = {
+ closeCode: code,
+ httpStatus: null,
+ message: reason?.toString() ?? "",
+ };
+ }
+ localSocket.end();
+ });
+ ws.on("error", (err) => {
+ // 'unexpected-response' already logged the rejection and its message;
+ // 'ws' also emits a generic error for the same failure, which would
+ // otherwise be a duplicate, less useful log line.
+ if (!rejected) {
+ log(`tunnel dial failed: ${err.message}`);
+ }
+ });
+
+ localSocket.on("close", () => {
+ if (
+ ws.readyState === WebSocketImpl.OPEN ||
+ ws.readyState === WebSocketImpl.CONNECTING
+ ) {
+ ws.close();
+ }
+ });
+ localSocket.on("error", () => ws.close());
+ }
+
+ // allowHalfOpen: true — without it, Node auto-closes this socket's writable
+ // side the instant the local client's FIN arrives, silently dropping any
+ // response still in flight from the tunnel (e.g. a client that writes a
+ // request and immediately half-closes while awaiting a reply). Closing is
+ // instead driven explicitly by the ws "close" handler below.
+ const server = createServer({ allowHalfOpen: true }, bridgeConnection);
+
+ return new Promise((resolve, reject) => {
+ function onListenError(err) {
+ reject(err);
+ }
+ server.once("error", onListenError);
+ server.listen(localPort, address, () => {
+ server.off("error", onListenError);
+ // Post-startup errors (e.g. a client resetting a connection mid-accept)
+ // still need a handler or Node treats them as uncaught.
+ server.on("error", (err) => log(`listener error: ${err.message}`));
+ const boundPort = server.address().port;
+ log(
+ `forwarding ${address}:${boundPort} -> port ${remotePort} in session ${sessionId}`,
+ );
+ resolve({
+ sessionId,
+ remotePort,
+ localPort: boundPort,
+ getLastUpstreamFailure: () => lastUpstreamFailure,
+ stop() {
+ for (const socket of activeSockets) {
+ socket.destroy();
+ }
+ server.close();
+ },
+ });
+ });
+ });
+}
diff --git a/scripts/tunnel-registry.mjs b/scripts/tunnel-registry.mjs
new file mode 100644
index 0000000000..15f67666d0
--- /dev/null
+++ b/scripts/tunnel-registry.mjs
@@ -0,0 +1,226 @@
+/**
+ * Session-to-port tunnel registry (MARSOHS-1428).
+ *
+ * Tracks one MARS port-forward tunnel per attached session, since a user can
+ * attach more than one MARS session as a backend at the same time (see
+ * openhands-canvas-dataplane-design.md's "Session-to-port tracking"). Builds
+ * directly on scripts/tunnel-client.mjs's startPortForwardTunnel() — this
+ * module owns the session_id -> tunnel map, not the tunnel mechanics
+ * themselves.
+ *
+ * Responsibilities (design doc scope for this ticket):
+ * - Port allocation with no collisions across concurrently attached
+ * sessions — free by construction: startPortForwardTunnel()'s default
+ * `localPort: 0` asks the OS for a free port, and the OS never hands out
+ * the same port to two independent listeners. No manual bookkeeping
+ * needed here beyond recording which port each session ended up with.
+ * - Reuse: calling attach() again for a session that already has a live
+ * tunnel returns that tunnel instead of opening a duplicate — after
+ * waking the session again, since it may have idle-paused (or been
+ * paused by hand) since the tunnel opened.
+ * - Targeted teardown: detach() stops one session's tunnel without
+ * touching any other session's.
+ * - Concurrent-attach dedup: two attach() calls for the same session
+ * firing before either has resolved share one in-flight attempt rather
+ * than racing to open two tunnels.
+ * - Waking a paused session before dialing it, via the injected
+ * ensureAwake (mars-session.mjs's ensureSessionAwake()) — MARS
+ * auto-pauses idle sessions, and a tunnel that isn't open yet has
+ * generated no activity to have prevented that.
+ *
+ * Explicitly NOT this module's job:
+ * - Reconnect-after-app-restart detection. Because tunnels here run
+ * in-process (see tunnel-client.mjs's header comment for why), an app
+ * restart unconditionally kills every tunnel — there is no "is the old
+ * one still alive?" check to perform, unlike a design where tunnels ran
+ * as independent subprocesses that could outlive a restart. This
+ * registry always starts empty on a fresh process. What DOES persist
+ * across restarts is the `Backend` record in Canvas's UI-facing
+ * backend-registry (a separate system) — comparing "what's persisted"
+ * against "what's actually attached right now" and deciding whether to
+ * re-attach (optionally passing the previous `localPort` back into
+ * attach() to reuse it) or surface as disconnected is Ticket 3's job
+ * (MARSOHS-1429), which owns that comparison. This registry only
+ * provides the primitive that makes it possible: attach() accepts an
+ * optional `localPort` to re-request a specific port, falling back to
+ * an OS-picked one when something else has taken it in the meantime.
+ * - Wiring into Electron's app lifecycle (app quit, session pause/end).
+ * That's also Ticket 3 — this module is a standalone, directly testable
+ * piece, following the same shape as Ticket 1.
+ */
+
+import { startPortForwardTunnel } from "./tunnel-client.mjs";
+
+/**
+ * @typedef {{
+ * sessionId: string,
+ * status: "connecting" | "connected" | "error",
+ * remotePort: number,
+ * localPort: number | undefined,
+ * error: string | undefined,
+ * upstreamFailure: { closeCode: number | null, httpStatus: number | null, message: string } | null,
+ * }} TunnelEntrySnapshot
+ */
+
+/**
+ * @param {object} options
+ * @param {typeof startPortForwardTunnel} [options.startTunnel] Override for tests
+ * @param {(options: { sessionId: string, apiUrl?: string, getAccessToken: () => string | null }) => Promise<unknown>} options.ensureAwake
+ * Resolves once the session is READY (mars-session.mjs's
+ * ensureSessionAwake over a client authenticated with the tunnel's own
+ * token, in the bridge).
+ */
+export function createTunnelRegistry({
+ startTunnel = startPortForwardTunnel,
+ ensureAwake,
+}) {
+ if (typeof ensureAwake !== "function") {
+ throw new Error("ensureAwake is required");
+ }
+ /** @type {Map<string, { status: "connecting" | "connected" | "error", remotePort: number, apiUrl: string | undefined, getAccessToken: () => string | null, owner: string | undefined, tunnel: object | null, error: Error | null, promise: Promise<void> | null }>} */
+ const entries = new Map();
+
+ function snapshot(sessionId) {
+ const entry = entries.get(sessionId);
+ if (!entry) return undefined;
+ return {
+ sessionId,
+ status: entry.status,
+ remotePort: entry.remotePort,
+ localPort: entry.tunnel?.localPort,
+ error: entry.error?.message,
+ upstreamFailure: entry.tunnel?.getLastUpstreamFailure?.() ?? null,
+ };
+ }
+
+ /**
+ * A restored Backend asks for the port it had before the restart, which
+ * another process may have bound since.
+ */
+ async function startOnPreferredPort(options) {
+ try {
+ return await startTunnel(options);
+ } catch (error) {
+ if (!options.localPort || error?.code !== "EADDRINUSE") throw error;
+ return startTunnel({ ...options, localPort: 0 });
+ }
+ }
+
+ /**
+ * Attach (or reuse) the tunnel for one session. Resolves once the tunnel
+ * is up, or rejects if dialing it failed — either way, the outcome is
+ * also queryable afterward via get(sessionId).
+ *
+ * @param {object} options
+ * @param {string} options.sessionId
+ * @param {number} options.remotePort
+ * @param {() => string | null} options.getAccessToken Read on every dial,
+ * so a tunnel keeps using whichever credential it was opened with and
+ * stops working once that credential is gone.
+ * @param {string} [options.apiUrl]
+ * @param {number} [options.localPort] Reuse a specific local port (e.g. the
+ * one a previously persisted Backend recorded) instead of letting the OS
+ * pick a new one.
+ * @param {string} [options.owner] Opaque tag for detachOwnedBy(), e.g. the
+ * credential the tunnel dials with.
+ * @returns {Promise<TunnelEntrySnapshot>}
+ */
+ async function attach(options) {
+ const { sessionId, remotePort, getAccessToken, apiUrl, localPort, owner } =
+ options;
+ if (!sessionId) {
+ throw new Error("sessionId is required");
+ }
+
+ const existing = entries.get(sessionId);
+ if (existing) {
+ if (existing.status === "connected") {
+ await ensureAwake({
+ sessionId,
+ apiUrl: existing.apiUrl,
+ getAccessToken: existing.getAccessToken,
+ });
+ return snapshot(sessionId);
+ }
+ if (existing.status === "connecting") {
+ // Piggyback on the in-flight attempt rather than racing it — once it
+ // settles (either way), re-run attach() to either reuse the tunnel
+ // it produced or retry after its failure.
+ await existing.promise.catch(() => {});
+ return attach(options);
+ }
+ // status === "error": fall through and retry below.
+ }
+
+ const entry = {
+ status: "connecting",
+ remotePort,
+ apiUrl,
+ getAccessToken,
+ owner,
+ tunnel: null,
+ error: null,
+ promise: null,
+ };
+ entries.set(sessionId, entry);
+
+ entry.promise = (async () => {
+ // MARS auto-pauses idle sessions, and a tunnel that isn't open yet
+ // can't have generated any activity to prevent that — so a session
+ // being attached to for the first time in a while may need waking
+ // before dialing it can succeed at all.
+ await ensureAwake({ sessionId, apiUrl, getAccessToken });
+ const tunnel = await startOnPreferredPort({
+ sessionId,
+ remotePort,
+ getAccessToken,
+ apiUrl,
+ localPort,
+ });
+ entry.tunnel = tunnel;
+ entry.status = "connected";
+ })().catch((err) => {
+ entry.error = err;
+ entry.status = "error";
+ throw err;
+ });
+
+ await entry.promise;
+ return snapshot(sessionId);
+ }
+
+ /** @returns {TunnelEntrySnapshot | undefined} */
+ function get(sessionId) {
+ return snapshot(sessionId);
+ }
+
+ /** Tear down one session's tunnel, if any, without affecting others. */
+ async function detach(sessionId) {
+ const entry = entries.get(sessionId);
+ if (!entry) return;
+ entries.delete(sessionId);
+ // Let an in-flight attach() settle first so its tunnel (if it succeeds)
+ // doesn't get created after we've already "detached" and get orphaned.
+ if (entry.status === "connecting") {
+ await entry.promise.catch(() => {});
+ }
+ entry.tunnel?.stop();
+ }
+
+ async function detachAll() {
+ await Promise.all(
+ [...entries.keys()].map((sessionId) => detach(sessionId)),
+ );
+ }
+
+ /** Tear down every tunnel attached with the given `owner`. */
+ async function detachOwnedBy(owner) {
+ await Promise.all(
+ [...entries]
+ .filter(([, entry]) => entry.owner === owner)
+ .map(([sessionId]) => detach(sessionId)),
+ );
+ }
+
+ return { attach, get, detach, detachAll, detachOwnedBy };
+}
diff --git a/src/api/agent-server-compatibility.ts b/src/api/agent-server-compatibility.ts
index 0ee3dab2b5..8222a3660b 100644
--- a/src/api/agent-server-compatibility.ts
+++ b/src/api/agent-server-compatibility.ts
@@ -340,6 +340,19 @@ export async function validateLocalBackend(
}
}
+/**
+ * Whether a {@link validateLocalBackend} failure is a decided answer from the
+ * server (rejected key, too-old version) rather than a transient miss, so
+ * probing again cannot change the outcome.
+ */
+export function isDefinitiveLocalBackendError(error: unknown): boolean {
+ return (
+ (error instanceof Error &&
+ error.message === INVALID_BACKEND_API_KEY_ERROR) ||
+ isAgentServerUnsupportedVersionError(error)
+ );
+}
+
export async function loadAgentServerInfo() {
// The probe is a *local* agent-server concern — it verifies the runtime
// hosting the GUI is reachable. It must NEVER run against the active
diff --git a/src/api/backend-registry/types.ts b/src/api/backend-registry/types.ts
index 33e0bbac9c..07008eab9b 100644
--- a/src/api/backend-registry/types.ts
+++ b/src/api/backend-registry/types.ts
@@ -10,6 +10,15 @@ export interface Backend {
authMode?: BackendAuthMode;
/** Changes whenever connection credentials change, invalidating keyed data. */
connectionRevision?: number;
+ /**
+ * Set when `host` reaches a DigitalOcean MARS session — the loopback end
+ * of a port-forward tunnel (or the web server's proxy for it). The far end is an
+ * ordinary agent-server, so the backend stays `kind: "local"`; this only
+ * lets the Managed Agents screen and connection lifecycle recognise it.
+ */
+ marsSessionId?: string;
+ /** The MARS agent config the session was launched from, when known. */
+ marsConfigId?: string;
}
export interface BackendSelection {
diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.ts
index a90f3cf9c1..17b0dabcc2 100644
--- a/src/api/conversation-service/agent-server-conversation-service.api.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts
@@ -853,7 +853,7 @@ class AgentServerConversationService {
return batchGetCloudConversations(ids);
}
- const data = await new ConversationClient(
+ const data: unknown = await new ConversationClient(
getAgentServerClientOptions(),
).getConversations<DirectConversationInfo>(ids);
diff --git a/src/api/mars/AGENTS.md b/src/api/mars/AGENTS.md
new file mode 100644
index 0000000000..65f16165b8
--- /dev/null
+++ b/src/api/mars/AGENTS.md
@@ -0,0 +1,18 @@
+# DigitalOcean Managed Agents (MARS)
+
+Available in the Electron desktop app, and in the web build when its server runs with `MARS_WEB=1`. A DigitalOcean *agent* is an immutable Agent Config (DigitalOcean's console calls it an environment); a *session* is a microVM launched from one, running an OpenHands agent-server with its own disk and conversations.
+
+- **Surfaces**: the "Choose how you want to connect" chooser (`AddBackendChooser` in `backend-form-modal.tsx`) gains a third **DigitalOcean** tab, `DigitalOceanConnectPanel`: sign in (OAuth or token), then pick an OpenHands agent — opening it resumes the agent's latest live session or launches its first, and closes the modal. Each agent row expands to list its sessions as children (any connectable one opens directly), and **New Agent** (`DigitalOceanNewAgentForm`) creates an OpenHands Agent Config and launches its first session. While a MARS backend is active, `MarsSessionPanel` (`src/components/features/sidebar/mars-session-panel.tsx`) replaces the sidebar conversation list: the agent's sessions read like thread folders (the current one expands to its conversations, others open with a click), the header "+" launches a new session, and the agent menu switches agent or opens `ManageBackendsModal initialView="managed-agents"` — the full management view in `src/components/features/backends/managed-agents/`. Everything is gated on `getMarsBridge()`: Electron's preload provides it, and the web build gets a fetch-backed one from the Agent Canvas server when that server hosts the MARS web bridge (below); a page with neither never shows it.
+- **OpenHands only**: agent configs are shown only when their manifest's `agent` is `openhands` (flat `agent:` or `spec.agent`). The list endpoint omits manifests, so `listAgentConfigs` in `scripts/mars-tunnel-bridge.mjs` fetches each config once (configs are immutable) and adds `agent`. The match is strict: a manifest without `agent: openhands` (older specs that no longer launch) or one that could not be read (`agent: null`, retried on the next list) is hidden. Sessions are shown only when their `config_id` names a matching config; `agent_kind` is not used, since OpenHands sessions report `AGENT_KIND_UNSPECIFIED`.
+- **New Agent**: `createOpenHandsAgent({name, size?})` in `scripts/mars-tunnel-bridge.mjs` posts `POST /v2/agents/configs` `{name, manifest_yaml}` with the manifest from `buildOpenHandsManifest()` (`scripts/mars-api.mjs`): flat `agent: openhands` + `template: openhands` + `keep_warm: false`, plus `size:` when one is chosen. No LLM key goes into the manifest; the LLM is set up in the session's agent-server (Settings → LLM) after connecting. The manifest is built in the main process, not accepted over IPC, so the renderer can only create OpenHands agents (same reasoning as pinning the guest port). Keep `template` explicit — harness-api has no agent kind that derives an OpenHands template. Names follow harness-api's rule (`isValidAgentName`: 1–64 of `[A-Za-z0-9._-]`, alphanumeric at both ends).
+- **Sandbox size**: the New Agent form's "Sandbox size" picker lists `GET /v2/agents/sessions/sandbox/sizes` (`listSandboxSizes`, `useMarsSandboxSizes`; static, so `staleTime: Infinity`) and defaults to DigitalOcean's choice. The chosen slug goes into the manifest as a top-level `size:` line (slug-validated in `buildOpenHandsManifest`), because sessions created from a config cannot carry a size; it therefore applies to every session of that agent. A failed or pending catalog leaves only the default and never blocks create.
+- **Shared hooks**: `useLaunchMarsSession()` (open / launch / create agent / "open agent", with create-vs-connect error copy) and `useMarsSignIn()` (sign-in, switch connection, sign-out) back the chooser tab, the Managed Agents view and the sidebar; reuse them instead of calling `createSession` + connect directly.
+- **Port-forward tunnel**: `openTunnel` opens the port-forward tunnel and, on desktop, returns `{transport: "tunnel", host: http://127.0.0.1:<port>}`; the renderer registers that host as an ordinary local backend. The public ingress URL path (direct connection to `GET /v2/agents/sessions/{id}/ingress`) was built and tested here and then removed from this branch on 2026-10-08 — REST worked over it but its WebSocket is reset inside the platform (microVM LB → activator, fix in microvm#1920) — and will come back once that is deployed.
+- **Web build (browser)**: the server that fronts the web build (`scripts/ingress.mjs` for `npm run dev`, `scripts/static-server.mjs` for `dev:static` and Docker) hosts the same bridge via `scripts/mars-web-bridge.mjs` and exposes it same-origin: `POST /mars/rpc/<method>` (an explicit allow-list of the `MarsBridge` surface, `RPC_METHODS`; `src/api/mars/mars-web-bridge.ts` installs a fetch-backed `window.marsBridge` from `entry.client.tsx` after probing `GET /mars/health`), and `/mars/sessions/<id>/…` as an HTTP + WebSocket reverse proxy to the tunnel listener the server holds for that session (through the bridge's own `createProxyHandlers` instance: no idle/response timeout, since agent-server calls can stay silent for minutes, no `X-Forwarded-*`, and upstream failures answer a JSON 502 `{error:{message}}`; the tunnel client itself pings the harness socket every 30 s). `openTunnel` therefore answers `host: <origin>/mars/sessions/<id>`, a path-prefixed backend; proxied JSON has agent-server URLs (`conversation_url` and friends) rewritten to that prefix so the event WebSocket lands on the proxy. This is what makes the browser work at all: harness-api has no CORS, the tunnel needs a Node process, and the token must stay off the page. The routes are **off unless `MARS_WEB=1`** and, when on, want the server's session key on every request: the renderer sends it as `X-Session-API-Key` on `/mars/rpc/*` and gets an `HttpOnly; SameSite=Strict; Path=/mars` cookie back, which the browser attaches on its own to the proxied REST calls and the WebSocket upgrade (the one request a browser cannot put a header on). The key is `MARS_WEB_KEY`, else the server's `--session-api-key` (`dev-with-automation` hands the stack's key to `ingress.mjs`); with neither, `mountMarsWebBridge` mounts only on a loopback bind, where a `Host` check stops DNS rebinding. Only `conversation_url` fields are rewritten (a URL inside a message is content), JSON past 8 MB streams through untouched, `Cookie` and the key header never reach the session host, a malformed session path is a 400, an upstream WebSocket the browser abandoned mid-handshake is terminated, and `dispose()` closes both ends of every proxied WebSocket. Credentials are in-memory (no keychain; `MARS_TOKEN` seeds one at startup), OAuth is not offered (`canUseOAuth: false`), and cross-origin requests are refused.
+- **Stop and delete are confirmed, destructive, and gated**: Stop (`destroySession`) ends the session and its sandbox through `DELETE /v2/agents/sessions/{id}`, detaching any live connection first; Delete agent (`deleteAgentConfig`) soft-deletes the config through `DELETE /v2/agents/configs/{id}`. harness-api does not refuse a delete while sessions run, so the renderer only enables it once none of the agent's sessions is live (paused counts as live). Both sit behind `ConfirmationModal` and ride the same IPC / web-RPC surface as pause. In a session row the main action (Connect / Resume and connect / Open) is rightmost with Stop directly left of it. Removing a MARS backend in Manage Backends opens `MarsBackendRemovalModal` instead of the generic confirmation: "Disconnect only" (the session keeps running and billing) or "Stop session" (destroy first, then remove; a refused destroy keeps the backend and shows the error), and Manage Backends ignores Escape / outside clicks while it is open.
+- **One backend per session**: connecting registers an ordinary `kind: "local"` backend named after the session (`buildMarsBackendName`) whose `host` is the loopback tunnel (in the web build, the server's `/mars/sessions/<id>` proxy), carrying `marsSessionId` / `marsConfigId`. The backend record persists while tunnels and (in the web build) credentials do not, so `useRestoreMarsTunnels` reconnects the active MARS backend once a usable DigitalOcean connection exists — after sign-in, not before — and Manage Backends keeps a MARS backend selectable while its health is red, since selecting it is what reconnects it. The far end is a real agent-server, so conversations, files, and the terminal work unmodified. Connect logic is shared through `useConnectMarsSession()` (`src/hooks/use-connect-mars-session.ts`), which lands the user in the session's most recent conversation (or a new chat) with the URL pinned to the new backend.
+- **Server-side ownership**: tunnels, the harness-api REST client, OAuth, and credentials live in a Node process — the Electron main process on desktop, the web server in the web build (`scripts/mars-tunnel-bridge.mjs`, `tunnel-client.mjs`, `tunnel-registry.mjs`, `mars-api.mjs`, `mars-oauth.mjs`, `mars-credentials.mjs`) — and reach the renderer only via `window.marsBridge` (`electron/preload-main.cjs`, or `/mars/rpc/*`). harness-api sends no CORS headers and tokens must never reach the page, so do not move these calls into the renderer.
+- **Fail fast, explain why**: the tunnel records the last upstream failure (`getTunnel().upstreamFailure`). `waitForMarsAgentServer` throws `MarsAttachError("refused")` immediately on close code 4001 or HTTP 401/403, and `MarsAttachError("not-openhands")` when close code 4002 (guest dial failed — nothing on :8000) outlasts a 20 s grace window, since a just-woken sandbox also closes 4002 while booting. `getMarsConnectErrorMessage` maps both to `DO_AGENTS$ERROR_*` copy.
+- **Cost**: every probe and tunnel dial counts as sandbox activity and keeps it from auto-pausing. `useRestoreMarsTunnels` reopens only the *active* backend's tunnel, and `useBackendsHealth` probes non-active MARS backends once without interval/focus/reconnect refetches. Do not add background polling of sessions the user is not on.
+- **Auth**: on desktop, OAuth uses DigitalOcean's implicit grant (no client secret can ship in a desktop binary) with a fixed loopback redirect `http://127.0.0.1:53682/callback`; personal access tokens always work, and are the only option in the web build. The public client ID comes from `DO_OAUTH_CLIENT_ID`, else `mars.oauthClientId` in `config/defaults.json` (empty = PAT only); `MARS_API_BASE_URL` / `mars.apiBaseUrl` select the harness API. Desktop credentials are `safeStorage`-encrypted (session-only when the OS keychain is unavailable); web-build credentials are in-memory, so a server restart signs the user out.
+- **Tests**: `__tests__/components/backends/managed-agents-view.test.tsx`, `managed-agents-session-row.test.tsx`, `digitalocean-new-agent-form.test.tsx`, the "DigitalOcean" blocks of `add-backend-modal.test.tsx` and `manage-backends-modal.test.tsx`, `__tests__/components/features/sidebar/mars-session-panel.test.tsx`, `__tests__/hooks/use-mars-tunnel-backend.test.tsx`, `__tests__/i18n/mars-session-count.test.ts`, and `__tests__/scripts/{mars-*,tunnel-*}.test.ts`. Component tests fake `window.marsBridge`, not the hooks.
diff --git a/src/api/mars/mars-sandbox-setup.ts b/src/api/mars/mars-sandbox-setup.ts
new file mode 100644
index 0000000000..11004d1b04
--- /dev/null
+++ b/src/api/mars/mars-sandbox-setup.ts
@@ -0,0 +1,107 @@
+/**
+ * Works around two gaps in DigitalOcean's `openhands` sandbox template. Drop
+ * this once the template sources the session env and sets TMUX_TMPDIR.
+ *
+ * - The agent-server starts before the session env (manifest secrets) is
+ * written and never reads it, so it runs without OH_SECRET_KEY and every
+ * encrypted settings read 503s once a secret is stored. The server also
+ * reads `secret_key` from its JSON config file, which lives in the
+ * workspace it owns, so we write one there and restart it once; s6
+ * restarts the process and the key persists with the sandbox disk.
+ * - Its TMPDIR pushes tmux's socket path past the Unix limit, so the default
+ * tmux terminal fails as soon as an agent runs. The subprocess terminal
+ * needs no socket.
+ */
+
+import {
+ BashClient,
+ SettingsClient,
+} from "@openhands/typescript-client/clients";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
+import {
+ MARS_GUEST_API_KEY,
+ waitForMarsAgentServer,
+} from "#/api/mars/mars-tunnel-backend";
+
+const SETUP_TIMEOUT_MS = 30_000;
+/** The script kills the server one second after answering. */
+const RESTART_GRACE_MS = 2_000;
+
+/**
+ * Prints `restarting` when it wrote a key the running server has not loaded,
+ * `ready` when nothing is needed, `unsupported` when the layout is not the
+ * one this works around. Generates the key in the guest so it never leaves it.
+ */
+export const ENSURE_SECRET_KEY_SCRIPT = String.raw`servers=" $(ps -o pid= -C openhands-agent-server | tr -s ' \n' ' ') "
+main=""
+for p in $servers; do
+ parent=$(ps -o ppid= -p "$p" | tr -d ' ')
+ case "$servers" in *" $parent "*) ;; *) main=$p ;; esac
+done
+if [ -z "$main" ]; then echo unsupported; exit 0; fi
+if tr '\0' '\n' < "/proc/$main/environ" | grep -q '^OH_SECRET_KEY='; then echo ready; exit 0; fi
+cfg=$(tr '\0' '\n' < "/proc/$main/environ" | sed -n 's/^OPENHANDS_AGENT_SERVER_CONFIG_PATH=//p')
+cfg=$(cd "/proc/$main/cwd" && realpath -m "$(printf %s "$cfg" | grep . || echo workspace/openhands_agent_server_config.json)")
+python3 - "$cfg" <<'PY' || { echo unsupported; exit 0; }
+import json, os, secrets, sys
+path = sys.argv[1]
+data = json.load(open(path)) if os.path.exists(path) else {}
+if not data.get("secret_key"):
+ data["secret_key"] = secrets.token_hex(32)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(fd, "w") as f:
+ json.dump(data, f)
+PY
+started=$(( $(date +%s) - $(ps -o etimes= -p "$main" | tr -d ' ') ))
+if [ "$(stat -c %Y "$cfg")" -ge "$started" ]; then
+ (sleep 1; kill "$main") >/dev/null 2>&1 &
+ echo restarting
+else
+ echo ready
+fi`;
+
+/** The server's default tool set, with the terminal forced off tmux. */
+export const MARS_SANDBOX_TOOLS = [
+ { name: "terminal", params: { terminal_type: "subprocess" } },
+ { name: "file_editor", params: {} },
+ { name: "task_tracker", params: {} },
+ { name: "browser_tool_set", params: {} },
+];
+
+/**
+ * Best-effort: a sandbox this cannot prepare still connects, and the failure
+ * surfaces where it bites (conversation start) instead of blocking attach.
+ */
+export async function prepareMarsSandbox(
+ host: string,
+ sessionId: string,
+): Promise<void> {
+ const options = getAgentServerClientOptions({
+ host,
+ sessionApiKey: MARS_GUEST_API_KEY,
+ timeout: SETUP_TIMEOUT_MS,
+ });
+ try {
+ const output = await new BashClient(options).executeCommand({
+ command: ENSURE_SECRET_KEY_SCRIPT,
+ timeout: SETUP_TIMEOUT_MS / 1000,
+ });
+ if (output.stdout?.trim() === "restarting") {
+ await new Promise((resolve) => {
+ setTimeout(resolve, RESTART_GRACE_MS);
+ });
+ await waitForMarsAgentServer(host, { sessionId });
+ }
+
+ const settingsClient = new SettingsClient(options);
+ const settings = await settingsClient.getSettings();
+ if (settings.agent_settings?.tools == null) {
+ await settingsClient.updateSettings({
+ agent_settings_diff: { tools: MARS_SANDBOX_TOOLS },
+ });
+ }
+ } catch (error) {
+ console.warn("Could not prepare the DigitalOcean sandbox", error);
+ }
+}
diff --git a/src/api/mars/mars-tunnel-backend.ts b/src/api/mars/mars-tunnel-backend.ts
new file mode 100644
index 0000000000..1acfc8f20d
--- /dev/null
+++ b/src/api/mars/mars-tunnel-backend.ts
@@ -0,0 +1,496 @@
+/**
+ * Renderer-side view of the DigitalOcean MARS bridge exposed by
+ * `electron/preload-main.cjs`, plus the helpers that turn a connected MARS
+ * session into an ordinary local backend.
+ *
+ * A session is reached over a port-forward tunnel on loopback. The far end
+ * is a plain agent-server, so the backend is `kind: "local"`.
+ *
+ * `window.marsBridge` comes from Electron's preload in the desktop build, or
+ * from the Agent Canvas server in the web build (src/api/mars/mars-web-bridge.ts,
+ * installed before first render when the server hosts it). harness-api sends
+ * no CORS headers and the token must live in a trusted process, so a page
+ * with neither cannot offer MARS at all. Callers gate on `getMarsBridge()`
+ * rather than catching per-call failures.
+ */
+
+import { ConversationSortOrder } from "@openhands/typescript-client";
+import { ConversationClient } from "@openhands/typescript-client/clients";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
+import {
+ isDefinitiveLocalBackendError,
+ validateLocalBackend,
+} from "#/api/agent-server-compatibility";
+import type { Backend } from "#/api/backend-registry/types";
+
+export type MarsCredentialKind = "oauth" | "pat";
+
+/** Non-secret description of a stored credential. Never carries the token. */
+export interface MarsConnection {
+ id: string;
+ kind: MarsCredentialKind;
+ label: string;
+ teamName: string | null;
+ /** ISO timestamp; OAuth grants expire after 30 days and cannot be refreshed. */
+ expiresAt: string | null;
+ isExpired: boolean;
+}
+
+export interface MarsAuthState {
+ connections: MarsConnection[];
+ active: MarsConnection | null;
+ /** False when the OS keychain is unavailable, so tokens are session-only. */
+ isPersistent: boolean;
+ /** False when this build has no registered OAuth client; PAT still works. */
+ canUseOAuth: boolean;
+}
+
+export interface MarsSession {
+ session_id: string;
+ name?: string | null;
+ status?: string | null;
+ agent_kind?: string | null;
+ config_id?: string | null;
+ repo_hint?: string | null;
+ created_at?: string | null;
+ last_event_at?: string | null;
+}
+
+export interface MarsSessionPage {
+ sessions: MarsSession[];
+ nextPageToken: string | null;
+}
+
+/**
+ * Durable agent definition — what a user calls "an agent". One config has
+ * many sessions. Not to be confused with `MarsSession.agent_kind`, which is
+ * just an enum naming the coding agent inside the sandbox.
+ */
+export interface MarsAgentConfig {
+ id: string;
+ name?: string | null;
+ created_by?: string | null;
+ updated_at?: string | null;
+ /**
+ * The manifest's `agent` (e.g. `openhands`), lowercased. Filled in by the
+ * main process; null when the manifest could not be read.
+ */
+ agent?: string | null;
+}
+
+const OPENHANDS_AGENT = "openhands";
+
+/**
+ * Whether a config's manifest declares `agent: openhands`. Manifests without
+ * it are older specs that no longer launch, so an unknown agent never counts.
+ */
+export function isOpenHandsConfig(config: MarsAgentConfig): boolean {
+ return config.agent === OPENHANDS_AGENT;
+}
+
+export interface NewMarsAgentInput {
+ name: string;
+ /**
+ * Sandbox size slug from `listSandboxSizes`, written into the agent's
+ * manifest so every session of the agent gets it. Omitted = DO's default.
+ */
+ size?: string;
+}
+
+/** One entry of DigitalOcean's sandbox size catalog. */
+export interface MarsSandboxSize {
+ slug: string;
+ vcpus: number;
+ memory_mb: number;
+ price_per_hour_usd?: number | null;
+ price_per_month_usd?: number | null;
+}
+
+/** harness-api's Agent Config name rule. */
+const AGENT_NAME_PATTERN = /^[A-Za-z0-9]([A-Za-z0-9._-]{0,62}[A-Za-z0-9])?$/;
+
+export function isValidAgentName(name: string): boolean {
+ return AGENT_NAME_PATTERN.test(name);
+}
+
+export interface MarsAgentConfigPage {
+ configs: MarsAgentConfig[];
+ nextPageToken: string | null;
+}
+
+/** Most recent failed upstream dial behind an otherwise healthy listener. */
+export interface MarsUpstreamFailure {
+ /** harness-api WebSocket close code (4001 / 4002 / 4011), if any. */
+ closeCode: number | null;
+ /** HTTP status when the upgrade itself was refused. */
+ httpStatus: number | null;
+ message: string;
+}
+
+/** How a connected session is reached. Only the loopback tunnel today. */
+export type MarsTransport = "tunnel";
+
+export interface MarsTunnelStatus {
+ sessionId: string;
+ status: "connecting" | "connected" | "error";
+ transport?: MarsTransport;
+ /** Base URL the renderer registers as the backend host. */
+ host?: string;
+ remotePort: number;
+ /** Loopback listener port; only set over the tunnel. */
+ localPort: number | undefined;
+ error: string | undefined;
+ upstreamFailure?: MarsUpstreamFailure | null;
+}
+
+export interface OpenMarsTunnelParams {
+ sessionId: string;
+ /** Re-request a specific local port, e.g. to revive a persisted backend. */
+ localPort?: number;
+}
+
+interface ListOptions {
+ pageSize?: number;
+ pageToken?: string;
+ status?: string;
+}
+
+export interface MarsBridge {
+ getAuthState: () => Promise<MarsAuthState>;
+ signInWithOAuth: () => Promise<MarsAuthState>;
+ savePat: (payload: {
+ token: string;
+ label?: string;
+ }) => Promise<MarsAuthState>;
+ setActiveConnection: (id: string) => Promise<MarsAuthState>;
+ signOut: (id?: string) => Promise<MarsAuthState>;
+ listSessions: (options?: ListOptions) => Promise<MarsSessionPage>;
+ listAgentConfigs: (
+ options?: Omit<ListOptions, "status">,
+ ) => Promise<MarsAgentConfigPage>;
+ /** Empty means "no sessions yet", not "config is gone". */
+ listConfigSessions: (
+ configId: string,
+ options?: ListOptions,
+ ) => Promise<MarsSessionPage>;
+ /** Static catalog, smallest first; every slug is valid for a new agent. */
+ listSandboxSizes: () => Promise<MarsSandboxSize[]>;
+ createOpenHandsAgent: (input: NewMarsAgentInput) => Promise<MarsAgentConfig>;
+ /** Resolves once the new session is READY. */
+ createSession: (configId: string, name: string) => Promise<MarsSession>;
+ pauseSession: (sessionId: string) => Promise<void>;
+ resumeSession: (sessionId: string) => Promise<void>;
+ /** Ends the session and its sandbox for good; any live connection is dropped first. */
+ destroySession: (sessionId: string) => Promise<void>;
+ /** Soft-deletes the agent definition; only offered when none of its sessions is live. */
+ deleteAgentConfig: (configId: string) => Promise<void>;
+ openTunnel: (params: OpenMarsTunnelParams) => Promise<MarsTunnelStatus>;
+ closeTunnel: (sessionId: string) => Promise<void>;
+ getTunnel: (sessionId: string) => Promise<MarsTunnelStatus | undefined>;
+}
+
+declare global {
+ interface Window {
+ marsBridge?: MarsBridge;
+ }
+}
+
+export function getMarsBridge(): MarsBridge | null {
+ if (typeof window === "undefined") return null;
+ return window.marsBridge ?? null;
+}
+
+export function requireMarsBridge(): MarsBridge {
+ const bridge = getMarsBridge();
+ if (!bridge) {
+ throw new Error(
+ "window.marsBridge is unavailable — Managed Agents need the Electron desktop build or an Agent Canvas server that hosts the MARS bridge.",
+ );
+ }
+ return bridge;
+}
+
+/**
+ * Connects to one MARS session over a port-forward tunnel, waking it if
+ * paused. The listener port can change between connects, so callers read
+ * the host from the returned status rather than reusing a remembered one.
+ */
+export function openMarsTunnel(
+ params: OpenMarsTunnelParams,
+): Promise<MarsTunnelStatus> {
+ return requireMarsBridge().openTunnel(params);
+}
+
+const IPC_ERROR_PREFIX =
+ /^Error invoking remote method '[^']+': (?:\w*Error: )?/;
+
+/**
+ * Message for a failed bridge call, without the wrapper Electron puts around
+ * errors thrown in the main process.
+ */
+export function getMarsErrorMessage(error: unknown): string | null {
+ const message = error instanceof Error ? error.message : null;
+ return message ? message.replace(IPC_ERROR_PREFIX, "") : null;
+}
+
+export const SESSION_STATUS_READY = "SESSION_STATUS_READY";
+export const SESSION_STATUS_PAUSED = "SESSION_STATUS_PAUSED";
+export const SESSION_STATUS_DESTROYING = "SESSION_STATUS_DESTROYING";
+export const SESSION_STATUS_DESTROYED = "SESSION_STATUS_DESTROYED";
+export const SESSION_STATUS_FAILED = "SESSION_STATUS_FAILED";
+
+/** Where a freshly connected MARS session lands. */
+export const NEW_CHAT_PATH = "/conversations";
+
+/** Statuses a session can never come back from. */
+const TERMINAL_SESSION_STATUSES = new Set([
+ SESSION_STATUS_DESTROYING,
+ SESSION_STATUS_DESTROYED,
+ SESSION_STATUS_FAILED,
+]);
+
+export type MarsSessionPhase =
+ | "ready"
+ | "paused"
+ | "starting"
+ | "ended"
+ | "failed";
+
+/**
+ * Collapse `SESSION_STATUS_*` into the few states the UI treats differently.
+ * Statuses are added server-side without a client release, so anything
+ * unrecognised that is not terminal reads as "starting" (transitional).
+ */
+export function getSessionPhase(
+ status: string | null | undefined,
+): MarsSessionPhase {
+ if (status === SESSION_STATUS_READY) return "ready";
+ if (status === SESSION_STATUS_PAUSED) return "paused";
+ if (status === SESSION_STATUS_FAILED) return "failed";
+ if (TERMINAL_SESSION_STATUSES.has(status ?? "")) return "ended";
+ return "starting";
+}
+
+/** READY or PAUSED — connecting resumes a paused session first. */
+export function isConnectableSession(session: MarsSession): boolean {
+ const phase = getSessionPhase(session.status);
+ return phase === "ready" || phase === "paused";
+}
+
+const SESSION_NAME_MAX_STEM = 32;
+
+/**
+ * Name for a session launched from an agent: the agent it came from plus a
+ * suffix to keep siblings apart, narrowed to the character set MARS's own
+ * generated names use.
+ */
+export function buildNewSessionName(configName: string | null | undefined) {
+ const stem =
+ (configName ?? "")
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, SESSION_NAME_MAX_STEM) || "agent";
+ return `${stem}-${Math.random().toString(36).slice(2, 8)}`;
+}
+
+/**
+ * The in-guest agent-server's session key is set by the sandbox template, not
+ * by us. The DigitalOcean token is the authorization boundary instead:
+ * dialing the tunnel requires it.
+ */
+export const MARS_GUEST_API_KEY = "";
+
+/**
+ * An idle-paused session cold-wakes on first traffic and the in-guest
+ * agent-server needs a moment more before it answers, so early probes
+ * legitimately fail.
+ */
+const AGENT_SERVER_WAIT_MS = 60_000;
+const AGENT_SERVER_PROBE_TIMEOUT_MS = 5_000;
+const AGENT_SERVER_PROBE_INTERVAL_MS = 2_000;
+/**
+ * A just-woken sandbox also closes 4002 while its agent-server boots, so only
+ * a 4002 that outlasts this window means nothing will ever serve the port.
+ */
+const GUEST_PORT_CLOSED_GRACE_MS = 20_000;
+
+const CLOSE_SESSION_UNAVAILABLE = 4001;
+const CLOSE_GUEST_DIAL_FAILED = 4002;
+const HTTP_UNAUTHORIZED = 401;
+const HTTP_FORBIDDEN = 403;
+
+export type MarsAttachFailureReason =
+ /** The sandbox answers, but not with an OpenHands agent-server on :8000. */
+ | "not-openhands"
+ /** DigitalOcean refused the tunnel for this token or session. */
+ | "refused";
+
+/** A failure the UI can explain precisely instead of a generic timeout. */
+export class MarsAttachError extends Error {
+ readonly reason: MarsAttachFailureReason;
+
+ constructor(reason: MarsAttachFailureReason, message: string) {
+ super(message);
+ this.name = "MarsAttachError";
+ this.reason = reason;
+ }
+}
+
+function isRefusal(failure: MarsUpstreamFailure): boolean {
+ return (
+ failure.closeCode === CLOSE_SESSION_UNAVAILABLE ||
+ failure.httpStatus === HTTP_UNAUTHORIZED ||
+ failure.httpStatus === HTTP_FORBIDDEN
+ );
+}
+
+async function readUpstreamFailure(
+ sessionId: string | undefined,
+): Promise<MarsUpstreamFailure | null> {
+ const bridge = getMarsBridge();
+ if (!sessionId || !bridge) return null;
+ try {
+ return (await bridge.getTunnel(sessionId))?.upstreamFailure ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Poll a freshly opened tunnel until the agent-server behind it answers.
+ * When `sessionId` is given, the tunnel's own upstream failures cut the wait
+ * short with a {@link MarsAttachError}; otherwise the last probe failure is
+ * rethrown so the user sees why it never came up. A definitive probe failure
+ * (rejected key, unsupported version) is rethrown at once.
+ */
+export async function waitForMarsAgentServer(
+ host: string,
+ {
+ sessionId,
+ budgetMs = AGENT_SERVER_WAIT_MS,
+ }: { sessionId?: string; budgetMs?: number } = {},
+): Promise<string | null> {
+ const startedAt = Date.now();
+ const deadline = startedAt + budgetMs;
+ let guestPortClosedSince: number | null = null;
+ for (;;) {
+ try {
+ return await validateLocalBackend(
+ { host, apiKey: MARS_GUEST_API_KEY },
+ AGENT_SERVER_PROBE_TIMEOUT_MS,
+ );
+ } catch (error) {
+ // A rejected key or too-old server will not change by waiting.
+ if (isDefinitiveLocalBackendError(error)) throw error;
+ const failure = await readUpstreamFailure(sessionId);
+ if (failure && isRefusal(failure)) {
+ throw new MarsAttachError("refused", failure.message);
+ }
+ const now = Date.now();
+ if (failure?.closeCode === CLOSE_GUEST_DIAL_FAILED) {
+ guestPortClosedSince ??= now;
+ if (now - guestPortClosedSince >= GUEST_PORT_CLOSED_GRACE_MS) {
+ throw new MarsAttachError("not-openhands", failure.message);
+ }
+ } else {
+ guestPortClosedSince = null;
+ }
+ if (now >= deadline) throw error;
+ await new Promise((resolve) => {
+ setTimeout(resolve, AGENT_SERVER_PROBE_INTERVAL_MS);
+ });
+ }
+ }
+}
+
+const LATEST_CONVERSATION_TIMEOUT_MS = 10_000;
+
+/**
+ * Id of the most recently updated conversation on a session's agent-server,
+ * read through an explicit host override so it cannot race the registry
+ * switching the active backend. Best-effort: null on any failure, because
+ * the caller can always fall back to a fresh chat.
+ */
+export async function fetchLatestMarsConversationId(
+ host: string,
+): Promise<string | null> {
+ try {
+ const page = await new ConversationClient(
+ getAgentServerClientOptions({
+ host,
+ sessionApiKey: MARS_GUEST_API_KEY,
+ timeout: LATEST_CONVERSATION_TIMEOUT_MS,
+ }),
+ ).searchConversations({
+ limit: 1,
+ sort_order: ConversationSortOrder.UPDATED_AT_DESC,
+ });
+ return page?.items?.[0]?.id ?? null;
+ } catch {
+ return null;
+ }
+}
+
+export function buildMarsBackendHost(localPort: number): string {
+ return `http://127.0.0.1:${localPort}`;
+}
+
+/**
+ * The base URL a connection status says to register: the tunnel's loopback
+ * listener. A status from a bridge that predates `host` is still honoured
+ * through its `localPort`.
+ */
+export function getMarsConnectionHost(
+ status: MarsTunnelStatus,
+): string | undefined {
+ if (status.host) return status.host;
+ return status.localPort === undefined
+ ? undefined
+ : buildMarsBackendHost(status.localPort);
+}
+
+/**
+ * Local port a persisted MARS backend's tunnel was listening on, so a
+ * restore can ask for it again. Undefined for a host that is not a loopback
+ * listener.
+ */
+export function getMarsBackendLocalPort(backend: Backend): number | undefined {
+ try {
+ const url = new URL(backend.host);
+ if (url.hostname !== "127.0.0.1") return undefined;
+ const port = Number.parseInt(url.port, 10);
+ return Number.isInteger(port) && port > 0 ? port : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Build the Backend record for a session that now answers at `host`. The far
+ * end really is an ordinary agent-server, so this is a `kind: "local"`
+ * backend like any other.
+ */
+export function buildMarsBackendInput({
+ name,
+ host,
+ sessionId,
+ configId,
+ apiKey = MARS_GUEST_API_KEY,
+}: {
+ name: string;
+ host: string;
+ sessionId: string;
+ configId?: string;
+ apiKey?: string;
+}): Omit<Backend, "id" | "connectionRevision"> {
+ return {
+ name,
+ host,
+ apiKey,
+ kind: "local",
+ authMode: "api-key",
+ marsSessionId: sessionId,
+ ...(configId ? { marsConfigId: configId } : {}),
+ };
+}
diff --git a/src/api/mars/mars-web-bridge.ts b/src/api/mars/mars-web-bridge.ts
new file mode 100644
index 0000000000..fd92eb962b
--- /dev/null
+++ b/src/api/mars/mars-web-bridge.ts
@@ -0,0 +1,155 @@
+/**
+ * `window.marsBridge` for the web build.
+ *
+ * The desktop app gets the bridge from Electron's preload; a browser gets it
+ * from the Agent Canvas server instead, which hosts the same main-process
+ * bridge and exposes it same-origin under `/mars/rpc/<method>` (see
+ * scripts/mars-web-bridge.mjs). Every method here is one POST carrying the
+ * call's arguments, so the rest of the Managed Agents UI runs unchanged: it
+ * only ever talks to the `MarsBridge` interface.
+ *
+ * Connections resolve to a path-prefixed backend on this origin
+ * (`/mars/sessions/<id>`), which the server proxies to the port-forward
+ * tunnel it holds for the session. The DigitalOcean token is used only on the
+ * server to dial that tunnel and never reaches the page.
+ *
+ * The server wants its session key on these routes. Each RPC carries it as
+ * `X-Session-API-Key` (the key this page already holds for the agent-server);
+ * the server answers with an HttpOnly cookie that the browser then sends by
+ * itself on the proxied REST calls and the WebSocket upgrade.
+ */
+
+import { getAgentServerHeaders } from "#/api/agent-server-config";
+import type { MarsBridge } from "./mars-tunnel-backend";
+
+export const MARS_WEB_HEALTH_PATH = "/mars/health";
+const RPC_PREFIX = "/mars/rpc/";
+const PROBE_TIMEOUT_MS = 1_500;
+
+interface RpcEnvelope<T> {
+ result?: T;
+ error?: { message?: string; status?: number };
+}
+
+/** A bridge call the server refused; `status` is the HTTP status it chose. */
+export class MarsWebBridgeError extends Error {
+ readonly status: number;
+
+ constructor(message: string, status: number) {
+ super(message);
+ this.name = "MarsWebBridgeError";
+ this.status = status;
+ }
+}
+
+async function rpc<T>(
+ baseUrl: string,
+ method: string,
+ args: unknown[],
+ fetchImpl: typeof fetch,
+): Promise<T> {
+ const response = await fetchImpl(`${baseUrl}${RPC_PREFIX}${method}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...getAgentServerHeaders(),
+ },
+ body: JSON.stringify({ args }),
+ });
+ let envelope: RpcEnvelope<T> = {};
+ try {
+ envelope = (await response.json()) as RpcEnvelope<T>;
+ } catch {
+ // A non-JSON body (edge error page) falls through to the status line.
+ }
+ if (!response.ok) {
+ throw new MarsWebBridgeError(
+ envelope.error?.message ?? `${response.status} ${response.statusText}`,
+ envelope.error?.status ?? response.status,
+ );
+ }
+ return envelope.result as T;
+}
+
+/**
+ * @param baseUrl Origin (and path prefix) the Agent Canvas server is on;
+ * empty means the page's own origin.
+ */
+export function createMarsWebBridge(
+ baseUrl = "",
+ fetchImpl: typeof fetch = (...params) => fetch(...params),
+): MarsBridge {
+ const call =
+ <T>(method: string) =>
+ (...args: unknown[]) =>
+ rpc<T>(baseUrl, method, args, fetchImpl);
+ return {
+ getAuthState: call("getAuthState"),
+ // The web server never offers OAuth (no trusted loopback redirect); the
+ // auth state it returns says so, and the UI hides the button.
+ signInWithOAuth: async () => {
+ throw new MarsWebBridgeError(
+ "OAuth sign-in is only available in the desktop app; use a personal access token.",
+ 400,
+ );
+ },
+ savePat: call("savePat"),
+ setActiveConnection: call("setActiveConnection"),
+ signOut: call("signOut"),
+ listSessions: call("listSessions"),
+ listAgentConfigs: call("listAgentConfigs"),
+ listConfigSessions: call("listConfigSessions"),
+ listSandboxSizes: call("listSandboxSizes"),
+ createOpenHandsAgent: call("createOpenHandsAgent"),
+ createSession: call("createSession"),
+ pauseSession: call("pauseSession"),
+ resumeSession: call("resumeSession"),
+ destroySession: call("destroySession"),
+ deleteAgentConfig: call("deleteAgentConfig"),
+ openTunnel: call("openTunnel"),
+ closeTunnel: call("closeTunnel"),
+ getTunnel: call("getTunnel"),
+ };
+}
+
+/** Whether the server this page came from hosts the MARS web bridge. */
+export async function probeMarsWebBridge(
+ baseUrl = "",
+ fetchImpl: typeof fetch = (...params) => fetch(...params),
+ timeoutMs = PROBE_TIMEOUT_MS,
+): Promise<boolean> {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const response = await fetchImpl(`${baseUrl}${MARS_WEB_HEALTH_PATH}`, {
+ signal: controller.signal,
+ });
+ if (!response.ok) return false;
+ // A server that answers every path with index.html is also a 200; only
+ // the bridge says `{ ok: true }`.
+ try {
+ const body = (await response.json()) as { ok?: unknown };
+ return body?.ok === true;
+ } catch {
+ return false;
+ }
+ } catch {
+ return false;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/**
+ * Install the web bridge as `window.marsBridge` when this page is served by
+ * an Agent Canvas server that hosts it. A no-op in Electron (the preload has
+ * already provided the bridge) and when the server does not offer MARS, so
+ * the Managed Agents UI stays hidden exactly as before. Resolves before the
+ * app renders because `getMarsBridge()` is read synchronously.
+ */
+export async function installMarsWebBridge(): Promise<boolean> {
+ if (typeof window === "undefined" || window.marsBridge) return false;
+ if (!(await probeMarsWebBridge())) return false;
+ window.marsBridge = createMarsWebBridge();
+ return true;
+}
diff --git a/src/assets/branding/digitalocean-logo.svg b/src/assets/branding/digitalocean-logo.svg
new file mode 100644
index 0000000000..545d861baa
--- /dev/null
+++ b/src/assets/branding/digitalocean-logo.svg
@@ -0,0 +1 @@
+<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M16 32v-6.2c6.56 0 11.65-6.5 9.13-13.4a9.26 9.26 0 0 0-5.53-5.53C12.7 4.35 6.2 9.44 6.2 16H0C0 5.55 10.1-2.6 21.06.82c4.78 1.5 8.6 5.31 10.09 10.1C34.58 21.9 26.44 32 16 32Z" fill="#0069FF"/><path d="M16 25.83H9.84v-6.16H16v6.16Z" fill="#0069FF"/><path d="M9.84 30.57H5.1v-4.74h4.74v4.74Z" fill="#0069FF"/><path d="M5.1 25.83H1.13v-3.97H5.1v3.97Z" fill="#0069FF"/></svg>
diff --git a/src/components/features/automations/recommended-automations-launcher.tsx b/src/components/features/automations/recommended-automations-launcher.tsx
index a5c57a4884..5c7163dd0d 100644
--- a/src/components/features/automations/recommended-automations-launcher.tsx
+++ b/src/components/features/automations/recommended-automations-launcher.tsx
@@ -34,6 +34,7 @@ import {
getRequiredIntegrationIds,
} from "#/utils/automation-catalog";
import { isResponderAutomation } from "#/utils/responder-deployment";
+import { useAutomationHealth } from "#/hooks/query/use-automation-health";
import { useAutomations } from "#/hooks/query/use-automations";
import { useNativeGitIntegrations } from "#/hooks/query/use-native-git-integrations";
import { cloudIntegrationsUrl } from "#/utils/cloud-integrations-url";
@@ -114,8 +115,11 @@ export function RecommendedAutomationsLauncher({
const [isPreparingLocalResponder, setIsPreparingLocalResponder] =
useState(false);
const isRail = variant === "rail";
+ // Backends without an automation service (remote agent-servers such as a
+ // DigitalOcean sandbox) 404 the list, which would surface as an error toast.
+ const { data: automationHealth } = useAutomationHealth();
const { data: automationsData, isLoading: isAutomationsLoading } =
- useAutomations({ enabled: isRail });
+ useAutomations({ enabled: isRail && automationHealth?.status === "ok" });
const {
getNativeIntegration,
isJiraEnabled,
diff --git a/src/components/features/backends/backend-form-modal.tsx b/src/components/features/backends/backend-form-modal.tsx
index b906a5c031..5ba1a532b7 100644
--- a/src/components/features/backends/backend-form-modal.tsx
+++ b/src/components/features/backends/backend-form-modal.tsx
@@ -1,9 +1,20 @@
import React from "react";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
-import { ChevronDown, Globe, Info, Monitor } from "lucide-react";
+import {
+ ChevronDown,
+ ChevronRight,
+ CloudCog,
+ Globe,
+ Info,
+ Monitor,
+} from "lucide-react";
import { ServerClient } from "@openhands/typescript-client/clients";
import OpenHandsLogoWhite from "#/assets/branding/openhands-logo-white.svg?react";
+import DigitalOceanLogo from "#/assets/branding/digitalocean-logo.svg?react";
+import { getMarsBridge } from "#/api/mars/mars-tunnel-backend";
+import { DigitalOceanConnectPanel } from "./managed-agents/digitalocean-connect-panel";
+import { BackNavButton } from "#/components/shared/buttons/back-nav-button";
import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
import {
MODAL_MAX_WIDTH_VIEWPORT,
@@ -155,7 +166,7 @@ const DEPLOYMENT_OPTIONS_URL =
export type BackendConnectionMethod = "manual" | "cloud_login";
export type BackendAddedSource = CloudConnectionSource;
-type AddBackendOption = "cloud" | "agent-server";
+type AddBackendOption = "cloud" | "agent-server" | "providers";
type AgentServerLocation = "local" | "remote";
function getConnectionTestFailedTitle(
@@ -1124,11 +1135,12 @@ function BackendOptionTab({
role="tab"
aria-selected={isSelected}
aria-controls={panelId}
+ aria-describedby={`${tabId}-description`}
data-testid={testId}
onClick={() => onSelect(value)}
className={cn(
- "relative flex min-h-16 w-full cursor-pointer items-center gap-3 px-3 py-3 text-left transition-colors",
- "first:border-r first:border-r-border",
+ "relative flex min-h-14 w-full cursor-pointer items-center gap-2.5 px-2.5 py-2.5 text-left transition-colors",
+ "not-last:border-r not-last:border-r-border",
"focus-visible:z-10 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-blue-300",
isSelected
? "bg-surface-raised text-contrast after:absolute after:inset-x-0 after:bottom-0 after:h-0.5 after:bg-primary"
@@ -1136,14 +1148,14 @@ function BackendOptionTab({
)}
>
<span
- className="flex size-8 shrink-0 items-center justify-center"
+ className="flex size-7 shrink-0 items-center justify-center"
aria-hidden
>
{icon}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium">{title}</span>
- <span className="mt-0.5 block text-xs leading-tight text-muted">
+ <span id={`${tabId}-description`} className="sr-only">
{description}
</span>
</span>
@@ -1326,6 +1338,7 @@ function AgentServerGuidance({ location }: { location: AgentServerLocation }) {
function AddBackendChooser({
onConnected,
+ onSelectProvider,
source,
}: {
onConnected: (
@@ -1333,6 +1346,7 @@ function AddBackendChooser({
connectionMethod: BackendConnectionMethod,
metadata?: BackendConnectionTestMetadata,
) => void;
+ onSelectProvider: () => void;
source: BackendAddedSource;
}) {
const { t } = useTranslation("openhands");
@@ -1343,13 +1357,124 @@ function AddBackendChooser({
const panelId = "add-backend-selected-panel";
const selectedTabId = `add-backend-option-${selectedOption}-tab`;
const isCloudSelected = selectedOption === "cloud";
+ const canUseDigitalOcean = getMarsBridge() !== null;
+
+ let panel: React.ReactNode;
+ if (selectedOption === "providers") {
+ panel = (
+ <div
+ data-testid="add-backend-providers-panel"
+ className="flex flex-col gap-4"
+ >
+ <button
+ type="button"
+ data-testid="add-backend-provider-digitalocean"
+ onClick={onSelectProvider}
+ className="flex w-full cursor-pointer items-center gap-3 rounded-xl border border-border bg-base-secondary px-4 py-3 text-left transition-colors hover:bg-surface-raised focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-300"
+ >
+ <span
+ className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-surface-raised"
+ aria-hidden
+ >
+ <DigitalOceanLogo width={32} height={32} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-sm font-medium text-contrast">
+ {t(I18nKey.DO_AGENTS$BADGE)}
+ </span>
+ <span className="mt-0.5 block text-xs leading-tight text-muted">
+ {t(I18nKey.DO_AGENTS$TAB_DESCRIPTION)}
+ </span>
+ </span>
+ <ChevronRight className="size-4 shrink-0 text-muted" aria-hidden />
+ </button>
+ <p className="text-xs text-muted">
+ {t(I18nKey.BACKEND$PROVIDERS_COMING_SOON)}
+ </p>
+ </div>
+ );
+ } else if (isCloudSelected) {
+ /* Padding keeps the CTA and Advanced host field from hugging the
+ border; when Advanced expands the panel grows with the content
+ instead of squeezing it into the reserved min-height. */
+ panel = (
+ <div
+ data-testid="add-backend-cloud-panel"
+ className={cn(
+ "relative isolate flex min-h-[13.5rem] w-full items-center justify-center rounded-xl border border-border px-5 py-6",
+ // A soft greyscale halo sits behind the CTA; -z-10 keeps it under the
+ // content rather than washing over it.
+ "before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-xl",
+ "before:bg-[radial-gradient(75%_75%_at_50%_50%,rgba(255,255,255,0.1)_0%,rgba(255,255,255,0)_70%)]",
+ )}
+ >
+ <CloudLoginColumn
+ onConnected={onConnected}
+ testIdRoot="add-backend"
+ analyticsSource={source}
+ showBranding={false}
+ />
+ </div>
+ );
+ } else {
+ panel = (
+ <div
+ data-testid="add-backend-agent-server-panel"
+ className="mx-auto w-full max-w-xl"
+ >
+ {/* Rules on either side center the toggle and read as a
+ divider between the chooser and the connection form. */}
+ <div className="flex items-center gap-3">
+ <span className="h-px flex-1 bg-border" aria-hidden />
+ <SegmentedToggle<AgentServerLocation>
+ value={agentServerLocation}
+ options={[
+ {
+ value: "local",
+ label: t(I18nKey.BACKEND$KIND_LOCAL),
+ icon: <Monitor aria-hidden />,
+ },
+ {
+ value: "remote",
+ label: t(I18nKey.BACKEND$KIND_REMOTE),
+ icon: <Globe aria-hidden />,
+ },
+ ]}
+ onChange={setAgentServerLocation}
+ ariaLabel={t(I18nKey.BACKEND$AGENT_SERVER_LOCATION)}
+ testId="add-backend-location"
+ />
+ <span className="h-px flex-1 bg-border" aria-hidden />
+ </div>
+
+ <div className="mt-4 flex flex-col gap-4">
+ <AgentServerGuidance
+ key={agentServerLocation}
+ location={agentServerLocation}
+ />
+ <ManualConnectionColumn
+ onConnected={onConnected}
+ testIdRoot="add-backend"
+ requireApiKey={agentServerLocation === "remote"}
+ submitLabel={t(I18nKey.BACKEND$CONNECT)}
+ submittingLabel={t(I18nKey.ONBOARDING$BACKEND_STATUS_CHECKING)}
+ fixedKind="local"
+ showKindSelector={false}
+ />
+ </div>
+ </div>
+ );
+ }
return (
<div data-testid="add-backend-chooser" className="flex flex-col">
<div
role="tablist"
aria-label={t(I18nKey.BACKEND$CHOOSER_TITLE)}
- className="grid grid-cols-2 overflow-hidden rounded-lg border border-border"
+ className={cn(
+ "grid overflow-hidden rounded-lg border border-border",
+ canUseDigitalOcean ? "grid-cols-3" : "grid-cols-2",
+ )}
>
<BackendOptionTab
value="cloud"
@@ -1378,6 +1503,18 @@ function AddBackendChooser({
panelId={panelId}
testId="add-backend-option-agent-server"
/>
+ {canUseDigitalOcean ? (
+ <BackendOptionTab
+ value="providers"
+ selectedValue={selectedOption}
+ title={t(I18nKey.BACKEND$PROVIDERS_TITLE)}
+ description={t(I18nKey.BACKEND$PROVIDERS_OPTION_DESCRIPTION)}
+ icon={<CloudCog className="size-6" aria-hidden />}
+ onSelect={setSelectedOption}
+ panelId={panelId}
+ testId="add-backend-option-providers"
+ />
+ ) : null}
</div>
<div className="mt-6">
@@ -1388,76 +1525,7 @@ function AddBackendChooser({
aria-labelledby={selectedTabId}
className="min-w-0"
>
- {isCloudSelected ? (
- /* Padding keeps the CTA and Advanced host field from hugging the
- border; when Advanced expands the panel grows with the content
- instead of squeezing it into the reserved min-height. */
- <div
- data-testid="add-backend-cloud-panel"
- className={cn(
- "relative isolate flex min-h-[13.5rem] w-full items-center justify-center rounded-xl border border-border px-5 py-6",
- // A soft greyscale halo sits behind the CTA; -z-10 keeps it under the
- // content rather than washing over it.
- "before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-xl",
- "before:bg-[radial-gradient(75%_75%_at_50%_50%,rgba(255,255,255,0.1)_0%,rgba(255,255,255,0)_70%)]",
- )}
- >
- <CloudLoginColumn
- onConnected={onConnected}
- testIdRoot="add-backend"
- analyticsSource={source}
- showBranding={false}
- />
- </div>
- ) : (
- <div
- data-testid="add-backend-agent-server-panel"
- className="mx-auto w-full max-w-xl"
- >
- {/* Rules on either side center the toggle and read as a
- divider between the chooser and the connection form. */}
- <div className="flex items-center gap-3">
- <span className="h-px flex-1 bg-border" aria-hidden />
- <SegmentedToggle<AgentServerLocation>
- value={agentServerLocation}
- options={[
- {
- value: "local",
- label: t(I18nKey.BACKEND$KIND_LOCAL),
- icon: <Monitor aria-hidden />,
- },
- {
- value: "remote",
- label: t(I18nKey.BACKEND$KIND_REMOTE),
- icon: <Globe aria-hidden />,
- },
- ]}
- onChange={setAgentServerLocation}
- ariaLabel={t(I18nKey.BACKEND$AGENT_SERVER_LOCATION)}
- testId="add-backend-location"
- />
- <span className="h-px flex-1 bg-border" aria-hidden />
- </div>
-
- <div className="mt-4 flex flex-col gap-4">
- <AgentServerGuidance
- key={agentServerLocation}
- location={agentServerLocation}
- />
- <ManualConnectionColumn
- onConnected={onConnected}
- testIdRoot="add-backend"
- requireApiKey={agentServerLocation === "remote"}
- submitLabel={t(I18nKey.BACKEND$CONNECT)}
- submittingLabel={t(
- I18nKey.ONBOARDING$BACKEND_STATUS_CHECKING,
- )}
- fixedKind="local"
- showKindSelector={false}
- />
- </div>
- </div>
- )}
+ {panel}
</section>
</AnimatedPanelHeight>
</div>
@@ -1468,9 +1536,11 @@ function AddBackendChooser({
function AddBackendConnectionOptions({
onClose,
source,
+ onSelectProvider,
}: {
onClose: () => void;
source: BackendAddedSource;
+ onSelectProvider: () => void;
}) {
const { addBackend } = useActiveBackendContext();
// @spec BM-002 — Adding a backend auto-switches the active selection to it
@@ -1510,45 +1580,55 @@ function AddBackendConnectionOptions({
);
}
- return <AddBackendChooser onConnected={handleConnected} source={source} />;
+ return (
+ <AddBackendChooser
+ onConnected={handleConnected}
+ onSelectProvider={onSelectProvider}
+ source={source}
+ />
+ );
}
-// ── Modal wrappers ──────────────────────────────────────────────────
-
-/**
- * Modal wrapper. In **add** mode it renders a two-column layout
- * (manual connection | OR | Cloud login). In **edit** mode it wraps
- * the standard `BackendForm`.
- */
-export function BackendFormModal({
- mode,
- backend,
+function AddBackendAddModeBody({
+ hideCloseButton,
onClose,
- source = "add_backend_modal",
- hideCloseButton = false,
-}: BackendFormModalProps) {
+ source,
+}: {
+ hideCloseButton: boolean;
+ onClose: () => void;
+ source: BackendAddedSource;
+}) {
const { t } = useTranslation("openhands");
+ const [providerOpen, setProviderOpen] = React.useState(false);
+ const railRef = React.useRef<HTMLDivElement>(null);
- if (mode === "add") {
- return (
- <ModalBackdrop
- onClose={hideCloseButton ? undefined : onClose}
- closeOnEscape={false}
- closeOnBackdropClick={!hideCloseButton}
- aria-label={t(I18nKey.BACKEND$ADD_TITLE)}
+ React.useEffect(() => {
+ const focusTarget = providerOpen
+ ? "add-backend-providers-back"
+ : "add-backend-provider-digitalocean";
+ railRef.current
+ ?.querySelector<HTMLButtonElement>(`[data-testid="${focusTarget}"]`)
+ ?.focus();
+ }, [providerOpen]);
+
+ const goBack = () => setProviderOpen(false);
+
+ return (
+ <AnimatedPanelHeight>
+ <div
+ ref={railRef}
+ data-testid="add-backend-slide-rail"
+ className="relative overflow-hidden"
>
<div
- data-testid={
- hideCloseButton ? "onboarding-modal" : "add-backend-modal"
- }
+ aria-hidden={providerOpen}
+ inert={providerOpen ? true : undefined}
+ style={{ transform: `translateX(${providerOpen ? -100 : 0}%)` }}
className={cn(
- "relative max-h-[92vh] w-180 overflow-y-auto rounded-xl border border-border bg-base-secondary p-6",
- MODAL_MAX_WIDTH_VIEWPORT,
+ "w-full transition-transform duration-300 ease-out motion-reduce:transition-none",
+ providerOpen && "pointer-events-none absolute inset-0",
)}
>
- {hideCloseButton ? null : (
- <ModalCloseButton onClose={onClose} testId="add-backend-close" />
- )}
{hideCloseButton ? null : (
<div className="pr-8">
<h2 className={modalTitleLgClassName}>
@@ -1578,9 +1658,92 @@ export function BackendFormModal({
)}
<div className={hideCloseButton ? undefined : "mt-5"}>
- <AddBackendConnectionOptions onClose={onClose} source={source} />
+ <AddBackendConnectionOptions
+ onClose={onClose}
+ source={source}
+ onSelectProvider={() => setProviderOpen(true)}
+ />
</div>
</div>
+ <div
+ aria-hidden={!providerOpen}
+ inert={!providerOpen ? true : undefined}
+ style={{ transform: `translateX(${providerOpen ? 0 : 100}%)` }}
+ className={cn(
+ "w-full transition-transform duration-300 ease-out motion-reduce:transition-none",
+ !providerOpen && "pointer-events-none absolute inset-0",
+ )}
+ >
+ {providerOpen ? (
+ <div className="flex flex-col gap-4">
+ <BackNavButton
+ onClick={goBack}
+ testId="add-backend-providers-back"
+ >
+ {t(I18nKey.BUTTON$BACK)}
+ </BackNavButton>
+ <div className="flex min-w-0 items-center gap-3 pr-8">
+ <span
+ className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-surface-raised"
+ aria-hidden
+ >
+ <DigitalOceanLogo width={32} height={32} />
+ </span>
+ <h2 className={modalTitleLgMediumClassName}>
+ {t(I18nKey.DO_AGENTS$BADGE)}
+ </h2>
+ </div>
+ <DigitalOceanConnectPanel onConnected={onClose} />
+ </div>
+ ) : null}
+ </div>
+ </div>
+ </AnimatedPanelHeight>
+ );
+}
+
+// ── Modal wrappers ──────────────────────────────────────────────────
+
+/**
+ * Modal wrapper. In **add** mode it renders a two-column layout
+ * (manual connection | OR | Cloud login). In **edit** mode it wraps
+ * the standard `BackendForm`.
+ */
+export function BackendFormModal({
+ mode,
+ backend,
+ onClose,
+ source = "add_backend_modal",
+ hideCloseButton = false,
+}: BackendFormModalProps) {
+ const { t } = useTranslation("openhands");
+
+ if (mode === "add") {
+ return (
+ <ModalBackdrop
+ onClose={hideCloseButton ? undefined : onClose}
+ closeOnEscape={false}
+ closeOnBackdropClick={!hideCloseButton}
+ aria-label={t(I18nKey.BACKEND$ADD_TITLE)}
+ >
+ <div
+ data-testid={
+ hideCloseButton ? "onboarding-modal" : "add-backend-modal"
+ }
+ className={cn(
+ "relative max-h-[92vh] w-180 overflow-x-hidden overflow-y-auto rounded-xl border border-border bg-base-secondary p-6",
+ MODAL_MAX_WIDTH_VIEWPORT,
+ )}
+ >
+ {hideCloseButton ? null : (
+ <ModalCloseButton onClose={onClose} testId="add-backend-close" />
+ )}
+ <AddBackendAddModeBody
+ hideCloseButton={hideCloseButton}
+ onClose={onClose}
+ source={source}
+ />
+ </div>
</ModalBackdrop>
);
}
diff --git a/src/components/features/backends/backend-row.tsx b/src/components/features/backends/backend-row.tsx
index 048b580de4..b03b023eb9 100644
--- a/src/components/features/backends/backend-row.tsx
+++ b/src/components/features/backends/backend-row.tsx
@@ -59,8 +59,14 @@ export function BackendRow({
? "text-red-300"
: "text-muted";
const dotStatus = isInvalidApiKey ? false : (health?.isConnected ?? null);
- const canSelect = health?.isConnected === true && !isInvalidApiKey;
const lockedCloudHost = getLockedCloudHost();
+ // The host is a tunnel's loopback port, owned by the Managed Agents screen.
+ const isMarsSession = Boolean(backend.marsSessionId);
+ // A MARS session reads offline whenever its tunnel is gone (e.g. after a
+ // restart), and selecting it is what reopens the tunnel — so it stays
+ // selectable rather than forcing a new session.
+ const canSelect =
+ (health?.isConnected === true || isMarsSession) && !isInvalidApiKey;
return (
<li
@@ -94,7 +100,9 @@ export function BackendRow({
{orgLabel}
</span>
) : null}
- <span className="truncate text-xs text-muted">{backend.host}</span>
+ <span className="truncate text-xs text-muted">
+ {isMarsSession ? t(I18nKey.DO_AGENTS$HOSTED_SESSION) : backend.host}
+ </span>
<span
data-testid={`manage-backends-status-${backend.name}`}
className={cn("truncate text-xs", statusClassName)}
@@ -112,9 +120,11 @@ export function BackendRow({
) : null}
</div>
<span className="px-2 py-1 rounded-full text-[11px] uppercase tracking-wide text-text-tertiary bg-surface border border-border">
- {backend.kind === "cloud"
- ? t(I18nKey.BACKEND$KIND_CLOUD)
- : t(I18nKey.BACKEND$KIND_LOCAL)}
+ {isMarsSession
+ ? t(I18nKey.DO_AGENTS$BADGE)
+ : backend.kind === "cloud"
+ ? t(I18nKey.BACKEND$KIND_CLOUD)
+ : t(I18nKey.BACKEND$KIND_LOCAL)}
</span>
</button>
<div className="flex shrink-0 items-center gap-2 px-3 py-3">
@@ -134,7 +144,7 @@ export function BackendRow({
analyticsSource="manage_backends_modal"
/>
) : null}
- {!lockedCloudHost && (
+ {!lockedCloudHost && !isMarsSession && (
<button
type="button"
onClick={onEdit}
diff --git a/src/components/features/backends/manage-backends-modal.tsx b/src/components/features/backends/manage-backends-modal.tsx
index 8dae25d50d..dd6c9571b9 100644
--- a/src/components/features/backends/manage-backends-modal.tsx
+++ b/src/components/features/backends/manage-backends-modal.tsx
@@ -4,6 +4,7 @@ import { Plus } from "lucide-react";
import { getLockedCloudHost } from "#/api/agent-server-config";
import { type Backend } from "#/api/backend-registry/types";
+import { getMarsBridge } from "#/api/mars/mars-tunnel-backend";
import { BrandButton } from "#/components/features/settings/brand-button";
import { ConfirmationModal } from "#/components/shared/modals/confirmation-modal";
import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
@@ -22,6 +23,8 @@ import { modalTitleLgClassName } from "#/utils/modal-classes";
import { BackendFormModal } from "./backend-form-modal";
import { BackendRow } from "./backend-row";
import { DeviceFlowAuth } from "./device-flow-auth";
+import { ManagedAgentsView } from "./managed-agents/managed-agents-view";
+import { MarsBackendRemovalModal } from "./managed-agents/mars-backend-removal-modal";
import { useBackendSwitchRedirect } from "./use-backend-switch-redirect";
interface ManageBackendsModalProps {
@@ -31,11 +34,16 @@ interface ManageBackendsModalProps {
* app shell behind the modal, so dismiss controls would be misleading.
*/
recoveryMode?: boolean;
+ /** Open straight onto the DigitalOcean Managed Agents screen. */
+ initialView?: ManageBackendsView;
}
+export type ManageBackendsView = "backends" | "managed-agents";
+
interface PendingRemoval {
id: string;
name: string;
+ marsSessionId?: string;
}
/**
@@ -64,6 +72,7 @@ function resolveBackendOrgLabel(
export function ManageBackendsModal({
onClose,
recoveryMode = false,
+ initialView = "backends",
}: ManageBackendsModalProps) {
const { t } = useTranslation("openhands");
const { backends, active, removeBackend, setActive, updateBackend } =
@@ -95,7 +104,12 @@ export function ManageBackendsModal({
null,
);
const [showAddForm, setShowAddForm] = React.useState(false);
-
+ // The tunnel lives in the Electron main process, so the browser and library
+ // builds have nothing to offer here.
+ const showManagedAgents = getMarsBridge() !== null && !isLockedToCloud;
+ const [view, setView] = React.useState<ManageBackendsView>(
+ showManagedAgents ? initialView : "backends",
+ );
const handleConfirmRemoval = () => {
if (!pendingRemoval) return;
removeBackend(pendingRemoval.id);
@@ -131,21 +145,25 @@ export function ManageBackendsModal({
[lockedCloudBackend, updateBackend],
);
+ // A removal confirmation on top owns Escape and outside clicks; closing this
+ // modal under it would unmount it mid-stop and swallow a refused destroy.
+ const isClosable = !recoveryMode && pendingRemoval === null;
+
return (
<>
<ModalBackdrop
- onClose={recoveryMode ? undefined : onClose}
- closeOnEscape={!recoveryMode}
- closeOnBackdropClick={!recoveryMode}
+ onClose={isClosable ? onClose : undefined}
+ closeOnEscape={isClosable}
+ closeOnBackdropClick={isClosable}
aria-label={modalTitle}
>
<div
data-testid="manage-backends-modal"
className={cn(
"relative flex flex-col bg-surface border border-border rounded-xl",
- modalWidthClassName("lg"),
+ modalWidthClassName(view === "managed-agents" ? "xl" : "lg"),
MODAL_MAX_WIDTH_VIEWPORT,
- "max-h-[70vh]",
+ view === "managed-agents" ? "h-[80vh]" : "max-h-[70vh]",
)}
>
{recoveryMode ? null : (
@@ -154,87 +172,97 @@ export function ManageBackendsModal({
testId="close-manage-backends-modal"
/>
)}
- <div className={cn("p-5", !recoveryMode && "pr-12")}>
- <h2 className={modalTitleLgClassName}>{modalTitle}</h2>
- </div>
+ {view === "managed-agents" ? (
+ <ManagedAgentsView
+ onBack={() => setView("backends")}
+ onDone={onClose}
+ />
+ ) : (
+ <>
+ <div className={cn("p-5", !recoveryMode && "pr-12")}>
+ <h2 className={modalTitleLgClassName}>{modalTitle}</h2>
+ </div>
- <div className="flex min-h-0 flex-1 flex-col px-5">
- <div
- className="flex-1 overflow-auto rounded-md border border-border bg-surface-raised custom-scrollbar-always"
- data-testid="manage-backends-list"
- >
- {backends.length === 0 ? (
- <p className="px-3 py-6 text-center text-sm text-text-secondary">
- {t(I18nKey.BACKEND$MANAGE_EMPTY)}
- </p>
- ) : (
- <ul className="divide-y divide-border">
- {backends.map((backend) => (
- <BackendRow
- key={backend.id}
- backend={backend}
- health={healthByBackendId[backend.id]}
- orgLabel={resolveBackendOrgLabel(
- backend,
- cloudOrgs,
- currentUserIds,
- personalWorkspaceLabel,
- )}
- onSelect={() => handleSelectBackend(backend)}
- onEdit={() => setEditingBackend(backend)}
- onRemove={() =>
- setPendingRemoval({
- id: backend.id,
- name: backend.name,
- })
- }
- onLogin={
- backend.authMode === "cookie"
- ? undefined
- : (apiKey) => handleCloudLogin(backend, apiKey)
- }
- />
- ))}
- </ul>
- )}
- </div>
- </div>
+ <div className="flex min-h-0 flex-1 flex-col px-5">
+ <div
+ className="flex-1 overflow-auto rounded-md border border-border bg-surface-raised custom-scrollbar-always"
+ data-testid="manage-backends-list"
+ >
+ {backends.length === 0 ? (
+ <p className="px-3 py-6 text-center text-sm text-text-secondary">
+ {t(I18nKey.BACKEND$MANAGE_EMPTY)}
+ </p>
+ ) : (
+ <ul className="divide-y divide-border">
+ {backends.map((backend) => (
+ <BackendRow
+ key={backend.id}
+ backend={backend}
+ health={healthByBackendId[backend.id]}
+ orgLabel={resolveBackendOrgLabel(
+ backend,
+ cloudOrgs,
+ currentUserIds,
+ personalWorkspaceLabel,
+ )}
+ onSelect={() => handleSelectBackend(backend)}
+ onEdit={() => setEditingBackend(backend)}
+ onRemove={() =>
+ setPendingRemoval({
+ id: backend.id,
+ name: backend.name,
+ marsSessionId: backend.marsSessionId,
+ })
+ }
+ onLogin={
+ backend.authMode === "cookie"
+ ? undefined
+ : (apiKey) => handleCloudLogin(backend, apiKey)
+ }
+ />
+ ))}
+ </ul>
+ )}
+ </div>
+ </div>
- <div className="flex justify-end gap-2 p-5">
- {isLockedToCloud ? (
- lockedCloudBackend ? (
- <DeviceFlowAuth
- host={lockedCloudReconnectHost}
- onSuccess={handleLockedCloudReconnect}
- testIdRoot="manage-backends-reconnect-cloud"
- idleButtonLabel={t(I18nKey.BACKEND$RECONNECT_CLOUD)}
- className="w-full sm:w-auto"
- buttonClassName="w-full sm:w-auto"
- statusDisplay="modal"
- />
- ) : null
- ) : (
- <BrandButton
- type="button"
- variant={recoveryMode ? "primary" : "secondary"}
- onClick={() => setShowAddForm(true)}
- testId="manage-backends-add"
- startContent={<Plus width={14} height={14} />}
- >
- {t(I18nKey.BACKEND$ADD)}
- </BrandButton>
- )}
- {recoveryMode ? null : (
- <BrandButton
- type="button"
- variant="primary"
- onClick={onClose}
- testId="manage-backends-done"
- >
- {t(I18nKey.HOME$DONE)}
- </BrandButton>
- )}
- </div>
+ <div className="flex justify-end gap-2 p-5">
+ {isLockedToCloud ? (
+ lockedCloudBackend ? (
+ <DeviceFlowAuth
+ host={lockedCloudReconnectHost}
+ onSuccess={handleLockedCloudReconnect}
+ testIdRoot="manage-backends-reconnect-cloud"
+ idleButtonLabel={t(I18nKey.BACKEND$RECONNECT_CLOUD)}
+ className="w-full sm:w-auto"
+ buttonClassName="w-full sm:w-auto"
+ statusDisplay="modal"
+ />
+ ) : null
+ ) : (
+ <BrandButton
+ type="button"
+ variant={recoveryMode ? "primary" : "secondary"}
+ onClick={() => setShowAddForm(true)}
+ testId="manage-backends-add"
+ startContent={<Plus width={14} height={14} />}
+ >
+ {t(I18nKey.BACKEND$ADD)}
+ </BrandButton>
+ )}
+ {recoveryMode ? null : (
+ <BrandButton
+ type="button"
+ variant="primary"
+ onClick={onClose}
+ testId="manage-backends-done"
+ >
+ {t(I18nKey.HOME$DONE)}
+ </BrandButton>
+ )}
+ </div>
+ </>
+ )}
</div>
</ModalBackdrop>
@@ -254,7 +282,14 @@ export function ManageBackendsModal({
/>
) : null}
- {pendingRemoval ? (
+ {pendingRemoval?.marsSessionId ? (
+ <MarsBackendRemovalModal
+ name={pendingRemoval.name}
+ sessionId={pendingRemoval.marsSessionId}
+ onRemove={handleConfirmRemoval}
+ onCancel={() => setPendingRemoval(null)}
+ />
+ ) : pendingRemoval ? (
<ConfirmationModal
text={t(I18nKey.BACKEND$REMOVE_CONFIRMATION, {
name: pendingRemoval.name,
diff --git a/src/components/features/backends/managed-agents/account-bar.tsx b/src/components/features/backends/managed-agents/account-bar.tsx
new file mode 100644
index 0000000000..dd9ae15217
--- /dev/null
+++ b/src/components/features/backends/managed-agents/account-bar.tsx
@@ -0,0 +1,83 @@
+import { useTranslation } from "react-i18next";
+
+import type {
+ MarsAuthState,
+ MarsConnection,
+} from "#/api/mars/mars-tunnel-backend";
+import { I18nKey } from "#/i18n/declaration";
+
+interface AccountBarProps {
+ authState: MarsAuthState | undefined;
+ activeConnection: MarsConnection;
+ onSwitchConnection: (id: string) => void;
+ onAddConnection: () => void;
+ onSignOut: () => void;
+}
+
+/** The signed-in DigitalOcean team, with switch, add, and sign-out. */
+export function AccountBar({
+ authState,
+ activeConnection,
+ onSwitchConnection,
+ onAddConnection,
+ onSignOut,
+}: AccountBarProps) {
+ const { t } = useTranslation("openhands");
+ const connections = authState?.connections ?? [];
+
+ return (
+ <div
+ data-testid="managed-agents-account"
+ className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-md border border-border px-3 py-2 text-xs"
+ >
+ {connections.length > 1 ? (
+ <label className="flex min-w-0 flex-1 items-center gap-2 text-muted">
+ <span className="shrink-0">
+ {t(I18nKey.BACKEND$DIGITALOCEAN_SWITCH_CONNECTION)}
+ </span>
+ <select
+ value={activeConnection.id}
+ onChange={(event) => onSwitchConnection(event.target.value)}
+ data-testid="managed-agents-connection-switcher"
+ className="min-w-0 flex-1 cursor-pointer rounded border border-border bg-transparent px-1.5 py-0.5 text-white"
+ >
+ {connections.map((connection) => (
+ <option key={connection.id} value={connection.id}>
+ {connection.teamName ?? connection.label}
+ </option>
+ ))}
+ </select>
+ </label>
+ ) : (
+ <span className="flex min-w-0 flex-1 items-center gap-2 truncate text-white">
+ <span
+ aria-hidden
+ className="size-1.5 rounded-full bg-status-success"
+ />
+ {activeConnection.teamName ?? activeConnection.label}
+ </span>
+ )}
+ <button
+ type="button"
+ onClick={onAddConnection}
+ data-testid="managed-agents-add-connection"
+ className="cursor-pointer text-primary hover:underline"
+ >
+ {t(I18nKey.BACKEND$DIGITALOCEAN_ADD_CONNECTION)}
+ </button>
+ <button
+ type="button"
+ onClick={onSignOut}
+ data-testid="managed-agents-sign-out"
+ className="cursor-pointer text-muted hover:text-white"
+ >
+ {t(I18nKey.BACKEND$DIGITALOCEAN_SIGN_OUT)}
+ </button>
+ {authState?.isPersistent === false ? (
+ <p className="w-full text-warning">
+ {t(I18nKey.BACKEND$DIGITALOCEAN_NOT_PERSISTENT)}
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/src/components/features/backends/managed-agents/agent-group-section.tsx b/src/components/features/backends/managed-agents/agent-group-section.tsx
new file mode 100644
index 0000000000..b6dcba2672
--- /dev/null
+++ b/src/components/features/backends/managed-agents/agent-group-section.tsx
@@ -0,0 +1,103 @@
+import type React from "react";
+import { useTranslation } from "react-i18next";
+import { Loader2, Plus, Trash2 } from "lucide-react";
+
+import type { MarsAgentGroup } from "#/hooks/query/use-mars-agents";
+import { I18nKey } from "#/i18n/declaration";
+import { agentLabel, SESSION_COUNT_I18N_KEY } from "./managed-agents-labels";
+
+/** A filtered agent group plus counts taken from its unfiltered sessions. */
+export interface VisibleAgentGroup extends MarsAgentGroup {
+ totalSessions: number;
+ liveSessions: number;
+}
+
+interface AgentGroupSectionProps {
+ group: VisibleAgentGroup;
+ /** A session is being created for this agent. */
+ isCreating: boolean;
+ /** Any launch or connect is in flight. */
+ isLaunching: boolean;
+ error: string | null;
+ onNewSession: () => void;
+ onDeleteAgent: () => void;
+ children: React.ReactNode;
+}
+
+/** One agent's header, actions, and (as children) its session rows. */
+export function AgentGroupSection({
+ group,
+ isCreating,
+ isLaunching,
+ error,
+ onNewSession,
+ onDeleteAgent,
+ children,
+}: AgentGroupSectionProps) {
+ const { t } = useTranslation("openhands");
+ const { config, sessions, totalSessions, liveSessions } = group;
+ const deleteTitle =
+ liveSessions > 0
+ ? t(I18nKey.DO_AGENTS$DELETE_AGENT_BLOCKED)
+ : t(I18nKey.DO_AGENTS$DELETE_AGENT);
+
+ return (
+ <section
+ data-testid={`managed-agents-agent-${config.id}`}
+ className="overflow-hidden rounded-lg border border-border bg-surface-raised"
+ >
+ <header className="flex items-center gap-3 border-b border-border px-3 py-2">
+ <div className="flex min-w-0 flex-1 items-baseline gap-2">
+ <h4 className="truncate text-sm font-medium text-white">
+ {agentLabel(config)}
+ </h4>
+ <span className="shrink-0 text-xs text-muted">
+ {t(SESSION_COUNT_I18N_KEY, { count: totalSessions })}
+ </span>
+ </div>
+ <button
+ type="button"
+ onClick={onNewSession}
+ disabled={isLaunching}
+ data-testid={`managed-agents-new-session-${config.id}`}
+ className="inline-flex shrink-0 cursor-pointer items-center gap-1.5 rounded-md px-2 py-1 text-xs text-primary transition-colors hover:bg-interactive-hover disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ {isCreating ? (
+ <Loader2 className="size-3.5 animate-spin" aria-hidden />
+ ) : (
+ <Plus className="size-3.5" aria-hidden />
+ )}
+ {isCreating
+ ? t(I18nKey.BACKEND$DIGITALOCEAN_CREATING_SESSION)
+ : t(I18nKey.DO_AGENTS$NEW_SESSION)}
+ </button>
+ <button
+ type="button"
+ onClick={onDeleteAgent}
+ disabled={isLaunching || liveSessions > 0}
+ aria-label={t(I18nKey.DO_AGENTS$DELETE_AGENT)}
+ title={deleteTitle}
+ data-testid={`managed-agents-delete-agent-${config.id}`}
+ className="inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted transition-colors hover:bg-interactive-hover hover:text-status-error disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ <Trash2 className="size-3.5" aria-hidden />
+ </button>
+ </header>
+ {error ? (
+ <p
+ role="alert"
+ className="border-b border-border px-3 py-2 text-xs text-status-error"
+ >
+ {error}
+ </p>
+ ) : null}
+ {sessions.length > 0 ? (
+ <ul className="divide-y divide-border">{children}</ul>
+ ) : (
+ <p className="px-3 py-3 text-xs text-muted">
+ {t(I18nKey.DO_AGENTS$NO_SESSIONS)}
+ </p>
+ )}
+ </section>
+ );
+}
diff --git a/src/components/features/backends/managed-agents/digitalocean-connect-panel.tsx b/src/components/features/backends/managed-agents/digitalocean-connect-panel.tsx
new file mode 100644
index 0000000000..4f111b5372
--- /dev/null
+++ b/src/components/features/backends/managed-agents/digitalocean-connect-panel.tsx
@@ -0,0 +1,436 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { ChevronRight, Loader2, Plus, RefreshCw } from "lucide-react";
+
+import {
+ getMarsErrorMessage,
+ getSessionPhase,
+ isConnectableSession,
+ type MarsAgentConfig,
+ type MarsSession,
+ type NewMarsAgentInput,
+} from "#/api/mars/mars-tunnel-backend";
+import {
+ getUsableConnectionId,
+ useMarsAgents,
+ useMarsAuthState,
+ type MarsAgentGroup,
+} from "#/hooks/query/use-mars-agents";
+import { useLaunchMarsSession } from "#/hooks/use-launch-mars-session";
+import { useMarsSignIn } from "#/hooks/use-mars-sign-in";
+import { I18nKey } from "#/i18n/declaration";
+import { cn } from "#/utils/utils";
+import { DigitalOceanNewAgentForm } from "./digitalocean-new-agent-form";
+import {
+ agentLabel,
+ SESSION_COUNT_I18N_KEY,
+ STAGE_LABEL_KEY,
+} from "./managed-agents-labels";
+import { ManagedAgentsSignIn } from "./managed-agents-sign-in";
+import { SessionStatusDot } from "./session-status-dot";
+import {
+ getConnectStage,
+ useSessionActivityLabel,
+ useSessionMeta,
+} from "./use-session-meta";
+
+const PANEL_CLASS =
+ "flex min-h-[13.5rem] w-full flex-col rounded-xl border border-border";
+const ICON_BUTTON_CLASS =
+ "inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted hover:bg-interactive-hover hover:text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-300 disabled:cursor-not-allowed disabled:opacity-40";
+
+type Launcher = ReturnType<typeof useLaunchMarsSession>;
+
+interface SessionChildRowProps {
+ session: MarsSession;
+ launcher: Launcher;
+ onOpen: () => void;
+}
+
+function SessionChildRow({ session, launcher, onOpen }: SessionChildRowProps) {
+ const { t } = useTranslation("openhands");
+ const stage = getConnectStage(launcher.connecting, session);
+ const { name, phase, meta, stageLabel } = useSessionMeta(session, stage);
+
+ return (
+ <li>
+ <button
+ type="button"
+ onClick={onOpen}
+ disabled={launcher.isBusy || !isConnectableSession(session)}
+ aria-label={t(I18nKey.DO_AGENTS$OPEN_AGENT, { name })}
+ data-testid={`digitalocean-session-${session.session_id}`}
+ className="flex w-full min-w-0 cursor-pointer items-center gap-2.5 rounded-md px-2 py-1.5 text-left hover:bg-surface-raised focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-blue-300 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ <SessionStatusDot phase={phase} className="size-1.5" />
+ <span className="min-w-0 flex-1 truncate text-xs text-white">
+ {name}
+ </span>
+ <span className="shrink-0 truncate text-xs tabular-nums text-muted">
+ {stageLabel ?? meta}
+ </span>
+ {stage ? (
+ <Loader2
+ className="size-3.5 shrink-0 animate-spin text-muted"
+ aria-hidden
+ />
+ ) : null}
+ </button>
+ </li>
+ );
+}
+
+interface AgentRowProps {
+ group: MarsAgentGroup;
+ launcher: Launcher;
+ error: string | null;
+ onOpen: () => void;
+ onOpenSession: (session: MarsSession) => void;
+ onNewSession: () => void;
+}
+
+/** An agent with its sessions nested beneath it, collapsed by default. */
+function AgentRow({
+ group,
+ launcher,
+ error,
+ onOpen,
+ onOpenSession,
+ onNewSession,
+}: AgentRowProps) {
+ const { t } = useTranslation("openhands");
+ const [isExpanded, setIsExpanded] = React.useState(false);
+ const { config, sessions } = group;
+ const name = agentLabel(config);
+ const latest = sessions[0];
+ const activity = useSessionActivityLabel(latest);
+ const sessionIds = new Set(sessions.map((s) => s.session_id));
+ const stage =
+ launcher.connecting && sessionIds.has(launcher.connecting.sessionId)
+ ? launcher.connecting.stage
+ : null;
+ const isLaunching = launcher.launchingConfigId === config.id;
+ const isWorking = isLaunching || stage !== null;
+ const sessionsId = `digitalocean-agent-sessions-${config.id}`;
+
+ let meta: string;
+ if (isLaunching) meta = t(I18nKey.BACKEND$DIGITALOCEAN_CREATING_SESSION);
+ else if (stage) meta = t(STAGE_LABEL_KEY[stage]);
+ else if (!latest) meta = t(I18nKey.DO_AGENTS$NO_SESSIONS_SHORT);
+ else {
+ meta = [t(SESSION_COUNT_I18N_KEY, { count: sessions.length }), activity]
+ .filter(Boolean)
+ .join(" · ");
+ }
+
+ return (
+ <li data-testid={`digitalocean-agent-${config.id}`}>
+ <div className="flex items-center gap-1 pl-1 pr-2">
+ <button
+ type="button"
+ onClick={() => setIsExpanded((value) => !value)}
+ aria-expanded={isExpanded}
+ aria-controls={sessionsId}
+ aria-label={t(
+ isExpanded
+ ? I18nKey.DO_AGENTS$HIDE_SESSIONS
+ : I18nKey.DO_AGENTS$SHOW_SESSIONS,
+ { name },
+ )}
+ data-testid={`digitalocean-agent-toggle-${config.id}`}
+ className={cn(ICON_BUTTON_CLASS, "size-6")}
+ >
+ <ChevronRight
+ className={cn(
+ "size-4 transition-transform duration-150",
+ isExpanded && "rotate-90",
+ )}
+ aria-hidden
+ />
+ </button>
+ <button
+ type="button"
+ onClick={onOpen}
+ disabled={launcher.isBusy}
+ aria-label={t(I18nKey.DO_AGENTS$OPEN_AGENT, { name })}
+ data-testid={`digitalocean-agent-open-${config.id}`}
+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 rounded-lg px-2 py-2.5 text-left hover:bg-surface-raised focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-blue-300 disabled:cursor-not-allowed"
+ >
+ <span
+ aria-hidden
+ className="relative flex size-8 shrink-0 items-center justify-center rounded-md bg-surface-raised text-sm font-medium text-white"
+ >
+ {name.charAt(0).toUpperCase()}
+ {latest ? (
+ <SessionStatusDot
+ phase={getSessionPhase(latest.status)}
+ className="absolute -bottom-0.5 -right-0.5 ring-2 ring-surface"
+ />
+ ) : null}
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-sm text-white">{name}</span>
+ <span className="truncate text-xs tabular-nums text-muted">
+ {meta}
+ </span>
+ </span>
+ {isWorking ? (
+ <Loader2
+ className="size-4 shrink-0 animate-spin text-muted"
+ aria-hidden
+ />
+ ) : null}
+ </button>
+ <button
+ type="button"
+ onClick={onNewSession}
+ disabled={launcher.isBusy}
+ aria-label={t(I18nKey.DO_AGENTS$NEW_SESSION_FOR, { name })}
+ title={t(I18nKey.DO_AGENTS$NEW_SESSION)}
+ data-testid={`digitalocean-agent-new-${config.id}`}
+ className={ICON_BUTTON_CLASS}
+ >
+ <Plus className="size-4" aria-hidden />
+ </button>
+ </div>
+ {error ? (
+ <p
+ role="alert"
+ data-testid={`digitalocean-agent-error-${config.id}`}
+ className="mx-3 mb-2 text-pretty text-xs text-status-error"
+ >
+ {error}
+ </p>
+ ) : null}
+ {isExpanded ? (
+ <ul
+ id={sessionsId}
+ className="mb-1 ml-14 mr-2 flex flex-col border-l border-border pl-2"
+ >
+ {sessions.length === 0 ? (
+ <li className="px-2 py-1.5 text-xs text-muted">
+ {t(I18nKey.DO_AGENTS$NO_SESSIONS_SHORT)}
+ </li>
+ ) : (
+ sessions.map((session) => (
+ <SessionChildRow
+ key={session.session_id}
+ session={session}
+ launcher={launcher}
+ onOpen={() => onOpenSession(session)}
+ />
+ ))
+ )}
+ </ul>
+ ) : null}
+ </li>
+ );
+}
+
+interface DigitalOceanConnectPanelProps {
+ /** A session is open and the user is now in its conversation. */
+ onConnected: () => void;
+}
+
+/**
+ * The "DigitalOcean" option in the connect chooser: sign in once, then pick
+ * one of the team's OpenHands agents (or create one) to open. Each agent
+ * lists its sessions beneath it; opening the agent itself resumes its latest
+ * session (or starts its first).
+ */
+export function DigitalOceanConnectPanel({
+ onConnected,
+}: DigitalOceanConnectPanelProps) {
+ const { t } = useTranslation("openhands");
+ const authQuery = useMarsAuthState();
+ const authState = authQuery.data;
+ const connectionId = getUsableConnectionId(authState);
+ const agentsQuery = useMarsAgents(connectionId);
+ const signIn = useMarsSignIn();
+ const launcher = useLaunchMarsSession();
+ const [failure, setFailure] = React.useState<{
+ configId: string;
+ message: string;
+ } | null>(null);
+ const [isNewAgentOpen, setIsNewAgentOpen] = React.useState(false);
+ const [newAgentError, setNewAgentError] = React.useState<string | null>(null);
+
+ const run = async (configId: string, action: () => Promise<unknown>) => {
+ setFailure(null);
+ try {
+ await action();
+ onConnected();
+ } catch (error) {
+ setFailure({ configId, message: launcher.describeError(error) });
+ }
+ };
+
+ const createAgent = async (input: NewMarsAgentInput) => {
+ setNewAgentError(null);
+ let config: MarsAgentConfig;
+ try {
+ config = await launcher.createAgent(input);
+ } catch (error) {
+ setNewAgentError(launcher.describeError(error));
+ return;
+ }
+ setIsNewAgentOpen(false);
+ await run(config.id, () => launcher.launch(config));
+ };
+
+ const closeNewAgent = () => {
+ setIsNewAgentOpen(false);
+ setNewAgentError(null);
+ };
+
+ if (authQuery.isPending) {
+ return (
+ <div className={cn(PANEL_CLASS, "items-center justify-center")}>
+ <Loader2 className="size-5 animate-spin text-muted" aria-hidden />
+ </div>
+ );
+ }
+
+ if (!connectionId) {
+ return (
+ <div
+ data-testid="digitalocean-connect-panel"
+ className={cn(PANEL_CLASS, "items-center justify-center px-5")}
+ >
+ <ManagedAgentsSignIn
+ showBranding={false}
+ canUseOAuth={authState?.canUseOAuth ?? false}
+ isExpired={authState?.active?.isExpired === true}
+ isSigningIn={signIn.isSigningIn}
+ isSavingToken={signIn.isSavingToken}
+ error={signIn.error}
+ onSignInWithOAuth={signIn.signInWithOAuth}
+ onSaveToken={signIn.saveToken}
+ />
+ </div>
+ );
+ }
+
+ const groups = agentsQuery.data?.groups ?? [];
+ const active = authState?.active;
+
+ return (
+ <div data-testid="digitalocean-connect-panel" className={PANEL_CLASS}>
+ <div className="flex items-center gap-2 px-4 pb-2 pt-3">
+ <h3 className="min-w-0 flex-1 truncate text-sm font-medium text-white">
+ {t(I18nKey.DO_AGENTS$AGENTS_HEADING)}
+ </h3>
+ <button
+ type="button"
+ onClick={() =>
+ isNewAgentOpen ? closeNewAgent() : setIsNewAgentOpen(true)
+ }
+ disabled={launcher.isBusy}
+ aria-expanded={isNewAgentOpen}
+ data-testid="digitalocean-new-agent"
+ className={cn(
+ "inline-flex h-8 shrink-0 cursor-pointer items-center gap-1.5 rounded-md px-2.5 text-xs font-medium text-muted hover:bg-interactive-hover hover:text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-300 disabled:cursor-not-allowed disabled:opacity-40",
+ isNewAgentOpen && "bg-interactive-hover text-white",
+ )}
+ >
+ <Plus className="size-4" aria-hidden />
+ {t(I18nKey.DO_AGENTS$NEW_AGENT)}
+ </button>
+ <button
+ type="button"
+ onClick={() => void agentsQuery.refetch()}
+ aria-label={t(I18nKey.BACKEND$DIGITALOCEAN_AGENTS_REFRESH)}
+ title={t(I18nKey.BACKEND$DIGITALOCEAN_AGENTS_REFRESH)}
+ data-testid="digitalocean-agents-refresh"
+ className={ICON_BUTTON_CLASS}
+ >
+ <RefreshCw
+ className={cn("size-4", agentsQuery.isFetching && "animate-spin")}
+ aria-hidden
+ />
+ </button>
+ </div>
+
+ {isNewAgentOpen ? (
+ <DigitalOceanNewAgentForm
+ isCreating={launcher.isCreatingAgent}
+ error={newAgentError}
+ onSubmit={(input) => void createAgent(input)}
+ onCancel={closeNewAgent}
+ />
+ ) : null}
+
+ <div className="max-h-72 min-h-0 flex-1 overflow-y-auto px-1 custom-scrollbar-always">
+ {agentsQuery.isPending ? (
+ <p className="px-3 py-6 text-center text-sm text-muted">
+ {t(I18nKey.BACKEND$DIGITALOCEAN_AGENTS_LOADING)}
+ </p>
+ ) : null}
+ {agentsQuery.error ? (
+ <p
+ role="alert"
+ className="mx-3 my-2 text-pretty text-sm text-status-error"
+ >
+ {getMarsErrorMessage(agentsQuery.error) ??
+ t(I18nKey.BACKEND$DIGITALOCEAN_AGENTS_FAILED)}
+ </p>
+ ) : null}
+ {agentsQuery.data && groups.length === 0 && !isNewAgentOpen ? (
+ <p
+ data-testid="digitalocean-agents-empty"
+ className="mx-auto max-w-sm px-3 py-6 text-center text-pretty text-sm text-muted"
+ >
+ {t(I18nKey.DO_AGENTS$NO_OPENHANDS_AGENTS)}
+ </p>
+ ) : null}
+ {groups.length > 0 ? (
+ <ul className="flex flex-col">
+ {groups.map((group) => (
+ <AgentRow
+ key={group.config.id}
+ group={group}
+ launcher={launcher}
+ error={
+ failure?.configId === group.config.id ? failure.message : null
+ }
+ onOpen={() =>
+ void run(group.config.id, () => launcher.openAgent(group))
+ }
+ onOpenSession={(session) =>
+ void run(group.config.id, () =>
+ launcher.open(session, group.config),
+ )
+ }
+ onNewSession={() =>
+ void run(group.config.id, () => launcher.launch(group.config))
+ }
+ />
+ ))}
+ </ul>
+ ) : null}
+ </div>
+
+ <div className="mt-2 flex items-center gap-3 border-t border-border px-4 py-2.5 text-xs">
+ <span
+ aria-hidden
+ className="size-1.5 shrink-0 rounded-full bg-status-success"
+ />
+ <span
+ data-testid="digitalocean-account"
+ className="min-w-0 flex-1 truncate text-muted"
+ >
+ {active?.teamName ?? active?.label}
+ </span>
+ <button
+ type="button"
+ onClick={signIn.signOut}
+ disabled={signIn.isSigningOut}
+ data-testid="digitalocean-sign-out"
+ className="shrink-0 cursor-pointer text-muted hover:text-white disabled:cursor-not-allowed"
+ >
+ {t(I18nKey.BACKEND$DIGITALOCEAN_SIGN_OUT)}
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/features/backends/managed-agents/digitalocean-new-agent-form.tsx b/src/components/features/backends/managed-agents/digitalocean-new-agent-form.tsx
new file mode 100644
index 0000000000..2ad0e25609
--- /dev/null
+++ b/src/components/features/backends/managed-agents/digitalocean-new-agent-form.tsx
@@ -0,0 +1,178 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { Loader2 } from "lucide-react";
+
+import type { TFunction } from "i18next";
+
+import {
+ buildNewSessionName,
+ isValidAgentName,
+ type MarsSandboxSize,
+ type NewMarsAgentInput,
+} from "#/api/mars/mars-tunnel-backend";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { SettingsDropdownInput } from "#/components/features/settings/settings-dropdown-input";
+import { SettingsInput } from "#/components/features/settings/settings-input";
+import { useMarsSandboxSizes } from "#/hooks/query/use-mars-agents";
+import { I18nKey } from "#/i18n/declaration";
+import { cn } from "#/utils/utils";
+
+const DEFAULT_NAME_STEM = "openhands";
+const NAME_HINT_ID = "digitalocean-new-agent-name-hint";
+const HELPER_CLASS = "-mt-1 text-pretty text-xs text-muted";
+/** Never a valid slug, so it cannot collide with a real size. */
+const DEFAULT_SIZE_KEY = "__default__";
+const MB_PER_GB = 1024;
+
+function formatSizeLabel(
+ size: MarsSandboxSize,
+ t: TFunction,
+ language: string,
+): string {
+ const params = {
+ vcpus: size.vcpus,
+ memory: Number((size.memory_mb / MB_PER_GB).toFixed(2)),
+ };
+ if (typeof size.price_per_month_usd !== "number") {
+ return t(I18nKey.DO_AGENTS$SANDBOX_SIZE_OPTION, params);
+ }
+ const price = new Intl.NumberFormat(language, {
+ style: "currency",
+ currency: "USD",
+ maximumFractionDigits: 2,
+ }).format(size.price_per_month_usd);
+ return t(I18nKey.DO_AGENTS$SANDBOX_SIZE_OPTION_PRICE, { ...params, price });
+}
+
+interface DigitalOceanNewAgentFormProps {
+ isCreating: boolean;
+ error: string | null;
+ onSubmit: (input: NewMarsAgentInput) => void;
+ onCancel: () => void;
+}
+
+/** Name and sandbox size for a new OpenHands agent on DigitalOcean. */
+export function DigitalOceanNewAgentForm({
+ isCreating,
+ error,
+ onSubmit,
+ onCancel,
+}: DigitalOceanNewAgentFormProps) {
+ const { t, i18n } = useTranslation("openhands");
+ const [name, setName] = React.useState(() =>
+ buildNewSessionName(DEFAULT_NAME_STEM),
+ );
+ const [sizeKey, setSizeKey] = React.useState(DEFAULT_SIZE_KEY);
+ // A failed or pending catalog just leaves the default; it never blocks create.
+ const { data: sizes } = useMarsSandboxSizes();
+ const trimmedName = name.trim();
+ const isNameValid = isValidAgentName(trimmedName);
+ const showNameError = trimmedName !== "" && !isNameValid;
+
+ const sizeItems = React.useMemo(
+ () => [
+ {
+ key: DEFAULT_SIZE_KEY,
+ label: t(I18nKey.DO_AGENTS$SANDBOX_SIZE_DEFAULT),
+ },
+ ...(sizes ?? []).map((size) => ({
+ key: size.slug,
+ label: formatSizeLabel(size, t, i18n.language),
+ })),
+ ],
+ [sizes, t, i18n.language],
+ );
+
+ const submit = (event: React.FormEvent) => {
+ event.preventDefault();
+ if (!isNameValid || isCreating) return;
+ onSubmit({
+ name: trimmedName,
+ size: sizeKey === DEFAULT_SIZE_KEY ? undefined : sizeKey,
+ });
+ };
+
+ return (
+ <form
+ onSubmit={submit}
+ data-testid="digitalocean-new-agent-form"
+ className="flex flex-col gap-4 border-b border-border px-4 pb-4 pt-1"
+ >
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
+ <div className="flex min-w-0 flex-col gap-2">
+ <SettingsInput
+ testId="digitalocean-new-agent-name"
+ name="digitalocean-new-agent-name"
+ type="text"
+ label={t(I18nKey.DO_AGENTS$NEW_AGENT_NAME_LABEL)}
+ value={name}
+ onChange={setName}
+ isDisabled={isCreating}
+ ariaInvalid={showNameError}
+ ariaDescribedBy={NAME_HINT_ID}
+ inputClassName={cn(showNameError && "border-danger")}
+ />
+ <p
+ id={NAME_HINT_ID}
+ className={cn(HELPER_CLASS, showNameError && "text-feedback-error")}
+ >
+ {t(I18nKey.DO_AGENTS$NEW_AGENT_NAME_HINT)}
+ </p>
+ </div>
+ <div className="flex min-w-0 flex-col gap-2">
+ <SettingsDropdownInput
+ testId="digitalocean-new-agent-size"
+ name="digitalocean-new-agent-size"
+ label={t(I18nKey.DO_AGENTS$SANDBOX_SIZE)}
+ items={sizeItems}
+ selectedKey={sizeKey}
+ onSelectionChange={(key) =>
+ setSizeKey(key === null ? DEFAULT_SIZE_KEY : String(key))
+ }
+ onInputChange={() => {}}
+ isClearable={false}
+ allowsCustomValue={false}
+ isDisabled={isCreating}
+ />
+ <p className={HELPER_CLASS}>
+ {t(I18nKey.DO_AGENTS$SANDBOX_SIZE_HINT)}
+ </p>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <p
+ role={error ? "alert" : undefined}
+ data-testid={error ? "digitalocean-new-agent-error" : undefined}
+ className="min-w-0 flex-1 text-pretty text-xs text-status-error"
+ >
+ {error}
+ </p>
+ <BrandButton
+ type="button"
+ variant="secondary"
+ onClick={onCancel}
+ isDisabled={isCreating}
+ testId="digitalocean-new-agent-cancel"
+ >
+ {t(I18nKey.BUTTON$CANCEL)}
+ </BrandButton>
+ <BrandButton
+ type="submit"
+ variant="primary"
+ isDisabled={!isNameValid || isCreating}
+ testId="digitalocean-new-agent-submit"
+ startContent={
+ isCreating ? (
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ ) : null
+ }
+ >
+ {isCreating
+ ? t(I18nKey.DO_AGENTS$CREATING_AGENT)
+ : t(I18nKey.DO_AGENTS$NEW_AGENT_CREATE)}
+ </BrandButton>
+ </div>
+ </form>
+ );
+}
diff --git a/src/components/features/backends/managed-agents/managed-agents-labels.ts b/src/components/features/backends/managed-agents/managed-agents-labels.ts
new file mode 100644
index 0000000000..86e322a049
--- /dev/null
+++ b/src/components/features/backends/managed-agents/managed-agents-labels.ts
@@ -0,0 +1,69 @@
+import type { TFunction } from "i18next";
+
+import type {
+ MarsAgentConfig,
+ MarsSession,
+ MarsSessionPhase,
+} from "#/api/mars/mars-tunnel-backend";
+import type { MarsConnectStage } from "#/hooks/use-connect-mars-session";
+import { I18nKey } from "#/i18n/declaration";
+
+const SHORT_ID_LENGTH = 8;
+
+export const PHASE_DOT_CLASS: Record<MarsSessionPhase, string> = {
+ ready:
+ "bg-status-success shadow-[0_0_0_3px_color-mix(in_srgb,var(--oh-status-success)_22%,transparent)]",
+ paused: "bg-warning",
+ starting: "bg-interactive-selected animate-pulse",
+ failed: "bg-status-error",
+ ended: "bg-text-tertiary",
+};
+
+export const PHASE_LABEL_KEY: Record<MarsSessionPhase, I18nKey> = {
+ ready: I18nKey.COMMON$RUNNING,
+ paused: I18nKey.DO_AGENTS$STATUS_PAUSED,
+ starting: I18nKey.COMMON$STARTING,
+ failed: I18nKey.DO_AGENTS$STATUS_FAILED,
+ ended: I18nKey.DO_AGENTS$STATUS_ENDED,
+};
+
+export const STAGE_LABEL_KEY: Record<MarsConnectStage, I18nKey> = {
+ waking: I18nKey.DO_AGENTS$STAGE_WAKING,
+ tunnel: I18nKey.DO_AGENTS$STAGE_TUNNEL,
+ agent: I18nKey.DO_AGENTS$STAGE_AGENT,
+};
+
+export function shortSessionId(session: MarsSession): string {
+ return session.session_id.slice(0, SHORT_ID_LENGTH);
+}
+
+export function agentLabel(config: MarsAgentConfig): string {
+ return config.name?.trim() || config.id;
+}
+
+export function getSessionDisplayName(
+ session: MarsSession,
+ t: TFunction<"openhands">,
+): string {
+ return (
+ session.name?.trim() ||
+ t(I18nKey.DO_AGENTS$SESSION_NAME_FALLBACK, { id: shortSessionId(session) })
+ );
+}
+
+/**
+ * Just the session's name: sessions launched here already carry their agent's
+ * name as a prefix, so repeating the agent only cluttered the backend menu.
+ */
+export function buildMarsBackendName(
+ session: MarsSession,
+ t: TFunction<"openhands">,
+): string {
+ return getSessionDisplayName(session, t);
+}
+
+/**
+ * Plural key (`_zero` … `_other` entries in translation.json), so it is not
+ * an `I18nKey` member; pass `{ count }`.
+ */
+export const SESSION_COUNT_I18N_KEY = "DO_AGENTS$SESSION_COUNT";
diff --git a/src/components/features/backends/managed-agents/managed-agents-session-row.tsx b/src/components/features/backends/managed-agents/managed-agents-session-row.tsx
new file mode 100644
index 0000000000..ae3434cae1
--- /dev/null
+++ b/src/components/features/backends/managed-agents/managed-agents-session-row.tsx
@@ -0,0 +1,187 @@
+import { useTranslation } from "react-i18next";
+import { Loader2, Pause, Square, Unplug } from "lucide-react";
+
+import {
+ isConnectableSession,
+ type MarsSession,
+} from "#/api/mars/mars-tunnel-backend";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import type { MarsConnectStage } from "#/hooks/use-connect-mars-session";
+import { I18nKey } from "#/i18n/declaration";
+import { cn } from "#/utils/utils";
+import { shortSessionId } from "./managed-agents-labels";
+import { SessionStatusDot } from "./session-status-dot";
+import { useSessionMeta } from "./use-session-meta";
+
+const ICON_BUTTON_CLASS =
+ "inline-flex size-8 cursor-pointer items-center justify-center rounded-md text-muted transition-colors hover:bg-interactive-hover hover:text-white disabled:cursor-not-allowed disabled:opacity-40";
+
+interface ManagedAgentsSessionRowProps {
+ session: MarsSession;
+ isConnected: boolean;
+ /** Set while this row's connect flow is running. */
+ connectStage: MarsConnectStage | null;
+ /** Another row is connecting or this row has a pause or stop in flight. */
+ isBusy: boolean;
+ error: string | null;
+ onConnect: () => void;
+ onOpen: () => void;
+ onDisconnect: () => void;
+ onPause: () => void;
+ /** Ends the session for good; the parent confirms before calling. */
+ onStop: () => void;
+}
+
+export function ManagedAgentsSessionRow({
+ session,
+ isConnected,
+ connectStage,
+ isBusy,
+ error,
+ onConnect,
+ onOpen,
+ onDisconnect,
+ onPause,
+ onStop,
+}: ManagedAgentsSessionRowProps) {
+ const { t } = useTranslation("openhands");
+ const { name, phase, meta, stageLabel } = useSessionMeta(
+ session,
+ connectStage,
+ );
+ const isConnecting = connectStage !== null;
+ const canConnect = isConnectableSession(session);
+ // Anything not already over can be stopped, including a failed or stuck
+ // provisioning session whose sandbox still needs tearing down.
+ const canStop = phase !== "ended";
+ const stopButton = canStop ? (
+ <button
+ type="button"
+ onClick={onStop}
+ disabled={isBusy}
+ aria-label={t(I18nKey.DO_AGENTS$STOP)}
+ title={t(I18nKey.DO_AGENTS$STOP)}
+ data-testid={`managed-agents-stop-${session.session_id}`}
+ className={ICON_BUTTON_CLASS}
+ >
+ <Square className="size-4" aria-hidden />
+ </button>
+ ) : null;
+
+ return (
+ <li
+ data-testid={`managed-agents-session-${session.session_id}`}
+ className={cn(
+ "flex flex-col gap-1 border-l-2 px-3 py-2.5",
+ isConnected ? "border-l-primary" : "border-l-transparent",
+ )}
+ >
+ <div className="flex items-center gap-3">
+ <SessionStatusDot phase={phase} />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-sm text-white" title={name}>
+ {name}
+ </span>
+ <span
+ className="truncate text-xs text-muted"
+ data-testid={`managed-agents-session-status-${session.session_id}`}
+ >
+ {meta}
+ <span className="ml-2 font-mono text-[11px] text-text-tertiary">
+ {shortSessionId(session)}
+ </span>
+ </span>
+ </div>
+
+ <div className="flex shrink-0 items-center gap-1.5">
+ {isConnecting ? (
+ <span
+ role="status"
+ aria-live="polite"
+ data-testid={`managed-agents-connecting-${session.session_id}`}
+ className="flex items-center gap-2 text-xs text-muted"
+ >
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ {stageLabel}
+ </span>
+ ) : null}
+
+ {!isConnecting && isConnected ? (
+ <>
+ <span className="rounded-full border border-primary/40 px-2 py-0.5 text-[11px] uppercase tracking-wide text-primary">
+ {t(I18nKey.DO_AGENTS$CONNECTED)}
+ </span>
+ <button
+ type="button"
+ onClick={onDisconnect}
+ disabled={isBusy}
+ aria-label={t(I18nKey.BUTTON$DISCONNECT)}
+ title={t(I18nKey.BUTTON$DISCONNECT)}
+ data-testid={`managed-agents-disconnect-${session.session_id}`}
+ className={ICON_BUTTON_CLASS}
+ >
+ <Unplug className="size-4" aria-hidden />
+ </button>
+ {stopButton}
+ <BrandButton
+ type="button"
+ variant="secondary"
+ onClick={onOpen}
+ testId={`managed-agents-open-${session.session_id}`}
+ className="h-8"
+ >
+ {t(I18nKey.DO_AGENTS$OPEN)}
+ </BrandButton>
+ </>
+ ) : null}
+
+ {!isConnecting && !isConnected && canConnect ? (
+ <>
+ {phase === "ready" ? (
+ <button
+ type="button"
+ onClick={onPause}
+ disabled={isBusy}
+ aria-label={t(I18nKey.DO_AGENTS$PAUSE)}
+ title={t(I18nKey.DO_AGENTS$PAUSE)}
+ data-testid={`managed-agents-pause-${session.session_id}`}
+ className={ICON_BUTTON_CLASS}
+ >
+ <Pause className="size-4" aria-hidden />
+ </button>
+ ) : null}
+ {stopButton}
+ <BrandButton
+ type="button"
+ variant="primary"
+ onClick={onConnect}
+ isDisabled={isBusy}
+ testId={`managed-agents-connect-${session.session_id}`}
+ className="h-8"
+ >
+ {phase === "paused"
+ ? t(I18nKey.DO_AGENTS$RESUME_AND_CONNECT)
+ : t(I18nKey.BACKEND$CONNECT)}
+ </BrandButton>
+ </>
+ ) : null}
+
+ {/* The main action (Open / Connect) is always rightmost, with Stop
+ just left of it (rendered above), so the destructive action is
+ never mistaken for part of it. */}
+ {!isConnecting && !isConnected && !canConnect ? stopButton : null}
+ </div>
+ </div>
+
+ {error ? (
+ <p
+ role="alert"
+ data-testid={`managed-agents-session-error-${session.session_id}`}
+ className="pl-5 text-xs text-status-error whitespace-pre-wrap break-words"
+ >
+ {error}
+ </p>
+ ) : null}
+ </li>
+ );
+}
diff --git a/src/components/features/backends/managed-agents/managed-agents-sign-in.tsx b/src/components/features/backends/managed-agents/managed-agents-sign-in.tsx
new file mode 100644
index 0000000000..6fd37a7a60
--- /dev/null
+++ b/src/components/features/backends/managed-agents/managed-agents-sign-in.tsx
@@ -0,0 +1,157 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { ExternalLink, Loader2 } from "lucide-react";
+
+import DigitalOceanLogo from "#/assets/branding/digitalocean-logo.svg?react";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { SettingsInput } from "#/components/features/settings/settings-input";
+import { ErrorAlert } from "#/components/shared/error-alert";
+import { I18nKey } from "#/i18n/declaration";
+
+export const DO_CREATE_TOKEN_URL =
+ "https://cloud.digitalocean.com/account/api/tokens";
+
+interface ManagedAgentsSignInProps {
+ canUseOAuth: boolean;
+ isExpired: boolean;
+ isSigningIn: boolean;
+ isSavingToken: boolean;
+ error: string | null;
+ onSignInWithOAuth: () => void;
+ onSaveToken: (token: string) => void;
+ /** Offered when adding a second connection, to return to the list. */
+ onCancel?: () => void;
+ /** Off where the surrounding tab already shows the DigitalOcean logo. */
+ showBranding?: boolean;
+}
+
+/**
+ * OAuth is one click when this build has a registered client; otherwise the
+ * token field is the primary path rather than hiding behind a disclosure.
+ */
+export function ManagedAgentsSignIn({
+ canUseOAuth,
+ isExpired,
+ isSigningIn,
+ isSavingToken,
+ error,
+ onSignInWithOAuth,
+ onSaveToken,
+ onCancel,
+ showBranding = true,
+}: ManagedAgentsSignInProps) {
+ const { t } = useTranslation("openhands");
+ const [token, setToken] = React.useState("");
+ const isBusy = isSigningIn || isSavingToken;
+
+ const submitToken = (event: React.FormEvent) => {
+ event.preventDefault();
+ if (token.trim() && !isBusy) onSaveToken(token);
+ };
+
+ return (
+ <div
+ data-testid="managed-agents-sign-in"
+ className="mx-auto flex w-full max-w-sm flex-col items-center gap-4 py-6"
+ >
+ {showBranding ? (
+ <div className="flex size-14 items-center justify-center rounded-2xl border border-border bg-surface-raised">
+ <DigitalOceanLogo width={32} height={32} aria-hidden />
+ </div>
+ ) : null}
+ <div className="flex flex-col items-center gap-1.5 text-center">
+ <h3 className="text-balance text-base font-medium text-white">
+ {t(I18nKey.DO_AGENTS$SIGN_IN_TITLE)}
+ </h3>
+ <p className="text-pretty text-sm leading-relaxed text-muted">
+ {t(I18nKey.DO_AGENTS$SIGN_IN_DESCRIPTION)}
+ </p>
+ </div>
+
+ {isExpired ? (
+ <p
+ data-testid="managed-agents-expired"
+ className="w-full rounded-md border border-warning/40 bg-warning/10 p-2.5 text-center text-xs text-warning"
+ >
+ {t(I18nKey.BACKEND$DIGITALOCEAN_EXPIRED)}
+ </p>
+ ) : null}
+
+ {canUseOAuth ? (
+ <BrandButton
+ type="button"
+ variant="primary"
+ isDisabled={isBusy}
+ onClick={onSignInWithOAuth}
+ testId="managed-agents-oauth"
+ className="w-full"
+ startContent={
+ isSigningIn ? (
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ ) : null
+ }
+ >
+ {isSigningIn
+ ? t(I18nKey.BACKEND$DIGITALOCEAN_SIGNING_IN)
+ : t(I18nKey.BACKEND$DIGITALOCEAN_SIGN_IN)}
+ </BrandButton>
+ ) : null}
+
+ <form onSubmit={submitToken} className="flex w-full flex-col gap-2">
+ <SettingsInput
+ testId="managed-agents-token"
+ name="managed-agents-token"
+ type="password"
+ label={t(I18nKey.BACKEND$DIGITALOCEAN_TOKEN_LABEL)}
+ value={token}
+ onChange={setToken}
+ placeholder=""
+ className="w-full"
+ />
+ <p className="text-xs leading-relaxed text-muted">
+ {t(I18nKey.BACKEND$DIGITALOCEAN_TOKEN_HINT)}{" "}
+ <a
+ href={DO_CREATE_TOKEN_URL}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex items-center gap-1 text-primary hover:underline"
+ >
+ {t(I18nKey.DO_AGENTS$CREATE_TOKEN)}
+ <ExternalLink className="size-3" aria-hidden />
+ </a>
+ </p>
+ <BrandButton
+ type="submit"
+ variant={canUseOAuth ? "secondary" : "primary"}
+ isDisabled={!token.trim() || isBusy}
+ testId="managed-agents-token-submit"
+ className="w-full"
+ startContent={
+ isSavingToken ? (
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ ) : null
+ }
+ >
+ {t(I18nKey.BACKEND$DIGITALOCEAN_TOKEN_SUBMIT)}
+ </BrandButton>
+ </form>
+
+ {error ? (
+ <ErrorAlert testId="managed-agents-auth-error" className="w-full">
+ {error}
+ </ErrorAlert>
+ ) : null}
+
+ {onCancel ? (
+ <button
+ type="button"
+ onClick={onCancel}
+ data-testid="managed-agents-sign-in-cancel"
+ className="cursor-pointer text-xs text-muted hover:text-white"
+ >
+ {t(I18nKey.BUTTON$CANCEL)}
+ </button>
+ ) : null}
+ </div>
+ );
+}
diff --git a/src/components/features/backends/managed-agents/managed-agents-view.tsx b/src/components/features/backends/managed-agents/managed-agents-view.tsx
new file mode 100644
index 0000000000..b63f4a0fc1
--- /dev/null
+++ b/src/components/features/backends/managed-agents/managed-agents-view.tsx
@@ -0,0 +1,527 @@
+import React from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { useTranslation } from "react-i18next";
+import { Loader2, RefreshCw, Search } from "lucide-react";
+
+import DigitalOceanLogo from "#/assets/branding/digitalocean-logo.svg?react";
+import {
+ getMarsErrorMessage,
+ getSessionPhase,
+ requireMarsBridge,
+ type MarsAgentConfig,
+ type MarsSession,
+} from "#/api/mars/mars-tunnel-backend";
+import type { Backend } from "#/api/backend-registry/types";
+import { SegmentedToggle } from "#/components/features/files-tab/segmented-toggle";
+import { BackNavButton } from "#/components/shared/buttons/back-nav-button";
+import { ErrorAlert } from "#/components/shared/error-alert";
+import { ConfirmationModal } from "#/components/shared/modals/confirmation-modal";
+import { useActiveBackendContext } from "#/contexts/active-backend-context";
+import { MARS_QUERY_KEYS } from "#/hooks/query/query-keys";
+import {
+ useMarsAgents,
+ useMarsAuthState,
+ type MarsAgentsSnapshot,
+} from "#/hooks/query/use-mars-agents";
+import {
+ MarsLaunchConnectError,
+ useLaunchMarsSession,
+} from "#/hooks/use-launch-mars-session";
+import { useMarsSignIn } from "#/hooks/use-mars-sign-in";
+import { useMarsTunnelBackend } from "#/hooks/use-mars-tunnel-backend";
+import { I18nKey } from "#/i18n/declaration";
+import { cn } from "#/utils/utils";
+import { AccountBar } from "./account-bar";
+import {
+ AgentGroupSection,
+ type VisibleAgentGroup,
+} from "./agent-group-section";
+import { ManagedAgentsSignIn } from "./managed-agents-sign-in";
+import { ManagedAgentsSessionRow } from "./managed-agents-session-row";
+import { agentLabel, getSessionDisplayName } from "./managed-agents-labels";
+import { getConnectStage } from "./use-session-meta";
+
+/** A destructive action awaiting the user's confirmation. */
+type PendingAction =
+ | { kind: "stop"; session: MarsSession }
+ | { kind: "delete-agent"; config: MarsAgentConfig };
+
+/** A session that is still around to be stopped (or must be, before its agent goes). */
+function isLiveSession(session: MarsSession): boolean {
+ return getSessionPhase(session.status) !== "ended";
+}
+
+type StatusFilter = "all" | "ready" | "paused";
+
+const STATUS_FILTERS: { value: StatusFilter; label: I18nKey }[] = [
+ { value: "all", label: I18nKey.DO_AGENTS$FILTER_ALL },
+ { value: "ready", label: I18nKey.COMMON$RUNNING },
+ { value: "paused", label: I18nKey.DO_AGENTS$STATUS_PAUSED },
+];
+
+interface ManagedAgentsViewProps {
+ onBack: () => void;
+ /** Leave the backends modal entirely — used once a session is opened. */
+ onDone: () => void;
+}
+
+function matchesQuery(text: string | null | undefined, query: string) {
+ return (text ?? "").toLowerCase().includes(query);
+}
+
+/**
+ * Groups and other sessions left after the search and status filter. Each
+ * group keeps the counts of its unfiltered sessions for the header and for
+ * gating Delete agent.
+ */
+function filterAgents(
+ data: MarsAgentsSnapshot | undefined,
+ query: string,
+ statusFilter: StatusFilter,
+): { groups: VisibleAgentGroup[]; otherSessions: MarsSession[] } {
+ const normalizedQuery = query.trim().toLowerCase();
+ const filterSessions = (sessions: MarsSession[], agentMatches: boolean) =>
+ sessions.filter((session) => {
+ const phase = getSessionPhase(session.status);
+ if (statusFilter !== "all" && phase !== statusFilter) return false;
+ if (!normalizedQuery || agentMatches) return true;
+ return (
+ matchesQuery(session.name, normalizedQuery) ||
+ matchesQuery(session.session_id, normalizedQuery)
+ );
+ });
+
+ const groups = (data?.groups ?? [])
+ .map((group): VisibleAgentGroup & { agentMatches: boolean } => {
+ const agentMatches =
+ !normalizedQuery ||
+ matchesQuery(agentLabel(group.config), normalizedQuery);
+ return {
+ config: group.config,
+ sessions: filterSessions(
+ group.sessions,
+ !!normalizedQuery && agentMatches,
+ ),
+ totalSessions: group.sessions.length,
+ liveSessions: group.sessions.filter(isLiveSession).length,
+ agentMatches,
+ };
+ })
+ .filter(
+ (group) =>
+ group.sessions.length > 0 ||
+ (statusFilter === "all" && group.agentMatches),
+ )
+ .map(({ agentMatches, ...group }) => group);
+
+ return {
+ groups,
+ otherSessions: filterSessions(data?.otherSessions ?? [], false),
+ };
+}
+
+/**
+ * DigitalOcean Managed Agents: sign in once, then see every agent and session
+ * on the team with live status, and connect any of them as a backend.
+ *
+ * Connecting opens a port-forward tunnel in the Electron main process and
+ * registers `http://127.0.0.1:<port>` as an ordinary local backend — after
+ * the tunnel the far end genuinely is an agent-server, so conversations,
+ * files, and the terminal all work unmodified.
+ */
+export function ManagedAgentsView({ onBack, onDone }: ManagedAgentsViewProps) {
+ const { t } = useTranslation("openhands");
+ const queryClient = useQueryClient();
+ const { backends } = useActiveBackendContext();
+ const { detach } = useMarsTunnelBackend();
+ const launcher = useLaunchMarsSession();
+ const [isAddingConnection, setIsAddingConnection] = React.useState(false);
+ const auth = useMarsSignIn({
+ onAuthChanged: () => setIsAddingConnection(false),
+ });
+
+ const [query, setQuery] = React.useState("");
+ const [statusFilter, setStatusFilter] = React.useState<StatusFilter>("all");
+ const [busySessionId, setBusySessionId] = React.useState<string | null>(null);
+ const [errors, setErrors] = React.useState<Record<string, string>>({});
+ const [pendingAction, setPendingAction] =
+ React.useState<PendingAction | null>(null);
+ const [isConfirming, setIsConfirming] = React.useState(false);
+ // One launch at a time: overlapping connects reset each other's progress
+ // and navigate twice, and a create can take up to a minute.
+ const isLaunching = launcher.isBusy;
+
+ const setError = (key: string, message: string | null) =>
+ setErrors((previous) => {
+ const next = { ...previous };
+ if (message) next[key] = message;
+ else delete next[key];
+ return next;
+ });
+
+ const authQuery = useMarsAuthState();
+ const authState = authQuery.data;
+ const activeConnection = authState?.active ?? null;
+ const isSignedIn =
+ activeConnection !== null &&
+ !activeConnection.isExpired &&
+ !isAddingConnection;
+
+ const agentsQuery = useMarsAgents(isSignedIn ? activeConnection.id : null);
+
+ const connectedBySession = React.useMemo(() => {
+ const map = new Map<string, Backend>();
+ for (const backend of backends) {
+ if (backend.marsSessionId) map.set(backend.marsSessionId, backend);
+ }
+ return map;
+ }, [backends]);
+
+ const refreshAgents = () =>
+ queryClient.invalidateQueries({
+ queryKey: MARS_QUERY_KEYS.agents(activeConnection?.id ?? null),
+ });
+
+ /** Run a connect or launch, then leave the modal for the session. */
+ const runLaunch = async (
+ errorKey: string,
+ action: () => Promise<unknown>,
+ ) => {
+ setError(errorKey, null);
+ try {
+ await action();
+ void refreshAgents();
+ onDone();
+ } catch (error) {
+ // A launch that created its session but failed to connect reports on
+ // that session's row, where a later connect clears it.
+ setError(
+ error instanceof MarsLaunchConnectError ? error.sessionId : errorKey,
+ launcher.describeError(error),
+ );
+ }
+ };
+
+ const openSession = (session: MarsSession, config?: MarsAgentConfig) =>
+ runLaunch(session.session_id, () => launcher.open(session, config));
+
+ const launchSession = (config: MarsAgentConfig) =>
+ runLaunch(config.id, () => launcher.launch(config));
+
+ const runSessionAction = async (
+ sessionId: string,
+ action: () => Promise<unknown>,
+ ) => {
+ setError(sessionId, null);
+ setBusySessionId(sessionId);
+ try {
+ await action();
+ await refreshAgents();
+ } catch (error) {
+ setError(
+ sessionId,
+ getMarsErrorMessage(error) ??
+ t(I18nKey.DO_AGENTS$SESSION_ACTION_FAILED),
+ );
+ } finally {
+ setBusySessionId(null);
+ }
+ };
+
+ // Stop = destroy: harness-api tears the sandbox down and the session is
+ // gone for good, so it sits behind a confirmation. The destroy goes first:
+ // it can be refused (409 while a checkpoint/fork/rollback holds the
+ // session, 423 locked), and then the session is still running and the
+ // user must keep their connection to it. Only once it succeeded is a
+ // connected backend detached, so nothing keeps probing a torn-down sandbox.
+ const stopSession = async (session: MarsSession) => {
+ const backend = connectedBySession.get(session.session_id);
+ await runSessionAction(session.session_id, async () => {
+ await requireMarsBridge().destroySession(session.session_id);
+ if (backend) await detach(backend);
+ });
+ };
+
+ // harness-api soft-deletes a config without looking at its sessions, so
+ // the UI only offers it once none is live; otherwise the sessions would
+ // silently drop out of their group while still running (and billing).
+ const deleteAgent = async (config: MarsAgentConfig) => {
+ setError(config.id, null);
+ try {
+ await requireMarsBridge().deleteAgentConfig(config.id);
+ await refreshAgents();
+ } catch (error) {
+ setError(
+ config.id,
+ getMarsErrorMessage(error) ??
+ t(I18nKey.DO_AGENTS$SESSION_ACTION_FAILED),
+ );
+ }
+ };
+
+ const confirmPendingAction = async () => {
+ if (!pendingAction) return;
+ setIsConfirming(true);
+ try {
+ if (pendingAction.kind === "stop")
+ await stopSession(pendingAction.session);
+ else await deleteAgent(pendingAction.config);
+ } finally {
+ setIsConfirming(false);
+ setPendingAction(null);
+ }
+ };
+
+ const data = agentsQuery.data;
+ const { groups: visibleGroups, otherSessions: visibleOther } = React.useMemo(
+ () => filterAgents(data, query, statusFilter),
+ [data, query, statusFilter],
+ );
+ const hasAnyAgentsOrSessions =
+ (data?.groups.length ?? 0) > 0 || (data?.otherSessions.length ?? 0) > 0;
+ const connectedCount = connectedBySession.size;
+
+ const renderSession = (session: MarsSession, config?: MarsAgentConfig) => {
+ const backend = connectedBySession.get(session.session_id);
+ return (
+ <ManagedAgentsSessionRow
+ key={session.session_id}
+ session={session}
+ isConnected={backend !== undefined}
+ connectStage={getConnectStage(launcher.connecting, session)}
+ isBusy={isLaunching || busySessionId === session.session_id}
+ error={errors[session.session_id] ?? null}
+ onConnect={() => void openSession(session, config)}
+ // The registry reuses a live tunnel, so this is a fast re-probe that
+ // also lands in the session's latest chat — or revives a dead tunnel.
+ onOpen={() => void openSession(session, config)}
+ onDisconnect={() => {
+ if (backend) {
+ void runSessionAction(session.session_id, () => detach(backend));
+ }
+ }}
+ onPause={() =>
+ void runSessionAction(session.session_id, () =>
+ requireMarsBridge().pauseSession(session.session_id),
+ )
+ }
+ onStop={() => setPendingAction({ kind: "stop", session })}
+ />
+ );
+ };
+
+ let body: React.ReactNode;
+ if (authQuery.isPending) {
+ body = (
+ <div className="flex justify-center py-10">
+ <Loader2 className="size-5 animate-spin text-muted" aria-hidden />
+ </div>
+ );
+ } else if (!isSignedIn) {
+ body = (
+ <ManagedAgentsSignIn
+ canUseOAuth={authState?.canUseOAuth ?? false}
+ isExpired={!isAddingConnection && activeConnection?.isExpired === true}
+ isSigningIn={auth.isSigningIn}
+ isSavingToken={auth.isSavingToken}
+ error={auth.error}
+ onSignInWithOAuth={auth.signInWithOAuth}
+ onSaveToken={auth.saveToken}
+ onCancel={
+ isAddingConnection
+ ? () => {
+ setIsAddingConnection(false);
+ auth.clearError();
+ }
+ : undefined
+ }
+ />
+ );
+ } else {
+ body = (
+ <div className="flex min-h-0 flex-1 flex-col gap-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <label className="relative flex min-w-48 flex-1 items-center">
+ <Search
+ className="pointer-events-none absolute left-2.5 size-4 text-muted"
+ aria-hidden
+ />
+ <input
+ type="search"
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t(I18nKey.DO_AGENTS$SEARCH_PLACEHOLDER)}
+ aria-label={t(I18nKey.DO_AGENTS$SEARCH_PLACEHOLDER)}
+ data-testid="managed-agents-search"
+ className="h-9 w-full rounded-md border border-border bg-transparent pl-8 pr-3 text-sm text-white placeholder:text-muted focus:outline-none"
+ />
+ </label>
+ <SegmentedToggle<StatusFilter>
+ value={statusFilter}
+ options={STATUS_FILTERS.map((filter) => ({
+ value: filter.value,
+ label: t(filter.label),
+ }))}
+ onChange={setStatusFilter}
+ ariaLabel={t(I18nKey.COMMON$STATUS)}
+ testId="managed-agents-filter"
+ />
+ <button
+ type="button"
+ onClick={() => void refreshAgents()}
+ aria-label={t(I18nKey.BACKEND$DIGITALOCEAN_AGENTS_REFRESH)}
+ title={t(I18nKey.BACKEND$DIGITALOCEAN_AGENTS_REFRESH)}
+ data-testid="managed-agents-refresh"
+ className="inline-flex size-9 cursor-pointer items-center justify-center rounded-md text-muted transition-colors hover:bg-interactive-hover hover:text-white"
+ >
+ <RefreshCw
+ className={cn("size-4", agentsQuery.isFetching && "animate-spin")}
+ aria-hidden
+ />
+ </button>
+ </div>
+
+ {agentsQuery.error ? (
+ <ErrorAlert testId="managed-agents-load-error">
+ {getMarsErrorMessage(agentsQuery.error) ??
+ t(I18nKey.BACKEND$DIGITALOCEAN_AGENTS_FAILED)}
+ </ErrorAlert>
+ ) : null}
+
+ <div
+ className="min-h-0 flex-1 overflow-y-auto custom-scrollbar-always"
+ data-testid="managed-agents-list"
+ >
+ {agentsQuery.isPending ? (
+ <p className="py-6 text-center text-sm text-muted">
+ {t(I18nKey.BACKEND$DIGITALOCEAN_AGENTS_LOADING)}
+ </p>
+ ) : null}
+
+ {data && !hasAnyAgentsOrSessions ? (
+ <p
+ data-testid="managed-agents-empty"
+ className="py-6 text-center text-sm text-muted"
+ >
+ {t(I18nKey.BACKEND$DIGITALOCEAN_AGENTS_EMPTY)}
+ </p>
+ ) : null}
+
+ {data &&
+ hasAnyAgentsOrSessions &&
+ visibleGroups.length === 0 &&
+ visibleOther.length === 0 ? (
+ <p
+ data-testid="managed-agents-no-matches"
+ className="py-6 text-center text-sm text-muted"
+ >
+ {t(I18nKey.DO_AGENTS$NO_MATCHES)}
+ </p>
+ ) : null}
+
+ <div className="flex flex-col gap-3">
+ {visibleGroups.map((group) => (
+ <AgentGroupSection
+ key={group.config.id}
+ group={group}
+ isCreating={launcher.launchingConfigId === group.config.id}
+ isLaunching={isLaunching}
+ error={errors[group.config.id] ?? null}
+ onNewSession={() => void launchSession(group.config)}
+ onDeleteAgent={() =>
+ setPendingAction({
+ kind: "delete-agent",
+ config: group.config,
+ })
+ }
+ >
+ {group.sessions.map((session) =>
+ renderSession(session, group.config),
+ )}
+ </AgentGroupSection>
+ ))}
+
+ {visibleOther.length > 0 ? (
+ <section
+ data-testid="managed-agents-other-sessions"
+ className="overflow-hidden rounded-lg border border-border bg-surface-raised"
+ >
+ <header className="border-b border-border px-3 py-2">
+ <h4 className="text-sm font-medium text-white">
+ {t(I18nKey.DO_AGENTS$OTHER_SESSIONS)}
+ </h4>
+ </header>
+ <ul className="divide-y divide-border">
+ {visibleOther.map((session) => renderSession(session))}
+ </ul>
+ </section>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div
+ data-testid="managed-agents-view"
+ className="flex min-h-0 flex-1 flex-col"
+ >
+ <div className="flex flex-col gap-3 p-5 pb-4 pr-12">
+ <BackNavButton onClick={onBack} testId="managed-agents-back">
+ {t(I18nKey.DO_AGENTS$BACK)}
+ </BackNavButton>
+ <div className="flex items-center gap-3">
+ <DigitalOceanLogo width={28} height={28} aria-hidden />
+ <div className="flex min-w-0 flex-col">
+ <h2 className="text-lg font-medium text-white">
+ {t(I18nKey.DO_AGENTS$TITLE)}
+ </h2>
+ <p className="text-xs text-muted">
+ {t(I18nKey.DO_AGENTS$ENTRY_DESCRIPTION)}
+ </p>
+ </div>
+ {isSignedIn && connectedCount > 0 ? (
+ <span className="ml-auto shrink-0 rounded-full border border-primary/40 px-2 py-0.5 text-xs text-primary">
+ {t(I18nKey.DO_AGENTS$CONNECTED_COUNT, { count: connectedCount })}
+ </span>
+ ) : null}
+ </div>
+
+ {isSignedIn ? (
+ <AccountBar
+ authState={authState}
+ activeConnection={activeConnection}
+ onSwitchConnection={auth.switchConnection}
+ onAddConnection={() => setIsAddingConnection(true)}
+ onSignOut={auth.signOut}
+ />
+ ) : null}
+ </div>
+
+ <div className="flex min-h-0 flex-1 flex-col px-5 pb-5">{body}</div>
+
+ {pendingAction ? (
+ <ConfirmationModal
+ text={
+ pendingAction.kind === "stop"
+ ? t(I18nKey.DO_AGENTS$STOP_CONFIRM, {
+ name: getSessionDisplayName(pendingAction.session, t),
+ })
+ : t(I18nKey.DO_AGENTS$DELETE_AGENT_CONFIRM, {
+ name: agentLabel(pendingAction.config),
+ })
+ }
+ confirmText={
+ pendingAction.kind === "stop"
+ ? t(I18nKey.DO_AGENTS$STOP)
+ : t(I18nKey.DO_AGENTS$DELETE_AGENT)
+ }
+ isConfirming={isConfirming}
+ onConfirm={() => void confirmPendingAction()}
+ onCancel={() => setPendingAction(null)}
+ />
+ ) : null}
+ </div>
+ );
+}
diff --git a/src/components/features/backends/managed-agents/mars-backend-removal-modal.tsx b/src/components/features/backends/managed-agents/mars-backend-removal-modal.tsx
new file mode 100644
index 0000000000..271fd0535c
--- /dev/null
+++ b/src/components/features/backends/managed-agents/mars-backend-removal-modal.tsx
@@ -0,0 +1,107 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { useQueryClient } from "@tanstack/react-query";
+import {
+ getMarsBridge,
+ getMarsErrorMessage,
+} from "#/api/mars/mars-tunnel-backend";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { ErrorAlert } from "#/components/shared/error-alert";
+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
+import { MARS_QUERY_KEYS } from "#/hooks/query/query-keys";
+import { I18nKey } from "#/i18n/declaration";
+
+interface MarsBackendRemovalModalProps {
+ name: string;
+ sessionId: string;
+ /** Drops the backend from the registry (which also closes its tunnel). */
+ onRemove: () => void;
+ onCancel: () => void;
+}
+
+/**
+ * Removing a MARS backend only disconnects it: the DigitalOcean session keeps
+ * running (and billing) and can be reconnected from Managed Agents. This says
+ * so, and offers to stop the session for good instead. As in Managed Agents,
+ * the destroy goes first — it can be refused (409/423) while the session is
+ * still running, and then the user keeps their connection to it.
+ */
+export function MarsBackendRemovalModal({
+ name,
+ sessionId,
+ onRemove,
+ onCancel,
+}: MarsBackendRemovalModalProps) {
+ const { t } = useTranslation("openhands");
+ const queryClient = useQueryClient();
+ const [isStopping, setIsStopping] = React.useState(false);
+ const [error, setError] = React.useState<string | null>(null);
+ const canStop = getMarsBridge() !== null;
+
+ const stopSession = async () => {
+ const bridge = getMarsBridge();
+ if (!bridge) return;
+ setIsStopping(true);
+ setError(null);
+ try {
+ await bridge.destroySession(sessionId);
+ onRemove();
+ void queryClient.invalidateQueries({ queryKey: MARS_QUERY_KEYS.all });
+ } catch (stopError) {
+ setError(
+ getMarsErrorMessage(stopError) ??
+ t(I18nKey.DO_AGENTS$SESSION_ACTION_FAILED),
+ );
+ setIsStopping(false);
+ }
+ };
+
+ return (
+ <ModalBackdrop
+ onClose={isStopping ? undefined : onCancel}
+ closeOnEscape={!isStopping}
+ aria-label={t(I18nKey.BACKEND$REMOVE)}
+ >
+ <div
+ data-testid="mars-backend-removal-modal"
+ className="bg-base-secondary p-4 rounded-xl flex flex-col gap-4 border border-border max-w-md"
+ >
+ <p>{t(I18nKey.BACKEND$REMOVE_MARS_CONFIRMATION, { name })}</p>
+ {error ? (
+ <ErrorAlert testId="mars-backend-removal-error">{error}</ErrorAlert>
+ ) : null}
+ <div className="w-full flex flex-wrap justify-end gap-2">
+ <BrandButton
+ testId="cancel-button"
+ type="button"
+ variant="secondary"
+ onClick={onCancel}
+ isDisabled={isStopping}
+ >
+ {t(I18nKey.BUTTON$CANCEL)}
+ </BrandButton>
+ <BrandButton
+ testId="disconnect-only-button"
+ type="button"
+ variant="secondary"
+ onClick={onRemove}
+ isDisabled={isStopping}
+ >
+ {t(I18nKey.BACKEND$DISCONNECT_ONLY)}
+ </BrandButton>
+ {canStop ? (
+ <BrandButton
+ testId="stop-session-button"
+ type="button"
+ variant="danger"
+ onClick={stopSession}
+ isDisabled={isStopping}
+ >
+ {t(I18nKey.DO_AGENTS$STOP)}
+ </BrandButton>
+ ) : null}
+ </div>
+ </div>
+ </ModalBackdrop>
+ );
+}
diff --git a/src/components/features/backends/managed-agents/session-status-dot.tsx b/src/components/features/backends/managed-agents/session-status-dot.tsx
new file mode 100644
index 0000000000..feb4bcf180
--- /dev/null
+++ b/src/components/features/backends/managed-agents/session-status-dot.tsx
@@ -0,0 +1,23 @@
+import type { MarsSessionPhase } from "#/api/mars/mars-tunnel-backend";
+import { cn } from "#/utils/utils";
+import { PHASE_DOT_CLASS } from "./managed-agents-labels";
+
+interface SessionStatusDotProps {
+ phase: MarsSessionPhase;
+ /** Size and placement; defaults to `size-2`. */
+ className?: string;
+}
+
+/** The colored dot that shows a MARS session's phase at a glance. */
+export function SessionStatusDot({ phase, className }: SessionStatusDotProps) {
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ "size-2 shrink-0 rounded-full",
+ PHASE_DOT_CLASS[phase],
+ className,
+ )}
+ />
+ );
+}
diff --git a/src/components/features/backends/managed-agents/use-session-meta.ts b/src/components/features/backends/managed-agents/use-session-meta.ts
new file mode 100644
index 0000000000..46897c26c0
--- /dev/null
+++ b/src/components/features/backends/managed-agents/use-session-meta.ts
@@ -0,0 +1,79 @@
+import { useTranslation } from "react-i18next";
+
+import {
+ getSessionPhase,
+ type MarsSession,
+ type MarsSessionPhase,
+} from "#/api/mars/mars-tunnel-backend";
+import type {
+ MarsConnectingState,
+ MarsConnectStage,
+} from "#/hooks/use-connect-mars-session";
+import {
+ formatRelativeTime,
+ isInvalidTimestamp,
+} from "#/utils/format-relative-time";
+import {
+ getSessionDisplayName,
+ PHASE_LABEL_KEY,
+ STAGE_LABEL_KEY,
+} from "./managed-agents-labels";
+
+/** The stage of the connect in flight for this session, if any. */
+export function getConnectStage(
+ connecting: MarsConnectingState | null,
+ session: MarsSession,
+): MarsConnectStage | null {
+ return connecting?.sessionId === session.session_id ? connecting.stage : null;
+}
+
+/**
+ * When the session last did anything, or null when the backend left the
+ * timestamp unset (the epoch) or unparseable.
+ */
+export function getSessionLastActivity(
+ session: MarsSession | undefined,
+): string | null {
+ const at = session?.last_event_at ?? session?.created_at;
+ return isInvalidTimestamp(at) ? null : at!;
+}
+
+/** "5 minutes ago" for the session's last activity, or null when unknown. */
+export function useSessionActivityLabel(
+ session: MarsSession | undefined,
+): string | null {
+ const { t, i18n } = useTranslation("openhands");
+ const at = getSessionLastActivity(session);
+ return at ? formatRelativeTime(at, i18n.language, t) : null;
+}
+
+export interface SessionMeta {
+ name: string;
+ phase: MarsSessionPhase;
+ phaseLabel: string;
+ /** Label for the connect stage in flight, or null when not connecting. */
+ stageLabel: string | null;
+ /** Guarded last-activity timestamp; null when unknown. */
+ lastActivityAt: string | null;
+ /** "Running · 5 minutes ago". */
+ meta: string;
+}
+
+/** Display name, phase, and "status · time" line shared by session rows. */
+export function useSessionMeta(
+ session: MarsSession,
+ stage: MarsConnectStage | null = null,
+): SessionMeta {
+ const { t } = useTranslation("openhands");
+ const phase = getSessionPhase(session.status);
+ const phaseLabel = t(PHASE_LABEL_KEY[phase]);
+ const activity = useSessionActivityLabel(session);
+ return {
+ name: getSessionDisplayName(session, t),
+ phase,
+ phaseLabel,
+ stageLabel: stage ? t(STAGE_LABEL_KEY[stage]) : null,
+ lastActivityAt: getSessionLastActivity(session),
+ meta: [phaseLabel, activity].filter(Boolean).join(" · "),
+ };
+}
diff --git a/src/components/features/settings/llm-profiles/llm-profile-form.ts b/src/components/features/settings/llm-profiles/llm-profile-form.ts
index 9372a9cbc2..78dcc75d17 100644
--- a/src/components/features/settings/llm-profiles/llm-profile-form.ts
+++ b/src/components/features/settings/llm-profiles/llm-profile-form.ts
@@ -107,6 +107,17 @@ export function buildProfileLlmConfig({
Object.prototype.hasOwnProperty.call(dirtyLlm, "model") &&
dirtyLlm.model !== base.model;
const llmConfig: Record<string, unknown> = { ...base, ...dirtyLlm };
+ // The embedded form reports dirty fields only. A new profile's model is
+ // prefilled from the default and usually never touched, so it is not
+ // dirty and there is no base config to inherit it from — yet it is
+ // exactly the model being saved. Without this the save failed with
+ // "Model is required" for anyone who kept the suggested model.
+ if (typeof llmConfig.model !== "string" || !llmConfig.model) {
+ const currentModel = values["llm.model"];
+ if (typeof currentModel === "string" && currentModel) {
+ llmConfig.model = currentModel;
+ }
+ }
const authType = resolveLlmAuthType(llmConfig.auth_type);
// A profile linked to a provider connection sources its credential from the
diff --git a/src/components/features/sidebar/mars-session-panel.tsx b/src/components/features/sidebar/mars-session-panel.tsx
new file mode 100644
index 0000000000..842fdb672d
--- /dev/null
+++ b/src/components/features/sidebar/mars-session-panel.tsx
@@ -0,0 +1,454 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { Check, ChevronsUpDown, Loader2, Plus, Settings2 } from "lucide-react";
+
+import DigitalOceanLogo from "#/assets/branding/digitalocean-logo.svg?react";
+import type { Backend } from "#/api/backend-registry/types";
+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
+import {
+ isConnectableSession,
+ NEW_CHAT_PATH,
+ SESSION_STATUS_READY,
+ type MarsAgentConfig,
+ type MarsSession,
+} from "#/api/mars/mars-tunnel-backend";
+import { agentLabel } from "#/components/features/backends/managed-agents/managed-agents-labels";
+import { SessionStatusDot } from "#/components/features/backends/managed-agents/session-status-dot";
+import {
+ getConnectStage,
+ useSessionMeta,
+} from "#/components/features/backends/managed-agents/use-session-meta";
+import { ConversationStatusDot } from "#/components/features/conversation-panel/conversation-status-dot";
+import { NEW_CONVERSATION_DROPDOWN_SURFACE } from "#/components/features/conversation-panel/new-conversation-dropdown-styles";
+import { ErrorAlert } from "#/components/shared/error-alert";
+import { NavigationLink } from "#/components/shared/navigation-link";
+import { useNavigation } from "#/context/navigation-context";
+import {
+ getUsableConnectionId,
+ useMarsAgents,
+ useMarsAuthState,
+ type MarsAgentsSnapshot,
+} from "#/hooks/query/use-mars-agents";
+import { usePaginatedConversations } from "#/hooks/query/use-paginated-conversations";
+import { useBackendScopedPath } from "#/hooks/use-backend-scoped-path";
+import { useClickOutsideElement } from "#/hooks/use-click-outside-element";
+import { useCloseOnEscape } from "#/hooks/use-close-on-escape";
+import { useLaunchMarsSession } from "#/hooks/use-launch-mars-session";
+import { I18nKey } from "#/i18n/declaration";
+import { Divider } from "#/ui/divider";
+import {
+ dropdownMenuListClassName,
+ dropdownMenuRowClassName,
+} from "#/utils/dropdown-classes";
+import { formatTimeDelta } from "#/utils/format-time-delta";
+import { cn } from "#/utils/utils";
+
+const ManageBackendsModal = React.lazy(() =>
+ import("#/components/features/backends/manage-backends-modal").then((m) => ({
+ default: m.ManageBackendsModal,
+ })),
+);
+
+/** Listing sessions is a harness-api read; it never wakes a sandbox. */
+const SESSIONS_REFETCH_MS = 30_000;
+
+const ICON_BUTTON_CLASS =
+ "inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted hover:bg-white/10 hover:text-white focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-border disabled:cursor-not-allowed disabled:opacity-50";
+
+interface SessionContext {
+ config: MarsAgentConfig | undefined;
+ sessions: MarsSession[];
+}
+
+/**
+ * The agent the active session belongs to and that agent's sessions; for a
+ * session launched outside any listed agent, the team's other sessions.
+ */
+function resolveSessionContext(
+ data: MarsAgentsSnapshot | undefined,
+ backend: Backend,
+): SessionContext {
+ const groups = data?.groups ?? [];
+ const group =
+ groups.find((g) => g.config.id === backend.marsConfigId) ??
+ groups.find((g) =>
+ g.sessions.some((s) => s.session_id === backend.marsSessionId),
+ );
+ return {
+ config: group?.config,
+ sessions: group?.sessions ?? data?.otherSessions ?? [],
+ };
+}
+
+/**
+ * The list can lag a just-created or just-connected session; the one the
+ * backend points at must still show, or its conversations would vanish.
+ */
+function withCurrentSession(
+ sessions: MarsSession[],
+ backend: Backend,
+): MarsSession[] {
+ const sessionId = backend.marsSessionId;
+ if (!sessionId || sessions.some((s) => s.session_id === sessionId)) {
+ return sessions;
+ }
+ // Connected implies its tunnel answered, so it reads as running.
+ return [{ session_id: sessionId, status: SESSION_STATUS_READY }, ...sessions];
+}
+
+/** The active session's conversations, nested under its row. */
+function SessionConversations({
+ conversations,
+}: {
+ conversations: AppConversation[];
+}) {
+ const { t } = useTranslation("openhands");
+ const { conversationId } = useNavigation();
+ const backendScopedPath = useBackendScopedPath();
+
+ if (conversations.length === 0) return null;
+ return (
+ <ul
+ data-testid="mars-session-conversations"
+ className="mt-0.5 flex flex-col gap-0.5"
+ >
+ {conversations.map((conversation) => (
+ <li key={conversation.id}>
+ <NavigationLink
+ to={backendScopedPath(`/conversations/${conversation.id}`)}
+ data-testid={`mars-session-conversation-${conversation.id}`}
+ className={cn(
+ "flex h-8 min-w-0 items-center gap-2 rounded-md pl-6 pr-2 text-sm text-white hover:bg-surface",
+ conversation.id === conversationId && "bg-surface",
+ )}
+ >
+ <ConversationStatusDot
+ executionStatus={conversation.execution_status}
+ sandboxStatus={conversation.sandbox_status}
+ showTooltip={false}
+ />
+ <span className="min-w-0 flex-1 truncate">
+ {conversation.title || t(I18nKey.CONVERSATION$UNTITLED)}
+ </span>
+ <time className="shrink-0 text-xs tabular-nums text-muted">
+ {formatTimeDelta(
+ conversation.updated_at ?? conversation.created_at,
+ )}
+ </time>
+ </NavigationLink>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+type Launcher = ReturnType<typeof useLaunchMarsSession>;
+
+interface MarsSessionRowProps {
+ session: MarsSession;
+ isCurrent: boolean;
+ launcher: Launcher;
+ conversations: AppConversation[];
+ /** Go to the current session's latest conversation, or a new chat. */
+ onOpenCurrent: () => void;
+ onOpen: () => void;
+ onNewChat: () => void;
+}
+
+/** One session, read like a thread folder; the current one lists its chats. */
+function MarsSessionRow({
+ session,
+ isCurrent,
+ launcher,
+ conversations,
+ onOpenCurrent,
+ onOpen,
+ onNewChat,
+}: MarsSessionRowProps) {
+ const { t } = useTranslation("openhands");
+ const stage = getConnectStage(launcher.connecting, session);
+ const { name, phase, phaseLabel, stageLabel, lastActivityAt } =
+ useSessionMeta(session, stage);
+
+ let trailing: React.ReactNode = null;
+ if (stage) {
+ trailing = (
+ <Loader2 className="size-3.5 shrink-0 animate-spin" aria-hidden />
+ );
+ } else if (!isCurrent && lastActivityAt) {
+ trailing = (
+ <time className="shrink-0 text-xs tabular-nums">
+ {formatTimeDelta(lastActivityAt)}
+ </time>
+ );
+ }
+
+ return (
+ <li data-testid={`mars-session-${session.session_id}`}>
+ <div
+ className={cn(
+ "group flex h-8 w-full min-w-0 items-center gap-0.5 rounded-md pl-2 pr-1 text-sm hover:bg-surface-raised",
+ isCurrent ? "text-white" : "text-muted hover:text-white",
+ )}
+ >
+ <button
+ type="button"
+ disabled={
+ launcher.isBusy || (!isCurrent && !isConnectableSession(session))
+ }
+ aria-current={isCurrent ? "true" : undefined}
+ title={stageLabel ?? phaseLabel}
+ onClick={isCurrent ? onOpenCurrent : onOpen}
+ data-testid={`mars-session-open-${session.session_id}`}
+ className="flex min-h-8 min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md py-1 text-left text-inherit outline-none focus-visible:ring-1 focus-visible:ring-border disabled:cursor-not-allowed"
+ >
+ <SessionStatusDot phase={phase} />
+ <span className="min-w-0 flex-1 truncate">{name}</span>
+ {stageLabel ? <span className="sr-only">{stageLabel}</span> : null}
+ {trailing}
+ </button>
+ {isCurrent ? (
+ <button
+ type="button"
+ onClick={onNewChat}
+ aria-label={t(I18nKey.DO_AGENTS$NEW_CHAT_IN_SESSION, { name })}
+ title={t(I18nKey.DO_AGENTS$NEW_CHAT_IN_SESSION, { name })}
+ data-testid="mars-session-new-chat"
+ className={ICON_BUTTON_CLASS}
+ >
+ <Plus className="size-3.5" aria-hidden strokeWidth={2} />
+ </button>
+ ) : null}
+ </div>
+ {isCurrent ? (
+ <SessionConversations conversations={conversations} />
+ ) : null}
+ </li>
+ );
+}
+
+interface MarsSessionPanelProps {
+ /** The active backend; must carry a `marsSessionId`. */
+ backend: Backend;
+}
+
+/**
+ * Sidebar list for a DigitalOcean Managed Agents backend, in place of the
+ * conversation list. Sessions of the active agent read like thread folders:
+ * the one you are on expands to its conversations, any other opens with a
+ * click, and the header launches a new session or switches agent.
+ */
+export function MarsSessionPanel({ backend }: MarsSessionPanelProps) {
+ const { t } = useTranslation("openhands");
+ const { navigate } = useNavigation();
+ const backendScopedPath = useBackendScopedPath();
+ const launcher = useLaunchMarsSession();
+
+ const [menuOpen, setMenuOpen] = React.useState(false);
+ const [manageOpen, setManageOpen] = React.useState(false);
+ const [error, setError] = React.useState<string | null>(null);
+ const closeMenu = () => setMenuOpen(false);
+ const menuRef = useClickOutsideElement<HTMLDivElement>(closeMenu);
+ const menuTriggerRef = React.useRef<HTMLButtonElement>(null);
+ useCloseOnEscape(menuOpen, closeMenu, menuTriggerRef);
+
+ const authQuery = useMarsAuthState();
+ const agentsQuery = useMarsAgents(getUsableConnectionId(authQuery.data), {
+ refetchIntervalMs: SESSIONS_REFETCH_MS,
+ });
+ const context = resolveSessionContext(agentsQuery.data, backend);
+ const { config } = context;
+ const sessions = withCurrentSession(context.sessions, backend);
+ const groups = agentsQuery.data?.groups ?? [];
+ const { data: conversationPages } = usePaginatedConversations();
+ const conversations =
+ conversationPages?.pages.flatMap((page) => page.items) ?? [];
+ const latestConversationId = conversations[0]?.id;
+
+ const run = async (action: () => Promise<unknown>) => {
+ setError(null);
+ try {
+ await action();
+ } catch (failure) {
+ setError(launcher.describeError(failure));
+ }
+ };
+
+ const isLaunching = config ? launcher.launchingConfigId === config.id : false;
+ const title = config ? agentLabel(config) : backend.name;
+
+ return (
+ <div
+ data-testid="mars-session-panel"
+ className="flex h-full min-h-0 w-full flex-col"
+ >
+ <div className="-ml-2.5 box-border w-[calc(100%+0.625rem)] max-w-none">
+ <div className="flex min-w-0 flex-nowrap items-center gap-x-1 py-2 pl-2.5 pr-2.5">
+ <div ref={menuRef} className="relative min-w-0 flex-1">
+ <button
+ ref={menuTriggerRef}
+ type="button"
+ onClick={() => setMenuOpen((open) => !open)}
+ aria-expanded={menuOpen}
+ aria-haspopup="menu"
+ aria-label={t(I18nKey.DO_AGENTS$SWITCH_AGENT)}
+ data-testid="mars-session-panel-agent"
+ className="flex h-7 max-w-full cursor-pointer items-center gap-2 rounded-md px-1.5 text-sm font-medium text-muted hover:bg-surface-raised hover:text-white focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-border"
+ >
+ <DigitalOceanLogo
+ width={14}
+ height={14}
+ className="shrink-0"
+ aria-hidden
+ />
+ <span className="truncate">{title}</span>
+ <ChevronsUpDown className="size-3.5 shrink-0" aria-hidden />
+ </button>
+
+ {menuOpen ? (
+ <div
+ role="menu"
+ data-testid="mars-session-panel-agent-menu"
+ className={cn(
+ NEW_CONVERSATION_DROPDOWN_SURFACE,
+ "absolute left-0 top-full z-20 mt-1 w-64",
+ )}
+ >
+ <p className="px-2 pb-1 pt-1.5 text-xs text-text-tertiary">
+ {t(I18nKey.DO_AGENTS$AGENTS_HEADING)}
+ </p>
+ <div
+ className={cn(
+ "max-h-[40vh] overflow-y-auto",
+ dropdownMenuListClassName,
+ )}
+ >
+ {groups.map((group) => {
+ const isCurrent = group.config.id === config?.id;
+ return (
+ <button
+ key={group.config.id}
+ type="button"
+ role="menuitem"
+ disabled={launcher.isBusy}
+ onClick={() => {
+ setMenuOpen(false);
+ if (!isCurrent) {
+ void run(() => launcher.openAgent(group));
+ }
+ }}
+ data-testid={`mars-session-panel-agent-${group.config.id}`}
+ className={dropdownMenuRowClassName}
+ >
+ <span className="min-w-0 flex-1 truncate">
+ {agentLabel(group.config)}
+ </span>
+ {isCurrent ? (
+ <Check
+ className="size-3.5 shrink-0 text-primary"
+ aria-hidden
+ />
+ ) : null}
+ </button>
+ );
+ })}
+ <Divider inset="menu" />
+ <button
+ type="button"
+ role="menuitem"
+ onClick={() => {
+ setMenuOpen(false);
+ setManageOpen(true);
+ }}
+ data-testid="mars-session-panel-manage"
+ className={dropdownMenuRowClassName}
+ >
+ <Settings2 className="size-4" aria-hidden />
+ {t(I18nKey.DO_AGENTS$MANAGE)}
+ </button>
+ </div>
+ </div>
+ ) : null}
+ </div>
+
+ {config ? (
+ <button
+ type="button"
+ onClick={() => void run(() => launcher.launch(config))}
+ disabled={launcher.isBusy}
+ aria-label={t(I18nKey.DO_AGENTS$NEW_SESSION)}
+ title={t(I18nKey.DO_AGENTS$NEW_SESSION)}
+ data-testid="mars-session-panel-new"
+ className={ICON_BUTTON_CLASS}
+ >
+ {isLaunching ? (
+ <Loader2 className="size-3.5 animate-spin" aria-hidden />
+ ) : (
+ <Plus className="size-4" aria-hidden />
+ )}
+ </button>
+ ) : null}
+ </div>
+ </div>
+
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto overflow-x-hidden overscroll-contain custom-scrollbar-always">
+ {isLaunching ? (
+ <p
+ data-testid="mars-session-panel-launching"
+ className="flex h-8 items-center gap-2 pl-2 text-sm text-muted"
+ >
+ <Loader2 className="size-3.5 animate-spin" aria-hidden />
+ {t(I18nKey.BACKEND$DIGITALOCEAN_CREATING_SESSION)}
+ </p>
+ ) : null}
+
+ {error ? (
+ <ErrorAlert
+ testId="mars-session-panel-error"
+ className="mx-1 my-1 p-2 text-xs text-pretty"
+ >
+ {error}
+ </ErrorAlert>
+ ) : null}
+
+ {agentsQuery.data && sessions.length === 0 ? (
+ <p className="px-2 py-2 text-xs text-muted">
+ {t(I18nKey.DO_AGENTS$NO_SESSIONS)}
+ </p>
+ ) : null}
+
+ <ul className="flex flex-col gap-0.5">
+ {sessions.map((session) => (
+ <MarsSessionRow
+ key={session.session_id}
+ session={session}
+ isCurrent={session.session_id === backend.marsSessionId}
+ launcher={launcher}
+ conversations={conversations}
+ onOpenCurrent={() =>
+ navigate(
+ backendScopedPath(
+ latestConversationId
+ ? `/conversations/${latestConversationId}`
+ : NEW_CHAT_PATH,
+ ),
+ )
+ }
+ onOpen={() => void run(() => launcher.open(session, config))}
+ onNewChat={() => navigate(backendScopedPath(NEW_CHAT_PATH))}
+ />
+ ))}
+ </ul>
+ </div>
+
+ {manageOpen ? (
+ <React.Suspense fallback={null}>
+ <ManageBackendsModal
+ initialView="managed-agents"
+ onClose={() => setManageOpen(false)}
+ />
+ </React.Suspense>
+ ) : null}
+ </div>
+ );
+}
diff --git a/src/components/features/sidebar/sidebar-conversation-list.tsx b/src/components/features/sidebar/sidebar-conversation-list.tsx
index fffdbcf547..6065ca30fb 100644
--- a/src/components/features/sidebar/sidebar-conversation-list.tsx
+++ b/src/components/features/sidebar/sidebar-conversation-list.tsx
@@ -1,4 +1,7 @@
+import { getMarsBridge } from "#/api/mars/mars-tunnel-backend";
import { ConversationPanel } from "#/components/features/conversation-panel/conversation-panel";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { MarsSessionPanel } from "./mars-session-panel";
interface SidebarConversationListProps {
/**
@@ -23,10 +26,17 @@ interface SidebarConversationListProps {
export function SidebarConversationList({
collapsed,
}: SidebarConversationListProps) {
+ const { backend } = useActiveBackend();
+
if (collapsed) {
return null;
}
+ // A Managed Agents session's unit of work is the session, so its agent's
+ // sessions replace the list, with this session's conversations nested.
+ const showMarsSessions =
+ Boolean(backend.marsSessionId) && getMarsBridge() !== null;
+
return (
<div className="flex flex-col flex-1 min-h-0">
{/* Avoid overflow-hidden here: ConversationPanel's header uses `-ml-2.5` +
@@ -34,7 +44,11 @@ export function SidebarConversationList({
the aside; clipping would inset the border. Scroll stays on the inner
list. */}
<div className="flex min-h-0 w-full flex-1 flex-col">
- <ConversationPanel />
+ {showMarsSessions ? (
+ <MarsSessionPanel backend={backend} />
+ ) : (
+ <ConversationPanel />
+ )}
</div>
</div>
);
diff --git a/src/components/shared/error-alert.tsx b/src/components/shared/error-alert.tsx
new file mode 100644
index 0000000000..f14478a39f
--- /dev/null
+++ b/src/components/shared/error-alert.tsx
@@ -0,0 +1,24 @@
+import type { ReactNode } from "react";
+import { cn } from "#/utils/utils";
+
+interface ErrorAlertProps {
+ children: ReactNode;
+ testId?: string;
+ className?: string;
+}
+
+/** Inline error box announced to assistive tech; keeps server line breaks. */
+export function ErrorAlert({ children, testId, className }: ErrorAlertProps) {
+ return (
+ <div
+ role="alert"
+ data-testid={testId}
+ className={cn(
+ "rounded-md border border-status-error/40 bg-status-error/10 p-3 text-sm text-status-error whitespace-pre-wrap break-words",
+ className,
+ )}
+ >
+ {children}
+ </div>
+ );
+}
diff --git a/src/contexts/active-backend-context.tsx b/src/contexts/active-backend-context.tsx
index 2127e5a456..04a86c720c 100644
--- a/src/contexts/active-backend-context.tsx
+++ b/src/contexts/active-backend-context.tsx
@@ -19,6 +19,7 @@ import {
type BackendSelection,
type ResolvedActiveBackend,
} from "#/api/backend-registry/types";
+import { getMarsBridge } from "#/api/mars/mars-tunnel-backend";
import { QUERY_KEYS } from "#/hooks/query/query-keys";
import { queryClient } from "#/query-client-config";
import {
@@ -189,6 +190,13 @@ export function ActiveBackendProvider({
getSnapshot().active.backend.id === removed.id;
const list = getRegisteredBackends().filter((b) => b.id !== id);
setRegisteredBackends(list);
+ // Left open, the tunnel would keep a session awake that nothing is
+ // attached to any more.
+ if (removed?.marsSessionId) {
+ void getMarsBridge()
+ ?.closeTunnel(removed.marsSessionId)
+ .catch(() => {});
+ }
if (wasActiveCloud) {
setTelemetryCloudContext(null);
void setTelemetryIdentity(null);
diff --git a/src/entry.client.tsx b/src/entry.client.tsx
index 8e72274f94..c8900a698f 100644
--- a/src/entry.client.tsx
+++ b/src/entry.client.tsx
@@ -11,11 +11,15 @@ import {
AgentServerUIProviders,
DEFAULT_AGENT_SERVER_ANALYTICS,
} from "./components/providers";
+import { installMarsWebBridge } from "./api/mars/mars-web-bridge";
import { waitForI18n } from "./i18n";
import { shouldStartMockWorker } from "./mocks/should-start-mock-worker";
async function prepareApp() {
- await waitForI18n();
+ // DigitalOcean Managed Agents in the browser: present only when the server
+ // this page came from hosts the MARS bridge (scripts/mars-web-bridge.mjs).
+ // Must settle before render — the UI reads `window.marsBridge` synchronously.
+ await Promise.all([waitForI18n(), installMarsWebBridge()]);
if (shouldStartMockWorker()) {
const { worker } = await import("./mocks/browser");
diff --git a/src/hooks/query/query-keys.ts b/src/hooks/query/query-keys.ts
index c7e276602c..2015c8c221 100644
--- a/src/hooks/query/query-keys.ts
+++ b/src/hooks/query/query-keys.ts
@@ -112,6 +112,18 @@ export const SETUP_QUERY_KEYS = {
capabilities: () => ["setup-capabilities"] as const,
} as const;
+export const MARS_QUERY_KEYS = {
+ all: ["mars"] as const,
+ authState: ["mars", "auth-state"] as const,
+ /** Every connection's agent list, for invalidating after a change. */
+ allAgents: ["mars", "agents"] as const,
+ /** Keyed by connection so switching teams never shows another team's list. */
+ agents: (connectionId: string | null) =>
+ ["mars", "agents", connectionId] as const,
+ /** DigitalOcean's sandbox size catalog; the same for every team. */
+ sandboxSizes: ["mars", "sandbox-sizes"] as const,
+} as const;
+
export const APP_UPDATE_QUERY_KEYS = {
/** Latest published @openhands/agent-canvas version (npm `latest` dist-tag). */
latestVersion: ["agent-canvas-latest-version"] as const,
diff --git a/src/hooks/query/use-backends-health.ts b/src/hooks/query/use-backends-health.ts
index 508a07e54f..98b33530c8 100644
--- a/src/hooks/query/use-backends-health.ts
+++ b/src/hooks/query/use-backends-health.ts
@@ -7,10 +7,12 @@ import {
getCurrentCloudApiKey,
} from "#/api/cloud/organization-service.api";
import {
+ isDefinitiveLocalBackendError,
validateLocalBackend,
INVALID_BACKEND_API_KEY_ERROR,
} from "#/api/agent-server-compatibility";
import type { Backend } from "#/api/backend-registry/types";
+import { useActiveBackend } from "#/contexts/active-backend-context";
import {
isCorsOrNetworkError,
isCorsOrNetworkErrorMessage,
@@ -141,14 +143,15 @@ const PROBE_RETRY_DELAY_MS = 300;
* Retrying at the query level instead would call `recordBackendFailure` on
* every internal attempt and reach the disabled cap several times too fast.
*
- * Definitive auth failures (logged out, invalid/missing key) are NOT retried:
- * they are a decided server response, not a transient miss, so retrying only
- * delays surfacing the correct "disconnected" state (and the recovery UI).
+ * Definitive failures (logged out, invalid/missing key, unsupported version)
+ * are NOT retried: they are a decided server response, not a transient miss,
+ * so retrying only delays surfacing the correct "disconnected" state (and the
+ * recovery UI).
*/
function isRetryableProbeError(error: unknown): boolean {
if (!(error instanceof Error)) return true;
return (
- error.message !== INVALID_BACKEND_API_KEY_ERROR &&
+ !isDefinitiveLocalBackendError(error) &&
error.message !== MISSING_BACKEND_API_KEY_ERROR &&
error.message !== CLOUD_BACKEND_LOGGED_OUT_ERROR
);
@@ -220,10 +223,18 @@ export function useBackendsHealth(
getHealthSnapshot,
);
+ const activeBackendId = useActiveBackend().backend.id;
+
const results = useQueries({
queries: backends.map((b) => {
const entry = healthMap[b.id];
const hasMissingCloudApiKey = hasMissingBackendApiKey(b);
+ // Every probe of a MARS session travels its tunnel into the sandbox;
+ // polling sessions the user is not on would keep them from ever
+ // idle-pausing (and billing), so those are probed once on mount and
+ // only the active one is watched.
+ const isIdleMarsSession =
+ Boolean(b.marsSessionId) && b.id !== activeBackendId;
const isDisabled = entry?.disabled === true;
const refreshInterval =
b.kind === "cloud" ? CLOUD_REFRESH_INTERVAL_MS : REFRESH_INTERVAL_MS;
@@ -256,15 +267,21 @@ export function useBackendsHealth(
},
enabled: shouldProbe,
refetchInterval:
- isDisabled || hasMissingCloudApiKey
+ isDisabled || hasMissingCloudApiKey || isIdleMarsSession
? (false as const)
: refreshInterval,
refetchIntervalInBackground: false,
refetchOnMount: isDisabled && probeDisabledOnce ? "always" : true,
refetchOnReconnect:
- b.kind !== "cloud" && !isDisabled && !hasMissingCloudApiKey,
+ b.kind !== "cloud" &&
+ !isDisabled &&
+ !hasMissingCloudApiKey &&
+ !isIdleMarsSession,
refetchOnWindowFocus:
- b.kind !== "cloud" && !isDisabled && !hasMissingCloudApiKey,
+ b.kind !== "cloud" &&
+ !isDisabled &&
+ !hasMissingCloudApiKey &&
+ !isIdleMarsSession,
retry: false,
// Keep the previous verdict visible while the next probe is in
// flight so the indicator doesn't flicker on routine polling.
diff --git a/src/hooks/query/use-mars-agents.ts b/src/hooks/query/use-mars-agents.ts
new file mode 100644
index 0000000000..751a21dbb2
--- /dev/null
+++ b/src/hooks/query/use-mars-agents.ts
@@ -0,0 +1,128 @@
+import { useQuery } from "@tanstack/react-query";
+import {
+ getMarsBridge,
+ isOpenHandsConfig,
+ requireMarsBridge,
+ SESSION_STATUS_DESTROYED,
+ type MarsAgentConfig,
+ type MarsAuthState,
+ type MarsSession,
+} from "#/api/mars/mars-tunnel-backend";
+import { MARS_QUERY_KEYS } from "./query-keys";
+
+const PAGE_SIZE = 50;
+/** Sessions pause, wake, and provision on their own; keep the list honest. */
+const REFETCH_INTERVAL_MS = 10_000;
+
+export interface MarsAgentGroup {
+ config: MarsAgentConfig;
+ sessions: MarsSession[];
+}
+
+export interface MarsAgentsSnapshot {
+ groups: MarsAgentGroup[];
+ /** OpenHands-config sessions missing from their config's own listing. */
+ otherSessions: MarsSession[];
+}
+
+function byRecentActivity(a: MarsSession, b: MarsSession): number {
+ const at = (s: MarsSession) =>
+ Date.parse(s.last_event_at ?? s.created_at ?? "") || 0;
+ return at(b) - at(a);
+}
+
+/** Destroyed sessions are gone for good; listing them is only noise. */
+function visibleSessions(sessions: MarsSession[]): MarsSession[] {
+ return sessions
+ .filter((s) => s.status !== SESSION_STATUS_DESTROYED)
+ .sort(byRecentActivity);
+}
+
+async function fetchMarsAgents(): Promise<MarsAgentsSnapshot> {
+ const bridge = getMarsBridge();
+ if (!bridge) return { groups: [], otherSessions: [] };
+
+ const [{ configs }, { sessions: teamSessions }] = await Promise.all([
+ bridge.listAgentConfigs({ pageSize: PAGE_SIZE }),
+ bridge.listSessions({ pageSize: PAGE_SIZE }),
+ ]);
+
+ const openHandsConfigs = configs.filter(isOpenHandsConfig);
+ const openHandsConfigIds = new Set(openHandsConfigs.map((c) => c.id));
+
+ const groups = await Promise.all(
+ openHandsConfigs.map(async (config) => {
+ const { sessions } = await bridge.listConfigSessions(config.id, {
+ pageSize: PAGE_SIZE,
+ });
+ return { config, sessions: visibleSessions(sessions) };
+ }),
+ );
+
+ const grouped = new Set(
+ groups.flatMap((group) => group.sessions.map((s) => s.session_id)),
+ );
+ return {
+ groups,
+ otherSessions: visibleSessions(
+ teamSessions.filter(
+ (s) =>
+ !grouped.has(s.session_id) &&
+ openHandsConfigIds.has(s.config_id ?? ""),
+ ),
+ ),
+ };
+}
+
+export function useMarsAgents(
+ connectionId: string | null,
+ {
+ refetchIntervalMs = REFETCH_INTERVAL_MS,
+ }: { refetchIntervalMs?: number } = {},
+) {
+ return useQuery({
+ queryKey: MARS_QUERY_KEYS.agents(connectionId),
+ queryFn: fetchMarsAgents,
+ enabled: connectionId !== null && getMarsBridge() !== null,
+ refetchInterval: refetchIntervalMs,
+ staleTime: refetchIntervalMs,
+ retry: false,
+ meta: { disableToast: true },
+ });
+}
+
+/** Stored DigitalOcean connections; tokens never leave the main process. */
+export function useMarsAuthState() {
+ return useQuery({
+ queryKey: MARS_QUERY_KEYS.authState,
+ queryFn: () => requireMarsBridge().getAuthState(),
+ enabled: getMarsBridge() !== null,
+ // Sign-in/out and switching connections invalidate `MARS_QUERY_KEYS.all`,
+ // but token expiry (`isExpired` is computed when read) and a sign-in from
+ // another tab (the web build shares the server's state) do not, so it is
+ // re-read after a minute and on window focus.
+ staleTime: 60_000,
+ retry: false,
+ meta: { disableToast: true },
+ });
+}
+
+/** Sandbox sizes a new agent may pick. The catalog is static. */
+export function useMarsSandboxSizes() {
+ return useQuery({
+ queryKey: MARS_QUERY_KEYS.sandboxSizes,
+ queryFn: () => requireMarsBridge().listSandboxSizes(),
+ enabled: getMarsBridge() !== null,
+ staleTime: Infinity,
+ retry: false,
+ meta: { disableToast: true },
+ });
+}
+
+/** The active connection's id while it is still usable, else null. */
+export function getUsableConnectionId(
+ authState: MarsAuthState | undefined,
+): string | null {
+ const active = authState?.active;
+ return active && !active.isExpired ? active.id : null;
+}
diff --git a/src/hooks/use-connect-mars-session.ts b/src/hooks/use-connect-mars-session.ts
new file mode 100644
index 0000000000..1366ce77cc
--- /dev/null
+++ b/src/hooks/use-connect-mars-session.ts
@@ -0,0 +1,97 @@
+import React from "react";
+import type { TFunction } from "i18next";
+import { useTranslation } from "react-i18next";
+
+import { withBackendSelectionParams } from "#/api/backend-registry/url-selection";
+import {
+ getMarsErrorMessage,
+ getSessionPhase,
+ MarsAttachError,
+ NEW_CHAT_PATH,
+ type MarsSession,
+} from "#/api/mars/mars-tunnel-backend";
+import { useNavigation } from "#/context/navigation-context";
+import { I18nKey } from "#/i18n/declaration";
+import { useMarsTunnelBackend } from "./use-mars-tunnel-backend";
+
+export type MarsConnectStage = "waking" | "tunnel" | "agent";
+
+export interface MarsConnectingState {
+ sessionId: string;
+ stage: MarsConnectStage;
+}
+
+export interface ConnectMarsSessionParams {
+ session: MarsSession;
+ /** Display name for the registered backend. */
+ name: string;
+ configId?: string;
+}
+
+const ATTACH_FAILURE_MESSAGE_KEY = {
+ "not-openhands": I18nKey.DO_AGENTS$ERROR_NOT_OPENHANDS,
+ refused: I18nKey.DO_AGENTS$ERROR_REFUSED,
+} as const;
+
+/** User-facing explanation for a failed connect. */
+export function getMarsConnectErrorMessage(
+ error: unknown,
+ t: TFunction<"openhands">,
+): string {
+ if (error instanceof MarsAttachError) {
+ return t(ATTACH_FAILURE_MESSAGE_KEY[error.reason]);
+ }
+ return (
+ getMarsErrorMessage(error) ?? t(I18nKey.BACKEND$DIGITALOCEAN_ATTACH_FAILED)
+ );
+}
+
+/**
+ * Connect to a MARS session and land the user in it: the session's most
+ * recent conversation when it has one, otherwise a fresh chat. Tracks which
+ * stage the connect is in so callers can show real progress, since waking a
+ * paused sandbox can take tens of seconds.
+ */
+export function useConnectMarsSession() {
+ const { t } = useTranslation("openhands");
+ const { attach } = useMarsTunnelBackend();
+ const { navigate } = useNavigation();
+ const [connecting, setConnecting] =
+ React.useState<MarsConnectingState | null>(null);
+
+ const connect = React.useCallback(
+ async ({ session, name, configId }: ConnectMarsSessionParams) => {
+ const sessionId = session.session_id;
+ setConnecting({
+ sessionId,
+ stage:
+ getSessionPhase(session.status) === "paused" ? "waking" : "tunnel",
+ });
+ try {
+ const { backend, latestConversationId } = await attach({
+ sessionId,
+ name,
+ configId,
+ onTunnelReady: () => setConnecting({ sessionId, stage: "agent" }),
+ });
+ const path = latestConversationId
+ ? `/conversations/${latestConversationId}`
+ : NEW_CHAT_PATH;
+ // Pin the URL to the new backend so the route resolves against this
+ // session even while the registry switch is still propagating.
+ navigate(withBackendSelectionParams(path, { backend, orgId: null }));
+ return backend;
+ } finally {
+ setConnecting(null);
+ }
+ },
+ [attach, navigate],
+ );
+
+ const describeError = React.useCallback(
+ (error: unknown) => getMarsConnectErrorMessage(error, t),
+ [t],
+ );
+
+ return { connect, connecting, describeError };
+}
diff --git a/src/hooks/use-launch-mars-session.ts b/src/hooks/use-launch-mars-session.ts
new file mode 100644
index 0000000000..4d0295684b
--- /dev/null
+++ b/src/hooks/use-launch-mars-session.ts
@@ -0,0 +1,157 @@
+import React from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { useTranslation } from "react-i18next";
+
+import {
+ buildNewSessionName,
+ getMarsErrorMessage,
+ isConnectableSession,
+ requireMarsBridge,
+ type MarsAgentConfig,
+ type MarsSession,
+ type NewMarsAgentInput,
+} from "#/api/mars/mars-tunnel-backend";
+import { buildMarsBackendName } from "#/components/features/backends/managed-agents/managed-agents-labels";
+import { MARS_QUERY_KEYS } from "#/hooks/query/query-keys";
+import type { MarsAgentGroup } from "#/hooks/query/use-mars-agents";
+import { useConnectMarsSession } from "#/hooks/use-connect-mars-session";
+import { I18nKey } from "#/i18n/declaration";
+
+/** Creating an agent or session failed, as opposed to connecting afterwards. */
+class MarsCreateError extends Error {
+ constructor(
+ readonly original: unknown,
+ readonly fallbackKey: I18nKey,
+ ) {
+ super(getMarsErrorMessage(original) ?? "");
+ this.name = "MarsCreateError";
+ }
+}
+
+/**
+ * Connecting to a session `launch()` just created failed; the error belongs to
+ * that session, not to its agent.
+ */
+export class MarsLaunchConnectError extends Error {
+ constructor(
+ readonly original: unknown,
+ readonly sessionId: string,
+ ) {
+ super(original instanceof Error ? original.message : String(original));
+ this.name = "MarsLaunchConnectError";
+ }
+}
+
+/**
+ * Open, launch, and resume Managed Agents sessions, landing the user in the
+ * session's latest conversation each time. Every method rejects on failure;
+ * pass the error to `describeError` for copy.
+ */
+export function useLaunchMarsSession() {
+ const { t } = useTranslation("openhands");
+ const queryClient = useQueryClient();
+ const {
+ connect,
+ connecting,
+ describeError: describeConnectError,
+ } = useConnectMarsSession();
+ const [launchingConfigId, setLaunchingConfigId] = React.useState<
+ string | null
+ >(null);
+ const [isCreatingAgent, setIsCreatingAgent] = React.useState(false);
+
+ const open = React.useCallback(
+ (session: MarsSession, config?: MarsAgentConfig) =>
+ connect({
+ session,
+ name: buildMarsBackendName(session, t),
+ configId: config?.id ?? session.config_id ?? undefined,
+ }),
+ [connect, t],
+ );
+
+ const launch = React.useCallback(
+ async (config: MarsAgentConfig) => {
+ setLaunchingConfigId(config.id);
+ let session: MarsSession;
+ try {
+ session = await requireMarsBridge().createSession(
+ config.id,
+ buildNewSessionName(config.name),
+ );
+ } catch (error) {
+ throw new MarsCreateError(
+ error,
+ I18nKey.BACKEND$DIGITALOCEAN_SESSION_CREATE_FAILED,
+ );
+ } finally {
+ setLaunchingConfigId(null);
+ }
+ void queryClient.invalidateQueries({
+ queryKey: MARS_QUERY_KEYS.allAgents,
+ });
+ try {
+ return await open(session, config);
+ } catch (error) {
+ throw new MarsLaunchConnectError(error, session.session_id);
+ }
+ },
+ [open, queryClient],
+ );
+
+ /**
+ * Create an OpenHands agent and wait for the list to include it, so the
+ * caller can launch its first session from a row that is already visible.
+ */
+ const createAgent = React.useCallback(
+ async (input: NewMarsAgentInput) => {
+ setIsCreatingAgent(true);
+ try {
+ const config = await requireMarsBridge().createOpenHandsAgent(input);
+ await queryClient.invalidateQueries({
+ queryKey: MARS_QUERY_KEYS.allAgents,
+ });
+ return config;
+ } catch (error) {
+ throw new MarsCreateError(error, I18nKey.DO_AGENTS$AGENT_CREATE_FAILED);
+ } finally {
+ setIsCreatingAgent(false);
+ }
+ },
+ [queryClient],
+ );
+
+ /** Resume the agent's most recent live session, or start its first. */
+ const openAgent = React.useCallback(
+ ({ config, sessions }: MarsAgentGroup) => {
+ const latest = sessions.find(isConnectableSession);
+ return latest ? open(latest, config) : launch(config);
+ },
+ [launch, open],
+ );
+
+ const describeError = React.useCallback(
+ (error: unknown) => {
+ if (error instanceof MarsCreateError) {
+ return error.message || t(error.fallbackKey);
+ }
+ return describeConnectError(
+ error instanceof MarsLaunchConnectError ? error.original : error,
+ );
+ },
+ [describeConnectError, t],
+ );
+
+ return {
+ open,
+ launch,
+ createAgent,
+ openAgent,
+ connecting,
+ launchingConfigId,
+ isCreatingAgent,
+ isBusy:
+ connecting !== null || launchingConfigId !== null || isCreatingAgent,
+ describeError,
+ };
+}
diff --git a/src/hooks/use-mars-sign-in.ts b/src/hooks/use-mars-sign-in.ts
new file mode 100644
index 0000000000..1d1ff52350
--- /dev/null
+++ b/src/hooks/use-mars-sign-in.ts
@@ -0,0 +1,75 @@
+import React from "react";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useTranslation } from "react-i18next";
+
+import {
+ getMarsErrorMessage,
+ requireMarsBridge,
+} from "#/api/mars/mars-tunnel-backend";
+import { MARS_QUERY_KEYS } from "#/hooks/query/query-keys";
+import { I18nKey } from "#/i18n/declaration";
+
+/**
+ * DigitalOcean sign-in by OAuth or personal access token, plus switching
+ * between saved connections and signing out. The token goes straight to the
+ * main process, which verifies it against harness-api before keeping it, so a
+ * success here means the team really has Managed Agents.
+ */
+export function useMarsSignIn({
+ onAuthChanged,
+}: { onAuthChanged?: () => void } = {}) {
+ const { t } = useTranslation("openhands");
+ const queryClient = useQueryClient();
+ const [error, setError] = React.useState<string | null>(null);
+
+ // A new attempt drops the previous one's error (a failed sign-out included,
+ // which would otherwise linger on the sign-in form).
+ const onMutate = () => setError(null);
+ const onSuccess = () => {
+ setError(null);
+ void queryClient.invalidateQueries({ queryKey: MARS_QUERY_KEYS.all });
+ onAuthChanged?.();
+ };
+ const onError = (failure: unknown) =>
+ setError(
+ getMarsErrorMessage(failure) ??
+ t(I18nKey.BACKEND$DIGITALOCEAN_AUTH_FAILED),
+ );
+
+ const oauth = useMutation({
+ mutationFn: () => requireMarsBridge().signInWithOAuth(),
+ onMutate,
+ onSuccess,
+ onError,
+ });
+ const pat = useMutation({
+ mutationFn: (token: string) => requireMarsBridge().savePat({ token }),
+ onMutate,
+ onSuccess,
+ onError,
+ });
+ const switchConnection = useMutation({
+ mutationFn: (id: string) => requireMarsBridge().setActiveConnection(id),
+ onMutate,
+ onSuccess,
+ onError,
+ });
+ const signOut = useMutation({
+ mutationFn: () => requireMarsBridge().signOut(),
+ onMutate,
+ onSuccess,
+ onError,
+ });
+
+ return {
+ signInWithOAuth: () => oauth.mutate(),
+ saveToken: (token: string) => pat.mutate(token),
+ switchConnection: (id: string) => switchConnection.mutate(id),
+ signOut: () => signOut.mutate(),
+ isSigningIn: oauth.isPending,
+ isSavingToken: pat.isPending,
+ isSigningOut: signOut.isPending,
+ error,
+ clearError: () => setError(null),
+ };
+}
diff --git a/src/hooks/use-mars-tunnel-backend.ts b/src/hooks/use-mars-tunnel-backend.ts
new file mode 100644
index 0000000000..9c3c73007b
--- /dev/null
+++ b/src/hooks/use-mars-tunnel-backend.ts
@@ -0,0 +1,227 @@
+import React from "react";
+import {
+ buildMarsBackendInput,
+ fetchLatestMarsConversationId,
+ getMarsBackendLocalPort,
+ getMarsBridge,
+ getMarsConnectionHost,
+ openMarsTunnel,
+ waitForMarsAgentServer,
+} from "#/api/mars/mars-tunnel-backend";
+import { prepareMarsSandbox } from "#/api/mars/mars-sandbox-setup";
+import { resetBackendHealth } from "#/api/backend-registry/health-store";
+import { useActiveBackendContext } from "#/contexts/active-backend-context";
+import {
+ getUsableConnectionId,
+ useMarsAuthState,
+} from "#/hooks/query/use-mars-agents";
+import type { Backend } from "#/api/backend-registry/types";
+
+export interface AttachMarsSessionParams {
+ sessionId: string;
+ /** Display name for the registered backend. */
+ name: string;
+ configId?: string;
+ /** Fired once the session is reachable and the agent-server probe begins. */
+ onTunnelReady?: () => void;
+}
+
+export interface AttachMarsSessionResult {
+ backend: Backend;
+ /** Where to land the user; null when the session has no conversation yet. */
+ latestConversationId: string | null;
+}
+
+/**
+ * Connect to the session and return the base URL to register: the loopback
+ * tunnel listener (or, in the web build, the server's proxy path for it).
+ */
+async function openHealthyConnection(
+ sessionId: string,
+ localPort?: number,
+): Promise<string> {
+ const connection = await openMarsTunnel({ sessionId, localPort });
+ const host = getMarsConnectionHost(connection);
+ if (connection.status === "error" || host === undefined) {
+ throw new Error(
+ connection.error ?? `Failed to connect to session ${sessionId}`,
+ );
+ }
+ return host;
+}
+
+/**
+ * Connect and wait for the session's agent-server to answer. With
+ * `closeOnFailure`, a connection whose agent-server never answers is closed:
+ * registering a session nobody can use would keep failing the health probe
+ * every tick (and, over the tunnel, hold a listener). Restoring leaves it
+ * open — a slow wake can still recover through the health poll, the
+ * unreachable screen can report the agent-server's own error, and the
+ * tunnel may be shared with a concurrent attach.
+ */
+async function connectAndWait(
+ sessionId: string,
+ {
+ localPort,
+ onTunnelReady,
+ closeOnFailure = false,
+ }: {
+ localPort?: number;
+ onTunnelReady?: () => void;
+ closeOnFailure?: boolean;
+ } = {},
+): Promise<string> {
+ const host = await openHealthyConnection(sessionId, localPort);
+ onTunnelReady?.();
+ try {
+ await waitForMarsAgentServer(host, { sessionId });
+ } catch (error) {
+ if (closeOnFailure) {
+ await getMarsBridge()
+ ?.closeTunnel(sessionId)
+ .catch(() => {});
+ }
+ throw error;
+ }
+ return host;
+}
+
+/**
+ * Backend ids `attach()` has just connected, so the restore effect that sees
+ * them become active does not connect (and wait for) them all over again.
+ */
+const freshlyAttached = new Set<string>();
+
+/**
+ * Registration/lifecycle wiring between MARS sessions and the backend
+ * registry. `attach()` connects to the session, waits for its agent-server
+ * to answer, and registers it as an ordinary local `Backend` (or re-points
+ * the existing one for that session), making it active. `detach()` removes
+ * the Backend again, which forgets the connection.
+ */
+export function useMarsTunnelBackend() {
+ const { backends, addBackend, removeBackend, updateBackend, setActive } =
+ useActiveBackendContext();
+
+ const attach = React.useCallback(
+ async ({
+ sessionId,
+ name,
+ configId,
+ onTunnelReady,
+ }: AttachMarsSessionParams): Promise<AttachMarsSessionResult> => {
+ const host = await connectAndWait(sessionId, {
+ onTunnelReady,
+ closeOnFailure: true,
+ });
+ await prepareMarsSandbox(host, sessionId);
+ // Read before the registry switch below, while nothing else is
+ // pointed at this host yet.
+ const latestConversationId = await fetchLatestMarsConversationId(host);
+
+ const existing = backends.find((b) => b.marsSessionId === sessionId);
+ if (existing) {
+ freshlyAttached.add(existing.id);
+ updateBackend(existing.id, { host, name });
+ // The restore effect is skipped for it, and `updateBackend` resets
+ // health only when the host changes (it never does in the web build).
+ resetBackendHealth(existing.id);
+ setActive(existing.id);
+ return {
+ backend: { ...existing, host, name },
+ latestConversationId,
+ };
+ }
+ const backend = addBackend(
+ buildMarsBackendInput({ name, host, sessionId, configId }),
+ );
+ freshlyAttached.add(backend.id);
+ return { backend, latestConversationId };
+ },
+ [addBackend, backends, setActive, updateBackend],
+ );
+
+ // Removing the Backend also closes its session's tunnel (see
+ // `removeBackend`), so every removal path forgets the connection.
+ const detach = React.useCallback(
+ async (backend: Backend): Promise<void> => {
+ removeBackend(backend.id);
+ },
+ [removeBackend],
+ );
+
+ return { attach, detach };
+}
+
+/**
+ * Connections live in the Electron main process and die with it, while the
+ * Backend records pointing at them persist. Re-connect the *active* MARS
+ * backend — at startup and whenever the user switches to one — and update
+ * its host when the address changed. The previous local port is asked for
+ * again so queries keyed to that host survive the restart, and a port
+ * another process has since taken yields a new one.
+ *
+ * Only the active one: connecting resumes a paused session, so restoring
+ * every registered session would wake (and bill) sandboxes the user is not
+ * using.
+ *
+ * Returns true while the backend active at launch is still being
+ * reconnected, so the bootstrap can wait for it instead of probing a dead
+ * host and flashing the "unreachable backend" recovery screen.
+ */
+export function useRestoreMarsTunnels(): boolean {
+ const { active, updateBackend } = useActiveBackendContext();
+ const { backend } = active;
+ const attempted = React.useRef(new Set<string>());
+ const [launchRestoreId, setLaunchRestoreId] = React.useState(() =>
+ getMarsBridge() && backend.marsSessionId ? backend.id : null,
+ );
+ // Connecting needs a signed-in DigitalOcean connection. The web build keeps
+ // it only in server memory, so after a restart the user signs in again; the
+ // connection appearing re-runs the effect below and reconnects then.
+ const authQuery = useMarsAuthState();
+ const isAuthPending = authQuery.isPending;
+ const connectionId = getUsableConnectionId(authQuery.data);
+
+ React.useEffect(() => {
+ const sessionId = backend.marsSessionId;
+ if (!getMarsBridge() || !sessionId) return;
+ // attach() already connected it and waited for its agent-server.
+ if (freshlyAttached.delete(backend.id)) {
+ attempted.current.add(backend.id);
+ return;
+ }
+ if (isAuthPending) return;
+ if (!connectionId) {
+ // Nothing to connect with yet; don't hold the bootstrap for it.
+ setLaunchRestoreId((id) => (id === backend.id ? null : id));
+ return;
+ }
+ if (attempted.current.has(backend.id)) return;
+ attempted.current.add(backend.id);
+
+ // A paused sandbox is woken by the connect; its agent-server answers
+ // only once booted.
+ void connectAndWait(sessionId, {
+ localPort: getMarsBackendLocalPort(backend),
+ })
+ .then((host) => {
+ if (host === backend.host) {
+ resetBackendHealth(backend.id);
+ } else {
+ updateBackend(backend.id, { host });
+ }
+ })
+ .catch(() => {
+ // Signed out, session ended, or MARS unreachable: the health dot
+ // already reports the backend as offline, and the Managed Agents
+ // screen offers reconnecting. Allow a retry on the next switch.
+ attempted.current.delete(backend.id);
+ })
+ .finally(() => {
+ setLaunchRestoreId((id) => (id === backend.id ? null : id));
+ });
+ }, [backend, updateBackend, isAuthPending, connectionId]);
+
+ return launchRestoreId !== null && launchRestoreId === backend.id;
+}
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index f47a86d85b..e8f6baf9c9 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -31585,6 +31585,57 @@
"uk": "Підключіться до локального або віддаленого agent-server.",
"ca": "Connecta't a un agent-server local o remot."
},
+ "BACKEND$PROVIDERS_TITLE": {
+ "en": "Providers",
+ "ja": "プロバイダー",
+ "zh-CN": "云服务商",
+ "zh-TW": "雲端服務商",
+ "ko-KR": "프로바이더",
+ "no": "Leverandører",
+ "it": "Provider",
+ "pt": "Provedores",
+ "es": "Proveedores",
+ "ar": "المزوّدون",
+ "fr": "Fournisseurs",
+ "tr": "Sağlayıcılar",
+ "de": "Anbieter",
+ "uk": "Провайдери",
+ "ca": "Proveïdors"
+ },
+ "BACKEND$PROVIDERS_OPTION_DESCRIPTION": {
+ "en": "Connect through DigitalOcean and more.",
+ "ja": "DigitalOcean などから接続します。",
+ "zh-CN": "通过 DigitalOcean 等云服务商连接。",
+ "zh-TW": "透過 DigitalOcean 等雲端服務商連線。",
+ "ko-KR": "DigitalOcean 등으로 연결합니다.",
+ "no": "Koble til via DigitalOcean og flere.",
+ "it": "Connettiti tramite DigitalOcean e altri.",
+ "pt": "Conecte-se pelo DigitalOcean e outros.",
+ "es": "Conéctate a través de DigitalOcean y más.",
+ "ar": "اتصل عبر DigitalOcean والمزيد.",
+ "fr": "Connectez-vous via DigitalOcean et d'autres.",
+ "tr": "DigitalOcean ve diğerleri üzerinden bağlanın.",
+ "de": "Verbinden Sie sich über DigitalOcean und weitere Anbieter.",
+ "uk": "Підключіться через DigitalOcean та інші.",
+ "ca": "Connecta't amb DigitalOcean i més."
+ },
+ "BACKEND$PROVIDERS_COMING_SOON": {
+ "en": "More providers coming soon.",
+ "ja": "他のプロバイダーも近日追加予定です。",
+ "zh-CN": "更多云服务商即将推出。",
+ "zh-TW": "更多雲端服務商即將推出。",
+ "ko-KR": "더 많은 프로바이더가 곧 추가됩니다.",
+ "no": "Flere leverandører kommer snart.",
+ "it": "Altri provider in arrivo.",
+ "pt": "Mais provedores em breve.",
+ "es": "Más proveedores próximamente.",
+ "ar": "المزيد من المزوّدين قريبًا.",
+ "fr": "D'autres fournisseurs arrivent bientôt.",
+ "tr": "Daha fazla sağlayıcı yakında eklenecek.",
+ "de": "Weitere Anbieter folgen in Kürze.",
+ "uk": "Незабаром з'являться інші провайдери.",
+ "ca": "Aviat hi haurà més proveïdors."
+ },
"BACKEND$AGENT_SERVER_DESCRIPTION": {
"en": "Connect to an agent-server running locally or on another machine.",
"ja": "ローカルまたは別のマシンで実行中のエージェントサーバーに接続します。",
@@ -45593,6 +45644,1281 @@
"uk": "Кнопка мікрофона в полі чату використовує розпізнавання мовлення вашого браузера. Щоб натомість використовувати власний сервіс транскрибування, наприклад локальний сервер Whisper, введіть OpenAI-сумісну кінцеву точку. Ці налаштування зберігаються лише в цьому браузері.",
"ca": "El botó del micròfon de l'entrada del xat utilitza el reconeixement de veu del navegador. Per utilitzar el teu propi servei de transcripció, com ara un servidor Whisper local, introdueix un endpoint compatible amb OpenAI. Aquesta configuració només es desa en aquest navegador."
},
+ "BACKEND$DIGITALOCEAN_ADD_CONNECTION": {
+ "en": "Add another",
+ "ja": "別の接続を追加",
+ "zh-CN": "添加其他连接",
+ "zh-TW": "新增其他連線",
+ "ko-KR": "다른 연결 추가",
+ "no": "Legg til en annen",
+ "it": "Aggiungi un'altra",
+ "pt": "Adicionar outra",
+ "es": "Añadir otra",
+ "ar": "إضافة اتصال آخر",
+ "fr": "Ajouter une autre",
+ "tr": "Başka bir tane ekle",
+ "de": "Weitere hinzufügen",
+ "uk": "Додати інше",
+ "ca": "Afegeix-ne una altra"
+ },
+ "BACKEND$DIGITALOCEAN_AGENTS_EMPTY": {
+ "en": "No hosted agents found for this team.",
+ "ja": "このチームのホスト型エージェントは見つかりませんでした。",
+ "zh-CN": "未找到该团队的托管 Agent。",
+ "zh-TW": "找不到此團隊的託管 Agent。",
+ "ko-KR": "이 팀의 호스팅된 에이전트가 없습니다.",
+ "no": "Fant ingen vertsbaserte agenter for dette teamet.",
+ "it": "Nessun agente gestito trovato per questo team.",
+ "pt": "Nenhum agente hospedado encontrado para esta equipe.",
+ "es": "No se encontraron agentes alojados para este equipo.",
+ "ar": "لم يتم العثور على وكلاء مُستضافين لهذا الفريق.",
+ "fr": "Aucun agent hébergé trouvé pour cette équipe.",
+ "tr": "Bu ekip için barındırılan ajan bulunamadı.",
+ "de": "Keine gehosteten Agenten für dieses Team gefunden.",
+ "uk": "Для цієї команди не знайдено розміщених агентів.",
+ "ca": "No s'ha trobat cap agent allotjat per a aquest equip."
+ },
+ "BACKEND$DIGITALOCEAN_AGENTS_FAILED": {
+ "en": "Could not load your DigitalOcean agents.",
+ "ja": "DigitalOcean のエージェントを読み込めませんでした。",
+ "zh-CN": "无法加载你的 DigitalOcean Agent。",
+ "zh-TW": "無法載入你的 DigitalOcean Agent。",
+ "ko-KR": "DigitalOcean 에이전트를 불러올 수 없습니다.",
+ "no": "Kunne ikke laste DigitalOcean-agentene dine.",
+ "it": "Impossibile caricare i tuoi agenti DigitalOcean.",
+ "pt": "Não foi possível carregar seus agentes do DigitalOcean.",
+ "es": "No se pudieron cargar tus agentes de DigitalOcean.",
+ "ar": "تعذّر تحميل وكلاء DigitalOcean الخاصين بك.",
+ "fr": "Impossible de charger vos agents DigitalOcean.",
+ "tr": "DigitalOcean ajanlarınız yüklenemedi.",
+ "de": "Deine DigitalOcean-Agenten konnten nicht geladen werden.",
+ "uk": "Не вдалося завантажити ваших агентів DigitalOcean.",
+ "ca": "No s'han pogut carregar els teus agents de DigitalOcean."
+ },
+ "BACKEND$DIGITALOCEAN_AGENTS_LOADING": {
+ "en": "Loading agents…",
+ "ja": "エージェントを読み込み中…",
+ "zh-CN": "正在加载 Agent…",
+ "zh-TW": "正在載入 Agent…",
+ "ko-KR": "에이전트를 불러오는 중…",
+ "no": "Laster agenter…",
+ "it": "Caricamento agenti…",
+ "pt": "Carregando agentes…",
+ "es": "Cargando agentes…",
+ "ar": "جارٍ تحميل الوكلاء…",
+ "fr": "Chargement des agents…",
+ "tr": "Ajanlar yükleniyor…",
+ "de": "Agenten werden geladen…",
+ "uk": "Завантаження агентів…",
+ "ca": "S'estan carregant els agents…"
+ },
+ "BACKEND$DIGITALOCEAN_AGENTS_REFRESH": {
+ "en": "Refresh agents",
+ "ja": "エージェントを更新",
+ "zh-CN": "刷新 Agent",
+ "zh-TW": "重新整理 Agent",
+ "ko-KR": "에이전트 새로 고침",
+ "no": "Oppdater agenter",
+ "it": "Aggiorna agenti",
+ "pt": "Atualizar agentes",
+ "es": "Actualizar agentes",
+ "ar": "تحديث الوكلاء",
+ "fr": "Actualiser les agents",
+ "tr": "Ajanları yenile",
+ "de": "Agenten aktualisieren",
+ "uk": "Оновити агентів",
+ "ca": "Actualitza els agents"
+ },
+ "BACKEND$DIGITALOCEAN_ATTACH_FAILED": {
+ "en": "Could not attach to that session.",
+ "ja": "そのセッションに接続できませんでした。",
+ "zh-CN": "无法连接到该会话。",
+ "zh-TW": "無法連線至該工作階段。",
+ "ko-KR": "해당 세션에 연결할 수 없습니다.",
+ "no": "Kunne ikke koble til den sesjonen.",
+ "it": "Impossibile collegarsi a quella sessione.",
+ "pt": "Não foi possível conectar-se a essa sessão.",
+ "es": "No se pudo conectar con esa sesión.",
+ "ar": "تعذّر الاتصال بتلك الجلسة.",
+ "fr": "Impossible de rejoindre cette session.",
+ "tr": "O oturuma bağlanılamadı.",
+ "de": "Verbindung zu dieser Sitzung nicht möglich.",
+ "uk": "Не вдалося підключитися до цієї сесії.",
+ "ca": "No s'ha pogut connectar amb aquesta sessió."
+ },
+ "BACKEND$DIGITALOCEAN_AUTH_FAILED": {
+ "en": "Could not connect to DigitalOcean.",
+ "ja": "DigitalOcean に接続できませんでした。",
+ "zh-CN": "无法连接到 DigitalOcean。",
+ "zh-TW": "無法連線至 DigitalOcean。",
+ "ko-KR": "DigitalOcean에 연결할 수 없습니다.",
+ "no": "Kunne ikke koble til DigitalOcean.",
+ "it": "Impossibile connettersi a DigitalOcean.",
+ "pt": "Não foi possível conectar ao DigitalOcean.",
+ "es": "No se pudo conectar con DigitalOcean.",
+ "ar": "تعذّر الاتصال بـ DigitalOcean.",
+ "fr": "Impossible de se connecter à DigitalOcean.",
+ "tr": "DigitalOcean'a bağlanılamadı.",
+ "de": "Verbindung zu DigitalOcean nicht möglich.",
+ "uk": "Не вдалося підключитися до DigitalOcean.",
+ "ca": "No s'ha pogut connectar amb DigitalOcean."
+ },
+ "BACKEND$DIGITALOCEAN_CREATING_SESSION": {
+ "en": "Launching a new session…",
+ "ja": "新しいセッションを起動しています…",
+ "zh-CN": "正在启动新会话…",
+ "zh-TW": "正在啟動新工作階段…",
+ "ko-KR": "새 세션을 시작하는 중…",
+ "no": "Starter en ny økt…",
+ "it": "Avvio di una nuova sessione…",
+ "pt": "Iniciando uma nova sessão…",
+ "es": "Iniciando una nueva sesión…",
+ "ar": "جارٍ تشغيل جلسة جديدة…",
+ "fr": "Lancement d'une nouvelle session…",
+ "tr": "Yeni bir oturum başlatılıyor…",
+ "de": "Neue Sitzung wird gestartet…",
+ "uk": "Запуск нового сеансу…",
+ "ca": "S'està iniciant una sessió nova…"
+ },
+ "BACKEND$DIGITALOCEAN_EXPIRED": {
+ "en": "This DigitalOcean sign-in has expired. Sign in again to continue.",
+ "ja": "この DigitalOcean のサインインは期限切れです。続行するには再度サインインしてください。",
+ "zh-CN": "此 DigitalOcean 登录已过期。请重新登录以继续。",
+ "zh-TW": "此 DigitalOcean 登入已過期。請重新登入以繼續。",
+ "ko-KR": "이 DigitalOcean 로그인이 만료되었습니다. 계속하려면 다시 로그인하세요.",
+ "no": "Denne DigitalOcean-innloggingen er utløpt. Logg inn igjen for å fortsette.",
+ "it": "Questo accesso a DigitalOcean è scaduto. Accedi di nuovo per continuare.",
+ "pt": "Este login do DigitalOcean expirou. Entre novamente para continuar.",
+ "es": "Este inicio de sesión de DigitalOcean ha caducado. Vuelve a iniciar sesión para continuar.",
+ "ar": "انتهت صلاحية تسجيل الدخول إلى DigitalOcean. سجّل الدخول مرة أخرى للمتابعة.",
+ "fr": "Cette connexion DigitalOcean a expiré. Reconnectez-vous pour continuer.",
+ "tr": "Bu DigitalOcean girişinin süresi doldu. Devam etmek için yeniden giriş yapın.",
+ "de": "Diese DigitalOcean-Anmeldung ist abgelaufen. Melde dich erneut an, um fortzufahren.",
+ "uk": "Термін дії цього входу DigitalOcean закінчився. Увійдіть знову, щоб продовжити.",
+ "ca": "Aquest inici de sessió de DigitalOcean ha caducat. Torna a iniciar la sessió per continuar."
+ },
+ "BACKEND$DIGITALOCEAN_NOT_PERSISTENT": {
+ "en": "Your system keychain is unavailable, so this connection lasts only until you quit.",
+ "ja": "システムのキーチェーンが利用できないため、この接続はアプリを終了するまで有効です。",
+ "zh-CN": "系统密钥链不可用,因此此连接仅在退出前有效。",
+ "zh-TW": "系統金鑰鏈無法使用,因此此連線僅在結束前有效。",
+ "ko-KR": "시스템 키체인을 사용할 수 없어 이 연결은 종료할 때까지만 유지됩니다.",
+ "no": "Systemets nøkkelring er utilgjengelig, så denne tilkoblingen varer bare til du avslutter.",
+ "it": "Il keychain di sistema non è disponibile, quindi questa connessione dura solo fino alla chiusura.",
+ "pt": "O chaveiro do sistema está indisponível, então esta conexão dura apenas até você sair.",
+ "es": "El llavero del sistema no está disponible, por lo que esta conexión solo dura hasta que salgas.",
+ "ar": "سلسلة مفاتيح النظام غير متاحة، لذا يبقى هذا الاتصال حتى إغلاق التطبيق فقط.",
+ "fr": "Le trousseau système est indisponible : cette connexion ne durera que jusqu'à la fermeture de l'application.",
+ "tr": "Sistem anahtar zinciri kullanılamıyor, bu nedenle bu bağlantı yalnızca uygulamadan çıkana kadar sürer.",
+ "de": "Der System-Schlüsselbund ist nicht verfügbar, daher besteht diese Verbindung nur bis zum Beenden.",
+ "uk": "Системне сховище ключів недоступне, тому це підключення діє лише до виходу з програми.",
+ "ca": "El clauer del sistema no està disponible, així que aquesta connexió només dura fins que surtis."
+ },
+ "BACKEND$DIGITALOCEAN_SESSION_CREATE_FAILED": {
+ "en": "Could not launch a new session.",
+ "ja": "新しいセッションを起動できませんでした。",
+ "zh-CN": "无法启动新会话。",
+ "zh-TW": "無法啟動新工作階段。",
+ "ko-KR": "새 세션을 시작할 수 없습니다.",
+ "no": "Kunne ikke starte en ny økt.",
+ "it": "Impossibile avviare una nuova sessione.",
+ "pt": "Não foi possível iniciar uma nova sessão.",
+ "es": "No se pudo iniciar una nueva sesión.",
+ "ar": "تعذّر تشغيل جلسة جديدة.",
+ "fr": "Impossible de lancer une nouvelle session.",
+ "tr": "Yeni bir oturum başlatılamadı.",
+ "de": "Neue Sitzung konnte nicht gestartet werden.",
+ "uk": "Не вдалося запустити новий сеанс.",
+ "ca": "No s'ha pogut iniciar una sessió nova."
+ },
+ "BACKEND$DIGITALOCEAN_SIGNING_IN": {
+ "en": "Waiting for your browser…",
+ "ja": "ブラウザでの操作を待っています…",
+ "zh-CN": "正在等待浏览器…",
+ "zh-TW": "正在等待瀏覽器…",
+ "ko-KR": "브라우저를 기다리는 중…",
+ "no": "Venter på nettleseren din…",
+ "it": "In attesa del browser…",
+ "pt": "Aguardando seu navegador…",
+ "es": "Esperando tu navegador…",
+ "ar": "في انتظار المتصفح…",
+ "fr": "En attente de votre navigateur…",
+ "tr": "Tarayıcınız bekleniyor…",
+ "de": "Warten auf deinen Browser…",
+ "uk": "Очікування вашого браузера…",
+ "ca": "Esperant el teu navegador…"
+ },
+ "BACKEND$DIGITALOCEAN_SIGN_IN": {
+ "en": "Sign in with DigitalOcean",
+ "ja": "DigitalOcean でサインイン",
+ "zh-CN": "使用 DigitalOcean 登录",
+ "zh-TW": "使用 DigitalOcean 登入",
+ "ko-KR": "DigitalOcean으로 로그인",
+ "no": "Logg inn med DigitalOcean",
+ "it": "Accedi con DigitalOcean",
+ "pt": "Entrar com o DigitalOcean",
+ "es": "Iniciar sesión con DigitalOcean",
+ "ar": "تسجيل الدخول باستخدام DigitalOcean",
+ "fr": "Se connecter avec DigitalOcean",
+ "tr": "DigitalOcean ile giriş yap",
+ "de": "Mit DigitalOcean anmelden",
+ "uk": "Увійти через DigitalOcean",
+ "ca": "Inicia la sessió amb DigitalOcean"
+ },
+ "BACKEND$DIGITALOCEAN_SIGN_OUT": {
+ "en": "Sign out",
+ "ja": "サインアウト",
+ "zh-CN": "退出登录",
+ "zh-TW": "登出",
+ "ko-KR": "로그아웃",
+ "no": "Logg ut",
+ "it": "Esci",
+ "pt": "Sair",
+ "es": "Cerrar sesión",
+ "ar": "تسجيل الخروج",
+ "fr": "Se déconnecter",
+ "tr": "Çıkış yap",
+ "de": "Abmelden",
+ "uk": "Вийти",
+ "ca": "Tanca la sessió"
+ },
+ "BACKEND$DIGITALOCEAN_SWITCH_CONNECTION": {
+ "en": "Connection",
+ "ja": "接続",
+ "zh-CN": "连接",
+ "zh-TW": "連線",
+ "ko-KR": "연결",
+ "no": "Tilkobling",
+ "it": "Connessione",
+ "pt": "Conexão",
+ "es": "Conexión",
+ "ar": "الاتصال",
+ "fr": "Connexion",
+ "tr": "Bağlantı",
+ "de": "Verbindung",
+ "uk": "Підключення",
+ "ca": "Connexió"
+ },
+ "BACKEND$DIGITALOCEAN_TOKEN_HINT": {
+ "en": "Use a token to connect a specific team, or when your organization does not allow third-party sign-in.",
+ "ja": "特定のチームに接続する場合や、組織がサードパーティのサインインを許可していない場合はトークンを使用します。",
+ "zh-CN": "若要连接特定团队,或你的组织不允许第三方登录,请使用令牌。",
+ "zh-TW": "若要連線特定團隊,或你的組織不允許第三方登入,請使用權杖。",
+ "ko-KR": "특정 팀에 연결하거나 조직이 타사 로그인을 허용하지 않을 때 토큰을 사용하세요.",
+ "no": "Bruk et token for å koble til et bestemt team, eller når organisasjonen din ikke tillater tredjepartsinnlogging.",
+ "it": "Usa un token per connettere un team specifico o quando la tua organizzazione non consente l'accesso tramite terze parti.",
+ "pt": "Use um token para conectar uma equipe específica ou quando sua organização não permitir login de terceiros.",
+ "es": "Usa un token para conectar un equipo específico o cuando tu organización no permita el inicio de sesión de terceros.",
+ "ar": "استخدم رمزًا للاتصال بفريق معيّن، أو عندما لا تسمح مؤسستك بتسجيل الدخول من جهات خارجية.",
+ "fr": "Utilisez un jeton pour connecter une équipe précise ou lorsque votre organisation n'autorise pas la connexion via un tiers.",
+ "tr": "Belirli bir ekibe bağlanmak için veya kuruluşunuz üçüncü taraf girişine izin vermediğinde belirteç kullanın.",
+ "de": "Verwende ein Token, um ein bestimmtes Team zu verbinden, oder wenn deine Organisation Anmeldungen über Dritte nicht erlaubt.",
+ "uk": "Використовуйте токен, щоб підключити конкретну команду або якщо ваша організація не дозволяє вхід через сторонні сервіси.",
+ "ca": "Utilitza un token per connectar un equip concret o quan la teva organització no permeti l'inici de sessió de tercers."
+ },
+ "BACKEND$DIGITALOCEAN_TOKEN_LABEL": {
+ "en": "Personal access token",
+ "ja": "パーソナルアクセストークン",
+ "zh-CN": "个人访问令牌",
+ "zh-TW": "個人存取權杖",
+ "ko-KR": "개인 액세스 토큰",
+ "no": "Personlig tilgangstoken",
+ "it": "Token di accesso personale",
+ "pt": "Token de acesso pessoal",
+ "es": "Token de acceso personal",
+ "ar": "رمز الوصول الشخصي",
+ "fr": "Jeton d'accès personnel",
+ "tr": "Kişisel erişim belirteci",
+ "de": "Persönliches Zugriffstoken",
+ "uk": "Особистий токен доступу",
+ "ca": "Token d'accés personal"
+ },
+ "BACKEND$DIGITALOCEAN_TOKEN_SUBMIT": {
+ "en": "Connect with token",
+ "ja": "トークンで接続",
+ "zh-CN": "使用令牌连接",
+ "zh-TW": "使用權杖連線",
+ "ko-KR": "토큰으로 연결",
+ "no": "Koble til med token",
+ "it": "Connetti con token",
+ "pt": "Conectar com token",
+ "es": "Conectar con token",
+ "ar": "الاتصال باستخدام الرمز",
+ "fr": "Se connecter avec un jeton",
+ "tr": "Belirteç ile bağlan",
+ "de": "Mit Token verbinden",
+ "uk": "Підключитися за токеном",
+ "ca": "Connecta amb un token"
+ },
+ "DO_AGENTS$AGENTS_HEADING": {
+ "ar": "وكلاء OpenHands",
+ "ca": "Agents OpenHands",
+ "de": "OpenHands-Agenten",
+ "en": "OpenHands agents",
+ "es": "Agentes OpenHands",
+ "fr": "Agents OpenHands",
+ "it": "Agenti OpenHands",
+ "ja": "OpenHands エージェント",
+ "ko-KR": "OpenHands 에이전트",
+ "no": "OpenHands-agenter",
+ "pt": "Agentes OpenHands",
+ "tr": "OpenHands ajanları",
+ "uk": "Агенти OpenHands",
+ "zh-CN": "OpenHands 智能体",
+ "zh-TW": "OpenHands 代理"
+ },
+ "DO_AGENTS$AGENT_CREATE_FAILED": {
+ "ar": "تعذّر إنشاء الوكيل.",
+ "ca": "No s'ha pogut crear l'agent.",
+ "de": "Der Agent konnte nicht erstellt werden.",
+ "en": "Could not create the agent.",
+ "es": "No se pudo crear el agente.",
+ "fr": "Impossible de créer l'agent.",
+ "it": "Impossibile creare l'agente.",
+ "ja": "エージェントを作成できませんでした。",
+ "ko-KR": "에이전트를 만들 수 없습니다.",
+ "no": "Kunne ikke opprette agenten.",
+ "pt": "Não foi possível criar o agente.",
+ "tr": "Ajan oluşturulamadı.",
+ "uk": "Не вдалося створити агента.",
+ "zh-CN": "无法创建智能体。",
+ "zh-TW": "無法建立代理。"
+ },
+ "DO_AGENTS$BACK": {
+ "ar": "العودة إلى الخوادم",
+ "ca": "Torna als backends",
+ "de": "Zurück zu den Backends",
+ "en": "Back to backends",
+ "es": "Volver a los backends",
+ "fr": "Retour aux backends",
+ "it": "Torna ai backend",
+ "ja": "バックエンドに戻る",
+ "ko-KR": "백엔드로 돌아가기",
+ "no": "Tilbake til backends",
+ "pt": "Voltar aos backends",
+ "tr": "Arka uçlara dön",
+ "uk": "Назад до бекендів",
+ "zh-CN": "返回后端列表",
+ "zh-TW": "返回後端列表"
+ },
+ "DO_AGENTS$BADGE": {
+ "ar": "DigitalOcean",
+ "ca": "DigitalOcean",
+ "de": "DigitalOcean",
+ "en": "DigitalOcean",
+ "es": "DigitalOcean",
+ "fr": "DigitalOcean",
+ "it": "DigitalOcean",
+ "ja": "DigitalOcean",
+ "ko-KR": "DigitalOcean",
+ "no": "DigitalOcean",
+ "pt": "DigitalOcean",
+ "tr": "DigitalOcean",
+ "uk": "DigitalOcean",
+ "zh-CN": "DigitalOcean",
+ "zh-TW": "DigitalOcean"
+ },
+ "DO_AGENTS$CONNECTED": {
+ "ar": "متصل",
+ "ca": "Connectada",
+ "de": "Verbunden",
+ "en": "Connected",
+ "es": "Conectada",
+ "fr": "Connectée",
+ "it": "Connessa",
+ "ja": "接続済み",
+ "ko-KR": "연결됨",
+ "no": "Tilkoblet",
+ "pt": "Conectada",
+ "tr": "Bağlı",
+ "uk": "Підключено",
+ "zh-CN": "已连接",
+ "zh-TW": "已連線"
+ },
+ "DO_AGENTS$CONNECTED_COUNT": {
+ "ar": "{{count}} متصل",
+ "ca": "{{count}} connectades",
+ "de": "{{count}} verbunden",
+ "en": "{{count}} connected",
+ "es": "{{count}} conectadas",
+ "fr": "{{count}} connectée(s)",
+ "it": "{{count}} connesse",
+ "ja": "{{count}} 件接続中",
+ "ko-KR": "{{count}}개 연결됨",
+ "no": "{{count}} tilkoblet",
+ "pt": "{{count}} conectadas",
+ "tr": "{{count}} bağlı",
+ "uk": "Підключено: {{count}}",
+ "zh-CN": "已连接 {{count}} 个",
+ "zh-TW": "已連線 {{count}} 個"
+ },
+ "DO_AGENTS$CREATE_TOKEN": {
+ "ar": "إنشاء رمز",
+ "ca": "Crea un testimoni",
+ "de": "Token erstellen",
+ "en": "Create a token",
+ "es": "Crear un token",
+ "fr": "Créer un jeton",
+ "it": "Crea un token",
+ "ja": "トークンを作成",
+ "ko-KR": "토큰 만들기",
+ "no": "Opprett et token",
+ "pt": "Criar um token",
+ "tr": "Belirteç oluştur",
+ "uk": "Створити токен",
+ "zh-CN": "创建令牌",
+ "zh-TW": "建立權杖"
+ },
+ "DO_AGENTS$CREATING_AGENT": {
+ "ar": "جارٍ إنشاء الوكيل…",
+ "ca": "S'està creant l'agent…",
+ "de": "Agent wird erstellt…",
+ "en": "Creating agent…",
+ "es": "Creando agente…",
+ "fr": "Création de l'agent…",
+ "it": "Creazione dell'agente…",
+ "ja": "エージェントを作成しています…",
+ "ko-KR": "에이전트를 만드는 중…",
+ "no": "Oppretter agent…",
+ "pt": "Criando agente…",
+ "tr": "Ajan oluşturuluyor…",
+ "uk": "Створення агента…",
+ "zh-CN": "正在创建智能体…",
+ "zh-TW": "正在建立代理…"
+ },
+ "DO_AGENTS$ENTRY_DESCRIPTION": {
+ "ar": "اتصل بجلسات الوكلاء المستضافة لفريقك",
+ "ca": "Connecta't a les sessions d'agents allotjades del teu equip",
+ "de": "Mit den gehosteten Agentensitzungen deines Teams verbinden",
+ "en": "Connect to your team's hosted agent sessions",
+ "es": "Conéctate a las sesiones de agentes alojadas de tu equipo",
+ "fr": "Connectez-vous aux sessions d'agents hébergées de votre équipe",
+ "it": "Connettiti alle sessioni degli agenti ospitate dal tuo team",
+ "ja": "チームのホスト型エージェントセッションに接続します",
+ "ko-KR": "팀의 호스팅된 에이전트 세션에 연결합니다",
+ "no": "Koble til teamets hostede agentøkter",
+ "pt": "Conecte-se às sessões de agentes hospedadas da sua equipe",
+ "tr": "Ekibinizin barındırılan ajan oturumlarına bağlanın",
+ "uk": "Підключайтеся до розміщених сесій агентів вашої команди",
+ "zh-CN": "连接到团队托管的智能体会话",
+ "zh-TW": "連線到團隊託管的代理工作階段"
+ },
+ "DO_AGENTS$ERROR_NOT_OPENHANDS": {
+ "ar": "لا تشغّل هذه الجلسة خادم وكيل OpenHands، لذا لا يمكن فتحها هنا. ابدأ جلسة جديدة من وكيل يستخدم قالب OpenHands.",
+ "ca": "Aquesta sessió no executa un servidor d'agents d'OpenHands, així que no es pot obrir aquí. Inicia una sessió nova des d'un agent que utilitzi la plantilla d'OpenHands.",
+ "de": "In dieser Sitzung läuft kein OpenHands-Agent-Server, daher kann sie hier nicht geöffnet werden. Starte eine neue Sitzung über einen Agenten, der die OpenHands-Vorlage verwendet.",
+ "en": "This session isn't running an OpenHands agent server, so it can't be opened here. Start a new session from an agent that uses the OpenHands template.",
+ "es": "Esta sesión no ejecuta un servidor de agentes de OpenHands, por lo que no se puede abrir aquí. Inicia una sesión nueva desde un agente que use la plantilla de OpenHands.",
+ "fr": "Cette session n'exécute pas de serveur d'agent OpenHands et ne peut donc pas être ouverte ici. Démarrez une nouvelle session depuis un agent qui utilise le modèle OpenHands.",
+ "it": "Questa sessione non esegue un server agente OpenHands, quindi non può essere aperta qui. Avvia una nuova sessione da un agente che usa il modello OpenHands.",
+ "ja": "このセッションでは OpenHands エージェントサーバーが動作していないため、ここでは開けません。OpenHands テンプレートを使うエージェントから新しいセッションを開始してください。",
+ "ko-KR": "이 세션은 OpenHands 에이전트 서버를 실행하지 않아 여기에서 열 수 없습니다. OpenHands 템플릿을 사용하는 에이전트에서 새 세션을 시작하세요.",
+ "no": "Denne økten kjører ikke en OpenHands-agentserver, så den kan ikke åpnes her. Start en ny økt fra en agent som bruker OpenHands-malen.",
+ "pt": "Esta sessão não está executando um servidor de agente OpenHands, então não pode ser aberta aqui. Inicie uma nova sessão a partir de um agente que use o modelo OpenHands.",
+ "tr": "Bu oturumda bir OpenHands ajan sunucusu çalışmıyor, bu yüzden burada açılamaz. OpenHands şablonunu kullanan bir ajandan yeni bir oturum başlatın.",
+ "uk": "У цій сесії не працює сервер агента OpenHands, тому її не можна відкрити тут. Почніть нову сесію з агента, який використовує шаблон OpenHands.",
+ "zh-CN": "此会话未运行 OpenHands 代理服务器,因此无法在此打开。请从使用 OpenHands 模板的代理启动新会话。",
+ "zh-TW": "此工作階段未執行 OpenHands 代理伺服器,因此無法在此開啟。請從使用 OpenHands 範本的代理啟動新的工作階段。"
+ },
+ "DO_AGENTS$ERROR_REFUSED": {
+ "ar": "رفضت DigitalOcean الاتصال. سجّل الدخول مرة أخرى، أو تحقق من أن هذا الحساب يملك صلاحية الوصول إلى الوكلاء المُدارين.",
+ "ca": "DigitalOcean ha rebutjat la connexió. Torna a iniciar la sessió o comprova que aquest compte té accés als agents gestionats.",
+ "de": "DigitalOcean hat die Verbindung abgelehnt. Melde dich erneut an oder prüfe, ob dieses Konto Zugriff auf Managed Agents hat.",
+ "en": "DigitalOcean refused the connection. Sign in again, or check that this account has access to Managed Agents.",
+ "es": "DigitalOcean rechazó la conexión. Vuelve a iniciar sesión o comprueba que esta cuenta tiene acceso a los agentes gestionados.",
+ "fr": "DigitalOcean a refusé la connexion. Reconnectez-vous ou vérifiez que ce compte a accès aux agents gérés.",
+ "it": "DigitalOcean ha rifiutato la connessione. Accedi di nuovo o verifica che questo account abbia accesso agli agenti gestiti.",
+ "ja": "DigitalOcean が接続を拒否しました。もう一度サインインするか、このアカウントがマネージドエージェントにアクセスできるか確認してください。",
+ "ko-KR": "DigitalOcean이 연결을 거부했습니다. 다시 로그인하거나 이 계정에 관리형 에이전트 접근 권한이 있는지 확인하세요.",
+ "no": "DigitalOcean avviste tilkoblingen. Logg inn på nytt, eller sjekk at denne kontoen har tilgang til administrerte agenter.",
+ "pt": "A DigitalOcean recusou a conexão. Entre novamente ou verifique se esta conta tem acesso aos agentes gerenciados.",
+ "tr": "DigitalOcean bağlantıyı reddetti. Tekrar oturum açın veya bu hesabın Yönetilen Ajanlar erişimi olduğunu kontrol edin.",
+ "uk": "DigitalOcean відхилив з'єднання. Увійдіть знову або перевірте, що цей обліковий запис має доступ до керованих агентів.",
+ "zh-CN": "DigitalOcean 拒绝了连接。请重新登录,或检查此账号是否有权访问托管代理。",
+ "zh-TW": "DigitalOcean 拒絕了連線。請重新登入,或確認此帳號有權存取受管代理。"
+ },
+ "DO_AGENTS$FILTER_ALL": {
+ "ar": "الكل",
+ "ca": "Totes",
+ "de": "Alle",
+ "en": "All",
+ "es": "Todas",
+ "fr": "Toutes",
+ "it": "Tutte",
+ "ja": "すべて",
+ "ko-KR": "전체",
+ "no": "Alle",
+ "pt": "Todas",
+ "tr": "Tümü",
+ "uk": "Усі",
+ "zh-CN": "全部",
+ "zh-TW": "全部"
+ },
+ "DO_AGENTS$HIDE_SESSIONS": {
+ "ar": "إخفاء جلسات {{name}}",
+ "ca": "Amaga les sessions de {{name}}",
+ "de": "Sitzungen von {{name}} ausblenden",
+ "en": "Hide sessions for {{name}}",
+ "es": "Ocultar sesiones de {{name}}",
+ "fr": "Masquer les sessions de {{name}}",
+ "it": "Nascondi le sessioni di {{name}}",
+ "ja": "{{name}} のセッションを隠す",
+ "ko-KR": "{{name}}의 세션 숨기기",
+ "no": "Skjul økter for {{name}}",
+ "pt": "Ocultar sessões de {{name}}",
+ "tr": "{{name}} oturumlarını gizle",
+ "uk": "Сховати сесії {{name}}",
+ "zh-CN": "隐藏 {{name}} 的会话",
+ "zh-TW": "隱藏 {{name}} 的工作階段"
+ },
+ "DO_AGENTS$HOSTED_SESSION": {
+ "ar": "جلسة مستضافة على DigitalOcean",
+ "ca": "Sessió allotjada a DigitalOcean",
+ "de": "Gehostete Sitzung auf DigitalOcean",
+ "en": "Hosted session on DigitalOcean",
+ "es": "Sesión alojada en DigitalOcean",
+ "fr": "Session hébergée sur DigitalOcean",
+ "it": "Sessione ospitata su DigitalOcean",
+ "ja": "DigitalOcean 上のホスト型セッション",
+ "ko-KR": "DigitalOcean에서 호스팅되는 세션",
+ "no": "Hostet økt på DigitalOcean",
+ "pt": "Sessão hospedada na DigitalOcean",
+ "tr": "DigitalOcean'da barındırılan oturum",
+ "uk": "Розміщена сесія в DigitalOcean",
+ "zh-CN": "托管在 DigitalOcean 上的会话",
+ "zh-TW": "託管於 DigitalOcean 的工作階段"
+ },
+ "DO_AGENTS$MANAGE": {
+ "ar": "إدارة الوكلاء",
+ "ca": "Gestiona els agents",
+ "de": "Agenten verwalten",
+ "en": "Manage agents",
+ "es": "Gestionar agentes",
+ "fr": "Gérer les agents",
+ "it": "Gestisci agenti",
+ "ja": "エージェントを管理",
+ "ko-KR": "에이전트 관리",
+ "no": "Administrer agenter",
+ "pt": "Gerenciar agentes",
+ "tr": "Ajanları yönet",
+ "uk": "Керувати агентами",
+ "zh-CN": "管理代理",
+ "zh-TW": "管理代理"
+ },
+ "DO_AGENTS$NEW_AGENT": {
+ "ar": "وكيل جديد",
+ "ca": "Agent nou",
+ "de": "Neuer Agent",
+ "en": "New Agent",
+ "es": "Nuevo agente",
+ "fr": "Nouvel agent",
+ "it": "Nuovo agente",
+ "ja": "新しいエージェント",
+ "ko-KR": "새 에이전트",
+ "no": "Ny agent",
+ "pt": "Novo agente",
+ "tr": "Yeni ajan",
+ "uk": "Новий агент",
+ "zh-CN": "新建智能体",
+ "zh-TW": "新增代理"
+ },
+ "DO_AGENTS$NEW_AGENT_CREATE": {
+ "ar": "إنشاء وتشغيل",
+ "ca": "Crea i inicia",
+ "de": "Erstellen und starten",
+ "en": "Create and launch",
+ "es": "Crear e iniciar",
+ "fr": "Créer et lancer",
+ "it": "Crea e avvia",
+ "ja": "作成して起動",
+ "ko-KR": "만들고 시작",
+ "no": "Opprett og start",
+ "pt": "Criar e iniciar",
+ "tr": "Oluştur ve başlat",
+ "uk": "Створити й запустити",
+ "zh-CN": "创建并启动",
+ "zh-TW": "建立並啟動"
+ },
+ "DO_AGENTS$NEW_AGENT_NAME_HINT": {
+ "ar": "حتى 64 حرفًا أو رقمًا أو -، . ، _، ويبدأ وينتهي بحرف أو رقم.",
+ "ca": "Fins a 64 lletres, xifres, -, . o _, començant i acabant amb una lletra o xifra.",
+ "de": "Bis zu 64 Buchstaben, Ziffern, -, . oder _; Anfang und Ende alphanumerisch.",
+ "en": "Up to 64 letters, numbers, -, . or _, starting and ending with a letter or number.",
+ "es": "Hasta 64 letras, números, -, . o _, empezando y terminando con una letra o número.",
+ "fr": "Jusqu'à 64 lettres, chiffres, -, . ou _, commençant et finissant par une lettre ou un chiffre.",
+ "it": "Fino a 64 lettere, numeri, -, . o _, che iniziano e finiscono con una lettera o un numero.",
+ "ja": "英数字、-、.、_ を最大 64 文字。先頭と末尾は英数字にしてください。",
+ "ko-KR": "영문자, 숫자, -, ., _ 최대 64자이며 영문자나 숫자로 시작하고 끝나야 합니다.",
+ "no": "Opptil 64 bokstaver, tall, -, . eller _, som starter og slutter med en bokstav eller et tall.",
+ "pt": "Até 64 letras, números, -, . ou _, começando e terminando com letra ou número.",
+ "tr": "En fazla 64 harf, rakam, -, . veya _; harf ya da rakamla başlayıp bitmeli.",
+ "uk": "До 64 літер, цифр, -, . або _, що починаються й закінчуються літерою чи цифрою.",
+ "zh-CN": "最多 64 个字母、数字、-、. 或 _,须以字母或数字开头和结尾。",
+ "zh-TW": "最多 64 個字母、數字、-、. 或 _,須以字母或數字開頭和結尾。"
+ },
+ "DO_AGENTS$NEW_AGENT_NAME_LABEL": {
+ "ar": "اسم الوكيل",
+ "ca": "Nom de l'agent",
+ "de": "Agentenname",
+ "en": "Agent name",
+ "es": "Nombre del agente",
+ "fr": "Nom de l'agent",
+ "it": "Nome dell'agente",
+ "ja": "エージェント名",
+ "ko-KR": "에이전트 이름",
+ "no": "Agentnavn",
+ "pt": "Nome do agente",
+ "tr": "Ajan adı",
+ "uk": "Назва агента",
+ "zh-CN": "智能体名称",
+ "zh-TW": "代理名稱"
+ },
+ "DO_AGENTS$NEW_CHAT_IN_SESSION": {
+ "ar": "محادثة جديدة في {{name}}",
+ "ca": "Xat nou a {{name}}",
+ "de": "Neuer Chat in {{name}}",
+ "en": "New chat in {{name}}",
+ "es": "Nuevo chat en {{name}}",
+ "fr": "Nouveau chat dans {{name}}",
+ "it": "Nuova chat in {{name}}",
+ "ja": "{{name}} で新しいチャット",
+ "ko-KR": "{{name}}에서 새 채팅",
+ "no": "Ny chat i {{name}}",
+ "pt": "Novo chat em {{name}}",
+ "tr": "{{name}} içinde yeni sohbet",
+ "uk": "Новий чат у {{name}}",
+ "zh-CN": "在 {{name}} 中新建聊天",
+ "zh-TW": "在 {{name}} 中新增聊天"
+ },
+ "DO_AGENTS$NEW_SESSION": {
+ "ar": "جلسة جديدة",
+ "ca": "Sessió nova",
+ "de": "Neue Sitzung",
+ "en": "New session",
+ "es": "Nueva sesión",
+ "fr": "Nouvelle session",
+ "it": "Nuova sessione",
+ "ja": "新しいセッション",
+ "ko-KR": "새 세션",
+ "no": "Ny økt",
+ "pt": "Nova sessão",
+ "tr": "Yeni oturum",
+ "uk": "Нова сесія",
+ "zh-CN": "新建会话",
+ "zh-TW": "新增工作階段"
+ },
+ "DO_AGENTS$NEW_SESSION_FOR": {
+ "ar": "جلسة جديدة لـ {{name}}",
+ "ca": "Sessió nova per a {{name}}",
+ "de": "Neue Sitzung für {{name}}",
+ "en": "New session for {{name}}",
+ "es": "Nueva sesión para {{name}}",
+ "fr": "Nouvelle session pour {{name}}",
+ "it": "Nuova sessione per {{name}}",
+ "ja": "{{name}} の新しいセッション",
+ "ko-KR": "{{name}}의 새 세션",
+ "no": "Ny økt for {{name}}",
+ "pt": "Nova sessão para {{name}}",
+ "tr": "{{name}} için yeni oturum",
+ "uk": "Нова сесія для {{name}}",
+ "zh-CN": "为 {{name}} 新建会话",
+ "zh-TW": "為 {{name}} 新增工作階段"
+ },
+ "DO_AGENTS$NO_MATCHES": {
+ "ar": "لا يوجد وكلاء أو جلسات تطابق عوامل التصفية.",
+ "ca": "Cap agent ni sessió coincideix amb els filtres.",
+ "de": "Keine Agenten oder Sitzungen entsprechen deinen Filtern.",
+ "en": "No agents or sessions match your filters.",
+ "es": "Ningún agente ni sesión coincide con tus filtros.",
+ "fr": "Aucun agent ni aucune session ne correspond à vos filtres.",
+ "it": "Nessun agente o sessione corrisponde ai filtri.",
+ "ja": "フィルターに一致するエージェントやセッションはありません。",
+ "ko-KR": "필터와 일치하는 에이전트나 세션이 없습니다.",
+ "no": "Ingen agenter eller økter samsvarer med filtrene.",
+ "pt": "Nenhum agente ou sessão corresponde aos seus filtros.",
+ "tr": "Filtrelerinizle eşleşen ajan veya oturum yok.",
+ "uk": "Немає агентів чи сесій, що відповідають фільтрам.",
+ "zh-CN": "没有符合筛选条件的智能体或会话。",
+ "zh-TW": "沒有符合篩選條件的代理或工作階段。"
+ },
+ "DO_AGENTS$NO_OPENHANDS_AGENTS": {
+ "ar": "لا يملك هذا الفريق أي وكلاء OpenHands بعد. استخدم «وكيل جديد» لإنشاء واحد.",
+ "ca": "Aquest equip encara no té agents OpenHands. Fes servir Agent nou per crear-ne un.",
+ "de": "Dieses Team hat noch keine OpenHands-Agenten. Erstellen Sie einen mit „Neuer Agent“.",
+ "en": "This team has no OpenHands agents yet. Use New Agent to create one.",
+ "es": "Este equipo aún no tiene agentes OpenHands. Usa Nuevo agente para crear uno.",
+ "fr": "Cette équipe n'a pas encore d'agent OpenHands. Utilisez Nouvel agent pour en créer un.",
+ "it": "Questo team non ha ancora agenti OpenHands. Usa Nuovo agente per crearne uno.",
+ "ja": "このチームにはまだ OpenHands エージェントがありません。「新しいエージェント」で作成してください。",
+ "ko-KR": "이 팀에는 아직 OpenHands 에이전트가 없습니다. 새 에이전트로 하나를 만드세요.",
+ "no": "Dette teamet har ingen OpenHands-agenter ennå. Bruk Ny agent for å opprette en.",
+ "pt": "Esta equipe ainda não tem agentes OpenHands. Use Novo agente para criar um.",
+ "tr": "Bu ekibin henüz OpenHands ajanı yok. Oluşturmak için Yeni ajan'ı kullanın.",
+ "uk": "У цієї команди ще немає агентів OpenHands. Створіть його кнопкою «Новий агент».",
+ "zh-CN": "该团队还没有 OpenHands 智能体。使用“新建智能体”创建一个。",
+ "zh-TW": "此團隊尚無 OpenHands 代理。使用「新增代理」建立一個。"
+ },
+ "DO_AGENTS$NO_SESSIONS": {
+ "ar": "لا توجد جلسات بعد. ابدأ جلسة للبدء.",
+ "ca": "Encara no hi ha sessions. Inicia'n una per començar.",
+ "de": "Noch keine Sitzungen. Starte eine, um loszulegen.",
+ "en": "No sessions yet. Launch one to get started.",
+ "es": "Aún no hay sesiones. Inicia una para empezar.",
+ "fr": "Aucune session pour l'instant. Lancez-en une pour commencer.",
+ "it": "Ancora nessuna sessione. Avviane una per iniziare.",
+ "ja": "セッションはまだありません。起動して始めましょう。",
+ "ko-KR": "아직 세션이 없습니다. 하나를 시작해 보세요.",
+ "no": "Ingen økter ennå. Start en for å komme i gang.",
+ "pt": "Ainda não há sessões. Inicie uma para começar.",
+ "tr": "Henüz oturum yok. Başlamak için bir tane başlatın.",
+ "uk": "Сесій ще немає. Запустіть одну, щоб почати.",
+ "zh-CN": "还没有会话。启动一个即可开始。",
+ "zh-TW": "還沒有工作階段。啟動一個即可開始。"
+ },
+ "DO_AGENTS$NO_SESSIONS_SHORT": {
+ "ar": "لا توجد جلسات بعد",
+ "ca": "Encara no hi ha sessions",
+ "de": "Noch keine Sitzungen",
+ "en": "No sessions yet",
+ "es": "Aún no hay sesiones",
+ "fr": "Aucune session pour l'instant",
+ "it": "Ancora nessuna sessione",
+ "ja": "セッションはまだありません",
+ "ko-KR": "아직 세션이 없습니다",
+ "no": "Ingen økter ennå",
+ "pt": "Nenhuma sessão ainda",
+ "tr": "Henüz oturum yok",
+ "uk": "Сесій ще немає",
+ "zh-CN": "暂无会话",
+ "zh-TW": "尚無工作階段"
+ },
+ "DO_AGENTS$OPEN": {
+ "ar": "فتح",
+ "ca": "Obre",
+ "de": "Öffnen",
+ "en": "Open",
+ "es": "Abrir",
+ "fr": "Ouvrir",
+ "it": "Apri",
+ "ja": "開く",
+ "ko-KR": "열기",
+ "no": "Åpne",
+ "pt": "Abrir",
+ "tr": "Aç",
+ "uk": "Відкрити",
+ "zh-CN": "打开",
+ "zh-TW": "開啟"
+ },
+ "DO_AGENTS$OPEN_AGENT": {
+ "ar": "فتح {{name}}",
+ "ca": "Obre {{name}}",
+ "de": "{{name}} öffnen",
+ "en": "Open {{name}}",
+ "es": "Abrir {{name}}",
+ "fr": "Ouvrir {{name}}",
+ "it": "Apri {{name}}",
+ "ja": "{{name}} を開く",
+ "ko-KR": "{{name}} 열기",
+ "no": "Åpne {{name}}",
+ "pt": "Abrir {{name}}",
+ "tr": "{{name}} aç",
+ "uk": "Відкрити {{name}}",
+ "zh-CN": "打开 {{name}}",
+ "zh-TW": "開啟 {{name}}"
+ },
+ "DO_AGENTS$OTHER_SESSIONS": {
+ "ar": "جلسات أخرى",
+ "ca": "Altres sessions",
+ "de": "Weitere Sitzungen",
+ "en": "Other sessions",
+ "es": "Otras sesiones",
+ "fr": "Autres sessions",
+ "it": "Altre sessioni",
+ "ja": "その他のセッション",
+ "ko-KR": "기타 세션",
+ "no": "Andre økter",
+ "pt": "Outras sessões",
+ "tr": "Diğer oturumlar",
+ "uk": "Інші сесії",
+ "zh-CN": "其他会话",
+ "zh-TW": "其他工作階段"
+ },
+ "DO_AGENTS$PAUSE": {
+ "ar": "إيقاف الجلسة مؤقتًا",
+ "ca": "Posa la sessió en pausa",
+ "de": "Sitzung pausieren",
+ "en": "Pause session",
+ "es": "Pausar sesión",
+ "fr": "Mettre la session en pause",
+ "it": "Metti in pausa la sessione",
+ "ja": "セッションを一時停止",
+ "ko-KR": "세션 일시 중지",
+ "no": "Sett økten på pause",
+ "pt": "Pausar sessão",
+ "tr": "Oturumu duraklat",
+ "uk": "Призупинити сесію",
+ "zh-CN": "暂停会话",
+ "zh-TW": "暫停工作階段"
+ },
+ "DO_AGENTS$RESUME_AND_CONNECT": {
+ "ar": "استئناف واتصال",
+ "ca": "Reprèn i connecta",
+ "de": "Fortsetzen & verbinden",
+ "en": "Resume & connect",
+ "es": "Reanudar y conectar",
+ "fr": "Reprendre et connecter",
+ "it": "Riprendi e connetti",
+ "ja": "再開して接続",
+ "ko-KR": "재개 후 연결",
+ "no": "Gjenoppta og koble til",
+ "pt": "Retomar e conectar",
+ "tr": "Sürdür ve bağlan",
+ "uk": "Відновити й підключити",
+ "zh-CN": "恢复并连接",
+ "zh-TW": "繼續並連線"
+ },
+ "DO_AGENTS$SANDBOX_SIZE": {
+ "ar": "حجم بيئة العزل",
+ "ca": "Mida del sandbox",
+ "de": "Sandbox-Größe",
+ "en": "Sandbox size",
+ "es": "Tamaño del sandbox",
+ "fr": "Taille du sandbox",
+ "it": "Dimensione della sandbox",
+ "ja": "サンドボックスのサイズ",
+ "ko-KR": "샌드박스 크기",
+ "no": "Sandkassestørrelse",
+ "pt": "Tamanho do sandbox",
+ "tr": "Sandbox boyutu",
+ "uk": "Розмір пісочниці",
+ "zh-CN": "沙箱规格",
+ "zh-TW": "沙箱規格"
+ },
+ "DO_AGENTS$SANDBOX_SIZE_DEFAULT": {
+ "ar": "افتراضي (تختاره DigitalOcean)",
+ "ca": "Predeterminada (la tria DigitalOcean)",
+ "de": "Standard (DigitalOcean wählt)",
+ "en": "Default (DigitalOcean picks)",
+ "es": "Predeterminado (lo elige DigitalOcean)",
+ "fr": "Par défaut (choisie par DigitalOcean)",
+ "it": "Predefinita (sceglie DigitalOcean)",
+ "ja": "デフォルト(DigitalOcean が選択)",
+ "ko-KR": "기본값(DigitalOcean이 선택)",
+ "no": "Standard (DigitalOcean velger)",
+ "pt": "Padrão (a DigitalOcean escolhe)",
+ "tr": "Varsayılan (DigitalOcean seçer)",
+ "uk": "За замовчуванням (обирає DigitalOcean)",
+ "zh-CN": "默认(由 DigitalOcean 选择)",
+ "zh-TW": "預設(由 DigitalOcean 選擇)"
+ },
+ "DO_AGENTS$SANDBOX_SIZE_HINT": {
+ "ar": "ينطبق على كل جلسة لهذا الوكيل.",
+ "ca": "S'aplica a totes les sessions d'aquest agent.",
+ "de": "Gilt für jede Sitzung dieses Agenten.",
+ "en": "Applies to every session of this agent.",
+ "es": "Se aplica a todas las sesiones de este agente.",
+ "fr": "S'applique à chaque session de cet agent.",
+ "it": "Si applica a ogni sessione di questo agente.",
+ "ja": "このエージェントのすべてのセッションに適用されます。",
+ "ko-KR": "이 에이전트의 모든 세션에 적용됩니다.",
+ "no": "Gjelder for alle økter for denne agenten.",
+ "pt": "Aplica-se a todas as sessões deste agente.",
+ "tr": "Bu ajanın tüm oturumlarına uygulanır.",
+ "uk": "Застосовується до кожного сеансу цього агента.",
+ "zh-CN": "适用于此智能体的所有会话。",
+ "zh-TW": "套用至此代理的所有工作階段。"
+ },
+ "DO_AGENTS$SANDBOX_SIZE_OPTION": {
+ "ar": "{{vcpus}} vCPU · {{memory}} GB",
+ "ca": "{{vcpus}} vCPU · {{memory}} GB",
+ "de": "{{vcpus}} vCPU · {{memory}} GB",
+ "en": "{{vcpus}} vCPU · {{memory}} GB",
+ "es": "{{vcpus}} vCPU · {{memory}} GB",
+ "fr": "{{vcpus}} vCPU · {{memory}} Go",
+ "it": "{{vcpus}} vCPU · {{memory}} GB",
+ "ja": "{{vcpus}} vCPU · {{memory}} GB",
+ "ko-KR": "{{vcpus}} vCPU · {{memory}} GB",
+ "no": "{{vcpus}} vCPU · {{memory}} GB",
+ "pt": "{{vcpus}} vCPU · {{memory}} GB",
+ "tr": "{{vcpus}} vCPU · {{memory}} GB",
+ "uk": "{{vcpus}} vCPU · {{memory}} ГБ",
+ "zh-CN": "{{vcpus}} vCPU · {{memory}} GB",
+ "zh-TW": "{{vcpus}} vCPU · {{memory}} GB"
+ },
+ "DO_AGENTS$SANDBOX_SIZE_OPTION_PRICE": {
+ "ar": "{{vcpus}} vCPU · {{memory}} GB · {{price}} شهريًا",
+ "ca": "{{vcpus}} vCPU · {{memory}} GB · {{price}}/mes",
+ "de": "{{vcpus}} vCPU · {{memory}} GB · {{price}}/Monat",
+ "en": "{{vcpus}} vCPU · {{memory}} GB · {{price}}/month",
+ "es": "{{vcpus}} vCPU · {{memory}} GB · {{price}}/mes",
+ "fr": "{{vcpus}} vCPU · {{memory}} Go · {{price}}/mois",
+ "it": "{{vcpus}} vCPU · {{memory}} GB · {{price}}/mese",
+ "ja": "{{vcpus}} vCPU · {{memory}} GB · {{price}}/月",
+ "ko-KR": "{{vcpus}} vCPU · {{memory}} GB · 월 {{price}}",
+ "no": "{{vcpus}} vCPU · {{memory}} GB · {{price}}/måned",
+ "pt": "{{vcpus}} vCPU · {{memory}} GB · {{price}}/mês",
+ "tr": "{{vcpus}} vCPU · {{memory}} GB · {{price}}/ay",
+ "uk": "{{vcpus}} vCPU · {{memory}} ГБ · {{price}}/місяць",
+ "zh-CN": "{{vcpus}} vCPU · {{memory}} GB · {{price}}/月",
+ "zh-TW": "{{vcpus}} vCPU · {{memory}} GB · {{price}}/月"
+ },
+ "DO_AGENTS$SEARCH_PLACEHOLDER": {
+ "ar": "ابحث في الوكلاء والجلسات",
+ "ca": "Cerca agents i sessions",
+ "de": "Agenten und Sitzungen durchsuchen",
+ "en": "Search agents and sessions",
+ "es": "Buscar agentes y sesiones",
+ "fr": "Rechercher des agents et des sessions",
+ "it": "Cerca agenti e sessioni",
+ "ja": "エージェントとセッションを検索",
+ "ko-KR": "에이전트 및 세션 검색",
+ "no": "Søk i agenter og økter",
+ "pt": "Pesquisar agentes e sessões",
+ "tr": "Ajanlarda ve oturumlarda ara",
+ "uk": "Пошук агентів і сесій",
+ "zh-CN": "搜索智能体和会话",
+ "zh-TW": "搜尋代理與工作階段"
+ },
+ "DO_AGENTS$SESSION_ACTION_FAILED": {
+ "ar": "تعذّر تحديث تلك الجلسة.",
+ "ca": "No s'ha pogut actualitzar la sessió.",
+ "de": "Diese Sitzung konnte nicht aktualisiert werden.",
+ "en": "Could not update that session.",
+ "es": "No se pudo actualizar esa sesión.",
+ "fr": "Impossible de mettre à jour cette session.",
+ "it": "Impossibile aggiornare la sessione.",
+ "ja": "セッションを更新できませんでした。",
+ "ko-KR": "세션을 업데이트할 수 없습니다.",
+ "no": "Kunne ikke oppdatere økten.",
+ "pt": "Não foi possível atualizar essa sessão.",
+ "tr": "Oturum güncellenemedi.",
+ "uk": "Не вдалося оновити сесію.",
+ "zh-CN": "无法更新该会话。",
+ "zh-TW": "無法更新該工作階段。"
+ },
+ "DO_AGENTS$SESSION_COUNT_zero": {
+ "ar": "{{count}} جلسة",
+ "ca": "{{count}} sessions",
+ "de": "{{count}} Sitzungen",
+ "en": "{{count}} sessions",
+ "es": "{{count}} sesiones",
+ "fr": "{{count}} session",
+ "it": "{{count}} sessioni",
+ "ja": "{{count}} 件のセッション",
+ "ko-KR": "세션 {{count}}개",
+ "no": "{{count}} økter",
+ "pt": "{{count}} sessões",
+ "tr": "{{count}} oturum",
+ "uk": "{{count}} сесій",
+ "zh-CN": "{{count}} 个会话",
+ "zh-TW": "{{count}} 個工作階段"
+ },
+ "DO_AGENTS$SESSION_COUNT_one": {
+ "ar": "{{count}} جلسة",
+ "ca": "{{count}} sessió",
+ "de": "{{count}} Sitzung",
+ "en": "{{count}} session",
+ "es": "{{count}} sesión",
+ "fr": "{{count}} session",
+ "it": "{{count}} sessione",
+ "ja": "{{count}} 件のセッション",
+ "ko-KR": "세션 {{count}}개",
+ "no": "{{count}} økt",
+ "pt": "{{count}} sessão",
+ "tr": "{{count}} oturum",
+ "uk": "{{count}} сесія",
+ "zh-CN": "{{count}} 个会话",
+ "zh-TW": "{{count}} 個工作階段"
+ },
+ "DO_AGENTS$SESSION_COUNT_two": {
+ "ar": "{{count}} جلستان",
+ "ca": "{{count}} sessions",
+ "de": "{{count}} Sitzungen",
+ "en": "{{count}} sessions",
+ "es": "{{count}} sesiones",
+ "fr": "{{count}} sessions",
+ "it": "{{count}} sessioni",
+ "ja": "{{count}} 件のセッション",
+ "ko-KR": "세션 {{count}}개",
+ "no": "{{count}} økter",
+ "pt": "{{count}} sessões",
+ "tr": "{{count}} oturum",
+ "uk": "{{count}} сесії",
+ "zh-CN": "{{count}} 个会话",
+ "zh-TW": "{{count}} 個工作階段"
+ },
+ "DO_AGENTS$SESSION_COUNT_few": {
+ "ar": "{{count}} جلسات",
+ "ca": "{{count}} sessions",
+ "de": "{{count}} Sitzungen",
+ "en": "{{count}} sessions",
+ "es": "{{count}} sesiones",
+ "fr": "{{count}} sessions",
+ "it": "{{count}} sessioni",
+ "ja": "{{count}} 件のセッション",
+ "ko-KR": "세션 {{count}}개",
+ "no": "{{count}} økter",
+ "pt": "{{count}} sessões",
+ "tr": "{{count}} oturum",
+ "uk": "{{count}} сесії",
+ "zh-CN": "{{count}} 个会话",
+ "zh-TW": "{{count}} 個工作階段"
+ },
+ "DO_AGENTS$SESSION_COUNT_many": {
+ "ar": "{{count}} جلسة",
+ "ca": "{{count}} sessions",
+ "de": "{{count}} Sitzungen",
+ "en": "{{count}} sessions",
+ "es": "{{count}} sesiones",
+ "fr": "{{count}} sessions",
+ "it": "{{count}} sessioni",
+ "ja": "{{count}} 件のセッション",
+ "ko-KR": "세션 {{count}}개",
+ "no": "{{count}} økter",
+ "pt": "{{count}} sessões",
+ "tr": "{{count}} oturum",
+ "uk": "{{count}} сесій",
+ "zh-CN": "{{count}} 个会话",
+ "zh-TW": "{{count}} 個工作階段"
+ },
+ "DO_AGENTS$SESSION_COUNT_other": {
+ "ar": "{{count}} جلسة",
+ "ca": "{{count}} sessions",
+ "de": "{{count}} Sitzungen",
+ "en": "{{count}} sessions",
+ "es": "{{count}} sesiones",
+ "fr": "{{count}} sessions",
+ "it": "{{count}} sessioni",
+ "ja": "{{count}} 件のセッション",
+ "ko-KR": "세션 {{count}}개",
+ "no": "{{count}} økter",
+ "pt": "{{count}} sessões",
+ "tr": "{{count}} oturum",
+ "uk": "{{count}} сесії",
+ "zh-CN": "{{count}} 个会话",
+ "zh-TW": "{{count}} 個工作階段"
+ },
+ "DO_AGENTS$SESSION_NAME_FALLBACK": {
+ "ar": "الجلسة {{id}}",
+ "ca": "Sessió {{id}}",
+ "de": "Sitzung {{id}}",
+ "en": "Session {{id}}",
+ "es": "Sesión {{id}}",
+ "fr": "Session n° {{id}}",
+ "it": "Sessione {{id}}",
+ "ja": "セッション {{id}}",
+ "ko-KR": "세션 {{id}}",
+ "no": "Økt {{id}}",
+ "pt": "Sessão {{id}}",
+ "tr": "Oturum {{id}}",
+ "uk": "Сесія {{id}}",
+ "zh-CN": "会话 {{id}}",
+ "zh-TW": "工作階段 {{id}}"
+ },
+ "DO_AGENTS$SHOW_SESSIONS": {
+ "ar": "عرض جلسات {{name}}",
+ "ca": "Mostra les sessions de {{name}}",
+ "de": "Sitzungen von {{name}} anzeigen",
+ "en": "Show sessions for {{name}}",
+ "es": "Mostrar sesiones de {{name}}",
+ "fr": "Afficher les sessions de {{name}}",
+ "it": "Mostra le sessioni di {{name}}",
+ "ja": "{{name}} のセッションを表示",
+ "ko-KR": "{{name}}의 세션 표시",
+ "no": "Vis økter for {{name}}",
+ "pt": "Mostrar sessões de {{name}}",
+ "tr": "{{name}} oturumlarını göster",
+ "uk": "Показати сесії {{name}}",
+ "zh-CN": "显示 {{name}} 的会话",
+ "zh-TW": "顯示 {{name}} 的工作階段"
+ },
+ "DO_AGENTS$SIGN_IN_DESCRIPTION": {
+ "ar": "سجّل الدخول لفتح وكلاء OpenHands الخاصين بفريقك. تظهر جلساتهم في الشريط الجانبي مع محادثاتها.",
+ "ca": "Inicia la sessió per obrir els agents OpenHands del teu equip. Les seves sessions apareixen a la barra lateral amb les seves converses.",
+ "de": "Melden Sie sich an, um die OpenHands-Agenten Ihres Teams zu öffnen. Ihre Sitzungen erscheinen mit ihren Unterhaltungen in der Seitenleiste.",
+ "en": "Sign in to open your team's OpenHands agents. Their sessions show up in the sidebar with their conversations.",
+ "es": "Inicia sesión para abrir los agentes OpenHands de tu equipo. Sus sesiones aparecen en la barra lateral con sus conversaciones.",
+ "fr": "Connectez-vous pour ouvrir les agents OpenHands de votre équipe. Leurs sessions s'affichent dans la barre latérale avec leurs conversations.",
+ "it": "Accedi per aprire gli agenti OpenHands del tuo team. Le loro sessioni compaiono nella barra laterale insieme alle conversazioni.",
+ "ja": "サインインしてチームの OpenHands エージェントを開きます。セッションは会話とともにサイドバーに表示されます。",
+ "ko-KR": "로그인하여 팀의 OpenHands 에이전트를 여세요. 세션은 대화와 함께 사이드바에 표시됩니다.",
+ "no": "Logg på for å åpne teamets OpenHands-agenter. Øktene deres vises i sidefeltet sammen med samtalene.",
+ "pt": "Entre para abrir os agentes OpenHands da sua equipe. As sessões aparecem na barra lateral com as conversas.",
+ "tr": "Ekibinizin OpenHands ajanlarını açmak için oturum açın. Oturumları, konuşmalarıyla birlikte kenar çubuğunda görünür.",
+ "uk": "Увійдіть, щоб відкрити агентів OpenHands вашої команди. Їхні сесії з'являться на бічній панелі разом із розмовами.",
+ "zh-CN": "登录以打开你团队的 OpenHands 智能体。它们的会话会连同对话一起显示在侧边栏中。",
+ "zh-TW": "登入以開啟你團隊的 OpenHands 代理。其工作階段會連同對話顯示在側邊欄中。"
+ },
+ "DO_AGENTS$SIGN_IN_TITLE": {
+ "ar": "اربط فريقك على DigitalOcean",
+ "ca": "Connecta el teu equip de DigitalOcean",
+ "de": "Verbinde dein DigitalOcean-Team",
+ "en": "Connect your DigitalOcean team",
+ "es": "Conecta tu equipo de DigitalOcean",
+ "fr": "Connectez votre équipe DigitalOcean",
+ "it": "Collega il tuo team DigitalOcean",
+ "ja": "DigitalOcean チームを接続",
+ "ko-KR": "DigitalOcean 팀 연결",
+ "no": "Koble til DigitalOcean-teamet ditt",
+ "pt": "Conecte sua equipe da DigitalOcean",
+ "tr": "DigitalOcean ekibinizi bağlayın",
+ "uk": "Підключіть свою команду DigitalOcean",
+ "zh-CN": "连接你的 DigitalOcean 团队",
+ "zh-TW": "連結你的 DigitalOcean 團隊"
+ },
+ "DO_AGENTS$STAGE_AGENT": {
+ "ar": "في انتظار خادم الوكيل…",
+ "ca": "S'està esperant el servidor de l'agent…",
+ "de": "Warte auf den Agent-Server…",
+ "en": "Waiting for the agent server…",
+ "es": "Esperando al servidor del agente…",
+ "fr": "En attente du serveur de l'agent…",
+ "it": "In attesa del server dell'agente…",
+ "ja": "エージェントサーバーを待っています…",
+ "ko-KR": "에이전트 서버를 기다리는 중…",
+ "no": "Venter på agentserveren…",
+ "pt": "Aguardando o servidor do agente…",
+ "tr": "Ajan sunucusu bekleniyor…",
+ "uk": "Очікування сервера агента…",
+ "zh-CN": "正在等待智能体服务器…",
+ "zh-TW": "正在等待代理伺服器…"
+ },
+ "DO_AGENTS$STAGE_TUNNEL": {
+ "ar": "جارٍ فتح نفق آمن…",
+ "ca": "S'està obrint un túnel segur…",
+ "de": "Sicherer Tunnel wird geöffnet…",
+ "en": "Connecting to the session…",
+ "es": "Abriendo un túnel seguro…",
+ "fr": "Ouverture d'un tunnel sécurisé…",
+ "it": "Apertura di un tunnel sicuro…",
+ "ja": "セキュアなトンネルを開いています…",
+ "ko-KR": "보안 터널을 여는 중…",
+ "no": "Åpner en sikker tunnel…",
+ "pt": "Abrindo um túnel seguro…",
+ "tr": "Güvenli tünel açılıyor…",
+ "uk": "Відкриття захищеного тунелю…",
+ "zh-CN": "正在打开安全隧道…",
+ "zh-TW": "正在開啟安全通道…"
+ },
+ "DO_AGENTS$STAGE_WAKING": {
+ "ar": "جارٍ إيقاظ الجلسة…",
+ "ca": "S'està reactivant la sessió…",
+ "de": "Sitzung wird aufgeweckt…",
+ "en": "Waking the session…",
+ "es": "Reactivando la sesión…",
+ "fr": "Réveil de la session…",
+ "it": "Riattivazione della sessione…",
+ "ja": "セッションを起動しています…",
+ "ko-KR": "세션을 깨우는 중…",
+ "no": "Vekker økten…",
+ "pt": "Reativando a sessão…",
+ "tr": "Oturum uyandırılıyor…",
+ "uk": "Пробудження сесії…",
+ "zh-CN": "正在唤醒会话…",
+ "zh-TW": "正在喚醒工作階段…"
+ },
+ "DO_AGENTS$STATUS_ENDED": {
+ "ar": "انتهت",
+ "ca": "Finalitzada",
+ "de": "Beendet",
+ "en": "Ended",
+ "es": "Finalizada",
+ "fr": "Terminée",
+ "it": "Terminata",
+ "ja": "終了",
+ "ko-KR": "종료됨",
+ "no": "Avsluttet",
+ "pt": "Encerrada",
+ "tr": "Sona erdi",
+ "uk": "Завершено",
+ "zh-CN": "已结束",
+ "zh-TW": "已結束"
+ },
+ "DO_AGENTS$STATUS_FAILED": {
+ "ar": "فشل",
+ "ca": "Ha fallat",
+ "de": "Fehlgeschlagen",
+ "en": "Failed",
+ "es": "Fallida",
+ "fr": "Échec",
+ "it": "Non riuscita",
+ "ja": "失敗",
+ "ko-KR": "실패",
+ "no": "Mislyktes",
+ "pt": "Falhou",
+ "tr": "Başarısız",
+ "uk": "Помилка",
+ "zh-CN": "失败",
+ "zh-TW": "失敗"
+ },
+ "DO_AGENTS$STATUS_PAUSED": {
+ "ar": "متوقف مؤقتًا",
+ "ca": "En pausa",
+ "de": "Pausiert",
+ "en": "Paused",
+ "es": "En pausa",
+ "fr": "En pause",
+ "it": "In pausa",
+ "ja": "一時停止中",
+ "ko-KR": "일시 중지됨",
+ "no": "Satt på pause",
+ "pt": "Pausada",
+ "tr": "Duraklatıldı",
+ "uk": "Призупинено",
+ "zh-CN": "已暂停",
+ "zh-TW": "已暫停"
+ },
+ "DO_AGENTS$SWITCH_AGENT": {
+ "ar": "تبديل الوكيل",
+ "ca": "Canvia d'agent",
+ "de": "Agent wechseln",
+ "en": "Switch agent",
+ "es": "Cambiar de agente",
+ "fr": "Changer d'agent",
+ "it": "Cambia agente",
+ "ja": "エージェントを切り替え",
+ "ko-KR": "에이전트 전환",
+ "no": "Bytt agent",
+ "pt": "Trocar de agente",
+ "tr": "Ajan değiştir",
+ "uk": "Змінити агента",
+ "zh-CN": "切换智能体",
+ "zh-TW": "切換代理"
+ },
+ "DO_AGENTS$TAB_DESCRIPTION": {
+ "ar": "وكلاء OpenHands الخاصون بفريقك",
+ "ca": "Els agents OpenHands del teu equip",
+ "de": "Die OpenHands-Agenten Ihres Teams",
+ "en": "Your team's OpenHands agents",
+ "es": "Los agentes OpenHands de tu equipo",
+ "fr": "Les agents OpenHands de votre équipe",
+ "it": "Gli agenti OpenHands del tuo team",
+ "ja": "チームの OpenHands エージェント",
+ "ko-KR": "팀의 OpenHands 에이전트",
+ "no": "Teamets OpenHands-agenter",
+ "pt": "Os agentes OpenHands da sua equipe",
+ "tr": "Ekibinizin OpenHands ajanları",
+ "uk": "Агенти OpenHands вашої команди",
+ "zh-CN": "你团队的 OpenHands 智能体",
+ "zh-TW": "你團隊的 OpenHands 代理"
+ },
+ "DO_AGENTS$TITLE": {
+ "ar": "الوكلاء المُدارون من DigitalOcean",
+ "ca": "Agents gestionats de DigitalOcean",
+ "de": "Verwaltete Agenten von DigitalOcean",
+ "en": "DigitalOcean Managed Agents",
+ "es": "Agentes gestionados de DigitalOcean",
+ "fr": "Agents gérés DigitalOcean",
+ "it": "Agenti gestiti DigitalOcean",
+ "ja": "DigitalOcean マネージドエージェント",
+ "ko-KR": "DigitalOcean 관리형 에이전트",
+ "no": "DigitalOcean administrerte agenter",
+ "pt": "Agentes gerenciados da DigitalOcean",
+ "tr": "DigitalOcean Yönetilen Ajanlar",
+ "uk": "Керовані агенти DigitalOcean",
+ "zh-CN": "DigitalOcean 托管智能体",
+ "zh-TW": "DigitalOcean 託管代理"
+ },
"NOT_FOUND$TITLE": {
"en": "Page not found",
"ja": "ページが見つかりません",
@@ -45627,6 +46953,91 @@
"uk": "Ця адреса не відповідає жодній сторінці. Перевірте URL або поверніться на головну сторінку.",
"ca": "Aquesta adreça no correspon a cap pàgina. Comprova l'URL o torna a la pàgina d'inici."
},
+ "DO_AGENTS$STOP": {
+ "ar": "إيقاف الجلسة",
+ "ca": "Atura la sessió",
+ "de": "Sitzung beenden",
+ "en": "Stop session",
+ "es": "Detener sesión",
+ "fr": "Arrêter la session",
+ "it": "Termina la sessione",
+ "ja": "セッションを停止",
+ "ko-KR": "세션 중지",
+ "no": "Stopp økten",
+ "pt": "Encerrar sessão",
+ "tr": "Oturumu durdur",
+ "uk": "Зупинити сесію",
+ "zh-CN": "停止会话",
+ "zh-TW": "停止工作階段"
+ },
+ "DO_AGENTS$STOP_CONFIRM": {
+ "ar": "هل تريد إيقاف {{name}}؟ سيؤدي هذا إلى إنهاء الجلسة وحذف صندوق الحماية الخاص بها. لا يمكن التراجع عن ذلك.",
+ "ca": "Vols aturar {{name}}? Això finalitza la sessió i n'elimina el sandbox. No es pot desfer.",
+ "de": "{{name}} beenden? Dadurch wird die Sitzung beendet und ihre Sandbox gelöscht. Dies kann nicht rückgängig gemacht werden.",
+ "en": "Stop {{name}}? This ends the session and deletes its sandbox. It cannot be undone.",
+ "es": "¿Detener {{name}}? Esto finaliza la sesión y elimina su sandbox. No se puede deshacer.",
+ "fr": "Arrêter {{name}} ? Cela met fin à la session et supprime son bac à sable. Cette action est irréversible.",
+ "it": "Terminare {{name}}? La sessione verrà chiusa e la sua sandbox eliminata. L'operazione non può essere annullata.",
+ "ja": "{{name}} を停止しますか?セッションが終了し、サンドボックスが削除されます。元に戻せません。",
+ "ko-KR": "{{name}}을(를) 중지하시겠습니까? 세션이 종료되고 샌드박스가 삭제됩니다. 되돌릴 수 없습니다.",
+ "no": "Stoppe {{name}}? Dette avslutter økten og sletter sandkassen. Det kan ikke angres.",
+ "pt": "Encerrar {{name}}? Isto termina a sessão e elimina o seu sandbox. Não pode ser desfeito.",
+ "tr": "{{name}} durdurulsun mu? Bu, oturumu sonlandırır ve sandbox'ını siler. Geri alınamaz.",
+ "uk": "Зупинити {{name}}? Це завершить сесію та видалить її пісочницю. Дію не можна скасувати.",
+ "zh-CN": "停止 {{name}}?这将结束会话并删除其沙箱,且无法撤销。",
+ "zh-TW": "停止 {{name}}?這會結束工作階段並刪除其沙箱,且無法復原。"
+ },
+ "DO_AGENTS$DELETE_AGENT": {
+ "ar": "حذف الوكيل",
+ "ca": "Suprimeix l'agent",
+ "de": "Agent löschen",
+ "en": "Delete agent",
+ "es": "Eliminar agente",
+ "fr": "Supprimer l'agent",
+ "it": "Elimina agente",
+ "ja": "エージェントを削除",
+ "ko-KR": "에이전트 삭제",
+ "no": "Slett agent",
+ "pt": "Eliminar agente",
+ "tr": "Aracıyı sil",
+ "uk": "Видалити агента",
+ "zh-CN": "删除代理",
+ "zh-TW": "刪除代理程式"
+ },
+ "DO_AGENTS$DELETE_AGENT_CONFIRM": {
+ "ar": "هل تريد حذف الوكيل {{name}}؟ لا يمكن التراجع عن ذلك.",
+ "ca": "Vols suprimir l'agent {{name}}? No es pot desfer.",
+ "de": "Agent {{name}} löschen? Dies kann nicht rückgängig gemacht werden.",
+ "en": "Delete agent {{name}}? It cannot be undone.",
+ "es": "¿Eliminar el agente {{name}}? No se puede deshacer.",
+ "fr": "Supprimer l'agent {{name}} ? Cette action est irréversible.",
+ "it": "Eliminare l'agente {{name}}? L'operazione non può essere annullata.",
+ "ja": "エージェント {{name}} を削除しますか?元に戻せません。",
+ "ko-KR": "에이전트 {{name}}을(를) 삭제하시겠습니까? 되돌릴 수 없습니다.",
+ "no": "Slette agenten {{name}}? Det kan ikke angres.",
+ "pt": "Eliminar o agente {{name}}? Não pode ser desfeito.",
+ "tr": "{{name}} aracısı silinsin mi? Geri alınamaz.",
+ "uk": "Видалити агента {{name}}? Дію не можна скасувати.",
+ "zh-CN": "删除代理 {{name}}?此操作无法撤销。",
+ "zh-TW": "刪除代理程式 {{name}}?此操作無法復原。"
+ },
+ "DO_AGENTS$DELETE_AGENT_BLOCKED": {
+ "ar": "أوقف جلسات هذا الوكيل أولاً.",
+ "ca": "Primer atura les sessions d'aquest agent.",
+ "de": "Beenden Sie zuerst die Sitzungen dieses Agents.",
+ "en": "Stop this agent's sessions first.",
+ "es": "Primero detén las sesiones de este agente.",
+ "fr": "Arrêtez d'abord les sessions de cet agent.",
+ "it": "Prima termina le sessioni di questo agente.",
+ "ja": "先にこのエージェントのセッションを停止してください。",
+ "ko-KR": "먼저 이 에이전트의 세션을 중지하세요.",
+ "no": "Stopp denne agentens økter først.",
+ "pt": "Encerre primeiro as sessões deste agente.",
+ "tr": "Önce bu aracının oturumlarını durdurun.",
+ "uk": "Спочатку зупиніть сесії цього агента.",
+ "zh-CN": "请先停止此代理的会话。",
+ "zh-TW": "請先停止此代理程式的工作階段。"
+ },
"SCHEMA$ENABLE_SUB_AGENTS$DESCRIPTION": {
"en": "Enable sub-agent delegation via TaskToolSet.",
"ja": "TaskToolSet を介したサブエージェントへの委任を有効にします。",
@@ -47887,5 +49298,39 @@
"ca": "Webhook source {{source}} already exists, so this automation will use the existing source.",
"tr": "Webhook source {{source}} already exists, so this automation will use the existing source.",
"uk": "Webhook source {{source}} already exists, so this automation will use the existing source."
+ },
+ "BACKEND$REMOVE_MARS_CONFIRMATION": {
+ "en": "Remove \"{{name}}\"? This only disconnects it here: the DigitalOcean session keeps running (and billing) and you can reconnect it from Managed Agents. To end it and delete its sandbox, stop the session instead.",
+ "ja": "「{{name}}」を削除しますか?ここでの接続が解除されるだけです。DigitalOcean のセッションは実行(および課金)を続け、マネージドエージェントから再接続できます。終了してサンドボックスを削除するには、代わりにセッションを停止してください。",
+ "zh-CN": "移除“{{name}}”?这只会在此处断开连接:DigitalOcean 会话会继续运行(并计费),你可以在托管代理中重新连接。要结束会话并删除其沙箱,请改为停止会话。",
+ "zh-TW": "移除「{{name}}」?這只會在此處中斷連線:DigitalOcean 工作階段會繼續執行(並計費),你可以從受管代理程式重新連線。若要結束並刪除其沙箱,請改為停止工作階段。",
+ "ko-KR": "\"{{name}}\"을(를) 제거하시겠습니까? 여기서 연결만 해제됩니다. DigitalOcean 세션은 계속 실행(및 과금)되며 관리형 에이전트에서 다시 연결할 수 있습니다. 세션을 종료하고 샌드박스를 삭제하려면 대신 세션을 중지하세요.",
+ "no": "Fjerne «{{name}}»? Dette kobler den bare fra her: DigitalOcean-økten fortsetter å kjøre (og faktureres), og du kan koble til igjen fra Administrerte agenter. For å avslutte den og slette sandkassen, stopp økten i stedet.",
+ "ar": "إزالة \"{{name}}\"؟ هذا يقطع الاتصال هنا فقط: تستمر جلسة DigitalOcean في العمل (والفوترة) ويمكنك إعادة الاتصال بها من الوكلاء المُدارين. لإنهائها وحذف صندوق الحماية الخاص بها، أوقف الجلسة بدلاً من ذلك.",
+ "de": "„{{name}}“ entfernen? Dadurch wird die Verbindung nur hier getrennt: Die DigitalOcean-Sitzung läuft weiter (und wird abgerechnet) und kann über Verwaltete Agenten erneut verbunden werden. Um sie zu beenden und ihre Sandbox zu löschen, beende stattdessen die Sitzung.",
+ "fr": "Supprimer « {{name}} » ? Cela la déconnecte uniquement ici : la session DigitalOcean continue de s'exécuter (et d'être facturée) et vous pouvez vous y reconnecter depuis Agents gérés. Pour y mettre fin et supprimer son bac à sable, arrêtez plutôt la session.",
+ "it": "Rimuovere \"{{name}}\"? Viene solo disconnessa qui: la sessione DigitalOcean continua a essere eseguita (e fatturata) e puoi riconnetterla da Agenti gestiti. Per terminarla ed eliminarne la sandbox, termina invece la sessione.",
+ "pt": "Remover \"{{name}}\"? Isto apenas a desliga aqui: a sessão DigitalOcean continua em execução (e a ser faturada) e pode voltar a ligá-la a partir de Agentes geridos. Para a terminar e eliminar o seu sandbox, encerre antes a sessão.",
+ "es": "¿Quitar \"{{name}}\"? Esto solo la desconecta aquí: la sesión de DigitalOcean sigue en ejecución (y facturándose) y puedes volver a conectarla desde Agentes administrados. Para finalizarla y eliminar su sandbox, detén la sesión.",
+ "ca": "Vols treure \"{{name}}\"? Això només la desconnecta aquí: la sessió de DigitalOcean continua en execució (i facturant-se) i la pots tornar a connectar des d'Agents gestionats. Per finalitzar-la i eliminar-ne el sandbox, atura la sessió.",
+ "tr": "\"{{name}}\" kaldırılsın mı? Bu yalnızca buradaki bağlantıyı keser: DigitalOcean oturumu çalışmaya (ve faturalandırılmaya) devam eder ve Yönetilen Ajanlar'dan yeniden bağlanabilirsiniz. Oturumu sonlandırıp sandbox'ını silmek için bunun yerine oturumu durdurun.",
+ "uk": "Видалити «{{name}}»? Це лише від'єднає її тут: сесія DigitalOcean продовжить працювати (і тарифікуватися), і ви зможете повторно під'єднатися з розділу «Керовані агенти». Щоб завершити її та видалити пісочницю, натомість зупиніть сесію."
+ },
+ "BACKEND$DISCONNECT_ONLY": {
+ "en": "Disconnect only",
+ "ja": "接続解除のみ",
+ "zh-CN": "仅断开连接",
+ "zh-TW": "僅中斷連線",
+ "ko-KR": "연결만 해제",
+ "no": "Bare koble fra",
+ "ar": "قطع الاتصال فقط",
+ "de": "Nur trennen",
+ "fr": "Déconnecter uniquement",
+ "it": "Solo disconnetti",
+ "pt": "Apenas desligar",
+ "es": "Solo desconectar",
+ "ca": "Només desconnectar",
+ "tr": "Yalnızca bağlantıyı kes",
+ "uk": "Лише від'єднати"
}
}
diff --git a/src/root.tsx b/src/root.tsx
index bd5d0fd96f..f26e93ccad 100644
--- a/src/root.tsx
+++ b/src/root.tsx
@@ -41,6 +41,7 @@ import {
import { TOAST_OPTIONS } from "#/utils/custom-toast-handlers";
import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { useConfig } from "#/hooks/query/use-config";
+import { useRestoreMarsTunnels } from "#/hooks/use-mars-tunnel-backend";
import { QUERY_KEYS } from "#/hooks/query/query-keys";
import { AgentServerUIRoot } from "#/components/providers";
import { TelemetryConsentBanner } from "#/components/features/analytics/telemetry-consent-banner";
@@ -251,6 +252,7 @@ export default function App() {
const isActiveCloudBackend = active.backend.kind === "cloud";
const authMissing =
bakedKeyMissing && !hasRegisteredKey && !isActiveCloudBackend;
+ const restoringMarsTunnel = useRestoreMarsTunnels();
const queryClient = useQueryClient();
// In locked-to-Cloud mode the only valid backend is a Cloud backend whose
// host matches the configured locked Cloud host. A missing backend, a stale
@@ -325,6 +327,7 @@ export default function App() {
enabled:
!authMissing &&
!showFirstRunOnboarding &&
+ !restoringMarsTunnel &&
mainAppAuthAllowsBackendQueries,
});
const activeCloudHealth = useBackendsHealth(
@@ -371,6 +374,7 @@ export default function App() {
if (
waitingForMainAppAuth ||
redirectingToMainAppLogin ||
+ restoringMarsTunnel ||
(cookieSessionMaybeExpired && mainAppAuth.isFetching)
) {
return <AgentServerBootstrapLoading />;
diff --git a/src/routes/conversation.tsx b/src/routes/conversation.tsx
index 7dcf247e74..6167d20563 100644
--- a/src/routes/conversation.tsx
+++ b/src/routes/conversation.tsx
@@ -8,11 +8,12 @@ import { useCommandStore } from "#/stores/command-store";
import { useConversationStore } from "#/stores/conversation-store";
import { useAgentStore } from "#/stores/agent-store";
import { useConversationStateStore } from "#/stores/conversation-state-store";
-import { useActiveBackend } from "#/contexts/active-backend-context";
+import { useActiveBackendContext } from "#/contexts/active-backend-context";
import {
clearLastConversationId,
setLastConversationId,
} from "#/api/backend-registry/last-conversation-store";
+import { readBackendSelectionFromUrl } from "#/api/backend-registry/url-selection";
import { AgentState } from "#/types/agent-state";
import { EventHandler } from "../wrapper/event-handler";
@@ -39,25 +40,43 @@ function AppContent() {
const { isTask, taskStatus, taskDetail } = useTaskPollingController();
- // The conversationId in the URL belongs to whichever backend was
- // active when the route first mounted. If the user switches backends
- // while this route is still mounted, the id is meaningless under the
- // new backend — disable the active-conversation fetch (and its 404
- // toast) so we don't fire a request that the BackendSelector's
- // redirect will immediately navigate away from anyway. Mirrors the
- // same guard in `routes/automation-detail.tsx`.
- const active = useActiveBackend();
- const mountedBackendId = React.useRef(active.backend.id);
- const mountedOrgId = React.useRef(active.orgId);
+ // The conversationId in the URL belongs to whichever backend was active
+ // when the route arrived at it, unless the URL pins its owner with
+ // `?backend=` (and `?org=`). If the user switches backends while this route is still
+ // mounted, the id is meaningless under the new backend — disable the
+ // active-conversation fetch (and its 404 toast) so we don't fire a request
+ // that the BackendSelector's redirect will immediately navigate away from
+ // anyway. A navigation that lands on a conversation of the new backend
+ // (switching DigitalOcean sessions goes straight to one) re-anchors the
+ // owner instead of staying blank until a remount. Mirrors the same guard
+ // in `routes/automation-detail.tsx`.
+ const { backends, active } = useActiveBackendContext();
+ const navigate = useNavigate();
+ const location = useLocation();
+ const owner = React.useRef({
+ conversationId,
+ backendId: active.backend.id,
+ orgId: active.orgId,
+ });
+ const pinned = readBackendSelectionFromUrl(backends, location.search);
+ // A link without `?org=` pins only the backend.
+ const isPinnedToActive =
+ pinned?.backendId === active.backend.id &&
+ (pinned.orgId === null || pinned.orgId === active.orgId);
+ if (owner.current.conversationId !== conversationId || isPinnedToActive) {
+ owner.current = {
+ conversationId,
+ backendId: active.backend.id,
+ orgId: active.orgId,
+ };
+ }
const backendChanged =
- mountedBackendId.current !== active.backend.id ||
- mountedOrgId.current !== active.orgId;
+ owner.current.backendId !== active.backend.id ||
+ owner.current.orgId !== active.orgId;
const { data: conversation, isFetched } = useActiveConversation();
const { data: isAuthed } = useIsAuthed();
const { resetConversationState } = useConversationStore();
- const navigate = useNavigate();
- const location = useLocation();
const clearTerminal = useCommandStore((state) => state.clearTerminal);
const resetConversationRuntimeState = useConversationStateStore(
(state) => state.reset,