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
29 changes: 14 additions & 15 deletions examples/app-builder-preview/README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
# 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`.
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 120 lines) and `index.html`. A preview is one call, `POST /v1/previews`.

![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.
2. **One call per preview.** `POST /v1/previews` with `end_user` (your id for the person) and the build gets that user's phone (theirs again, started if parked, or a new one with a 30 Hz screen), installs the APK, or opens an Expo link (`exp://`, `exps://`, `https://expo.dev/…`) in the Expo Go that matches the project's SDK, and answers once the app is on screen.
3. **Embeds the live phone** with the `embed_url` from that answer, locked to your page's origin. Your user can tap, swipe and type on it.
4. **Says what went wrong.** A build that doesn't install or open comes back as `install_failed` or `open_failed` with the reason, and the page shows 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.

Expand Down Expand Up @@ -45,9 +45,7 @@ A workspace has one webhook URL, so if yours already points somewhere else the s

| 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}` |
| The end user's phone, the app on screen, the link | `preview()` | `POST /v1/previews {apk_url or expo_url, end_user, 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` |
Expand All @@ -60,22 +58,23 @@ A workspace has one webhook URL, so if yours already points somewhere else the s
- **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.
- **Plan for more users.** A workspace runs 3 phones at once to start. `POST /v1/account/limits {"running": n}` asks for more; `GET /v1/account` shows your limits.
- **Send an idempotency key** (`Idempotency-Key` header) with each preview if your server retries: a retry gets the same preview, never a second phone.

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:
**2026-11-25**, Node 24 on Linux, against production through a Cloudflare quick tunnel, Chrome, one `POST /v1/previews` per Preview:

| 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 |
| Preview, `user_43`, F-Droid Editor 1.98 APK, new phone | installed and on screen when the call returned, live in the page | 27 s |
| Preview, `user_8`, Expo SDK 58 project (`exp://…exp.direct`), new phone | Expo Go 58.0.6 installed itself, the app's first screen live in the page | 41 s |
| Park both | `phone.parked` (manual) arrived signed for each; usage: user_43 1.5 min, $0.02; user_8 1 min, $0.01 | 2 s |
| Preview again, `user_43` | the parked phone started (`reused: true`, `phone.ready`), app on screen | 15 s |
| Preview, `user_43`, an APK link that answers 404 | `install_failed: The app didn't install: f-droid.org answered 404.`, the same phone kept | 0.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.
Times include the tunnel. Expo Go shows its developer menu once on a new phone; your user closes it in the embed.
4 changes: 2 additions & 2 deletions examples/app-builder-preview/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,15 @@ <h2>Usage per end user, last 30 days <small class="hint"><button type="button" i
e.preventDefault()
const endUser = $('user').value.trim()
$('go').disabled = true
say('Getting the phone ready and loading the app… (about 10–30 s)')
say('Getting the phone ready and putting the app on screen…')
$('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}` : ''}`)
say(`${r.loaded} Phone ${r.phone}${r.reused ? `, ${endUser}'s own again` : ', new'}. 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 }
}

Expand Down
39 changes: 9 additions & 30 deletions examples/app-builder-preview/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,39 +18,20 @@ const HOOK_URL = `${PUBLIC_URL}/webhooks/mobilebox`

// --- Mobilebox REST, server-side only -----------------------------------------------------------------------------
async function mb(method, path, body) {
const res = await fetch(API + path, {
const res = await fetch(API + path, { signal: AbortSignal.timeout(300_000), // a new phone, a big APK: a preview can take a minute or two
method, headers: { authorization: `Bearer ${KEY}`, ...(body && { 'content-type': 'application/json' }) },
...(body && { body: JSON.stringify(body) }),
})
const data = res.status === 204 ? null : await res.json()
if (!res.ok) throw Object.assign(new Error(data?.error?.message ?? `${res.status}`), { status: res.status, mb: data?.error })
return data
}
// Waits cap at 55 s per call; a phone still booting is normal, so ask again.
async function ready(phone) {
while (phone.status === 'creating' || phone.status === 'starting') phone = await mb('GET', `/phones/${phone.id}?wait=ready`)
if (phone.status !== 'ready') throw new Error(`phone ${phone.id} is ${phone.status}`)
return phone
}

// One phone per end user: reuse it (start it if parked), or make it with the end_user label and a 30 Hz display.
async function phoneFor(endUser) {
const [mine] = (await mb('GET', `/phones?end_user=${encodeURIComponent(endUser)}`)).data
if (mine?.status === 'parked') return ready(await mb('POST', `/phones/${mine.id}/start?wait=ready`))
if (mine) return ready(mine)
return ready(await mb('POST', '/phones?wait=ready', { end_user: endUser, display_hz: 30, name: `preview-${endUser}`.slice(0, 64) }))
}

// The builder's app on the phone: an Expo link opens in Expo Go (Mobilebox installs the matching one), an APK URL installs.
async function load(phone, source) {
if (/^exps?:\/\/|^https:\/\/(\w+\.)?expo\.dev\//.test(source)) {
const { results } = await mb('POST', `/phones/${phone.id}/actions`, { actions: [{ type: 'open_url', url: source }] })
if (!results[0].ok) throw new Error(results[0].error.message)
return results[0].note ?? 'Opened the Expo link.'
}
const app = await mb('POST', `/phones/${phone.id}/apps`, { url: source, replace: true })
await mb('POST', `/phones/${phone.id}/actions`, { actions: [{ type: 'open_app', package: app.package }] })
return `Installed ${app.package} ${app.version_name ?? ''}`.trim() + '.'
// One call per preview: the end user's phone (theirs again, started if parked, or a new one at 30 Hz), the APK installed
// or the Expo link opened in the matching Expo Go, on screen, and an embed link locked to your page. A build that doesn't
// install or open fails with install_failed or open_failed and the phone id; the phone stays for the next try.
function preview(endUser, source, origin) {
const expo = /^exps?:\/\/|^https:\/\/(\w+\.)?expo\.dev\//.test(source)
return mb('POST', '/previews', { [expo ? 'expo_url' : 'apk_url']: source, end_user: endUser, origin, interactive: true, ttl: 900 })
}

// --- Webhooks: verify, keep the latest 200 events for the page to poll -----------------------------------------------
Expand Down Expand Up @@ -109,10 +90,8 @@ const server = createServer(async (req, res) => {
if (!END_USER.test(endUser ?? '') || !/^(https?|exps?):\/\/\S+$/.test(source ?? '')) return json(res, 400, { error: 'An end user id (letters, digits, . _ - @ : +) and an APK or Expo URL.' })
// The page that will hold the iframe: this server's own origin (locked by Mobilebox with frame-ancestors).
const origin = req.headers.origin === `http://localhost:${PORT}` ? req.headers.origin : ORIGIN
const phone = await phoneFor(endUser)
const loaded = await load(phone, source)
const embed = await mb('POST', `/phones/${phone.id}/embed`, { origin, interactive: true, ttl: 900 })
return json(res, 200, { phone: phone.id, display_hz: phone.display_hz, notice: phone.notice ?? null, loaded, url: embed.url, expires_at: embed.expires_at })
const p = await preview(endUser, source, origin)
return json(res, 200, { phone: p.phone_id, reused: p.reused, notice: p.notice ?? null, loaded: `${p.package} is on screen.`, url: p.embed_url, expires_at: p.expires_at })
}
if (req.method === 'POST' && url.pathname === '/api/park') {
const { endUser } = JSON.parse(await read(req))
Expand Down