Skip to content

Live view10 min read

How to stream a phone's live screen into your web app over WebRTC

Your users can watch the phone an agent is using without leaving your product. Here is which phones stream to an API key, how the signaling works step by step, and how to handle reconnects, several viewers and expiring credentials.

By Josiah Richards

TL;DR

  • Lusor's live view streams a phone's screen to a browser or app you build over WebRTC. The API carries only the signaling, and the video travels over the WebRTC connection.
  • With an API key it works on your own iPhone and your own Android phone. On a Lusor Phone every /stream/* route returns 403 live_view_not_available_for_api_keys, so watch it with screenshots or captures instead.
  • A live view belongs to a session. Open GET /v1/sessions/{id}/stream/events first, get the ICE servers, POST start, answer the phone's webrtc_offer through POST signal, and exchange ICE candidates the same way.
  • Keep the API key on your server. The server relays the event stream and the POSTs, and the browser runs the RTCPeerConnection.
  • Several viewers each pass their own viewer_id. The TURN credential has an expiresAt that the API cannot renew yet, so after it passes, start a new live view.

When your product runs a Lusor agent on someone's phone, the person often wants to see it work. Lusor's live view streams the phone's screen to a browser or app you build, over WebRTC. The API carries the signaling between your app and the phone, and the video travels over the WebRTC connection.

This post goes through which phones allow it with an API key, the signaling routes in order, a small server relay with the browser code that plays the stream, and what to do about frozen pictures, reconnects, several viewers and expiring credentials.

Why show the phone's screen inside your own app?

Because an agent run on a phone takes a while, and a status field says little about what is on the screen. With a live view, your user sees the app the agent opened and the screen it is on, in your product, next to your own controls.

  • Watching a run. The user who started the task sees the agent work on their own phone instead of waiting for a result.
  • Answering a question. When the agent stops to ask which account to use, the screen behind the question helps the person answer. Reading and answering the question is covered in when a phone agent stops to ask.
  • A support or operations desk. A team member watches the same phone as the user, as a second viewer.

A live view shows the phone as it is, so the viewer sees whatever is on the screen. What that means for a phone you own is the subject of whether it is safe to let an agent use your phone. To act on the phone from your code instead of watching it, drive the phone from your own code with the direct control routes.

Which phones can stream to an API key, and why not a Lusor Phone?

Your own iPhone and your own Android phone. A Lusor Phone cannot.

Live view with an API key
With an API key
Your own iPhoneAvailable.
Your own Android phoneAvailable. Pauses while the phone is locked and resumes when it is unlocked.
Lusor PhoneNot available. Every /stream/* route returns 403 live_view_not_available_for_api_keys.

The docs give the reason for the Lusor Phone row. A live view of a Lusor Phone can send taps and text over its own connection, outside the metering that direct control uses, so API keys cannot open one. The refusal applies to every route, the event stream included, so a viewer gets the 403 on its first call rather than partway through.

To watch a Lusor Phone from your code, take a screenshot with GET …/screenshot, or get the screen back with each action as a capture. People signed in to the Lusor app can still watch any phone there.

An Android phone pauses the live view while it is locked and resumes it when it is unlocked, so a black or still picture on Android can mean a locked screen.

How does the signaling flow work, step by step?

A live view belongs to a session on the phone, and every route is under /v1/sessions/{id}/stream/. When you send a task with POST /v1/agents/{id}/turns, the response's data.sessionId is that id, as the send a turn docs show. A session without a phone, such as a turn still waiting for one, returns 409 no_device.

The live view routes
Purpose
GET …/eventsThe phone's signaling messages, as Server-Sent Events. Open it first.
GET …/ice-serversThe STUN and TURN servers for your RTCPeerConnection.
POST …/startAsk the phone to start streaming. Optional width, height, fps, viewer_id.
POST …/signalSend your WebRTC answer or ICE candidates to the phone.
POST …/request_frameAsk the phone for a fresh keyframe.
POST …/keepaliveSend an extra keep-alive. Optional.
POST …/connectReconnect without starting over. Same body as start.
POST …/stopStop the live view.

1. Open the event stream. The phone sends its side of the handshake as Server-Sent Events. Open the stream before anything else, so the phone's offer cannot arrive before you listen.

curl -N https://api.lusor.ai/v1/sessions/$SESSION/stream/events \
  -H "X-Api-Key: $LUSOR_API_KEY"
event: signal
data: {"action":"stream_ready","session_id":"mobile_use_9c2e…","viewer_id":"mobile_use_9c2e…"}

event: signal
data: {"action":"webrtc_offer","session_id":"mobile_use_9c2e…","viewer_id":"mobile_use_9c2e…","sdp":{"type":"offer","sdp":"v=0…"}}

event: signal
data: {"action":"webrtc_ice","session_id":"mobile_use_9c2e…","viewer_id":"mobile_use_9c2e…","candidate":{"candidate":"candidate:…","sdpMid":"0","sdpMLineIndex":0}}

:keep-alive

Each event is named signal, and its data is one JSON message from the phone. Its action is webrtc_offer, webrtc_ice, stream_ready, stream_error, stream_stopped or ice_update_applied. A keep-alive comment arrives every 15 seconds, and the stream stays open until you disconnect.

2. Get the ICE servers.

curl https://api.lusor.ai/v1/sessions/$SESSION/stream/ice-servers \
  -H "X-Api-Key: $LUSOR_API_KEY"
{
  "data": {
    "iceServers": [
      { "urls": ["turn:…", "turns:…"], "username": "…", "credential": "…" }
    ],
    "generation": 1,
    "issuedAt": 1795510800,
    "expiresAt": 1795514400,
    "refreshAfter": 1795513800
  }
}

Pass data.iceServers to your RTCPeerConnection unchanged. The phone gets the same TURN servers when you start, so leave iceServers out of the start request. When data.iceServers is null, TURN is not available at that moment. The docs suggest falling back to STUN, but the phone software for your own iPhone and Android currently connects only through TURN. Without it, the start ends with a stream_error whose error is no_relay, so try again later.

3. Start the stream. width, height, fps and viewer_id are optional. The call returns deviceId, status and message, and the phone answers on the event stream with a webrtc_offer.

curl https://api.lusor.ai/v1/sessions/$SESSION/stream/start \
  -H "X-Api-Key: $LUSOR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'

4. Answer the offer. Set the offer's sdp as the remote description, create an answer, and send it in message. Send each of your ICE candidates the same way with "type": "webrtc_ice", and add the phone's webrtc_ice events to your connection as they arrive. signal passes the rest of message to the phone unchanged, and any other message.type returns 400.

curl https://api.lusor.ai/v1/sessions/$SESSION/stream/signal \
  -H "X-Api-Key: $LUSOR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "message": { "type": "webrtc_answer", "sdp": { "type": "answer", "sdp": "v=0…" } } }'

5. Stop when done. POST …/stop ends the live view. It takes an optional reason and viewer_id.

Where does the API key live when the viewer is a browser?

On your server. The authentication docs say to call the API from your server, never from a browser or a mobile app you ship, because anyone holding the key can act on the workspace's phones. The browser still runs the RTCPeerConnection, so your server relays the signaling. It forwards the event stream and the POST routes, and checks that the signed-in user may watch the session.

// Your server: the only place that holds the API key.
const LUSOR = "https://api.lusor.ai/v1/sessions";
const KEY = { "X-Api-Key": process.env.LUSOR_API_KEY };
const COMMANDS = new Set(["start", "signal", "request_frame", "connect", "stop"]);

// Check first that the signed-in user may watch this session.

// GET /live/:session/events and GET /live/:session/ice-servers
export async function read(request, sessionId, route) {
  const upstream = await fetch(`${LUSOR}/${sessionId}/stream/${route}`, {
    headers: KEY,
    signal: request.signal, // closing the page closes the upstream stream
  });
  return new Response(upstream.body, {
    status: upstream.status,
    headers: { "Content-Type": upstream.headers.get("Content-Type") ?? "text/plain" },
  });
}

// POST /live/:session/:route
export async function command(request, sessionId, route) {
  if (!COMMANDS.has(route)) return new Response(null, { status: 404 });
  const upstream = await fetch(`${LUSOR}/${sessionId}/stream/${route}`, {
    method: "POST",
    headers: { ...KEY, "Content-Type": "application/json" },
    body: await request.text(),
  });
  return new Response(upstream.body, {
    status: upstream.status,
    headers: { "Content-Type": "application/json" },
  });
}

The browser side builds the peer connection, listens for the phone's messages and plays the video. It handles one message at a time, in order, because an ICE candidate can arrive while the offer is still being applied.

// Your page: <video autoplay muted playsinline></video>
const base = `/live/${sessionId}`;
const post = (route, body = {}) =>
  fetch(`${base}/${route}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });

const { data } = await (await fetch(`${base}/ice-servers`)).json();
const pc = new RTCPeerConnection({ iceServers: data.iceServers ?? [] });
pc.ontrack = (event) => {
  document.querySelector("video").srcObject = new MediaStream([event.track]);
};
pc.onicecandidate = ({ candidate }) => {
  if (candidate) post("signal", { message: { type: "webrtc_ice", candidate: candidate.toJSON() } });
};

async function handle(msg) {
  if (msg.action === "webrtc_offer") {
    await pc.setRemoteDescription(msg.sdp);
    const answer = await pc.createAnswer();
    await pc.setLocalDescription(answer);
    await post("signal", { message: { type: "webrtc_answer", sdp: { type: "answer", sdp: answer.sdp } } });
  } else if (msg.action === "webrtc_ice" && msg.candidate?.candidate) {
    await pc.addIceCandidate(msg.candidate);
  } else if (msg.action === "stream_error" || msg.action === "stream_stopped") {
    console.warn(msg.action, msg.error ?? msg.message ?? msg.reason);
  }
}

// One message at a time, in the order the phone sent them.
let queue = Promise.resolve();
const events = new EventSource(`${base}/events`);
events.addEventListener("signal", (event) => {
  const msg = JSON.parse(event.data);
  // Every viewer of a session shares this stream: skip messages for other viewers.
  if (msg.viewer_id && msg.viewer_id !== sessionId) return;
  queue = queue.then(() => handle(msg));
});
// Start only once the event stream is open, so the offer cannot be missed.
events.addEventListener("open", () => post("start"), { once: true });

Your server is also a good place to stop a live view. When the browser's connection to your relay closes, the viewer is gone, and the server can call POST …/stop for it.

How do you recover a frozen picture or reconnect without starting over?

A browser asks the sender for a fresh keyframe on its own when it loses video packets, and the phone answers those requests, so a lost keyframe is replaced without any call from your code. The API also has POST …/request_frame, which the docs describe as the way to ask the phone for a keyframe. Today, the phone software for your own iPhone and Android takes that request without changing the WebRTC video, so calling it is harmless but not a fix.

When the picture stays frozen, or the peer connection reaches failed, re-arm it with POST …/connect. It takes the same body as start and reconnects without starting over. The phone reuses its running screen capture when it can. Close the old RTCPeerConnection, create a new one, call connect, and answer the new webrtc_offer that arrives on the same event stream.

POST …/keepalive is optional. Lusor already sends a keep-alive every 25 seconds while the stream is active, so a viewer does not need to call it.

What happens with several viewers and expiring credentials?

Each viewer needs its own viewer_id. Without one, a viewer is the default viewer, whose id is the session id, so a second viewer that leaves it out takes over the first one's stream. Pass the same viewer_id to start, connect, keepalive, request_frame and stop. signal takes no viewer_id field of its own. Lusor reads it from inside the message instead, so put it in every answer and ICE candidate as well.

# A second viewer starts with its own id ...
curl https://api.lusor.ai/v1/sessions/$SESSION/stream/start \
  -H "X-Api-Key: $LUSOR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "viewer_id": "support-desk" }'

# ... names it inside the message it signals ...
curl https://api.lusor.ai/v1/sessions/$SESSION/stream/signal \
  -H "X-Api-Key: $LUSOR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "message": { "type": "webrtc_answer", "viewer_id": "support-desk", "sdp": { "type": "answer", "sdp": "v=0…" } } }'

# ... and stops only itself.
curl https://api.lusor.ai/v1/sessions/$SESSION/stream/stop \
  -H "X-Api-Key: $LUSOR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "viewer_id": "support-desk" }'

Every viewer of a session reads the same event stream, and each message from the phone names the viewer_id it is for. A viewer keeps the messages with its own id and ignores the rest. A phone streams to at most four viewers at once, and a start beyond that gets a stream_error whose error is viewer_limit.

The TURN credential from ice-servers has an expiresAt time in Unix seconds, one hour after it was issued. Renewing it during a live view is not available through the API yet, so after expiresAt, start a new live view. Two more details matter when you plan for it.

  • Every viewer of a session gets the same credential. A viewer that joins late has less time left, so read expiresAt instead of counting an hour from your own start.
  • ice-servers returns the same credential until expiresAt has passed, and a new one, with a higher generation, after it. Starting over early gets the old credential back, so start over after that time.

A live view is for watching while a run is going. To check what the agent did once it says it is done, read the run as described in your agent says done, here is how to check, or ask it for JSON from the phone screen in a shape you define. If your users work in an AI app rather than your product, Lusor's MCP server for real phones gives the app the phone. The live view docs, the event stream reference and the ice-servers reference have every route and schema.

Frequently asked questions

Can an API key stream the screen of a Lusor Phone?

No. On a Lusor Phone every /stream/* route returns 403 live_view_not_available_for_api_keys. The docs give the reason: a live view of a Lusor Phone can send taps and text over its own connection, outside the metering that direct control uses. To watch a Lusor Phone from your code, use GET …/screenshot or a capture. People signed in to the Lusor app can still watch any phone there.

In what order do you call the Lusor live view routes?

Open GET /v1/sessions/{id}/stream/events first, then call GET …/ice-servers, then POST …/start. The phone sends a webrtc_offer on the event stream. Answer it with POST …/signal and a webrtc_answer message, send your ICE candidates the same way as webrtc_ice, and call POST …/stop when you are done.

Can the browser call the Lusor live view API directly?

Not with your API key. Lusor's docs say to call the API from your server, never from a browser. Your server relays the event stream and the POST routes for the sessions a user may watch, and the browser runs the RTCPeerConnection and plays the video.

What happens when ice-servers returns null?

TURN is not available at that moment. The docs suggest falling back to STUN, but the phone software for your own iPhone and Android currently connects only through TURN, so the start ends with a stream_error whose error is no_relay. Call ice-servers again later and start a new live view.

How do several people watch the same phone?

Each viewer picks its own viewer_id and passes it to start, connect, keepalive, request_frame and stop, and puts it inside the message it sends to signal. Every viewer of a session reads the same event stream, and each message names the viewer_id it is for. A phone streams to at most four viewers at once.

What do you do when the TURN credential expires?

Start a new live view. ice-servers returns expiresAt in Unix seconds, one hour after the credential was issued, and renewing it during a live view is not available through the API yet. Every viewer of a session shares the credential, and ice-servers returns the same one until expiresAt has passed, so start over after that time.