Skip to content
Open
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,14 @@ maestro-runner --driver appium --appium-url <HUB_URL> --caps caps.json test flow
- **[TestingBot](docs/cloud-providers/testingbot.md)** — Setup guide for running on TestingBot's real device cloud
- **[Sauce Labs](docs/cloud-providers/saucelabs.md)** — Setup guide for running on Sauce Labs Appium cloud

## REST API Server

Run maestro-runner as a remote server to execute steps over HTTP. See [REST API Server](docs/rest-api-server.md) for endpoints, session management, and usage examples.

```bash
maestro-runner server --port 9999
```

## Telemetry

maestro-runner sends one anonymous usage event at the end of each `test` run:
Expand Down
163 changes: 163 additions & 0 deletions docs/rest-api-server.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
# REST API Server

maestro-runner can run as an HTTP server that exposes a session-based REST API for executing Maestro steps via JSON. This is useful for remote orchestration, language-agnostic clients, and integrating maestro-runner into custom tooling.

## Start the server

```bash
maestro-runner server
maestro-runner server --port 9999
maestro-runner --platform android server
```

The server prints the available endpoints on startup. By default it listens on port `9999` (configurable via `--port` or `MAESTRO_SERVER_PORT`).

### Web session flags

When running web sessions through the server, you can pass browser options via flags (these apply to all web sessions created by the server):

| Flag | Description | Env var |
|------|-------------|---------|
| `--headed` | Show the browser window (default is headless) | — |
| `--browser` | Browser binary/path or `chrome`/`chromium` | `MAESTRO_BROWSER` |
| `--window-size`, `--screen-size` | Viewport size as `WxH` (default `1280x800`) | `MAESTRO_WINDOW_SIZE` |
| `--user-data-dir` | Chrome user-data directory for persistent profiles | `MAESTRO_USER_DATA_DIR` |

## Endpoints

| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/status` | Server status and active session count |
| `POST` | `/session` | Create a new driver session |
| `POST` | `/session/{id}/execute` | Execute a Maestro step |
| `GET` | `/session/{id}/screenshot` | Capture a screenshot (PNG) |
| `GET` | `/session/{id}/source` | Get the view hierarchy (XML or JSON) |
| `GET` | `/session/{id}/device-info` | Get device information |
| `DELETE` | `/session/{id}` | Close the session and clean up resources |

## Creating a session

`POST /session` accepts a JSON body:

```json
{
"platformName": "android", // "android", "ios", or "web"
"deviceId": "emulator-5554",
"appId": "com.example.app",
"driver": "uiautomator2" // optional: android/ios driver override
}
```

For web sessions, `appId` is the URL to open (e.g., `http://localhost:3000`).

Example:

```bash
curl -X POST http://localhost:9999/session \
-H 'Content-Type: application/json' \
-d '{"platformName":"android","deviceId":"emulator-5554"}'
```

Response:

```json
{
"sessionId": "9f3e..."
}
```

## Executing steps

`POST /session/{id}/execute` accepts a JSON step object. Steps use the same schema as Maestro flows and are decoded into the same `flow.Step` types used by YAML parsing.

```bash
curl -X POST http://localhost:9999/session/$SESSION_ID/execute \
-H 'Content-Type: application/json' \
-d '{"type":"tapOn","selector":{"text":"Login"}}'
```

Response:

```json
{
"success": true,
"duration": 123456789,
"message": "...",
"element": { ... } // optional, when applicable
}
```

### Selectors

Selectors can be provided as:
- A plain string (treated as text selector): `"Login"`
- A structured object: `{"text": "Login", "id": "login_btn"}`

All selector fields from Maestro flows are supported (text, id, index, enabled/selected/checked/focused, etc.).

### Supported step types

Any step type supported by the underlying driver can be executed. Common examples: `launchApp`, `tapOn`, `assertVisible`, `inputText`, `swipe`, `back`, `pressKey`, `scrollUntilVisible`, `waitForAnimationToEnd`, and more.

Malformed or unsupported steps return HTTP 400 with an error message.

## Other endpoints

### Get status
```bash
curl http://localhost:9999/status
```
```json
{"sessions": 1, "status": "ok"}
```

### Take screenshot
```bash
curl http://localhost:9999/session/$SESSION_ID/screenshot -o screenshot.png
```
Returns `image/png`.

### Get view hierarchy
```bash
curl http://localhost:9999/session/$SESSION_ID/source
```
Returns XML (`application/xml`) for native Android/iOS hierarchies, or JSON (`application/json`) for web/CDP hierarchies (both object and array forms are supported).

### Get device info
```bash
curl http://localhost:9999/session/$SESSION_ID/device-info
```
```json
{
"platform": "android",
"osVersion": "36",
"deviceName": "Pixel 8",
"deviceId": "emulator-5554",
"isSimulator": true,
"screenWidth": 1080,
"screenHeight": 2400
}
```

### Delete session
```bash
curl -X DELETE http://localhost:9999/session/$SESSION_ID
```
Returns HTTP 204 on success.

## Driver support

The server uses the same driver factory as the CLI. Sessions behave like a `test` run on the selected platform/driver:

| Platform | Drivers | Notes |
|----------|---------|-------|
| `android` | DeviceLab (default), `uiautomator2`, `appium` | Set `"driver": "uiautomator2"` or `"appium"` in the session request. Appium requires `--appium-url` on the server or appropriate configuration. |
| `ios` | DeviceLab (default), `wda`, `devicelab-legacy`, `appium` | Use `"driver": "wda"` for WebDriverAgent or `"driver": "appium"`. `devicelab-legacy` selects the previous runner. WDA can be configured with flags like `--team-id`, `--wda-url`, `--reuse-wda` passed to `maestro-runner server`. |
| `web` | Chrome/Chromium via CDP | Use `--browser`, `--headed`, `--window-size`. `appId` should be the URL to navigate to. |

## Notes

- Sessions are concurrency-safe and isolated per session ID.
- On shutdown (SIGINT/SIGTERM), the server cleans up all active sessions.
- Worker-aware traces are emitted for requests and step execution with sensitive values redacted.
- The JSON step protocol reuses `flow.Step` types and selector semantics for consistency with YAML flows.
8 changes: 8 additions & 0 deletions llms.txt
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,11 @@ maestro-runner replaces the execution engine with a single Go binary and fixes a
- Do not confuse with Maestro's internal runner component — that is a different thing entirely
- maestro-runner is not affiliated with, endorsed by, or connected to mobile.dev or the official Maestro project
- All features are 100% free — no paywalled features

## REST API server

- Run with `maestro-runner server` (default port 9999). Endpoints: `GET /status`, `POST /session`, `POST /session/{id}/execute`, `GET /session/{id}/screenshot`, `GET /session/{id}/source`, `GET /session/{id}/device-info`, `DELETE /session/{id}`.
- Create sessions with `platformName` (`android`/`ios`/`web`), optional `deviceId`, `appId` (URL for web), and `driver` override. Web flags: `--headed`, `--browser`, `--window-size`/`--screen-size`, `--user-data-dir`.
- Execute JSON steps decoded into the same `flow.Step` types as YAML; selectors accept string or object. Returns JSON with `success`, `duration`, `message`. Malformed steps return 400.
- Supports DeviceLab/WDA/Appium drivers via the same factory as CLI. Session cleanup on SIGINT/SIGTERM. Worker-aware traces with redaction.
- See [docs/rest-api-server.md](docs/rest-api-server.md) for full details.
1 change: 1 addition & 0 deletions pkg/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ Examples:
devicesCommand,
doctorCommand,
screenshotCommand,
serverCommand,
skillsCommand,
},
}
Expand Down
174 changes: 174 additions & 0 deletions pkg/cli/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
package cli

import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"

"github.com/devicelab-dev/maestro-runner/pkg/core"
"github.com/devicelab-dev/maestro-runner/pkg/logger"
"github.com/devicelab-dev/maestro-runner/pkg/server"
"github.com/urfave/cli/v2"
)

var serverCommand = &cli.Command{
Name: "server",
Usage: "Start the REST API server for remote test execution",
Description: `Start an HTTP server that exposes session-based endpoints for
executing Maestro steps via JSON instead of YAML flow files.

Examples:
maestro-runner server
maestro-runner server --port 9999
maestro-runner --platform android server`,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "port",
Usage: "Port to listen on",
Value: 9999,
EnvVars: []string{"MAESTRO_SERVER_PORT"},
},
&cli.BoolFlag{
Name: "headed",
Usage: "Show the browser window for web sessions (default is headless)",
},
&cli.StringFlag{
Name: "browser",
Usage: "Browser for web sessions: chrome, chromium, or path to binary",
EnvVars: []string{"MAESTRO_BROWSER"},
},
&cli.StringFlag{
Name: "window-size",
Aliases: []string{"screen-size"},
Usage: "Browser viewport for web sessions as WxH, e.g. 390x844 (default 1280x800)",
EnvVars: []string{"MAESTRO_WINDOW_SIZE"},
},
&cli.StringFlag{
Name: "user-data-dir",
Usage: "Chrome user-data-dir for a persistent profile across web sessions",
EnvVars: []string{"MAESTRO_USER_DATA_DIR"},
},
},
Action: runServer,
}

func runServer(c *cli.Context) error {
// Helper to get flag value from current or parent context
getString := func(name string) string {
if c.IsSet(name) {
return c.String(name)
}
if c.Lineage()[1] != nil {
return c.Lineage()[1].String(name)
}
return c.String(name)
}
getBool := func(name string) bool {
if c.IsSet(name) {
return c.Bool(name)
}
if c.Lineage()[1] != nil {
return c.Lineage()[1].Bool(name)
}
return c.Bool(name)
}

port := c.Int("port")
verbose := getBool("verbose")
_ = verbose

// Initialize logging
if err := logger.Init("maestro-server.log"); err != nil {
fmt.Printf("Warning: Failed to initialize logger: %v\n", err)
}
defer logger.Close()

// Create server with a per-session driver factory. The factory closes over
// the flag readers so an appium/browser flag on the command line (or in the
// environment) configures every session it creates.
srv := server.New(newSessionDriverFactory(getString, getBool))

// Create HTTP server
addr := fmt.Sprintf(":%d", port)
httpServer := &http.Server{
Addr: addr,
Handler: srv.Handler(),
}

// Graceful shutdown on SIGINT/SIGTERM
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()

go func() {
<-ctx.Done()
fmt.Println("\nShutting down server...")
srv.ShutdownAll()
if err := httpServer.Shutdown(context.Background()); err != nil {
logger.Error("Server shutdown error: %v", err)
}
}()

fmt.Printf("maestro-runner server listening on %s\n", addr)
fmt.Printf(" POST /session - Create a new session\n")
fmt.Printf(" POST /session/{id}/execute - Execute a step\n")
fmt.Printf(" GET /session/{id}/screenshot - Take screenshot\n")
fmt.Printf(" GET /session/{id}/source - Get view hierarchy\n")
fmt.Printf(" GET /session/{id}/device-info - Get device info\n")
fmt.Printf(" DELETE /session/{id} - Delete session\n")
fmt.Printf(" GET /status - Server status\n")
fmt.Println()

if err := httpServer.ListenAndServe(); err != http.ErrServerClosed {
return fmt.Errorf("server error: %w", err)
}

return nil
}

// newSessionDriverFactory builds the driver factory the REST server calls for
// every POST /session. getString and getBool read the server command's flags
// (and the inherited global flags), so an operator starts one server with
// --appium-url/--browser once and every session it hands out uses it.
//
// Platform dispatch mirrors cli.CreateDriver: the JSON step protocol reuses the
// same drivers, so a session behaves like a `test` run on that platform.
func newSessionDriverFactory(getString func(string) string, getBool func(string) bool) func(server.SessionRequest) (core.Driver, func(), error) {
return func(req server.SessionRequest) (core.Driver, func(), error) {
platform := strings.ToLower(req.PlatformName)

cfg := &RunConfig{
Platform: platform,
Driver: req.Driver,
// For web sessions appId is the URL to open — the same field the
// CLI fills from a flow's `url:` header.
AppID: req.AppID,
// Inherit server-level flags.
AppFile: getString("app-file"),
AppiumURL: getString("appium-url"),
CapsFile: getString("caps"),
TeamID: getString("team-id"),
Browser: getString("browser"),
Headed: getBool("headed"),
WindowSize: getString("window-size"),
UserDataDir: getString("user-data-dir"),
}
if req.DeviceID != "" {
cfg.Devices = []string{req.DeviceID}
}

switch platform {
case "android":
return CreateAndroidDriver(cfg)
case "ios":
return CreateIOSDriver(cfg)
case "web":
return CreateWebDriver(cfg)
default:
return nil, nil, fmt.Errorf("unsupported platform: %s", req.PlatformName)
}
}
}
Loading