Guide to migrating AgentBay Linux desktop to FC Agent Sandbox Desktop

Updated at:

Migrate Wuying AgentBay to FC Agent Sandbox e2b-desktop by mapping session.computer methods to e2b-desktop equivalents, building the Desktop template, and integrating noVNC for live desktop access.

Capability mapping

Method names and signatures are subject to the published e2b-desktop SDK. Some capabilities are supplemented by shell commands inside the sandbox and are labeled Aligned with shell commands in the following table.

Wuying AgentBay session.computer.*

e2b-desktop equivalent

Description

Mouse

click_mouse(x, y)

left_click(x, y)

Pass the coordinates directly; the two-step approach with move_mouse + left_click() also works.

click_mouse(x, y, button="right")

right_click(x, y)

Same as above.

move_mouse(x, y)

move_mouse(x, y)

Same name.

drag_mouse(x1, y1, x2, y2)

drag((x1, y1), (x2, y2))

Different signature; tuple parameters.

double_click()

double_click()

Same name.

scroll(x, y, direction, amount)

move_mouse(x, y) + scroll(direction, amount)

No coordinate parameters; move first and then scroll.

get_cursor_position()

commands.run("xdotool getmouselocation")

Aligned with shell commands.

Keyboard

input_text(text)

write(text)

Different method name.

press_keys(keys)

press(key) / press(["ctrl", "c"])

A single key, or a list of the keys that make up one key combination.

release_keys

commands.run("xdotool keyup <KEY>")

Aligned with shell commands.

Screenshot

screenshot()

screenshot()

Same name; PNG bytes.

beta_take_screenshot(format)

commands.run("scrot -q 80 /tmp/s.jpg") + files.read(path, format="bytes")

Aligned with shell commands (scrot supports jpg/png; jpg must be read explicitly as bytes).

Screen information

get_screen_size()

commands.run("xdpyinfo -display :0 | grep dimensions")

Aligned with shell commands.

get_current_window_id()

get_current_window_id()

Same name.

Window management

list_root_windows

commands.run('xdotool search --onlyvisible --name ""')

Aligned with shell commands.

activate_window

commands.run("xdotool windowactivate --sync <WINDOW-ID>")

Aligned with shell commands.

maximize_window

commands.run("xprop -id <WINDOW-ID> -f _NET_WM_STATE 32a -set _NET_WM_STATE _NET_WM_STATE_MAXIMIZED_VERT,_NET_WM_STATE_MAXIMIZED_HORZ")

Aligned with shell commands.

minimize_window

commands.run("xdotool windowminimize <WINDOW-ID>")

Aligned with shell commands.

resize_window

commands.run("xdotool windowsize --sync <WINDOW-ID> <WIDTH> <HEIGHT>")

Aligned with shell commands (for terminal-based applications, the window dimensions are rounded to character cells).

close_window

commands.run("xdotool windowclose <WINDOW-ID>")

Aligned with shell commands.

focus_mode

commands.run("xfconf-query -c xfwm4 -p /general/click_to_focus -s ...")

Aligned with shell commands.

Application management

start_app(app, work_directory)

commands.run("cd <YOUR-WORK-DIR> && <YOUR-APP> &")

Aligned with shell commands (launch(app[, url]) also works).

stop_app

commands.run("pkill <YOUR-APP>")

Aligned with shell commands.

get_installed_apps

commands.run("ls /usr/share/applications/")

Aligned with shell commands.

list_visible_apps

commands.run('xdotool search --onlyvisible --name ""')

Aligned with shell commands.

Agent (differences)

execute_task

None

C-1: not supported yet.

get_task_status

None

C-2: not supported yet.

terminate_task

None

C-3: not supported yet.

Desktop observation

get_link_url / VNC (Virtual Network Computing)

stream.start() + get_url()

Authentication is built in. See VNC live stream.

  • C-1 to C-3 (natural-language Agent) are not planned and fall outside the product design scope of FC Agent Sandbox; all other capabilities can be aligned through the SDK or shell commands.

  • Scenarios that do not require Computer Use: when you only interact with web pages, prefer Browser Use (CDP, Chrome DevTools Protocol); for pure batch-processing scenarios, use commands/code.

  • The mappings above have been verified item by item through actual runs with the e2b-desktop==2.4.1 + desktop:v0.0.44 template (29/29 passed).

  • The template comes preinstalled with xdotool / scrot / xdpyinfo / xprop / xwininfo / xfconf-query; not preinstalled: wmctrl. For window management, use the equivalent xdotool or xprop commands listed in the preceding table; if you need wmctrl semantics, run apt-get install -y wmctrl to install it, because the sandbox can access the Debian repositories.

  • The frontend examples in the WebSDK integration section have been verified in a real Chrome browser (the Remote Frame Buffer (RFB) connection, screen rendering, and real-time refresh of desktop changes all passed).

Limits

The Linux desktop (Computer Use) migration uses the e2b-desktop SDK:

  • Mouse, keyboard, and screenshot are existing SDK methods (two-step); the VNC live stream is built in and comes with authentication.

  • You must use its Sandbox subclass to create a sandbox. The sandbox lifecycle semantics are consistent with e2b (still use create/connect/list/kill).

  • Superset capabilities such as window management and application management are not within the scope of this SDK. See Capability mapping.

Built-in template mapping

AgentBay

FC E2B

Description

linux_latest (Computer Use)

desktop template (internal beta image fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/desktop:v0.0.44)

The FC image already has a desktop environment configured, and the desktop template is built from this image through Template.build(). See Prerequisites: Desktop template.

Prerequisites: Desktop template

The Desktop template is not a built-in template that is ready to use immediately after activation; it must be built from the FC Desktop image. The image already includes Xvfb + xfce4 + x11vnc + websockify + Chrome, so no Dockerfile is required.

Set environment variables

export E2B_API_KEY=<YOUR-API-KEY>
export E2B_API_URL=https://api.cn-beijing.e2b.fc.aliyuncs.com
export E2B_DOMAIN=cn-beijing.e2b.fc.aliyuncs.com

Build the template

  1. Install dependencies.

    pip install "e2b>=2.31.0" e2b-desktop==2.4.1 python-dotenv
  2. Save the following content as build.py.

    # build.py
    from dotenv import load_dotenv
    from e2b import Template, default_build_logger
    
    load_dotenv()
    
    # This is the current stable version; it will be updated later
    FROM_IMAGE = "fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/desktop:v0.0.44"
    
    build = Template.build(
        Template().from_image(FROM_IMAGE),
        name="my-desktop-template",  # You can set this to any value
        cpu_count=4,
        memory_mb=8192,
        on_build_logs=default_build_logger(),
    )
    print(f"template_id: {build.template_id}")
  3. Run the build.

    python build.py
  • The region of the image repository must be the same as that of E2B_API_URL / E2B_DOMAIN. For other regions, replace cn-beijing in the image address.

  • Recommended specifications: 4 vCPUs and 8192 MB of memory. The template does not require a start command or a readiness command; the Desktop SDK automatically starts the desktop environment and the live stream.

Main migration examples

Common interaction loop (screenshot + action)

# === Before migration: AgentBay ===
session = agent_bay.create(CreateSessionParams(image_id="linux_latest")).session
session.computer.move_mouse(640, 400)
session.computer.click_mouse(640, 400)
session.computer.input_text("echo hello")
session.computer.press_keys(["enter"])
png = session.computer.screenshot()

# === After migration: e2b-desktop SDK ===
from e2b_desktop import Sandbox

desktop = Sandbox.create(template="my-desktop-template", timeout=600)
try:
    # Start Chrome and wait for rendering
    desktop.launch("google-chrome", "https://example.com")
    desktop.wait(10000)

    # Mouse: the E2B SDK uses a two-step approach (move + click); use the drag tuple for dragging
    desktop.move_mouse(640, 400)
    desktop.left_click()
    desktop.double_click()
    desktop.drag((100, 100), (300, 300))
    desktop.scroll("down", 5)

    # Keyboard: write types text, press presses a single key or a key combination
    desktop.launch("xfce4-terminal")
    desktop.wait(3000)
    desktop.write("echo hello")
    desktop.press("enter")
    desktop.press(["ctrl", "c"])

    # Screenshot (PNG bytes, passed to the vision model)
    image = desktop.screenshot()
    with open("desktop.png", "wb") as f:
        f.write(image)
finally:
    desktop.kill()

VNC live stream (manual takeover)

# Corresponds to the link_url observation method of the Wuying desktop scenario; the E2B SDK stream has built-in authentication
desktop.stream.start()
stream_url = desktop.stream.get_url()
# Pass stream_url to a controlled backend / browser-side noVNC
desktop.stream.stop()

WebSDK integration

The browser side connects directly to the VNC live stream of the sandbox through noVNC (CDN JS), without the control-plane SDK or an npm build. The sandbox lifecycle is managed by the backend (Python), and the frontend is only responsible for desktop rendering.

Backend: get the VNC stream address

# Backend Python: create a sandbox and get the noVNC stream address
from e2b_desktop import Sandbox

desktop = Sandbox.create(template="my-desktop-template", timeout=600)
desktop.stream.start()
stream_url = desktop.stream.get_url()

# If the FC E2B side requires a traffic access token for the data plane, carry it as a query parameter

# token = getattr(desktop, "traffic_access_token", None)
# if token:
#     stream_url += f"&traffic_access_token={token}"

# Return stream_url to the frontend (for example, in an API response or over WebSocket)

Frontend: HTML + CDN noVNC

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>FC Desktop</title>
  <style>
    #vnc-screen { width: 100vw; height: 100vh; }
  </style>
</head>
<body>
  <div id="vnc-screen"></div>

  <script type="module">
    // ESM import of the official noVNC build (pinned version)
    import RFB from 'https://cdn.jsdelivr.net/gh/novnc/noVNC@v1.6.0/core/rfb.js';

    async function initVNC() {
      // Fetch from the backend API: stream_url
      const resp = await fetch('/api/sandbox/vnc-url');
      const { streamUrl } = await resp.json();

      const rfb = new RFB(
        document.getElementById('vnc-screen'),
        streamUrl,           // https://{sandbox-host}/vnc.html?autoconnect=true&resize=scale
                             // The same URL plays a dual role: opened directly in the browser, it is the noVNC page file; RFB upgrades it to
                             // wss://{sandbox-host}/vnc.html as the WebSocket endpoint (proxied by websockify to x11vnc)
        { credentials: { password: '' } }   // stream.start() leaves this empty when authentication is not enabled
      );

      rfb.scaleViewport = true;
      rfb.resizeSession = false;
    }

    initVNC();
  </script>
</body>
</html>
  • A direct browser connection to wss://{sandbox-host}/vnc.html requires no custom request headers (verified in practice: GET 200 and a successful RFB handshake). VNC authentication is controlled by stream.start(require_auth=True) + get_url(auth_key=...); after it is enabled, also return auth_key to the frontend and pass it into credentials.password.

  • If the data plane requires a traffic access token, the FC backend supports passing it as a query parameter (the backend concatenates it into stream_url before returning it; see Backend: get the VNC stream address). The browser WebSocket requires no custom headers and no relay service; noVNC is transparent to extra query parameters (verified in practice with the password= parameter).

  • The frontend does not need to develop its own Web SDK: noVNC (CDN ESM) is a complete data-plane client, and all connection parameters are in the URL.

Context storage

FC Agent Sandbox provides storage services as composable capabilities. Use AgenticFS or Object Storage Service (OSS) to persist and share data:

  1. Dynamic OSS mounts

  2. Mount an AgenticFS Volume

Appendix: noVNC integration demo

The following example provides a noVNC integration demo that can run locally and consists of three files: the backend demo.py, the frontend index.html, and the credential configuration .env. The sandbox lifecycle and credentials are managed by the backend, and the frontend is only responsible for desktop rendering.

Example files

demo.py (backend: sandbox lifecycle + HTTP service)

"""Linux Desktop + noVNC WebSDK integration demo (backend).

Three companion files: demo.py (this file), index.html (frontend), and .env (credentials).

Dependencies: pip install "e2b>=2.31.0" e2b-desktop==2.4.1 python-dotenv
Run: python demo.py   (open the printed http://127.0.0.1:<port>/ in a browser to see the live desktop)
"""
from __future__ import annotations

import json
import os
import signal
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

from dotenv import load_dotenv
from e2b import Template, default_build_logger
from e2b_desktop import Sandbox

BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / ".env")

TEMPLATE = os.environ["E2B_DESKTOP_TEMPLATE"]
IMAGE = os.environ.get("E2B_DESKTOP_IMAGE", "")
HOST = "127.0.0.1"


def ensure_template() -> str:
    if Template.exists(TEMPLATE):
        print(f"[demo] Reusing template: {TEMPLATE}", flush=True)
        return TEMPLATE
    if not IMAGE:
        raise SystemExit(
            f"[demo] Template {TEMPLATE!r} does not exist; configure E2B_DESKTOP_IMAGE in .env to build it automatically"
        )
    print(f"[demo] Building template {TEMPLATE!r} from image {IMAGE}", flush=True)
    build = Template.build(
        Template().from_image(IMAGE),
        name=TEMPLATE,
        cpu_count=4,
        memory_mb=8192,
        on_build_logs=default_build_logger(),
    )
    return build.template_id


class Handler(BaseHTTPRequestHandler):
    stream_url: str = ""

    def do_GET(self) -> None:
        if self.path == "/api/sandbox/vnc-url":
            body = json.dumps({"streamUrl": Handler.stream_url}).encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        if self.path in ("/", "/index.html"):
            body = (BASE_DIR / "index.html").read_bytes()
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        if self.path == "/favicon.ico":
            self.send_response(204)
            self.end_headers()
            return
        self.send_error(404)

    def log_message(self, *args) -> None:
        pass  # Does not output access logs, preventing any URL (including query parameters) from being written to disk


def _stop(_signum, _frame) -> None:
    raise KeyboardInterrupt


def main() -> None:
    signal.signal(signal.SIGTERM, _stop)

    template = ensure_template()
    print("[demo] Creating desktop sandbox (Xvfb + xfce4 + x11vnc + noVNC)...", flush=True)
    desktop = Sandbox.create(template=template, timeout=600, secure=True)
    server: ThreadingHTTPServer | None = None
    try:
        desktop.stream.start()
        stream_url = desktop.stream.get_url()
        # If the data plane requires a traffic access token, the FC backend supports passing it as a query parameter; concatenate it here:
        # token = getattr(desktop, "traffic_access_token", None)
        # if token:
        #     stream_url += f"&traffic_access_token={token}"

        Handler.stream_url = stream_url
        server = ThreadingHTTPServer((HOST, 0), Handler)
        print(f"[demo] Open in a browser: http://127.0.0.1:{server.server_port}/", flush=True)
        print("[demo] Ctrl-C to exit (automatically stops the stream and destroys the sandbox)", flush=True)
        server.serve_forever()
    except KeyboardInterrupt:
        print("\n[demo] Exiting...", flush=True)
    finally:
        if server is not None:
            server.server_close()
        try:
            desktop.stream.stop()
        except Exception:
            pass
        desktop.kill()
        print("[demo] Stopped the VNC stream and destroyed the sandbox", flush=True)


if __name__ == "__main__":
    main()

index.html (frontend: direct-connection rendering with noVNC CDN ESM)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>FC Linux Desktop (noVNC)</title>
  <style>
    html, body { margin: 0; height: 100%; }
    #vnc-screen { width: 100vw; height: 100vh; }
  </style>
</head>
<body>
  <div id="vnc-screen"></div>

  <script type="module">
    // ESM import of the official noVNC build (pinned version; the npm package's lib/rfb.js is CJS and cannot be loaded directly via <script src>)
    import RFB from 'https://cdn.jsdelivr.net/gh/novnc/noVNC@v1.6.0/core/rfb.js';

    async function initVNC() {
      // Fetch stream_url from the backend API (the sandbox lifecycle and credentials stay in the backend; the frontend never touches them)
      const resp = await fetch('/api/sandbox/vnc-url');
      const { streamUrl } = await resp.json();

      const rfb = new RFB(
        document.getElementById('vnc-screen'),
        // https://{sandbox-host}/vnc.html?... The same URL plays a dual role:
        // Opened directly in a browser, it is the noVNC page file; RFB upgrades it to wss://.../vnc.html as the WebSocket endpoint
        streamUrl,
        { credentials: { password: '' } }  // stream.start() leaves this empty when authentication is not enabled
      );

      rfb.scaleViewport = true;
      rfb.resizeSession = false;
    }

    initVNC();
  </script>
</body>
</html>
Warning

Once real values are filled in, the .env file contains secrets. Do not commit it to the code repository, share it, or paste it into chats or tickets.

.env (credential configuration, 5 keys)

# Linux Desktop + noVNC demo configuration (once real values are filled in, this file contains secrets: do not commit it to the repository, do not share it, and do not paste it into chats or tickets)
E2B_API_KEY=
E2B_API_URL=https://api.cn-beijing.e2b.fc.aliyuncs.com
E2B_DOMAIN=cn-beijing.e2b.fc.aliyuncs.com

# Desktop template name: if a template with this name already exists, that template is reused; if it does not exist, the template is built once automatically from E2B_DESKTOP_IMAGE
E2B_DESKTOP_TEMPLATE=my-desktop-template
E2B_DESKTOP_IMAGE=fc-e2b-registry.cn-beijing.cr.aliyuncs.com/runtime/desktop:v0.0.44

Data flow

Browser (index.html, noVNC CDN ESM)
  │  GET /api/sandbox/vnc-url ──→ demo.py (returns only streamUrl)
  │  RFB connects directly to wss://{sandbox-host}/vnc.html ──→ websockify ──→ x11vnc ──→ Xvfb desktop
  └─ Rendering + keyboard/mouse input (the data plane does not go through the backend)

How to run

  1. Install dependencies.

    pip install "e2b>=2.31.0" e2b-desktop==2.4.1 python-dotenv
  2. In .env, fill in the real values of credentials such as E2B_API_KEY.

  3. Run the demo.

    python demo.py
  4. Open the service address printed in the terminal (in the form of http://127.0.0.1:<RANDOM-PORT>/) in a browser to view and operate the live desktop.

  5. Press Ctrl-C to exit; the program automatically stops the VNC stream and destroys the sandbox.

Verification records

  • Backend API: /api/sandbox/vnc-url returns a streamUrl that starts with https:// and contains /vnc.html; / returns the page as expected.

  • Exit: after SIGTERM/Ctrl-C, the VNC stream is stopped and the sandbox is destroyed automatically.

  • Frontend: the RFB connection, screen rendering, and real-time refresh of desktop changes have been verified in a real Chrome browser.

References

  1. wuying-agentbay-sdk

  2. noVNC