Skip to content

Blog

Computer use on a Linux desktoprun a computer-use agent safely

Create a desktop, send its screenshots to the model, and turn each action it returns into one click, key press or screenshot.

· The Runtime team

13 min read

Read as Markdown

Runtime (withruntime.com) runs a full Linux desktop, with Chromium, inside its own Firecracker microVM. Some software has no API. Examples include an old internal admin tool, a desktop application, and a vendor portal built for people who use a mouse. A computer-use agent works this software the way a person would, from screenshots. That makes it the most powerful kind of agent, and the one that most needs a machine of its own. This post connects Claude's computer toolset to a Runtime desktop. It covers the parts that trip up first versions, and it sets the limits that make it safe to leave running.

When does an agent need a desktop, not a browser API?

Less often than it seems. A screenshot loop is slower and costs more tokens than any structured interface. Use it only where nothing else reaches:

Interface Speed per step What it reaches Use it for
An API or a CLI Milliseconds What the vendor exposes Everything it covers
A browser over CDP Under a second Web pages, through the page's structure Web apps, forms, scraping
A desktop through screenshots Seconds Anything drawn on a screen Desktop apps, canvas apps, odd portals

Many teams use both of the lower rows. They run a CDP browser for the web steps and a desktop for the one application that has only a window. Each is a product of its own on Runtime: Browser.create() and Desktop.create().

How does the computer toolset map onto a Runtime desktop?

Claude's computer toolset, computer_toolset_20260801, gives the model member tools such as screenshot, left_click and type. The model calls them as ordinary tool calls, often several in one reply. Your code performs each call. Nearly every member maps to one step of desktop.act():

Member tool Runtime step Notes
screenshot desktop.screenshot() PNG bytes, returned as an image
left_click, right_click, middle_click { type: "click", x, y, button, keys } At coordinate, or where the pointer is
double_click { type: "click", x, y, count: 2 }
mouse_move { type: "move", x, y }
left_click_drag { type: "drag", x, y, toX, toY }
left_mouse_down, left_mouse_up { type: "mouseDown" }, { type: "mouseUp" } For drags the model builds itself
type { type: "type", text } Literal text
key { type: "key", keys } Same key names: Return, ctrl+s
scroll { type: "scroll", dx, dy, x, y } Direction and amount become wheel clicks
cursor_position The cursor every act returns Returned as text
wait A sleep in your code
zoom, triple_click, hold_key Turned off in the request The toolset's configs turns them off

Turning off a member is better than supporting it partly. The model then never asks for it. Otherwise, it asks and gets an error.

What does the whole agent look like?

The loop is an ordinary tool loop with three details of its own. Results carry toolset_name: "computer". A screenshot goes back as an image. When one action in a batch fails, the rest are reported as not run:

TypeScriptimport Anthropic from "@anthropic-ai/sdk";import { type Action, Desktop, Runtime } from "withruntime";const client = new Anthropic(); // reads ANTHROPIC_API_KEYconst SYSTEM =  "You operate a Linux desktop. Before any purchase, deletion, message to a person or " +  "acceptance of terms, stop and describe what you are about to do instead of doing it.";type Point = [number, number];type Input = {  coordinate?: Point;  start_coordinate?: Point;  text?: string;  repeat?: number;  scroll_direction?: "up" | "down" | "left" | "right";  scroll_amount?: number;  duration?: number;};// One member tool call as desktop steps. A click's `text` is the keys held during it.function steps(name: string, input: Input): Action[] {  const [x, y] = input.coordinate ?? [];  const at = x === undefined ? {} : { x, y };  const keys = input.text;  const n = input.scroll_amount ?? 3;  const dir = input.scroll_direction;  switch (name) {    case "left_click":      return [{ type: "click", ...at, keys }];    case "right_click":      return [{ type: "click", ...at, button: "right", keys }];    case "middle_click":      return [{ type: "click", ...at, button: "middle", keys }];    case "double_click":      return [{ type: "click", ...at, count: 2, keys }];    case "mouse_move":      return [{ type: "move", x, y }];    case "left_click_drag": {      const [fromX, fromY] = input.start_coordinate!;      return [{ type: "drag", x: fromX, y: fromY, toX: x, toY: y }];    }    case "left_mouse_down":      return [{ type: "mouseDown" }];    case "left_mouse_up":      return [{ type: "mouseUp" }];    case "type":      return [{ type: "type", text: input.text }];    case "key":      return [{ type: "key", keys: Array(input.repeat ?? 1).fill(input.text).join(" ") }];    case "scroll":      return [        {          type: "scroll",          ...at,          dy: dir === "up" ? -n : dir === "down" ? n : 0,          dx: dir === "left" ? -n : dir === "right" ? n : 0,        },      ];    default:      throw new Error(`${name} is not available`);  }}// One member tool call on the desktop: a screenshot, a line of text, or "OK".async function act(desktop: Desktop, name: string, input: Input) {  if (name === "screenshot") return desktop.screenshot();  if (name === "wait") {    await new Promise((r) => setTimeout(r, Math.min(input.duration ?? 1, 30) * 1000));    return "OK";  }  if (name === "cursor_position") {    const { cursor } = await desktop.act([{ type: "wait", ms: 1 }]);    return `X=${cursor.x}, Y=${cursor.y}`;  }  await desktop.act(steps(name, input));  return "OK";}export async function computerUse(goal: string, maxTurns = 60): Promise<string> {  await using desktop = await Desktop.create({    diskGB: 8,    maxCost: "2.00", // pauses once it has cost this much    network: { allowOutbound: ["portal.example.com", "*.example.com"] },  });  const view = await new Runtime().previews.create(desktop.id, { port: 6080 }); // noVNC  console.log("watch it live:", `${view.info.url}?runtime_preview_token=${view.info.token}`);  await desktop.spawn("chromium https://portal.example.com");  const messages: Anthropic.MessageParam[] = [{ role: "user", content: goal }];  for (let turn = 0; turn < maxTurns; turn++) {    const reply = await client.messages.create({      model: "claude-opus-5-5",      max_tokens: 16_000,      system: SYSTEM,      tools: [        {          type: "computer_toolset_20260801",          configs: {            zoom: { enabled: false },            triple_click: { enabled: false },            hold_key: { enabled: false },          },        },      ],      messages,    });    messages.push({ role: "assistant", content: reply.content });    if (reply.stop_reason !== "tool_use")      return reply.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n");    const results: Anthropic.ToolResultBlockParam[] = [];    let failed = false;    for (const call of reply.content) {      if (call.type !== "tool_use") continue;      const result = {        type: "tool_result" as const,        tool_use_id: call.id,        toolset_name: "computer",      };      if (failed) {        results.push({          ...result,          is_error: true,          content: "Not executed: an earlier computer action in this turn failed.",        });        continue;      }      try {        const out = await act(desktop, call.name, call.input as Input);        const data = typeof out === "string" ? "" : Buffer.from(out).toString("base64");        results.push({          ...result,          content:            typeof out === "string"              ? [{ type: "text", text: out }]              : [{ type: "image", source: { type: "base64", media_type: "image/png", data } }],        });      } catch (error) {        failed = true;        results.push({          ...result,          is_error: true,          content: `Error: ${(error as Error).message}`,        });      }    }    messages.push({ role: "user", content: results });  }  return "Stopped at the turn limit.";}
Pythonimport base64import timeimport anthropicfrom withruntime import Action, Desktop, NetworkRules, Runtimeclient = anthropic.Anthropic()  # reads ANTHROPIC_API_KEYSYSTEM = ("You operate a Linux desktop. Before any purchase, deletion, message to a person or "          "acceptance of terms, stop and describe what you are about to do instead of doing it.")TOOLS = [{"type": "computer_toolset_20260801",          "configs": {"zoom": {"enabled": False}, "triple_click": {"enabled": False},                      "hold_key": {"enabled": False}}}]def steps(name: str, i: dict) -> list[Action]:    """One member tool call as desktop steps. A click's `text` is the keys held during it."""    x, y = i.get("coordinate") or (None, None)    keys = i.get("text")    n, direction = i.get("scroll_amount", 3), i.get("scroll_direction", "")    if name == "left_click":        return [Action(type="click", x=x, y=y, keys=keys)]    if name == "right_click":        return [Action(type="click", x=x, y=y, button="right", keys=keys)]    if name == "middle_click":        return [Action(type="click", x=x, y=y, button="middle", keys=keys)]    if name == "double_click":        return [Action(type="click", x=x, y=y, count=2, keys=keys)]    if name == "mouse_move":        return [Action(type="move", x=x, y=y)]    if name == "left_click_drag":        from_x, from_y = i["start_coordinate"]        return [Action(type="drag", x=from_x, y=from_y, to_x=x, to_y=y)]    if name == "left_mouse_down":        return [Action(type="mouseDown")]    if name == "left_mouse_up":        return [Action(type="mouseUp")]    if name == "type":        return [Action(type="type", text=i["text"])]    if name == "key":        return [Action(type="key", keys=" ".join([i["text"]] * i.get("repeat", 1)))]    if name == "scroll":        return [Action(type="scroll", x=x, y=y, dy={"up": -n, "down": n}.get(direction, 0),                       dx={"left": -n, "right": n}.get(direction, 0))]    raise ValueError(f"{name} is not available")def act(desktop: Desktop, name: str, i: dict):    """One member tool call on the desktop: a screenshot, a line of text, or "OK"."""    if name == "screenshot":        return desktop.screenshot()    if name == "wait":        time.sleep(min(i.get("duration", 1), 30))        return "OK"    if name == "cursor_position":        c = desktop.act([Action(type="wait", ms=1)]).cursor        return f"X={c.x}, Y={c.y}"    desktop.act(steps(name, i))    return "OK"def computer_use(goal: str, max_turns: int = 60) -> str:    with Desktop.create(disk_gb=8, max_cost="2.00",  # pauses once it has cost this much                        network=NetworkRules(allow_outbound=["portal.example.com", "*.example.com"])) as desktop:        view = Runtime().previews.create(desktop.id, port=6080)  # noVNC        print("watch it live:", f"{view.info.url}?runtime_preview_token={view.info.token}")        desktop.spawn("chromium https://portal.example.com")        messages: list[dict] = [{"role": "user", "content": goal}]        for _ in range(max_turns):            reply = client.messages.create(model="claude-opus-5-5", max_tokens=16_000, system=SYSTEM,                                           tools=TOOLS, messages=messages)            messages.append({"role": "assistant", "content": reply.content})            if reply.stop_reason != "tool_use":                return "\n".join(b.text for b in reply.content if b.type == "text")            results, failed = [], False            for call in (b for b in reply.content if b.type == "tool_use"):                result = {"type": "tool_result", "tool_use_id": call.id, "toolset_name": "computer"}                if failed:                    results.append({**result, "is_error": True,                                    "content": "Not executed: an earlier computer action in this turn failed."})                    continue                try:                    out = act(desktop, call.name, call.input)                except Exception as error:                    failed = True                    results.append({**result, "is_error": True, "content": f"Error: {error}"})                    continue                if isinstance(out, bytes):                    image = {"type": "base64", "media_type": "image/png", "data": base64.b64encode(out).decode()}                    results.append({**result, "content": [{"type": "image", "source": image}]})                else:                    results.append({**result, "content": [{"type": "text", "text": out}]})            messages.append({"role": "user", "content": results})        return "Stopped at the turn limit."

Why is the screen exactly 1280 by 800?

Your screen must match the screenshots you send. The model's clicks use the coordinates of those screenshots, and the API does not shrink images for you. A screenshot larger than the model's image limit is refused. If you shrink a screenshot yourself, every coordinate the model returns must be scaled up before the click. Skip that step once, and the agent clicks a little left of every button. That looks like a model failure, not a bug in your code.

The simplest fix is to send the screen at its own size. A Runtime desktop's screen is 1280 by 800, well inside the limit for current Claude models. It matches how most web applications are designed, and it keeps each screenshot to a modest number of tokens. Coordinates then pass straight through with no arithmetic. Larger screens make each step slower and more expensive, and they do not make the model more accurate.

What should a batch of actions do when one fails?

Stop. The model often sends a short plan in one reply: click the search box, type a query, press Return, and take a screenshot. If the click fails, the typed query lands somewhere else. Pressing Return may then submit a form that nobody meant to submit. The loop above runs the calls in order. After the first error, it marks each remaining call "Not executed". Every call still gets a result, and the model checks the screen again before it tries anything else.

How long can one run go on?

Every screenshot stays in the transcript, so a long task adds an image to its context at each step. Start with the turn limit: a task that needs more than sixty steps is usually two tasks. Do not delete old screenshots from the messages yourself. On current Claude models, editing earlier turns invalidates the model's later reasoning. When a run must go longer, use the API's tool result clearing instead. It removes old results on the server side.

How do you keep a computer-use agent from doing harm?

The model acts on whatever it sees. That includes text written by strangers: a web page, an email in the portal, or a document. Instructions in that text can steer it (prompt injection to code execution). Limit what a steered agent can reach:

  • Its own machine. The desktop is inside its own microVM, so a download it opens or a program it starts never touches yours.
  • A short network allow list. Name only the sites the task needs, so a page cannot send the agent somewhere new (allow only some hosts).
  • No logged-in browser of yours. Sign in with an account made for the agent. Give that account the least access the task needs.
  • A person for irreversible actions. The system prompt tells the model to stop and describe the action before a purchase, a deletion, a message to a person, or new terms. Your code sends that description to a human, not back to the model.
  • A record. Every screenshot and action is in messages. Store them, and when the agent does something unexpected, you can step through exactly what it saw. The live view lets you watch while the agent runs.

How fast is it, and what does it cost?

A desktop is created with its screen and Chromium already running, in about two seconds. Set it up once. Then take a memory snapshot of it, with the application open and the agent's account signed in. Each task then starts from the snapshot, already at the first screen (snapshots and forks).

After that, the model sets the pace. Each step is one model call with a screenshot in it. A step usually takes a few seconds, while the desktop's own actions return in a fraction of that time. A 40-step task takes a few minutes. During that time the desktop mostly waits. CPU is billed only when used, at $0.03 per vCPU-hour. Memory is billed at $0.008 per GiB-hour while the desktop runs. The model's image tokens are the larger cost. That is one more reason to keep the screen at 1280 by 800 rather than larger.

How do you test it without spending tokens?

Replay. Save the model's replies from one good run. Then feed them back through act against a fresh desktop from the same snapshot, and compare the final screenshot with the original. A replay that diverges means the application changed. That is what you want to learn before the next real run. The same idea, applied to whole agent runs, is in reproducible agent evals.

In short

  • Use a desktop only where no API or browser interface reaches; it is the slowest and most capable interface.
  • Map each computer toolset member to one desktop step, and turn off the members you do not support.
  • Send the screen at its own size, so coordinates need no scaling.
  • Stop a batch at its first failed action, and mark the rest as not run.
  • Contain it: its own microVM, a short allow list, an account made for it, a person for irreversible steps, and a record of every run.

Run it on Runtime

Runtime costs 36% to 87% less than fourteen other sandbox providers for an agent that mostly waits on a model (compare costs). A Runtime desktop is a machine of its own with Chromium on its screen and a private live view. Read how to control a desktop, then create an account at withruntime.com and point the agent above at the application that has no API.

Keep reading.

Cut your cloud billby 60%.

Redeem $5 free usage$0 today · 7 days free · cancel any time

7 days of Pro for $0. Billed by the second after.

Redeem $5 free usage$0 today · 7 days free · cancel any time