> ## 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.

# Watch an app and get alerts

> Check book prices and stock, compare snapshots, and receive task events.

Watch a book page, compare prices, and receive signed task events.

> [accordion] Setup (once)
>
> ```bash Python theme={null}
> pip install mobilerun-sdk
> export MOBILERUN_API_KEY=dr_sk_...   # API Keys page
> export DEVICE_ID=...                 # a ready device from the dashboard
> python example.py
> ```
>
> ```bash TypeScript theme={null}
> npm init -y && npm pkg set type=module
> npm install @mobilerun/sdk && npm install -D tsx
> export MOBILERUN_API_KEY=dr_sk_...   # API Keys page
> export DEVICE_ID=...                 # a ready device from the dashboard
> npx tsx example.ts
> ```

## Read a product page

Read one book page as [typed output](https://docs.mobilerun.ai/sdk/helpers.md#typed-output) and print its title, price, availability and stock count.

**Needs:** Mobilerun account · Cloud Android · Chrome · device credits · no third-party account · one-shot

> Open the A Light in the Attic product page on books.toscrape.com in Chrome. Return its title, numeric GBP price, whether it is in stock, and the exact stock count. Do not buy anything.

> [accordion] Show the code (Python and TypeScript)
>
> ```python Python theme={null}
> import os
> from pydantic import BaseModel
> from mobilerun_sdk import MobilerunSDK
>
>
> class Book(BaseModel):
>     title: str
>     price: float
>     in_stock: bool
>     stock_count: int
>
>
> url = "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html"
> mobilerun = MobilerunSDK()
> device = mobilerun.devices.from_id(os.environ["DEVICE_ID"])
> task = device.run(
>     task=f"Open {url} in Chrome. Read the title, numeric price in GBP, availability and exact stock count. Do not buy anything.",
>     output_schema=Book,
>     max_steps=25,
> )
> print(f"Task: {task.id}", flush=True)
> print(task.wait_output().output.model_dump_json())
> ```
>
> ```typescript TypeScript theme={null}
> import { MobilerunSDK } from '@mobilerun/sdk';
> import { output } from '@mobilerun/sdk/zod';
> import { z } from 'zod/v4';
>
> const url = 'https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html';
> const book = z.object({ title: z.string(), price: z.number(), in_stock: z.boolean(), stock_count: z.int() });
> const mobilerun = new MobilerunSDK();
> const device = mobilerun.devices.fromId(process.env.DEVICE_ID!);
> const task = await device.run({
>   task: `Open ${url} in Chrome. Read the title, numeric price in GBP, availability and exact stock count. Do not buy anything.`,
>   outputSchema: output(book),
>   maxSteps: 25,
> });
> console.log(`Task: ${task.id}`);
> console.log(JSON.stringify((await task.waitOutput()).output));
> ```

![A Light in the Attic product page, £51.77 and 22 available](https://docs.mobilerun.ai/images/examples/watch-and-alert/l1.png)

Result

```json theme={null}
{"title":"A Light in the Attic","price":51.77,"in_stock":true,"stock_count":22}
```

## Compare products and alert

Compare two or three products with a local snapshot and send changes to an optional JSON webhook.

**Needs:** Mobilerun account · Cloud Android · Chrome · device credits · 2–3 public product URLs · optional `WEBHOOK_URL` and `MONITOR_STATE_FILE` · one-shot

> [accordion] Show the code (Python and TypeScript)
>
> ```python Python theme={null}
> import json
> import os
> import sys
> from pathlib import Path
> from urllib.parse import urlparse
> from urllib.request import Request, urlopen
> from pydantic import BaseModel, Field, model_validator
> from mobilerun_sdk import MobilerunSDK
>
>
> class Product(BaseModel):
>     title: str = Field(min_length=1)
>     price: float = Field(ge=0)
>     currency: str = Field(min_length=1)
>     in_stock: bool
>     stock_count: int = Field(ge=0)
>
>     @model_validator(mode="after")
>     def stock_matches(self) -> "Product":
>         if self.in_stock != (self.stock_count > 0):
>             raise ValueError("in_stock must match stock_count")
>         return self
>
>
> def main() -> int:
>     urls = sys.argv[1:]
>     if not 2 <= len(urls) <= 3 or len(set(urls)) != len(urls):
>         raise ValueError("Pass 2–3 distinct product URLs")
>     for url in urls:
>         parsed = urlparse(url)
>         if parsed.scheme != "https" or parsed.netloc != "books.toscrape.com" or not parsed.path.endswith("/index.html"):
>             raise ValueError("Use HTTPS books.toscrape.com product page URLs")
>     state_file = Path(os.environ.get("MONITOR_STATE_FILE", "monitor-state.json"))
>     saved = json.loads(state_file.read_text()) if state_file.exists() else {}
>     previous = {url: Product.model_validate(value) for url, value in saved.items()}
>     mobilerun = MobilerunSDK()
>     device = mobilerun.devices.from_id(os.environ["DEVICE_ID"])
>     current: dict[str, Product] = {}
>     for url in urls:
>         task = device.run(
>             task=f"Open {url} in Chrome. Read the product title, numeric price, ISO currency code, availability and exact stock count. Return them in the requested fields. Do not buy anything.",
>             output_schema=Product,
>             max_steps=25,
>         )
>         print(f"Task: {task.id}")
>         current[url] = task.wait_output().output
>     fields = ("price", "currency", "in_stock", "stock_count")
>     changes = [
>         {"url": url, "before": previous[url].model_dump(), "after": item.model_dump()}
>         for url, item in current.items()
>         if url in previous and any(getattr(previous[url], f) != getattr(item, f) for f in fields)
>     ]
>     if changes:
>         payload = {"text": f"Product changes: {json.dumps(changes, ensure_ascii=False)}", "changes": changes}
>         print(payload["text"])
>         webhook = os.environ.get("WEBHOOK_URL")
>         if webhook:
>             request = Request(webhook, data=json.dumps(payload).encode(),
>                               headers={"Content-Type": "application/json"}, method="POST")
>             with urlopen(request, timeout=15) as response:
>                 if not 200 <= response.status < 300:
>                     raise RuntimeError(f"Webhook returned {response.status}")
>     else:
>         print("No changes (new products establish a baseline).")
>     state_file.write_text(json.dumps({u: p.model_dump() for u, p in current.items()}, indent=2, ensure_ascii=False) + "\n")
>     return 1 if changes else 0
>
>
> if __name__ == "__main__":
>     try:
>         sys.exit(main())
>     except Exception as error:
>         print(f"Monitor error: {error}", file=sys.stderr)
>         sys.exit(2)
> ```
>
> ```typescript TypeScript theme={null}
> import { readFile, writeFile } from 'node:fs/promises';
> import { MobilerunSDK } from '@mobilerun/sdk';
> import { output } from '@mobilerun/sdk/zod';
> import { z } from 'zod/v4';
>
> const product = z.object({
>   title: z.string().min(1),
>   price: z.number().nonnegative(),
>   currency: z.string().min(1),
>   in_stock: z.boolean(),
>   stock_count: z.int().nonnegative(),
> }).refine((p) => p.in_stock === p.stock_count > 0, 'in_stock must match stock_count');
> type Product = z.infer<typeof product>;
>
> async function main(): Promise<number> {
>   const urls = process.argv.slice(2);
>   if (urls.length < 2 || urls.length > 3 || new Set(urls).size !== urls.length) {
>     throw new Error('Pass 2–3 distinct product URLs');
>   }
>   for (const url of urls) {
>     const parsed = new URL(url);
>     if (parsed.protocol !== 'https:' || parsed.host !== 'books.toscrape.com' || !parsed.pathname.endsWith('/index.html')) {
>       throw new Error('Use HTTPS books.toscrape.com product page URLs');
>     }
>   }
>   const stateFile = process.env.MONITOR_STATE_FILE ?? 'monitor-state.json';
>   let saved: unknown = {};
>   try { saved = JSON.parse(await readFile(stateFile, 'utf8')); }
>   catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
>   const previous = z.record(z.string(), product).parse(saved);
>   const mobilerun = new MobilerunSDK();
>   const device = mobilerun.devices.fromId(process.env.DEVICE_ID!);
>   const current: Record<string, Product> = {};
>   for (const url of urls) {
>     const task = await device.run({
>       task: `Open ${url} in Chrome. Read the product title, numeric price, ISO currency code, availability and exact stock count. Return them in the requested fields. Do not buy anything.`,
>       outputSchema: output(product),
>       maxSteps: 25,
>     });
>     console.log(`Task: ${task.id}`);
>     current[url] = (await task.waitOutput()).output;
>   }
>   const fields: (keyof Product)[] = ['price', 'currency', 'in_stock', 'stock_count'];
>   const changes = urls.filter((url) => previous[url] && fields.some((field) => previous[url][field] !== current[url][field]))
>     .map((url) => ({ url, before: previous[url], after: current[url] }));
>   if (changes.length) {
>     const payload = { text: `Product changes: ${JSON.stringify(changes)}`, changes };
>     console.log(payload.text);
>     if (process.env.WEBHOOK_URL) {
>       const response = await fetch(process.env.WEBHOOK_URL, {
>         method: 'POST', headers: { 'Content-Type': 'application/json' },
>         body: JSON.stringify(payload), signal: AbortSignal.timeout(15_000),
>       });
>       if (!response.ok) throw new Error(`Webhook returned ${response.status}`);
>     }
>   } else console.log('No changes (new products establish a baseline).');
>   await writeFile(stateFile, JSON.stringify(current, null, 2) + '\n');
>   return changes.length ? 1 : 0;
> }
>
> main().then((code) => { process.exitCode = code; }).catch((error: unknown) => {
>   console.error('Monitor error:', error instanceof Error ? error.message : error);
>   process.exitCode = 2;
> });
> ```

![A Light in the Attic product page during the comparison run](https://docs.mobilerun.ai/images/examples/watch-and-alert/l2.png)

Result

```text theme={null}
Product changes: [{"url":"https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html","before":{"title":"A Light in the Attic","price":0.01,"currency":"GBP","in_stock":true,"stock_count":22},"after":{"title":"A Light in the Attic","price":51.77,"currency":"GBP","in_stock":true,"stock_count":22}}]
```

## Send webhook events on a schedule

Submit a check every minute and compare results after signed completion events arrive. Verifying the signature by hand is temporary: a dedicated helper replaces it, see [Webhooks](https://docs.mobilerun.ai/sdk/helpers.md#webhooks).

**Needs:** Mobilerun account · Cloud Android · Chrome · device credits · public HTTPS endpoint · `WEBHOOK_URL` · optional `PORT` and `INTERVAL_MINUTES` · keeps running until Ctrl+C

Start a tunnel and set `WEBHOOK_URL` to its HTTPS URL; stop the tunnel separately.

> [accordion] Show the code (Python and TypeScript)
>
> ```python Python theme={null}
> import json
> import os
> import threading
> import time
> from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
> from pydantic import BaseModel
> from mobilerun_sdk import MobilerunSDK, WebhookVerificationError, verify_webhook
>
>
> class Book(BaseModel):
>     title: str
>     price: float
>     in_stock: bool
>     stock_count: int
>
>
> mobilerun = MobilerunSDK()
> device = mobilerun.devices.from_id(os.environ["DEVICE_ID"])
> url = "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html"
> secret = ""
> seen = set()
> task_ids = set()
> previous = None
>
>
> def process_event(event):
>     global previous
>     task_id = event["data"]["id"]
>     if event["type"] == "task.run.failed":
>         print(f"Task failed: {task_id}", flush=True)
>         return
>     try:
>         result = mobilerun.tasks.from_id(task_id).get_status()  # One read after the webhook.
>         product = result.output
>         if not result.succeeded or not isinstance(product, dict):
>             raise ValueError("No structured output")
>         if previous is not None and any(previous.get(k) != product.get(k) for k in ("price", "in_stock", "stock_count")):
>             print(f"ALERT: {json.dumps({'before': previous, 'after': product})}", flush=True)
>         else:
>             print(f"Observation: {json.dumps(product)}", flush=True)
>         previous = product
>     except Exception as error:
>         print(f"Could not process {task_id}: {error}", flush=True)
>
>
> class Receiver(BaseHTTPRequestHandler):
>     def do_POST(self):
>         length = int(self.headers.get("Content-Length", "0"))
>         if length <= 0 or length > 1_000_000:
>             self.send_error(400)
>             return
>         raw = self.rfile.read(length)
>         try:
>             event = verify_webhook(raw, self.headers, secret)
>         except WebhookVerificationError:
>             self.send_error(400)
>             return
>         try:
>             event_id = event["id"]
>             event_type = event["type"]
>         except (KeyError, TypeError):
>             self.send_error(400)
>             return
>         if event_id not in seen and event.get("data", {}).get("id") in task_ids:
>             seen.add(event_id)
>             print(f"Event {event_type}: {json.dumps(event['data'])}", flush=True)
>             threading.Thread(target=process_event, args=(event,), daemon=True).start()
>         self.send_response(200)
>         self.end_headers()
>
>
> server = ThreadingHTTPServer(("127.0.0.1", int(os.environ.get("PORT", "19873"))), Receiver)
> threading.Thread(target=server.serve_forever, daemon=True).start()
> hook = None
> try:
>     hook = mobilerun.webhooks.create(url=os.environ["WEBHOOK_URL"], event_types=["task.run.completed", "task.run.failed"])
>     secret = getattr(getattr(hook.info, "data", None), "secret", None) or ""  # shown once, at create
>     if not secret:
>         raise RuntimeError("Webhook did not return a signing secret")
>     print(f"Webhook: {hook.id}", flush=True)
>     while True:
>         task = device.run(
>             task=f"Open {url} in Chrome. Read the title, numeric price in GBP, availability and exact stock count. Do not buy anything.",
>             output_schema=Book,
>             max_steps=25,
>         )
>         task_ids.add(task.id)
>         print(f"Task: {task.id}", flush=True)
>         time.sleep(float(os.environ.get("INTERVAL_MINUTES", "1")) * 60)
> except KeyboardInterrupt:
>     print("Stopping", flush=True)
> finally:
>     server.shutdown()
>     server.server_close()
>     if hook:
>         hook.delete()
>         print("Webhook deleted", flush=True)
> ```
>
> ```typescript TypeScript theme={null}
> import { createServer } from 'node:http';
> import { MobilerunSDK, verifyWebhook } from '@mobilerun/sdk';
> import { output } from '@mobilerun/sdk/zod';
> import { z } from 'zod/v4';
>
> const webhookUrl = process.env.WEBHOOK_URL;
> if (!webhookUrl) throw new Error('Set WEBHOOK_URL');
> const mobilerun = new MobilerunSDK();
> const device = mobilerun.devices.fromId(process.env.DEVICE_ID!);
> const url = 'https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html';
> const book = z.object({ title: z.string(), price: z.number(), in_stock: z.boolean(), stock_count: z.int() });
> let secret = '';
> const seen = new Set<string>();
> const taskIds = new Set<string>();
> let previous: Record<string, unknown> | undefined;
> async function processEvent(event: { type: string; data: { id: string } }): Promise<void> {
>   if (event.type === 'task.run.failed') { console.log(`Task failed: ${event.data.id}`); return; }
>   try {
>     const result = await mobilerun.tasks.fromId(event.data.id).getStatus(); // One read after the webhook.
>     if (!result.succeeded || !result.output || typeof result.output !== 'object') throw new Error('No structured output');
>     const product = result.output as Record<string, unknown>;
>     if (previous && ['price', 'in_stock', 'stock_count'].some(k => previous?.[k] !== product[k])) {
>       console.log(`ALERT: ${JSON.stringify({ before: previous, after: product })}`);
>     } else console.log(`Observation: ${JSON.stringify(product)}`);
>     previous = product;
>   } catch (error) { console.error(`Could not process ${event.data.id}:`, error); }
> }
> const server = createServer((req, res) => {
>   if (req.method !== 'POST') { res.writeHead(405).end(); return; }
>   const chunks: Buffer[] = [];
>   let size = 0;
>   req.on('data', (chunk: Buffer) => { size += chunk.length; if (size > 1_000_000) req.destroy(); else chunks.push(chunk); });
>   req.on('end', async () => {
>     const raw = Buffer.concat(chunks);
>     let event: { id: string; type: string; data: { id: string } };
>     try {
>       event = (await verifyWebhook({ body: new Uint8Array(raw), headers: req.headers as Record<string, string>, secret })) as typeof event;
>     } catch { res.writeHead(400).end(); return; }
>     try {
>       if (typeof event.id !== 'string' || typeof event.type !== 'string') throw new Error('Invalid event');
>       if (!seen.has(event.id) && taskIds.has(event.data?.id)) { seen.add(event.id); console.log(`Event ${event.type}: ${JSON.stringify(event.data)}`); void processEvent(event); }
>       res.writeHead(200).end();
>     } catch { res.writeHead(400).end(); }
>   });
> });
> await new Promise<void>(resolve => server.listen(Number(process.env.PORT ?? '19873'), '127.0.0.1', resolve));
> let stopped = false;
> process.on('SIGINT', () => { stopped = true; });
> try {
>   await using hook = await mobilerun.webhooks.create({ url: webhookUrl, eventTypes: ['task.run.completed', 'task.run.failed'] }); // deleted when the block ends
>   const info = hook.info; // the signing secret is in the create response only
>   secret = (info && 'data' in info && 'secret' in info.data ? info.data.secret : undefined) ?? '';
>   if (!secret) throw new Error('Webhook did not return a signing secret');
>   console.log(`Webhook: ${hook.id}`);
>   while (!stopped) {
>     const task = await device.run({
>       task: `Open ${url} in Chrome. Read the title, numeric price in GBP, availability and exact stock count. Do not buy anything.`,
>       outputSchema: output(book),
>       maxSteps: 25,
>     });
>     taskIds.add(task.id);
>     console.log(`Task: ${task.id}`);
>     await new Promise<void>(resolve => { const timer = setTimeout(resolve, Number(process.env.INTERVAL_MINUTES ?? '1') * 60_000); process.once('SIGINT', () => { clearTimeout(timer); resolve(); }); });
>   }
> } finally {
>   server.close();
> }
> ```

![A Light in the Attic product page during the webhook run](https://docs.mobilerun.ai/images/examples/watch-and-alert/l3.png)

Result

```text theme={null}
Event task.run.completed: {"id":"example-task-id", …}
Observation: {"title":"A Light in the Attic","price":51.77,"in_stock":true,"stock_count":22}
```

> [!NOTE]
>
> Ctrl+C deletes the webhook; if the process is killed abruptly, delete it in Webhooks. For production, use durable state and a hosted endpoint.

## Run it on many devices

> [!TIP]
>
> Watch as many products as you need: one device per product, all in parallel.

**Needs:** 2+ ready Cloud Android devices · Chrome · device credits · `PRODUCT_URLS` · `DEVICE_IDS` or all ready devices · one-shot

Set `PRODUCT_URLS` to comma-separated product URLs, in the same order as `DEVICE_IDS`; when using all ready devices, the URLs follow the returned device order.

> [accordion] Show the code (Python and TypeScript)
>
> ```python Python theme={null}
> import asyncio
> import os
> from pydantic import BaseModel
> from mobilerun_sdk import AsyncMobilerunSDK, AsyncDevice
>
>
> class Book(BaseModel):
>     title: str
>     price: float
>     in_stock: bool
>     stock_count: int
>
>
> mobilerun = AsyncMobilerunSDK()
>
>
> async def check(device: AsyncDevice, url: str) -> tuple[str, str, bool]:
>     name = device.name or device.id
>     try:
>         if device.state != "ready":
>             raise RuntimeError("Device is not ready")
>         task = await device.run(
>             task=f"Open {url} in Chrome. Read the title, numeric price in GBP, availability and exact stock count. Do not buy anything.",
>             output_schema=Book,
>             max_steps=25,
>         )
>         print(f"Task {name}: {task.id}", flush=True)
>         return name, (await task.wait_output()).output.model_dump_json(), False
>     except Exception as error:
>         return name, f"ERROR: {error}", True
>
>
> async def main() -> None:
>     ids = [v.strip() for v in os.getenv("DEVICE_IDS", "").split(",") if v.strip()]
>     urls = [v.strip() for v in os.environ["PRODUCT_URLS"].split(",") if v.strip()]
>     if ids:
>         devices = [await mobilerun.devices.get(i) for i in ids]
>     else:
>         devices = [d async for d in mobilerun.devices.list(state=["ready"], platform="android")]
>     if len(devices) < 2 or len(devices) != len(urls) or len({d.id for d in devices}) != len(devices) or len(set(urls)) != len(urls):
>         raise SystemExit("Provide 2+ distinct devices and one distinct PRODUCT_URLS URL per device")
>     rows = await asyncio.gather(*(check(d, u) for d, u in zip(devices, urls)))
>     print("Device | Result")
>     for name, result, _ in rows:
>         print(f"{name} | {result}")
>     if any(failed for _, _, failed in rows):
>         raise SystemExit(1)
>
>
> asyncio.run(main())
> ```
>
> ```typescript TypeScript theme={null}
> import { MobilerunSDK, type Device } from '@mobilerun/sdk';
> import { output } from '@mobilerun/sdk/zod';
> import { z } from 'zod/v4';
>
> const mobilerun = new MobilerunSDK();
> const ids = (process.env.DEVICE_IDS ?? '').split(',').map(v => v.trim()).filter(Boolean);
> const urls = (process.env.PRODUCT_URLS ?? '').split(',').map(v => v.trim()).filter(Boolean);
> const devices: Device[] = [];
> if (ids.length) {
>   for (const id of ids) devices.push(await mobilerun.devices.get(id));
> } else {
>   for await (const device of mobilerun.devices.list({ state: ['ready'], platform: 'android' })) devices.push(device);
> }
> if (devices.length < 2 || devices.length !== urls.length || new Set(devices.map(d => d.id)).size !== devices.length || new Set(urls).size !== urls.length) {
>   throw new Error('Provide 2+ distinct devices and one distinct PRODUCT_URLS URL per device');
> }
> const book = z.object({ title: z.string(), price: z.number(), in_stock: z.boolean(), stock_count: z.int() });
> const rows = await Promise.allSettled(devices.map(async (device, index) => {
>   if (device.state !== 'ready') throw new Error('Device is not ready');
>   const task = await device.run({
>     task: `Open ${urls[index]} in Chrome. Read the title, numeric price in GBP, availability and exact stock count. Do not buy anything.`,
>     outputSchema: output(book),
>     maxSteps: 25,
>   });
>   console.log(`Task ${device.name || device.id}: ${task.id}`);
>   return { name: device.name || device.id, output: (await task.waitOutput()).output };
> }));
> console.log('Device | Result');
> for (const [i, row] of rows.entries()) {
>   console.log(row.status === 'fulfilled' ? `${row.value.name} | ${JSON.stringify(row.value.output)}` : `${devices[i].id} | ERROR: ${row.reason instanceof Error ? row.reason.message : row.reason}`);
> }
> if (rows.some(row => row.status === 'rejected')) process.exitCode = 1;
> ```

![A Light in the Attic product page showing £51.77 and 22 available](https://docs.mobilerun.ai/images/examples/watch-and-alert/l4.png)

Result

| Device | Result |
| - | - |
| Docs test G (drive) | A Light in the Attic · £51.77 · in stock (22) |
| Docs test C | Tipping the Velvet · £53.74 · in stock (20) |

## Next steps

* Use a Mobilerun workflow schedule trigger as a hosted alternative.
* Learn about [tasks](https://docs.mobilerun.ai/tasks.md) and [webhooks](https://docs.mobilerun.ai/webhooks.md).

> [accordion] For AI agents
>
> Start with the first example on a ready device the user names. Uses `device.run`, `task.waitOutput()`, task webhooks, and local product snapshots. Ask before creating a webhook or starting a tunnel/schedule; never purchase anything or use real accounts. Report the result and any failed step.


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