> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mobilerun.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK helpers

> Waiting, typed output, file downloads, uploads, webhook checks and cleanup in the Mobilerun SDK.

Each helper replaces code you would otherwise write yourself, such as polling loops or signature
checks.

> [!NOTE]
>
> Needs SDK 6.2.0 or later. Start with the [Mobilerun SDK](https://docs.mobilerun.ai/guides/sdk-objects.md) guide.

## Devices

### Create and wait until ready

Replaces creating a device and polling until it is ready. Creating a device uses
[device minutes](https://docs.mobilerun.ai/credits.md#device-minutes) until you stop or terminate it. `params` must include
`deviceType`.

```text theme={null}
devices.create(params, { waitReady?, readyTimeoutMs?, disposeOnReadyFailure? }) → Device
```

```typescript TypeScript theme={null}
import { MobilerunSDK } from '@mobilerun/sdk';

const mobilerun = new MobilerunSDK();
const device = await mobilerun.devices.create({ deviceType: 'android_cloud_phone', billing: 'minute' });
```

```python Python theme={null}
from mobilerun_sdk import MobilerunSDK

mobilerun = MobilerunSDK()
device = mobilerun.devices.create(device_type="android_cloud_phone", billing="minute")
```

| Option | TypeScript | Python | Default |
| - | - | - | - |
| Return before the device is ready | `waitReady: false` | `wait_ready=False` | waits |
| Time limit for readiness | `readyTimeoutMs` | `ready_timeout` (seconds) | 5 minutes |
| Keep the device when it never becomes ready | `disposeOnReadyFailure: false` | `dispose_on_ready_failure=False` | terminates it |

If the device does not become ready, `create` throws `ObjectReadyError`.

### Stop and resume

A stopped device keeps its data and apps and stops using device minutes. Cloud iOS devices cannot be
stopped yet; call `device.terminate()` instead.

```text theme={null}
device.stop({ wait?, waitTimeoutMs? }) → Device
device.resume({ waitReady?, readyTimeoutMs? }) → Device
```

```typescript TypeScript theme={null}
await device.stop();
await device.resume();
```

```python Python theme={null}
device.stop()
device.resume()
```

| Option | TypeScript | Python | Default |
| - | - | - | - |
| `stop` returns right away | `wait: false` | `wait=False` | waits until stopped |
| `stop` time limit | `waitTimeoutMs` | `wait_timeout` (seconds) | 5 minutes |
| `resume` returns right away | `waitReady: false` | `wait_ready=False` | waits until ready |
| `resume` time limit | `readyTimeoutMs` | `ready_timeout` (seconds) | 5 minutes |

`stop` throws `WaitFailureError` or `WaitTimeoutError`. `resume` throws `ObjectReadyError`. The device
is not terminated when they happen.

### Actions

The device ID is already known to the object.

```text theme={null}
device.tap(x, y) · type(text) · swipe(startX, startY, endX, endY, duration)
device.home() · back() · openApp(packageName) · ui()
```

`duration` is in milliseconds. `ui()` returns the current accessibility tree of the screen.

```typescript TypeScript theme={null}
await device.openApp('com.android.settings');
await device.tap(540, 1200);
await device.type('hello');
const ui = await device.ui();
```

```python Python theme={null}
device.open_app("com.android.settings")
device.tap(540, 1200)
device.type("hello")
ui = device.ui()
```

### Screenshots

`device.screenshot()` returns a result with `bytes`, `save()`, `base64()` and `dataUrl()` (Python
`data_url()`). TypeScript also has `blob()`.

```text theme={null}
device.screenshot() → Screenshot
```

```typescript TypeScript theme={null}
const screenshot = await device.screenshot();
await screenshot.save('screen.png');
```

```python Python theme={null}
screenshot = device.screenshot()
screenshot.save("screen.png")
```

### Stream an Android or iOS device

Show a live device in your web app with `<DeviceStream />` from
[`@mobilerun/react`](https://github.com/droidrun/mobilerun-react#readme). Never send your API key to
the browser. The [Mobilerun SDK](https://docs.mobilerun.ai/guides/sdk-objects.md#stream-a-device-in-a-web-app) guide shows the
server and React parts.

> [tab] Android
>
> <video autoPlay muted loop playsInline preload="metadata" poster="/images/sdk/sdk-stream-android.jpg" src="https://mintcdn.com/mobilerun/oZ0TQelrSnTN0Cjq/images/sdk/sdk-stream-android.mp4?fit=max&auto=format&n=oZ0TQelrSnTN0Cjq&q=85&s=25894340b3dcdc6948da65bd69e7dc6c" />

> [tab] iPhone
>
> <video autoPlay muted loop playsInline preload="metadata" poster="/images/sdk/sdk-stream-ios.jpg" src="https://mintcdn.com/mobilerun/oZ0TQelrSnTN0Cjq/images/sdk/sdk-stream-ios.mp4?fit=max&auto=format&n=oZ0TQelrSnTN0Cjq&q=85&s=5a2e9474b15d94b1c81fd9c06bd3703c" />

## Tasks

### Wait for a task

Replaces a status polling loop with `setTimeout` or `time.sleep`. `task.wait()` returns the final
status once the task completed.

```text theme={null}
task.wait({ timeoutMs?, pollIntervalMs?, signal? }) → status
```

```typescript TypeScript theme={null}
const task = await device.run({ task: 'Open Settings and tell me the Android version' });
const status = await task.wait();
console.log(status.message);
```

```python Python theme={null}
task = device.run(task="Open Settings and tell me the Android version")
status = task.wait()
print(status.message)
```

| Option | TypeScript | Python | Default |
| - | - | - | - |
| Time limit | `timeoutMs` | `timeout` (seconds) | 10 minutes |
| Check interval | `pollIntervalMs` | `poll_interval` (seconds) | 1 second |
| Stop waiting early | `signal` (`AbortSignal`) | `cancel` (`threading.Event`) | none |

All wait errors extend `WaitError`.

| Error | When |
| - | - |
| `WaitFailureError` | The task or device ended in a failed state. `error.response` holds the last response |
| `WaitTimeoutError` | It did not finish in time. Set the limit with `timeoutMs` (Python `timeout`) |
| `OutputValidationError` | The output does not match your schema |

```typescript TypeScript theme={null}
import { WaitFailureError, WaitTimeoutError } from '@mobilerun/sdk';

try {
  await task.wait({ timeoutMs: 5 * 60_000 });
} catch (error) {
  if (error instanceof WaitFailureError) console.error(error.response);
  else if (error instanceof WaitTimeoutError) console.error('Still running');
  else throw error;
}
```

```python Python theme={null}
from mobilerun_sdk import WaitFailureError, WaitTimeoutError

try:
    task.wait(timeout=300)
except WaitFailureError as error:
    print(error.response)
except WaitTimeoutError:
    print("Still running")
```

### Typed output

Pass an output schema to `device.run()` and call `waitOutput()` (Python `wait_output()`) to get the
result as typed data. TypeScript uses [Zod](https://zod.dev) 4 through `output()` from
`@mobilerun/sdk/zod`. Python uses a Pydantic model.

```text theme={null}
task.waitOutput(options?) → { output, response }
```

```typescript TypeScript theme={null}
import { output } from '@mobilerun/sdk/zod';
import { z } from 'zod/v4';

const task = await device.run({
  task: 'Read the visible heading',
  outputSchema: output(z.object({ heading: z.string() })),
});
const result = await task.waitOutput();
console.log(result.output.heading);
```

```python Python theme={null}
from pydantic import BaseModel


class Heading(BaseModel):
    heading: str


task = device.run(task="Read the visible heading", output_schema=Heading)
result = task.wait_output()
print(result.output.heading)
```

`result.response` is the raw status response. Options are the same as for `wait()`. It throws
`OutputValidationError` when the output does not match your schema, plus the errors of `wait()`.

## Recordings and files

### Recordings

`recording.wait()` returns once the video is uploaded. Then `video()` and `trajectory()` return the
files as bytes.

```text theme={null}
recording.wait(options?) → status
recording.video() · recording.trajectory() → bytes
```

```typescript TypeScript theme={null}
const recording = await device.recordings.start();
const task = await device.run({ task: 'Open Settings' });
await task.wait();
await recording.stop();
await recording.wait();
const video = await recording.video();
```

```python Python theme={null}
recording = device.recordings.start()
task = device.run(task="Open Settings")
task.wait()
recording.stop()
recording.wait()
video = recording.video()
```

Options and errors are the same as for `task.wait()`.

### Saved screenshots

Save a screenshot with `device.screenshot({ save: true })` (Python `save=True`). `savedScreenshot.image()`
returns the PNG as bytes. `device.screenshots.list()` returns one page; read its saved screenshots from
`.items`.

```text theme={null}
savedScreenshot.image() → bytes
```

```typescript TypeScript theme={null}
const page = await device.screenshots.list();
const data = await page.items[0].image();
```

```python Python theme={null}
page = device.screenshots.list()
data = page.items[0].image()
```

### Agent files

`agentFile.download()` returns the file as bytes.

```text theme={null}
agentFile.download() → bytes
```

```typescript TypeScript theme={null}
const data = await mobilerun.files.fromId('FILE_ID').download();
```

```python Python theme={null}
data = mobilerun.files.from_id("FILE_ID").download()
```

## Uploads

### Upload an app

Uploads the files and returns an `App`. A string is a local file path, and the file streams from disk.
Uploads use storage quota and may incur storage charges.

```typescript TypeScript theme={null}
const app = await mobilerun.apps.upload({
  bundleId: 'com.example.app',
  displayName: 'Example',
  versionCode: 1,
  versionName: '1.0.0',
  files: ['app.apk'],
});
console.log(app.id);
```

```python Python theme={null}
app = mobilerun.apps.upload(
    bundle_id="com.example.app",
    display_name="Example",
    version_code=1,
    version_name="1.0.0",
    files=["app.apk"],
)
print(app.id)
```

### Upload a file

Uploads the file and returns an `AgentFile`. A string is a local file path.

```typescript TypeScript theme={null}
const file = await mobilerun.files.upload({ file: 'report.pdf' });
```

```python Python theme={null}
file = mobilerun.files.upload(file="report.pdf")
```

## Webhooks

Replaces writing the signature check yourself. `verifyWebhook` (Python `verify_webhook`) is a standalone
import and needs no API key. Pass the raw request body, exactly as received. If a framework parses the
JSON first, the signature no longer matches. The check also rejects requests that are too old or too far
in the future, so replays fail. Deduplicate replays with an ID inside the signed body, not the unsigned
`X-Mobilerun-Event-Id` header.

```typescript TypeScript theme={null}
import { verifyWebhook, WebhookVerificationError } from '@mobilerun/sdk';

export async function POST(request: Request): Promise<Response> {
  try {
    const event = await verifyWebhook({
      body: new Uint8Array(await request.arrayBuffer()),
      headers: request.headers,
      secret: process.env.WEBHOOK_SECRET!,
    });
    return Response.json(event);
  } catch (error) {
    if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 });
    throw error;
  }
}
```

```python Python theme={null}
import os
from flask import Flask, jsonify, request
from mobilerun_sdk import WebhookVerificationError, verify_webhook

app = Flask(__name__)


@app.post("/webhook")
def handle_webhook():
    try:
        event = verify_webhook(request.get_data(), request.headers, os.environ["WEBHOOK_SECRET"])
        return jsonify(event)
    except WebhookVerificationError:
        return "", 400
```

If it throws `WebhookVerificationError` (wrong signature or too old), respond with 400. See
[Webhooks](https://docs.mobilerun.ai/webhooks.md) for events and secrets.

## Common to all objects

* **Pagination.** Lists are iterated directly: `for await (const device of mobilerun.devices.list())`
  in TypeScript, `for device in mobilerun.devices.list()` in Python. Next pages load as needed.
* **`fromId()`.** `mobilerun.devices.fromId(id)` (Python `from_id`) gives you an object without a
  network call. Every collection, such as `mobilerun.tasks`, has it.
* **Automatic cleanup.** `await using` (TypeScript 5.2 or later) and `with` (Python) terminate a
  device from `devices.create()` when the block ends. Devices from `get`, `fromId` or a list are
  never cleaned up for you.
* **Safe logging.** Objects never print the API key. `console.log(device)` and `print(device)` are
  safe.

> [card] [Mobilerun SDK](https://docs.mobilerun.ai/guides/sdk-objects.md)
>
> Create devices, run tasks, stream, and the list of all objects.

> [card] [Cloud Quickstart](https://docs.mobilerun.ai/cloud/quickstart.md)
>
> Run your first task end to end.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.