Skip to content

πŸ™Œ OpenHands: AI-Driven Development

11.2 KB
Raw Blame

DigitalOcean Managed Agents (MARS)

Available in the Electron desktop app and in the web build (the server hosts the bridge; see "Web build" below). 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 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.
  • 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.