π OpenHands: AI-Driven Development
fix(mars): restore explicit opt-in for the web bridge (#18783)
Engel Nyst1e850162beea
diff --git a/.agents/skills/local-stack-runtime/references/guide.md b/.agents/skills/local-stack-runtime/references/guide.mdindex 38b3b687b5..906065c61d 100644--- a/.agents/skills/local-stack-runtime/references/guide.md+++ b/.agents/skills/local-stack-runtime/references/guide.md@@ -7,6 +7,7 @@ Supported deployment environment variables:- `VITE_WORKING_DIR` β default workspace path sent when starting conversations.- `VITE_ENABLE_BROWSER_TOOLS=false` β start the agent-server with the browser tool set off (`OH_ENABLE_BROWSER=false`).- `VITE_BASE_PATH` β serve the SPA under a subpath such as `/canvas`; pair it with `scripts/static-server.mjs --base-path` at runtime.+- `MARS_WEB=1` β opt in to the experimental DigitalOcean web bridge. Keep it off by default until the integration is ready; session-key authentication is a separate requirement. Static children and Electron keep their bridge disabled so the web ingress is the only owner.GitHub automation includes `.github/workflows/ci.yml` for `npm ci`, `npm test`, and `npm run build`, plus `.github/dependabot.yml` with weekly npm and GitHub Actions updates gated by a seven-day cooldown.diff --git a/.env.sample b/.env.sampleindex 2978a11d8b..30a5dfd7a2 100644--- a/.env.sample+++ b/.env.sample@@ -24,11 +24,11 @@ VITE_INSECURE_SKIP_VERIFY="false" # Skip TLS certificate verification for proxie# VITE_DO_NOT_TRACK="1" # Disable all telemetry, including anonymous install counts# DigitalOcean Managed Agents: the Electron desktop app and the web build (its-# server hosts the bridge by default). `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.+# server hosts the bridge only 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_KEY="" # Web build: key the /mars/* routes require; defaults to the server's --session-api-key. Required on a non-loopback bind.-# MARS_WEB="0" # Web build: turn the DigitalOcean bridge off for a server that must not host it (on by default)+# MARS_WEB="1" # Opt in to the experimental DigitalOcean web bridge (off by default)# 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 APIdiff --git a/.pr/mars-web/after-default-off.jpg b/.pr/mars-web/after-default-off.jpgnew file mode 100644index 0000000000..1f00ff2c85Binary files /dev/null and b/.pr/mars-web/after-default-off.jpg differdiff --git a/.pr/mars-web/after-explicit-opt-in.jpg b/.pr/mars-web/after-explicit-opt-in.jpgnew file mode 100644index 0000000000..04ce46ef7dBinary files /dev/null and b/.pr/mars-web/after-explicit-opt-in.jpg differdiff --git a/.pr/mars-web/before-default-on.jpg b/.pr/mars-web/before-default-on.jpgnew file mode 100644index 0000000000..0c1da6a5fdBinary files /dev/null and b/.pr/mars-web/before-default-on.jpg differdiff --git a/__tests__/scripts/mars-web-bridge.test.ts b/__tests__/scripts/mars-web-bridge.test.tsindex b26b5e15ca..a32830529f 100644--- a/__tests__/scripts/mars-web-bridge.test.ts+++ b/__tests__/scripts/mars-web-bridge.test.ts@@ -24,7 +24,6 @@ import { MARS_TUNNEL_IPC } from "../../scripts/mars-tunnel-bridge.mjs";import {RPC_METHODS,createMarsWebBridge,- isMarsWebDisabled,mountMarsWebBridge,rewriteAgentServerUrls,} from "../../scripts/mars-web-bridge.mjs";@@ -661,104 +660,84 @@ describe("createMarsWebBridge with a session key", () => {});describe("mountMarsWebBridge", () => {- it("mounts by default on a loopback bind, even without a key", async () => {+ // Launchers set MARS_WEB=0 on servers that inherit MARS_TOKEN, so an+ // explicit 0 stays quiet even then.+ it.each([+ {},+ { MARS_WEB_KEY: "k" },+ { MARS_WEB: "" },+ { MARS_WEB: "0", MARS_TOKEN: "dop_v1_test" },+ ])("stays off quietly without MARS_WEB=1: %j", (env) => {+ const log = vi.fn();+ const mounted = mountMarsWebBridge({+ env,+ host: "127.0.0.1",+ sessionApiKey: "stack-key",+ log,+ debug: log,+ });+ expect(mounted).toBeNull();+ expect(log).not.toHaveBeenCalled();+ });++ it.each([+ [{ MARS_WEB: "true" }, /MARS_WEB="true" is not "1"/],+ [{ MARS_WEB: "1 " }, /MARS_WEB="1 " is not "1"/],+ [{ MARS_WEB: '"1"' }, /MARS_WEB="\\"1\\"" is not "1"/],+ [+ { MARS_TOKEN: "dop_v1_test" },+ /MARS_TOKEN is set but MARS_WEB is not "1"/,+ ],+ ])("stays off but warns when it looks meant to be on: %j", (env, message) => {const warnings: string[] = [];const debugs: string[] = [];const mounted = mountMarsWebBridge({- env: {},+ env,host: "127.0.0.1",+ sessionApiKey: "stack-key",log: (m) => warnings.push(m),debug: (m) => debugs.push(m),});- expect(mounted).not.toBeNull();- expect(warnings).toEqual([]);- expect(debugs[0]).toMatch(/local callers only/);- await mounted!.dispose();- });-- it("is off with MARS_WEB=0 and its synonyms, silently", () => {- for (const value of ["0", "false", "off", "no", "OFF", " 0 "]) {- const logs: string[] = [];- expect(- mountMarsWebBridge({- env: { MARS_WEB: value, MARS_WEB_KEY: "k" },- host: "127.0.0.1",- log: (m) => logs.push(m),- debug: (m) => logs.push(m),- }),- ).toBeNull();- expect(logs).toEqual([]);- }+ expect(mounted).toBeNull();+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toMatch(message);+ expect(debugs).toEqual([]);});- it("stays on for the old MARS_WEB=1 opt-in, and warns once about a typo", async () => {- for (const value of ["1", "true", "on", "yes"]) {- const logs: string[] = [];- expect(isMarsWebDisabled({ MARS_WEB: value }, (m) => logs.push(m))).toBe(- false,- );- expect(logs).toEqual([]);- }- const logs: string[] = [];- expect(isMarsWebDisabled({ MARS_WEB: "nope" }, (m) => logs.push(m))).toBe(- false,- );- expect(logs[0]).toMatch(/not recognised/);+ it("mounts with MARS_WEB=1 on a loopback bind, even without a key", async () => {+ const warnings: string[] = [];+ const debugs: string[] = [];const mounted = mountMarsWebBridge({- env: { MARS_WEB: "nope" },+ env: { MARS_WEB: "1" },host: "127.0.0.1",- log: () => {},- debug: () => {},+ log: (m) => warnings.push(m),+ debug: (m) => debugs.push(m),});expect(mounted).not.toBeNull();+ expect(warnings).toEqual([]);+ expect(debugs[0]).toMatch(/local callers only/);await mounted!.dispose();});- it("only warns about an unmountable LAN bind when someone opted in", () => {+ it("refuses a non-loopback bind without a key, and mounts with one", async () => {+ // A warning, not a debug line: the operator opted in and DigitalOcean+ // will be missing.const warnings: string[] = [];const debugs: string[] = [];- // Nobody asked for DigitalOcean: a Docker public-mode instance must not- // see a warning on every start.expect(mountMarsWebBridge({- env: {},- host: "::",+ env: { MARS_WEB: "1" },+ host: "0.0.0.0",log: (m) => warnings.push(m),debug: (m) => debugs.push(m),}),).toBeNull();- expect(warnings).toEqual([]);- expect(debugs[0]).toMatch(/not loopback/);- // MARS_TOKEN, or the old MARS_WEB=1 opt-in, says they meant to use it, so- // the refusal is worth a warning.- for (const env of [{ MARS_TOKEN: "dop_v1_x" }, { MARS_WEB: "1" }]) {- const warned: string[] = [];- expect(- mountMarsWebBridge({- env,- host: "::",- log: (m) => warned.push(m),- debug: () => {},- }),- ).toBeNull();- expect(warned[0]).toMatch(/not loopback/);- }- });-- it("refuses a non-loopback bind without a key, and mounts with one", async () => {- const logs: string[] = [];- expect(- mountMarsWebBridge({- env: {},- host: "0.0.0.0",- log: (m) => logs.push(m),- debug: (m) => logs.push(m),- }),- ).toBeNull();- expect(logs[0]).toMatch(/not loopback/);+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toMatch(/not loopback/);+ expect(debugs).toEqual([]);const mounted = mountMarsWebBridge({- env: { MARS_WEB_KEY: "k" },+ env: { MARS_WEB: "1", MARS_WEB_KEY: "k" },host: "0.0.0.0",log: () => {},});diff --git a/__tests__/scripts/static-server.test.ts b/__tests__/scripts/static-server.test.tsindex 78104e9d90..9337e9514a 100644--- a/__tests__/scripts/static-server.test.ts+++ b/__tests__/scripts/static-server.test.ts@@ -1,5 +1,11 @@import { createServer, request, type Server } from "node:http";-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import path from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";@@ -1087,8 +1093,9 @@ describe("static-server.mjs MARS web bridge (Docker arguments)", () => {// docker/entrypoint.sh runs `--host :: --session-api-key <key>` with no// `--allow-lan-session-key`: the key is stripped from the HTML, but the- // bridge must still mount behind it.- it("mounts with the entrypoint's `--host :: --session-api-key` arguments", async () => {+ // opted-in bridge must still mount behind it.+ it("mounts with MARS_WEB=1 and the entrypoint's `--host :: --session-api-key` arguments", async () => {+ vi.stubEnv("MARS_WEB", "1");const warn = vi.spyOn(console, "warn").mockImplementation(() => {});const origin = await start({ host: "::", sessionApiKey: "docker-key" });expect(await (await fetch(`${origin}/mars/health`)).json()).toEqual({@@ -1102,17 +1109,42 @@ describe("static-server.mjs MARS web bridge (Docker arguments)", () => {).toBe(false);});- it("does not mount on a LAN bind with no key (public mode)", async () => {- vi.spyOn(console, "debug").mockImplementation(() => {});+ it("does not mount on a LAN bind with no key (public mode), and warns", async () => {+ vi.stubEnv("MARS_WEB", "1");+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});const origin = await start({ host: "::", authRequired: true });const response = await fetch(`${origin}/mars/health`);expect(response.headers.get("content-type")).toMatch(/text\/html/);+ expect(+ warn.mock.calls.some((c) =>+ /\[mars-web\].*not loopback/.test(String(c[0])),+ ),+ ).toBe(true);});- it("honours MARS_WEB=0", async () => {- vi.stubEnv("MARS_WEB", "0");- const origin = await start({ host: "127.0.0.1", sessionApiKey: "k" });- const response = await fetch(`${origin}/mars/health`);- expect(response.headers.get("content-type")).toMatch(/text\/html/);+ // The public-mode instance binds `::` with no key, so a container-wide+ // MARS_WEB=1 would make it warn on every start, or, with MARS_WEB_KEY set+ // too, host a second bridge with its own sign-in state.+ it("pins the entrypoint's public-mode instance to MARS_WEB=0", () => {+ const entrypoint = readFileSync(+ path.resolve(import.meta.dirname, "../../docker/entrypoint.sh"),+ "utf-8",+ );+ expect(+ entrypoint.match(/^.*node \/opt\/agent-canvas\/static-server\.mjs/gm),+ ).toEqual([+ "node /opt/agent-canvas/static-server.mjs",+ " MARS_WEB=0 node /opt/agent-canvas/static-server.mjs",+ ]);});++ it.each([undefined, "0"])(+ "does not mount with MARS_WEB=%s",+ async (value) => {+ vi.stubEnv("MARS_WEB", value);+ const origin = await start({ host: "127.0.0.1", sessionApiKey: "k" });+ const response = await fetch(`${origin}/mars/health`);+ expect(response.headers.get("content-type")).toMatch(/text\/html/);+ },+ );});diff --git a/config/defaults.json b/config/defaults.jsonindex 198e3f5686..3bcc6c8bc8 100644--- a/config/defaults.json+++ b/config/defaults.json@@ -39,7 +39,7 @@"workspace": "openhands-workspace"},"mars": {- "_comment": "DigitalOcean Managed Agents: the Electron desktop app and the web build (its server hosts the bridge by default). 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.",+ "_comment": "DigitalOcean Managed Agents: the Electron desktop app and the web build (its server hosts the experimental bridge only 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": ""},diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex f2eb72c8df..009f294876 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -32,6 +32,13 @@# the proxy route.# PUBLIC_MODE_PORT β If set, starts a second static server on this port# with --auth-required (no session key injected)+# MARS_WEB β Set to exactly 1 to opt in to the experimental+# DigitalOcean web bridge on $PORT (off by default).+# The public-mode server never hosts it.+# MARS_WEB_KEY β Key the bridge's /mars/* routes require (defaults to+# the session API key)+# MARS_TOKEN β DigitalOcean personal access token to sign the bridge+# in with at start (needs MARS_WEB=1)# AGENT_CANVAS_ALLOW_LAN_SESSION_KEY β Set to true only when the published# host port is restricted to loopback and you accept# embedding the session key in the served HTML@@ -470,9 +477,14 @@ PIDS+=("$STATIC_PID")# The token's scope is upstream's to fix and is tracked in# OpenHands/software-agent-sdk#4317; if the editor gets a credential of its own,# this exclusion and the --no-referrer-prefix below can both be revisited.+#+# MARS_WEB=0 keeps the DigitalOcean bridge on the main instance only. This one+# binds every interface with no key, so an opted-in container would otherwise+# warn on every start, or, with MARS_WEB_KEY set, host a second bridge with its+# own sign-in state.if [ -n "${PUBLIC_MODE_PORT:-}" ]; thenlog "Starting public-mode frontend on port $PUBLIC_MODE_PORT (--auth-required)..."- node /opt/agent-canvas/static-server.mjs \+ MARS_WEB=0 node /opt/agent-canvas/static-server.mjs \--port "$PUBLIC_MODE_PORT" \--host "$STATIC_SERVER_BIND_HOST" \--dir /opt/agent-canvas/frontend \diff --git a/scripts/ingress.mjs b/scripts/ingress.mjsindex c3d9066fa1..18b4c31d3c 100644--- a/scripts/ingress.mjs+++ b/scripts/ingress.mjs@@ -175,7 +175,7 @@ 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: this server hosts the MARS+ // DigitalOcean Managed Agents for the browser: with MARS_WEB=1, host 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 });diff --git a/scripts/mars-web-bridge.mjs b/scripts/mars-web-bridge.mjsindex b7efb9e9a3..cc2072a745 100644--- a/scripts/mars-web-bridge.mjs+++ b/scripts/mars-web-bridge.mjs@@ -102,6 +102,10 @@ const CANVAS_ONLY_HEADERS = ["cookie", AUTH_HEADER, "origin", "referer"];* `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.+ *+ * @param {object} [options]+ * @param {Record<string, string | undefined>} [options.env]+ * @param {string | null} [options.sessionApiKey]*/export function resolveMarsWebKey({env = process.env,@@ -114,21 +118,19 @@ export function resolveMarsWebKey({}/**- * Mount the bridge for a server, or return null when it must not be. On by- * default; off when:- *- * - `MARS_WEB=0`. The explicit opt-out, for a server that fronts nothing a- * browser reaches directly (dev-with-automation's static child behind the- * ingress) or runs under Electron, where the preload already provides the- * bridge and a second one would only hold its own sign-in state.- * - No key on a non-loopback bind: the routes would be open to the LAN with- * the DO token behind them.+ * The web integration is experimental: mount only with `MARS_WEB=1`.+ * This readiness flag is separate from authentication. An opted-in bridge+ * still refuses a non-loopback bind without a key. Launchers set `MARS_WEB=0`+ * on static children and under Electron so only the web ingress hosts it.+ * Off is silent unless the env suggests someone meant it on+ * (`marsWebOffWarning`).*- * The refusal is a warning only when someone asked for the bridge (the old- * `MARS_WEB=1` opt-in, or `MARS_TOKEN` set); a Docker public-mode instance- * that never uses DigitalOcean gets a debug line, not a warning on every- * start. `MARS_WEB_KEY` is not a signal here: with it set there is a key and- * this branch is never reached.+ * @param {object} [options]+ * @param {Record<string, string | undefined>} [options.env]+ * @param {string} [options.host]+ * @param {string | null} [options.sessionApiKey]+ * @param {(message: string) => void} [options.log]+ * @param {(message: string) => void} [options.debug]*/export function mountMarsWebBridge({env = process.env,@@ -137,11 +139,14 @@ export function mountMarsWebBridge({log = (message) => console.warn(`[mars-web] ${message}`),debug = (message) => console.debug(`[mars-web] ${message}`),} = {}) {- if (isMarsWebDisabled(env, log)) return null;+ if (env.MARS_WEB !== "1") {+ const warning = marsWebOffWarning(env);+ if (warning) log(warning);+ return null;+ }const key = resolveMarsWebKey({ env, sessionApiKey });if (!key && !isLoopbackBind(host)) {- const optedIn = env.MARS_WEB === "1" || Boolean(env.MARS_TOKEN?.trim());- (optedIn ? log : debug)(+ log(`no key and bind host ${host} is not loopback; not mounting /mars/* (set MARS_WEB_KEY or --session-api-key).`,);return null;@@ -150,27 +155,23 @@ export function mountMarsWebBridge({return createMarsWebBridge({ env, host, key });}-const MARS_WEB_OFF = new Set(["0", "false", "off", "no"]);-const MARS_WEB_ON = new Set(["", "1", "true", "on", "yes"]);-/**- * `MARS_WEB=0` (also `false`, `off`, `no`) turns the bridge off for a server- * that must not host it. The old `MARS_WEB=1` opt-in and its synonyms mean- * on, which is the default anyway. Anything else is a typo in the off switch:- * say so once, and stay on, since on is what no value means.+ * Why the bridge stays off, for an operator who seems to have wanted it on;+ * null otherwise, so a server nobody pointed at DigitalOcean starts quietly.+ * Any value but `1` or `0` (launchers set `0` on purpose) gets a line, since+ * it may be a mistyped opt-in (`true`, `"1 "`, a quoted `"1"` from+ * `docker run --env-file`), and so does `MARS_TOKEN` with no `MARS_WEB`.*/-export function isMarsWebDisabled(- env = process.env,- log = (message) => console.warn(`[mars-web] ${message}`),-) {- const value = (env.MARS_WEB ?? "").trim().toLowerCase();- if (MARS_WEB_OFF.has(value)) return true;- if (!MARS_WEB_ON.has(value)) {- log(- `MARS_WEB=${JSON.stringify(env.MARS_WEB)} is not recognised (use 0/false/off/no to turn the bridge off); leaving it on.`,- );+function marsWebOffWarning(env) {+ const value = env.MARS_WEB ?? "";+ if (value.trim() === "0") return null;+ if (value) {+ return `MARS_WEB=${JSON.stringify(value)} is not "1"; not mounting /mars/* (set MARS_WEB=1).`;}- return false;+ if (env.MARS_TOKEN?.trim()) {+ return `MARS_TOKEN is set but MARS_WEB is not "1"; not mounting /mars/* (set MARS_WEB=1).`;+ }+ return null;}function safeEqual(a, b) {diff --git a/scripts/static-server.mjs b/scripts/static-server.mjsindex 51836365b0..dd71eeb739 100644--- a/scripts/static-server.mjs+++ b/scripts/static-server.mjs@@ -680,7 +680,7 @@ export function startStaticServer(config) {const staticMiddleware = createStaticMiddleware(dirAbs);const uninstallDiagnostics = proxy.installDiagnostics();- // DigitalOcean Managed Agents for the browser: this server hosts the MARS+ // DigitalOcean Managed Agents for the browser: with MARS_WEB=1, host the MARS// bridge and proxies to sessions' tunnel listeners, behind the session key// (see mars-web-bridge.mjs). Deliberately `config.sessionApiKey`, not// `policy.sessionApiKey`: the policy decides whether the key may be bakeddiff --git a/src/api/mars/AGENTS.md b/src/api/mars/AGENTS.mdindex c133dae693..fcba042d7b 100644--- a/src/api/mars/AGENTS.md+++ b/src/api/mars/AGENTS.md@@ -8,7 +8,7 @@ Available in the Electron desktop app and in the web build (the server hosts the- **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 **mounted by default when a key is configured, or on a loopback bind** (`MARS_WEB=0` turns them off; both dev launchers set it on the static child so only the browser-facing ingress hosts a bridge, and Electron passes `marsWebBridge: false` so none runs there) and 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.+- **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 **mounted only with `MARS_WEB=1`, when a key is configured or on a loopback bind** (`MARS_WEB=0` keeps them off; both dev launchers set it on the static child so only the browser-facing ingress hosts a bridge, and Electron passes `marsWebBridge: false` so none runs there) and 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.