Queues and retries9 min read
How to queue and safely retry tasks on a busy phone
What a request does when the phone or the agent is busy, how to withdraw work that is still waiting, how to retry a timed-out request without running the task twice, and which requests retry on their own.
By Josiah Richards
TL;DR
- Lusor runs one session on a phone at a time, and an agent works on one turn at a time. Different agents work independently.
- A turn sent to a busy agent waits for it and answers 202. A follow-up waits behind its own session. A session started directly on a busy phone does not wait. It returns 429 device_busy with the currentSessionId of the session holding the phone.
- Withdraw a waiting turn with POST /v1/agents/{id}/turns/{sessionId}/cancel and a waiting follow-up with DELETE /v1/sessions/{id}/queue/{invocationId}. Both are safe to repeat.
- Send an Idempotency-Key of up to 256 characters with every request that starts work. A retry with the same key returns the original turn instead of starting a second one.
- The SDK retries reads on 408, 429, 502, 503 and 504 and never retries a write. A 429 is either rate_limit_exceeded, which you wait out with Retry-After, or device_busy, which a quick retry does not fix.
A backend that sends work to a phone meets two situations sooner or later. The phone is already busy, or a request times out and nobody knows whether Lusor received it. The API has a defined answer for both.
This post covers what each kind of request does when the phone or the agent is busy, how to withdraw work that is still waiting, how to retry a request without running the task twice, which requests the SDK retries on its own, and what to do with the two kinds of 429.
Why can't a phone run two tasks at once?
Because a phone has one screen. An agent works by reading the screen and then tapping and typing on it. Two tasks on the same phone would tap over each other and read each other's screens, so Lusor gives a phone to one session at a time. A session is the record of one piece of work on a phone. The send a turn docs put the rule in one line, a phone works on one session at a time.
An agent has a rule of its own. It remembers its earlier turns, so its turns run one after another on one conversation. A second turn to the same agent waits for the first. Two different agents work independently, and each waits only for the phone when it needs it.
To see what is holding a phone, read its occupancy. active is the run holding the phone, with its sessionId, and it is null when the phone is idle.
curl https://api.lusor.ai/v1/workspaces/$WORKSPACE/devices/$DEVICE/occupancy \
-H "X-Api-Key: $LUSOR_API_KEY"What happens to a turn sent while the phone is busy?
It depends on how the work reaches the phone. There are three ways in, and only one of them refuses.
| What you get | |
|---|---|
| POST / | 202. The turn waits behind the agent's earlier turns, and its phone work waits for the phone. |
| POST / | 202 with queued: true and an invocationId while its own session is still working. 429 device_busy when the phone is working on a different session. |
| POST / | 429 device_busy with the currentSessionId of the session holding the phone. It does not wait. |
A turn to an agent waits. Send it the usual way. The call returns 202 straight away.
curl https://api.lusor.ai/v1/agents/$AGENT/turns \
-H "X-Api-Key: $LUSOR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-1234" \
-d '{ "prompt": "Check the delivery status of my last order in the Shop app." }'{
"data": {
"id": "4f1d…",
"sessionId": "mobile_use_9c2e…",
"status": "queued",
"queued": true,
"needsDevice": false,
"invocationId": "inv_1c7a…"
}
}Today every new turn comes back with queued: true and needsDevice: false, whether or not the phone is free. The turn is accepted into the agent's queue first. When it needs the phone and another session holds it, its phone work waits until the phone is free. So queued does not tell you whether the phone was busy. To see that, read the phone's occupancy, shown above. To follow the turn itself, GET /v1/sessions/{id}/status says queued until the turn starts and running once it does, as the follow a session docs describe. Keep invocationId as well. It names the waiting turn.
A follow-up waits behind its own session. A follow-up message continues one session with a new prompt. If that session is still working, the follow-up waits and starts when the current work ends, and the response has queued: true and an invocationId. If the phone is working on a different session, the follow-up is refused with 429 device_busy. A 409 device_busy on a follow-up means something else. The phone is being reset or updated, so try again later. To give an agent its next task, send a new turn rather than a follow-up.
A session started directly on a phone does not wait. To give one task to a phone without an agent, you start a session on the phone. When the phone is busy, that call returns 429 at once.
curl https://api.lusor.ai/v1/workspaces/$WORKSPACE/devices/$DEVICE/sessions \
-H "X-Api-Key: $LUSOR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: price-check-1" \
-d '{ "prompt": "Find the price of a 12-pack of sparkling water in the grocery app." }'{
"error": "device_busy",
"message": "Another session is using this phone. Stop it or wait for it to finish, then try again.",
"currentSessionId": "mobile_use_7b31…"
}currentSessionId names the session holding the phone. Wait for it to reach a final status, or stop it if it is yours to stop, then send the request again. Sending it again sooner gets the same 429. To have Lusor do the waiting for you, send the task to an agent as a turn.
How do you cancel a turn that is still waiting?
Which call you use depends on whether the work has started. The stop a session docs list three.
A turn that has not started is withdrawn on the agent, by its sessionId.
curl -X POST https://api.lusor.ai/v1/agents/$AGENT/turns/$SESSION/cancel \
-H "X-Api-Key: $LUSOR_API_KEY"| Meaning | |
|---|---|
| 200, cancelled: true | The turn was withdrawn. It never starts. |
| 200, cancelled: false | The turn had already finished. Nothing changed. |
| 400 | The turn has already started. Stop its session instead. |
| 409 | The cancel is still settling. Send it again in a moment. |
A follow-up that is waiting is withdrawn by the invocationId from its 202. Sending it again returns alreadyCancelled: true, and an unknown invocationId returns 404.
curl -X DELETE https://api.lusor.ai/v1/sessions/$SESSION/queue/$INVOCATION \
-H "X-Api-Key: $LUSOR_API_KEY"A session that has started, or that is waiting for your answer, is stopped. It ends with status cancelled, and a repeat returns status: "noop".
curl -X POST https://api.lusor.ai/v1/sessions/$SESSION/stop \
-H "X-Api-Key: $LUSOR_API_KEY"All three are safe to repeat, so a cancel that timed out can simply be sent again. A turn that started between your status read and your cancel answers 400. That is the cue to call stop.
How does an Idempotency-Key keep a retry from running the task twice?
Picture the failure first. Your server sends a turn, the connection drops before the response arrives, and the turn may or may not exist. Without a key, the retry creates a second turn, and the agent does the task twice. The send a turn docs say it directly. Without the header, every request creates a new turn.
Send an Idempotency-Key header with a value unique to the task, up to 256 characters. When a request arrives with a key Lusor has already seen in the workspace, Lusor returns the original turn instead of starting another. Turns also take the key in the body as idempotencyKey, and the header wins when you send both. Sessions started on a phone and follow-ups take the same header. With turns, they are the requests that start work.
- Make the key from your own record.
order-1234ororder-1234-followup-1, as in the docs, ties the key to the task. A new random value on each attempt protects nothing, because every attempt then looks new. - Lusor matches the key, not the body. A retry that reuses the key with a changed prompt gets the original turn back. A key reused on a different agent returns
400 bad_request, so give each task its own key. - Retry with the key when the outcome is unknown. A timeout, a dropped connection, and a
5xxall qualify.502witherror: "dispatch_outcome_unknown"says so directly. It means Lusor could not confirm whether it accepted the request, and the errors docs say to retry it with the same key.
With the SDK, a retry loop around a turn looks like this.
import { LusorClient, LusorError, LusorTimeoutError } from "@lusor/sdk";
const lusor = new LusorClient({ apiKey: process.env.LUSOR_API_KEY! });
// One key per task, made from your own record, reused on every attempt.
const key = `order-${order.id}-delivery-check`;
async function sendTurn(attempt = 1) {
try {
return await lusor.agents.turns.create({
id: agentId,
prompt: "Check the delivery status of my last order in the Shop app.",
"Idempotency-Key": key,
});
} catch (err) {
const unknownOutcome =
err instanceof LusorTimeoutError ||
(err instanceof LusorError && (err.statusCode === undefined || err.statusCode >= 500));
if (!unknownOutcome || attempt >= 4) throw err;
await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt));
return sendTurn(attempt + 1); // same key, so Lusor returns the first turn if it exists
}
}
const { data: turn } = await sendTurn();The loop does not retry a 4xx. A 400 or a 402 credits_exhausted gives the same answer every time, so report it instead. A 429 has its own section below.
Which requests does the SDK retry on its own, and which never?
The published @lusor/sdk retries reads and never retries writes. It retries a GET on 408, 429, 502, 503 and 504, twice by default. maxRetries changes that on the client or per request. timeoutInSeconds sets each request's timeout, 60 seconds by default, and a timeout throws LusorTimeoutError.
Writes are left to you because most of them are not idempotent. A retried tap taps twice, and a retried chain runs again the steps that already ran.
| The SDK | Your code | |
|---|---|---|
| GET reads | Retried on 408, 429, 502, 503 and 504, twice by default. | Always safe to retry. |
| Turns, sessions, follow-ups | Never retried. | Retry with the same Idempotency-Key. |
| Taps, typing, chains | Never retried. | Read the screen before you act again. A repeated tap taps twice. |
| Cancel and stop | Never retried. | Safe to repeat. A repeat reports that nothing was left to do. |
Direct phone actions are where a blind retry costs the most. If a tap timed out, take a screenshot or read the screen before deciding whether to tap again. The post on how to drive a phone from your own code covers captures, which return the screen with each action.
What does a 429 mean, and what should your code do?
Lusor returns 429 for two different reasons, and they need opposite handling. Branch on error, as the rate limits docs advise.
rate_limit_exceededmeans your account sent too many requests in a short time. The limit is counted per account, across all its workspaces and API keys, and covers every authenticated/v1request exceptGET /v1/health. Wait the number of seconds inRetry-After, then retry.X-RateLimit-LimitandX-RateLimit-Remainingon every limited response show how close you are.device_busymeans the phone is working on another session, named incurrentSessionId. A quick retry gets the same answer. Wait for that session to finish, or stop it.
async function send(url, init) {
for (;;) {
const res = await fetch(url, init);
if (res.status !== 429) return res;
const body = await res.clone().json();
if (body.error === "rate_limit_exceeded") {
const wait = Number(res.headers.get("Retry-After") ?? "1");
await new Promise((r) => setTimeout(r, wait * 1000));
continue;
}
// device_busy: the phone is running body.currentSessionId.
// Retrying sooner does not help. Wait for that session, or stop it.
return res;
}
}The SDK's automatic retry on 429 applies to reads only, so it never retries a device_busy on a write for you.
Most rate limits come from polling. Poll GET /v1/sessions/{id}/status every few seconds rather than in a tight loop, pass since when you read events, and send several phone actions as one chain. Once a session is done, check what the agent did from its events, and if it stopped on awaiting_human, see when a phone agent stops to ask. To get the result back in a shape your code can store, ask for JSON from the phone screen. To let people watch a waiting or running turn, put the phone's live screen in your app, and to hand the same phones to an AI app, use Lusor's MCP server for real phones. Every status code here is in the errors docs, and the occupancy reference has the full phone read.
Frequently asked questions
What happens when you send a Lusor agent a turn while it is still working?
The call returns 202 and the turn waits. An agent works on one turn at a time, so the new turn starts when the earlier ones end, and when it needs the phone it waits for the phone too. The session's status is queued until it starts. Read it with GET /v1/sessions/{id}/status.
Why does a session started on a busy phone return 429 instead of waiting?
A session started with POST /v1/workspaces/{workspaceId}/devices/{deviceId}/sessions does not wait. When another session holds the phone, it returns 429 with error device_busy and the currentSessionId of that session. Wait for that session to finish or stop it, then send the request again. Retrying sooner does not help.
How do you cancel a Lusor turn that has not started yet?
Call POST /v1/agents/{id}/turns/{sessionId}/cancel. It answers 200 with cancelled: true when the turn was withdrawn, 200 with cancelled: false when it had already finished, 400 when it has started, and 409 while the cancel is settling. A waiting follow-up is withdrawn with DELETE /v1/sessions/{id}/queue/{invocationId}, and a session that has started is stopped with POST /v1/sessions/{id}/stop.
How does an Idempotency-Key stop a retry from running a task twice?
Send the same Idempotency-Key, up to 256 characters, on the first request and on every retry. Lusor returns the original turn for a key it has already seen in the workspace instead of starting a second one. Without the header, every request creates a new turn. Make the key from your own record, such as an order id, so every attempt sends the same value.
Which requests does the Lusor SDK retry by itself?
Reads. The published @lusor/sdk retries GET requests on 408, 429, 502, 503 and 504, twice by default, and maxRetries changes that on the client or per request. It never retries a write, because a retried tap taps twice and a retried chain runs its steps again. To retry a turn, send an Idempotency-Key and retry it yourself with the same key.
What should your code do with a 429 from Lusor?
Read the error field. rate_limit_exceeded means your account sent too many requests. Wait the number of seconds in the Retry-After header, then retry. device_busy means the phone is working on another session, named in currentSessionId. Wait for that session to finish or stop it, because retrying sooner does not help.