Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ Each creates a phone, checks one outcome and deletes the phone, also when the ch
| [typescript/mobilebox.ts](examples/typescript/mobilebox.ts) | minimal client + Settings check | Node 24 |
| [claude-code/](examples/claude-code) | Claude Code tests the APK you just built | an arm64 or universal APK |
| [github-actions/](examples/github-actions) | APK smoke test in a workflow | a repo secret with your key |
| [app-builder-preview/](examples/app-builder-preview) | your product shows each user their app on a live phone: a phone per end user, Expo or APK, embed, signed webhooks, usage per user | Node 20+, a public URL (a tunnel) |
| [proof-demo-calculator](https://github.com/mobilebox-dev/proof-demo-calculator/pulls?q=is%3Apr) | a real app (a Fossify Calculator fork) where every PR gets a proof comment: last screen, steps, time, cost | nothing: open its pull requests |
| [packages/python/](packages/python) | `mobilebox` Python client and `langchain-mobilebox` LangChain tools | Python 3.10+ |
| [integrations/](examples/integrations) | OpenAI Agents SDK, LangGraph, CrewAI, browser-use, Mastra, Vercel AI SDK, Claude Agent SDK, OpenHands, Haystack | the framework and a model key |
Expand Down
13 changes: 13 additions & 0 deletions examples/RUNS.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,16 @@ deleted: ph_on7c4dcbzlnk

17 s from the first step to the report, 15 s of phone time; the phone was deleted. The API key was absent from every log and file afterwards (OpenHands masks secrets and the example keeps the shell history off disk).

## App-builder preview

**2026-11-25**, Node 24 on Linux, `examples/app-builder-preview` against production through a Cloudflare quick tunnel, driven in Chrome. Details and the recording: [app-builder-preview/README.md](app-builder-preview/README.md#recorded-run).

| Step | Result | Time |
|---|---|---|
| Preview `user_42`, F-Droid Editor 1.98 APK, new phone | installed, live in the page at 30 Hz | 29 s |
| Preview `user_42` again, parked phone | started, `phone.ready` webhook, live | 15 s |
| Preview `user_7`, Expo SDK 58 tunnel link, new phone | Expo Go 58.0.6 installed itself, app live, Fast Refresh in the embed | 30 s |
| Park | `phone.parked` webhooks (signature checked), usage per end user updated | 2 s |

Afterwards both phones were deleted, the webhook removed and the page's origin taken off the list.

81 changes: 81 additions & 0 deletions examples/app-builder-preview/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# App-builder preview

Show each of your users their app on a cloud Android phone, live in your own page. The whole integration is two files and no dependencies: `server.mjs` (about 150 lines) and `index.html`.

![The example running against production: an APK and an Expo app previewed for two end users, webhooks arriving, usage per end user](demo.gif)

What it does:

1. **Keeps your API key on the server.** The browser only ever gets a short-lived embed URL.
2. **One phone per end user.** It creates the phone with `end_user` (your id for the person) and `display_hz: 30` for smooth scrolling, reuses it next time and starts it again if it's parked.
3. **Loads the app.** An APK URL installs and opens. An Expo link (`exp://`, `exps://`, `https://expo.dev/…`) opens in Expo Go, and Mobilebox installs the Expo Go that matches the project's SDK.
4. **Embeds the live phone** through `/embed`, locked to your page's origin. Your user can tap, swipe and type on it.
5. **Receives signed webhooks** (`phone.ready`, `phone.parked`, `phone.deleted`, `phone.failed`), checks the signature and shows each phone's state.
6. **Shows usage per end user**, the minutes and cost you can bill them for.

## Run it in 10 minutes

You need Node 20 or newer, a Mobilebox API key ([sign up](https://mobilebox.dev/signup)), and a public URL for this server so Mobilebox can send it webhooks. A Cloudflare quick tunnel works without an account:

```bash
git clone https://github.com/mobilebox-dev/mobilebox && cd mobilebox/examples/app-builder-preview
cloudflared tunnel --url http://localhost:3000 # prints https://….trycloudflare.com; leave it running
```

In a second terminal:

```bash
export MOBILESANDBOX_API_KEY=… # from https://mobilebox.dev/dashboard
export PUBLIC_URL=https://….trycloudflare.com # the URL the tunnel printed
node server.mjs
```

Open `PUBLIC_URL` in your browser. Pick an end user id, paste an APK URL (or press **an F-Droid APK**), and press **Preview**. A fresh phone takes about 30 s to boot and install; a parked one comes back in about 15 s.

For an Expo project, run `npx expo start --tunnel` and paste the `exp://` link it prints.

On start the server:

- adds your page's origin to the workspace's embed origins (`PUT /v1/embed/origins`, keeping the ones you have);
- points the workspace's webhook at `PUBLIC_URL/webhooks/mobilebox`.

A workspace has one webhook URL, so if yours already points somewhere else the server leaves it alone and says so. Use a separate workspace for this example, or set `MOBILEBOX_TAKE_WEBHOOK=1`.

## How it works

| Step | Code | Mobilebox API |
|---|---|---|
| A phone per end user | `phoneFor()` | `GET /v1/phones?end_user=…`, `POST /v1/phones {end_user, display_hz: 30}`, `POST /v1/phones/{id}/start` |
| The app on it | `load()` | `POST /v1/phones/{id}/apps {url}` + `open_app`, or `open_url` for Expo |
| The live phone in your page | `/api/preview` | `POST /v1/phones/{id}/embed {origin, interactive: true, ttl: 900}` |
| Phone state | `verify()`, `onWebhook()` | `PUT /v1/webhooks {url}`; events signed `Mobilebox-Signature: t=…,v1=…` |
| Usage per end user | `/api/usage` | `GET /v1/account/usage?by=end_user` |
| Done | `/api/park` | `DELETE /v1/phones/{id}/embed`, `POST /v1/phones/{id}/park` |

`node server.mjs --self-check` tests the signature check without a key.

## Before you ship it

- **Store state in your database.** This example keeps webhook events in memory. Keep the phone id and its last state per end user, and drop repeats by the event `id` (a retry sends the same one).
- **Answer webhooks fast.** Return 2xx within 10 s and do the work after. We retry after 10 s, 1 min, 10 min and 1 h.
- **Keep embed links short-lived.** Make a new link when one ends (the iframe tells your page with `mobilebox:end`). Revoke the link when your user leaves.
- **Park idle phones.** A parked phone keeps its apps and data and costs nothing. Phones also park by themselves after their idle timeout.
- **Plan for more users.** A workspace runs 3 phones at once to start. `POST /v1/account/limits {"running": n}` asks for more, and we answer within a day.

The page polls `/api/events` every 2 s instead of holding a server-sent event stream, because tunnels and proxies, Cloudflare's quick tunnels among them, often hold such a stream back.

Reference: [embed](https://mobilebox.dev/docs/embed), [Expo](https://mobilebox.dev/docs/expo), [labels, usage, webhooks and limits](https://mobilebox.dev/docs/reference#one-phone-per-end-user-labels-usage-webhooks-limits).

## Recorded run

**2026-11-25**, Node 24 on Linux, against production through a Cloudflare quick tunnel, Chrome:

| Step | Result | Time |
|---|---|---|
| Preview, `user_42`, F-Droid Editor 1.98 APK, new phone | installed, live in the page at 30 Hz, a click in the page reached the phone | 29 s |
| Park phone | `phone.parked` (manual) arrived signed; usage: user_42 2.2 min, $0.02 | 2 s |
| Preview again, `user_42` | parked phone started, `phone.ready`, app reinstalled, live | 15 s |
| Preview, `user_7`, Expo SDK 58 project (`exps://…exp.direct`), new phone | Expo Go 58.0.6 installed itself, app live; an edit showed by Fast Refresh in the embed | 30 s |
| Park phone, `user_7` | `phone.parked` arrived, the embed showed "This preview was closed", usage: user_7 1 min, $0.01 | 2 s |

An unsigned POST to the webhook URL got 401. Expo Go shows its developer menu once on a new phone; your user closes it in the embed.
Binary file added examples/app-builder-preview/demo.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
135 changes: 135 additions & 0 deletions examples/app-builder-preview/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>App preview · Mobilebox example</title>
<style>
:root { color-scheme: light dark; --edge: color-mix(in srgb, currentColor 18%, transparent); --muted: color-mix(in srgb, currentColor 62%, transparent); }
body { font: 15px/1.5 system-ui, sans-serif; margin: 0; padding: 24px; display: grid; grid-template-columns: minmax(300px, 440px) auto; gap: 32px; align-items: start; }
h1 { font-size: 20px; margin: 0 0 4px; } h2 { font-size: 15px; margin: 24px 0 8px; }
p.lede { margin: 0 0 20px; color: var(--muted); }
label { display: block; font-weight: 600; margin: 14px 0 4px; }
input { width: 100%; box-sizing: border-box; font: inherit; padding: 8px 10px; border: 1px solid var(--muted); border-radius: 8px; background: transparent; color: inherit; }
.hint { font-size: 13px; color: var(--muted); margin-top: 4px; } .hint button { font: inherit; padding: 0; border: 0; background: none; color: LinkText; cursor: pointer; text-decoration: underline; }
.actions { display: flex; gap: 10px; margin-top: 16px; }
.actions button { font: inherit; padding: 9px 16px; border-radius: 8px; border: 1px solid var(--edge); background: transparent; color: inherit; cursor: pointer; }
.actions button.primary { order: 2; background: CanvasText; color: Canvas; border-color: CanvasText; } /* the next step sits last */
button:disabled { opacity: .5; cursor: default; }
#status { margin-top: 12px; min-height: 1.5em; } #status.error, td.error { color: light-dark(#b42318, #ff8a7a); }
table { width: 100%; border-collapse: collapse; font-size: 14px; } td, th { text-align: left; padding: 5px 8px 5px 0; border-bottom: 1px solid var(--edge); } td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
ol#log { list-style: none; padding: 0; margin: 0; font: 13px/1.6 ui-monospace, monospace; max-height: 220px; overflow: auto; }
.phone { width: 360px; height: min(800px, calc(100vh - 48px)); position: sticky; top: 24px; border-radius: 28px; overflow: hidden; border: 1px solid var(--edge); display: grid; place-items: center; text-align: center; color: var(--muted); padding: 0; }
.phone iframe { width: 100%; height: 100%; border: 0; display: block; } /* the embed fits the phone into any frame */
@media (max-width: 900px) { body { grid-template-columns: 1fr; } .phone { width: min(360px, 100%); height: min(800px, 80vh); position: static; order: -1; } }
</style>
</head>
<body>
<main>
<h1>Preview your user's app on a cloud phone</h1>
<p class="lede">A cloud Android phone per end user, live in this page. The API key never leaves the server.</p>

<form id="preview">
<label for="user">End user</label>
<input id="user" name="user" value="user_42" autocomplete="off" required pattern="[\w.@:+\-]{1,128}" title="Letters, digits and . _ - @ : +, up to 128" aria-describedby="user-hint">
<div class="hint" id="user-hint">Your id for the person this preview is for. Their phone is reused, and their minutes add up under it. Park it when they're done.</div>

<label for="source">App</label>
<input id="source" name="source" placeholder="https://…/app.apk or exp://…" autocomplete="off" required aria-describedby="source-hint">
<div class="hint" id="source-hint">An APK download URL, or the link <code>npx expo start --tunnel</code> prints. Try
<button type="button" data-source="https://f-droid.org/repo/org.billthefarmer.editor_198.apk">an F-Droid APK</button>.</div>

<div class="actions">
<button type="submit" class="primary" id="go">Preview</button>
<button type="button" id="park">Park phone</button>
</div>
<div id="status" role="status" aria-live="polite"></div>
</form>

<h2>Phone state <small id="hooks" class="hint"></small></h2>
<ol id="log" tabindex="0" aria-label="Phone events"><li class="hint">No phone events yet.</li></ol>

<h2>Usage per end user, last 30 days <small class="hint"><button type="button" id="refresh">Refresh</button></small></h2>
<table><thead><tr><th>End user</th><th class="num">Minutes</th><th class="num">Cost</th></tr></thead><tbody id="usage"><tr><td colspan="3" class="hint">Loading…</td></tr></tbody></table>
</main>

<div class="phone" id="phone">Your user's phone shows here.</div>

<script>
const $ = (id) => document.getElementById(id)
const say = (text, error = false) => { $('status').textContent = text; $('status').className = error ? 'error' : '' }
const post = async (path, body) => {
const res = await fetch(path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
// A tunnel or proxy in between answers its own HTML page on a timeout: say what happened, not "Unexpected token".
const data = await res.json().catch(() => ({ error: `${res.status} ${res.statusText || 'from the network'}. Try again.` }))
if (!res.ok) throw new Error([data.error, data.next].filter(Boolean).join(' '))
return data
}
for (const b of document.querySelectorAll('[data-source]')) b.onclick = () => { $('source').value = b.dataset.source; $('source').focus() }

let shown = null // the end user whose phone is on screen: Park acts on it
$('preview').onsubmit = async (e) => {
e.preventDefault()
const endUser = $('user').value.trim()
$('go').disabled = true
say('Getting the phone ready and loading the app… (about 10–30 s)')
$('phone').textContent = 'Starting the phone…' // an ended preview would linger here otherwise
try {
const r = await post('/api/preview', { endUser, source: $('source').value.trim() })
$('phone').innerHTML = ''
$('phone').append(Object.assign(document.createElement('iframe'), { src: r.url, title: `Phone preview for ${endUser}`, allow: 'clipboard-write' }))
$('phone').scrollIntoView({ block: 'nearest' })
shown = endUser
say(`${r.loaded} Phone ${r.phone}, ${r.display_hz ?? 15} Hz. Link valid until ${new Date(r.expires_at).toLocaleTimeString()}.${r.notice ? ` ${r.notice}` : ''}`)
} catch (err) { say(err.message, true); $('phone').textContent = 'No preview.'; shown = null } finally { $('go').disabled = false }
}

$('park').onclick = async () => {
const endUser = shown ?? $('user').value.trim()
try { const r = await post('/api/park', { endUser }); say(`Parked ${endUser}'s phone ${r.phone}: apps and data stay, billing stops.`) } catch (err) { say(err.message, true) }
}

// The embed says when it goes live or ends; an ended link needs a new one from the server.
addEventListener('message', (e) => {
if (e.origin !== 'https://mobilebox.dev') return
if (e.data?.type === 'mobilebox:end') say(`The preview ended (${e.data.reason}). Press Preview for a new link.`, e.data.reason !== 'parked')
})

// Phone states arrive as signed webhooks on the server; the page asks for new ones every 2 s.
const line = (text) => { const li = document.createElement('li'); li.textContent = text; $('log').prepend(li) }
let since = 0
async function poll() {
try {
const { webhooks, events } = await (await fetch(`/api/events?since=${since}`)).json()
$('hooks').textContent = webhooks ? '· from signed webhooks' : '· webhooks off (see the server log)'
if (events.length && $('log').firstElementChild?.classList.contains('hint')) $('log').innerHTML = ''
for (const m of events) {
since = m.seq
line(`${new Date(m.at).toLocaleTimeString()} ${m.type.padEnd(13)} ${m.end_user ?? '-'} ${m.phone}${m.reason ? ` (${m.reason})` : ''}`)
if (m.type !== 'phone.ready') loadUsage()
}
} finally { setTimeout(poll, 2000) }
}
poll()

async function loadUsage() {
const note = (text, error) => { $('usage').innerHTML = ''; $('usage').append(Object.assign(document.createElement('tr'), { innerHTML: '<td colspan="3"></td>' })); Object.assign($('usage').querySelector('td'), { textContent: text, className: error ? 'error' : 'hint' }) }
let rows
try {
const res = await fetch('/api/usage')
rows = await res.json()
if (!res.ok) return note(`Couldn't load usage: ${rows.error}`, true)
} catch { return note("Couldn't load usage: the server didn't answer. Refresh to try again.", true) }
$('usage').innerHTML = ''
if (!rows.length) return note('No minutes yet: they show once a phone parks or is deleted.')
for (const u of rows) {
const tr = document.createElement('tr')
tr.append(...[u.end_user ?? '(no label)', Number(u.minutes).toFixed(1), `$${Number(u.cost_usd).toFixed(2)}`].map((v, i) => Object.assign(document.createElement('td'), { textContent: v, className: i ? 'num' : '' })))
$('usage').append(tr)
}
}
$('refresh').onclick = loadUsage
loadUsage()
</script>
</body>
</html>
Loading