Driving Lustro from agents and automation¶
Lustro is a browser-based Android debug toolkit, but every tab is also a JSON API under
/api/v1/, so AI agents, scripts, and the lustro CLI can drive it directly instead of scraping
HTML. This document is the operational guide for non-browser clients. The HTTP wire protocol,
not the Kotlin API, is the stable contract. It is versioned, and SemVer applies to it, under
wire-protocol/v1/.
This document is about using a running Lustro. To add Lustro to an app, follow Install and Quick start.
Status: pre-1.0. Until
1.0.0, the protocol may still change between minor versions. Always read_metaand the per-tab_schemaat runtime rather than hard-coding shapes.
The agent's view¶
- Discoverable tabs.
GET /api/v1/_metalists every tab that ships a schema. A tab is agent-discoverable only if it exposes one (a staticassets/lustro/<id>.openapi.json, a dynamicschema(), or the document of its declared routes); schema-less tabs are usable in the browser but absent from_meta. - Self-describing. Fetch
GET /api/v1/<id>/_schemafor a tab's OpenAPI document andGET /api/v1/_schemafor the shared envelope schemas. Drive operations from those, not from hard-coded paths. - Built-in tab.
lustrohas one built-in tab:network(capture, inspect, mock, throttle, Send Request, and the messages of WebSocket connections). Its contract islustro/openapi/network.openapi.json, the document that the tab's route declarations make. The app registers it, as it registers a plugin tab (addTab(NetworkDebugTab.create(...))); without it, thenetwork/routes are an enveloped404 Unknown tab: network. - Plugin tabs. An app can also register plugin tabs, such as
logs, the app's own logcat (see Logs tab operations), andprefs, the app's SharedPreferences and Preferences DataStores (see Preferences tab operations),sqlite, the app's SQLite and Room databases (see SQLite tab operations),work, the app's WorkManager work and the events of each run (see WorkManager tab operations), andscreen, the app's windows and UI tree (see Screen tab operations)._metalists the ones the app registered, and each plugin's_schemahas a version of its own ininfo.version.
Use the lustro CLI¶
Agents should drive Lustro with the lustro CLI. It is a Python client in lustro-cli/, and
each release publishes it to PyPI as lustro-cli:
uvx lustro-cli <command> runs it without an install. The PyPI package lustro is a different
project with a lustro command of its own: do not install it, and do not run uvx lustro.
The CLI reads the token and the endpoint from the LustroToken log line, and it prints much less
than the routes return: GET transactions returns every captured transaction with all its fields,
up to 1,000 of them, and lustro net list prints 50 short rows. The wire protocol in the sections
below stays the stable contract, and the curl examples use it directly.
lustro ready --package <package> # wait until the server answers; prints the endpoint, or the cause and its exit code
lustro open --print-only # forward the port; exits 1 when adb forward fails
lustro net list # the newest 50 transactions, newest first
lustro net get <id> --no-body # one transaction, without its bodies
lustro net wait --url /v1/orders -- adb shell input tap 540 1200
lustro net export --har out.har # every transaction as a HAR file
lustro net ws list # the WebSocket connections, newest first
lustro net ws events <id> --last 20 # the last 20 messages and lifecycle events of one
lustro api GET network/transactions --param search=orders # any route; prints the response
lustro meta # the library and protocol versions, and the registered tabs
These commands change the capture and the mock rules of the Network tab:
lustro net clear # remove the transactions and the WebSocket connections
lustro net pause # pause the capture, or resume it (a toggle)
lustro net overwrite # turn overwrite mode on or off (a toggle)
lustro net throttle 2000 # hold each OkHttp request for 2000 ms (at most 600000); 0 turns it off
lustro mock list # the mock rules, in the order they are tried
lustro mock add --id orders-500 --url-pattern /v1/orders --method GET --status 500 \
--header 'Content-Type: application/json' --body '{"error":"boom"}'
lustro mock add --id feed-offline --url-pattern /v1/feed --failure unknownHost # fail it as an offline network does
lustro mock toggle orders-500 # turn one rule off or on
lustro mock delete orders-500 # remove one rule
lustro mock sync rules.json # replace every rule with the rules in the file
mock add with an --id that a rule has replaces that rule, and without --id the app gives the
rule a new id. See Network tab operations for what each route does.
mock sync takes a JSON array of rules, or the output of lustro mock list --json, so a test can
save the rules and restore them after: lustro mock list --json > rules.json, change the rules,
then lustro mock sync rules.json.
lustro api METHOD PATH reaches every route, also those of a tab that has no commands of its own,
with the same discovery and the same error output: it prints the response body, and for an error
the error from the envelope on stderr, with exit status 1. When the app rejects a search (a 400
with field: "search"), the exit status is 2, as for a bad flag. A PATH without a leading / is
under /api/v1/. --param KEY=VALUE adds a query parameter, --body JSON or --input FILE (-
for stdin) sends a JSON body. A parameter that the route does not declare gets a warning on stderr,
such as warning: unknown query parameter "uniqueName" (see Unknown query
parameters), from every command. An app older than protocol 1.15
sends no such warning, so lustro api with query parameters to that app prints a note on stderr
that says so: check the names in the tab's OpenAPI document. lustro schema <tabId> prints the tab's OpenAPI document, which
describes its routes.
Each row of net list starts with a short transaction id: the first 8 characters of the id, or more
when two listed ids start with the same 8. net get, net body, and net export --ids take the short id, the full id,
or any start of an id that only one transaction has. When more than one id starts with it, they
print the matches and exit 2; when no id does, they exit 1. JSON output has the full id, which the
wire routes in the curl examples need. The filters --url, --method, --status (a code such as
404, or a class such as 5xx), and --errors combine with each other and with --search, which
the server runs over the URL, the method, the headers, and the bodies, as text or, with --regex,
as a regular expression (see Search). Global flags, such as --json and --port, go
before or after the command.
Global flags. --json prints JSON. --device SERIAL selects the device (see below).
--token TOKEN, --host HOST, and --port N set the token and the endpoint, so the CLI does not
look for them. Without --token, the CLI takes the LUSTRO_TOKEN environment variable. With
--package PKG, it then reads the app's private lustro_debug prefs file with adb shell run-as:
the token, and the host and port of the app's last bind. While the app is in the foreground and its
server listens, these are the values of its current process; before the bind they are those of the
last one.
When they give all three, the CLI runs no logcat, also with --token: a dump of the log takes
seconds on a device with full log buffers, and the prefs read takes about 0.2 s. Only for what
the prefs do not give, as for a build that is not debuggable, where run-as fails, the CLI reads
the LustroToken log line of the current process of that app: it gets its process ID with
adb shell pidof, and keeps the lines of that process in adb logcat -v threadtime. Without
--package, the CLI takes the last LustroToken log line, then the prefs of the app in the
foreground, which finds the token on a device that drops Info log lines. That last log line can be
another app's, such as another build of the same app: pass --package in each command, and
always when the device has more than one app with Lustro. The CLI sends a token that it found
only to a server whose listening socket, in /proc/net/tcp and /proc/net/tcp6 of the device, has
the uid of the app that owns the token: the app of the prefs, or the process that logged the line.
Any app can log a line with the tag, and bind the app's port while the app is in the background.
When another uid listens on the port, the CLI sends no request, names that app, and exits 6. A
token from --token or LUSTRO_TOKEN, and a port from --port, get no such check.
Wait until the app is ready. After a script starts the app, lustro ready --package <package>
--timeout 30 runs discovery and GET /api/v1/_meta again, once a second, until the server
answers, and prints the endpoint that the CLI reaches it at. The prefs or a ready line from an
earlier start of the app name a token and a port that may not answer, so the CLI does not trust
the first endpoint that it finds. When the time is over, it prints the cause and exits with its code (see Exit
codes). With --package, it checks the cause once after the first try that fails
too (while a device starts, once adb reaches it and its package manager answers), and stops at once with exit 4 for an app that is not installed or exit 5 for a build without
the runtime: the installed APK does not change while it waits. For every other cause, such as an
app that is not running yet, it waits. So install the app before ready: an adb install that
runs at the same time can end it at once with exit 4. A 401 for --token or LUSTRO_TOKEN, or another 4xx other than 429, ends the wait at once with exit 1; a 401 for a token that the CLI found does not, because the next try reads it again, and at the
timeout it gets the cause from adb, such as another app in the foreground, or another app with Lustro whose server still
holds the port (see "Two apps with Lustro on one device" below). Pass --package: without it, the CLI checks only the app in the
foreground, which can be the launcher, and only at the timeout. A 404 for _meta does not end the wait: Lustro always has
that route, so the 404 is from another server on the port, such as the debug server of another
app on the port that a stopped app's prefs keep. ready waits, and at the timeout prints the cause
and says that another server answers on the port.
Two apps with Lustro on one device. Both bind port 8080 by default, so they take turns: the
server of the app that starts binds the port when the server of the other app closes, when that
app goes to the background, about 0.7 s after the new app shows its first screen. Until then, the
other app's server answers the requests for the new app, with a 401 for its token. The CLI does
not send it the token: a command exits 6 and names that app, such as port 8080 of the device is
held by com.example.other (uid 10217), not by com.example.app (uid 10213), and lustro ready
--package waits until the app's own server answers. The CLI reads the uid that listens on the
app's port in /proc/net/tcp and /proc/net/tcp6, compares it with the app's uid, and gets the
name from pm list packages -U, or before API 26 from dumpsys package packages. A client that is not the CLI can't tell this 401 from one for a
wrong token: run lustro ready --package <package> before its first request, or compare the two
uids in the same way (see Troubleshooting). Give
each app with Lustro on the device its own serverPort, such as 8080 for the debug build and 8081
for a staging build: then the window does not occur.
The token in a script. lustro ready does not print the token. A script that needs it, for the
console URL or a curl call, runs lustro open --print-only --json: it prints url, token,
host, and port, and opens no browser. It forwards the port as lustro open does; add
--no-forward when the script forwards it itself.
lustro open forwards a local port to the app's port on the device: 8080, also when an earlier
command made a forward on another port, so that the console URL and the state that the browser keeps
for it do not change. When another process or a forward to another device holds 8080, it uses an
existing forward to the app, or else a free local port that adb chooses. --local-port N
forwards port N, and --local-port 0 keeps a forward to the app that is there, or else lets adb
choose a free port. --no-forward makes no forward, for when you forward the port yourself, and
--print-only prints the URL without opening a browser. The other commands find the forward in
adb forward --list, also one that you made yourself, so they need no --port. Without a
forward, they make one on a local port that adb chooses, not on 8080: the forward stays until adb
restarts, and on 8080 it would keep a proxy or a development server that starts later from binding
8080. When adb can't make the forward, they exit with the device's cause, 2 or 3, or else 6; only
open exits 1.
With more than one device connected, pass --device <serial> (or set ANDROID_SERIAL) on every
command. The CLI then connects only through a forward to that device, so agents that each drive
the app on their own emulator at the same time do not reach each other's app. Don't pass --port
for a device: --port N connects to local port N as it is, which can be a forward to another
device. A script that makes its own forward and passes its local port with --port also passes
--device or --package: with either one, a connection that fails gets the cause from adb.
Exit codes¶
Each cause has its own code, so a script can act on it without reading the message. Every command
that finds the app uses them, not only ready:
| Code | Cause | What to do |
|---|---|---|
| 0 | The command did its work. | |
| 1 | The app answered with an error, such as 404 not_found, or the command did not get what it waited for: net wait at its timeout, and open when adb forward fails. |
Read the error on stderr. |
| 2 | The command can't run as given: a bad flag or input, an id that more than one item starts with, a search that the app rejects, or more than one device with none selected. | Change the command, or pass --device. |
| 3 | No device: adb is not installed, or it finds no device, or the device is offline or not authorized. | Connect a device, or start an emulator. |
| 4 | The app of --package is not installed. |
Install a debug build that uses the Lustro artifacts. |
| 5 | The installed build of --package does not contain the Lustro runtime: a build with the -noop artifacts, or one from before the app added Lustro. |
Install a debug build that uses the Lustro artifacts. This replaces the installed build: when the user asked you to look at that build, ask first. |
| 6 | The app can't be reached: it is not running or not in the foreground, it logged no ready line, its port does not answer, or another app holds its port, so the CLI did not send the app's token there. | Start the app, and keep it in the foreground. For another app on the port, run lustro ready --package, which waits for the app's own server, and give each app its own serverPort. |
Without --package, an app in the foreground without the runtime exits 6, not 5, because that app
can be another app than yours. lustro --version prints the wire protocol that the CLI implements
and the revision of the CLI, such as lustro 0.1.0 (protocol 1.17, revision 1). When the app's
protocolVersion is newer, lustro ready and lustro meta print a warning on stderr: update the
CLI, or it lacks what the newer protocol adds.
The revision is a whole number that each change to the CLI on main increases by one, also a fix
that changes neither the version nor the protocol. A wrapper script that needs a fix requires the
revision of that fix or a later one, such as "revision 1 or later", and installs the CLI again
when the revision is lower. lustro --version --json, with the options in either order, prints
{"version":"0.1.0","protocol":"1.17","revision":1}, and lustro mcp reports revision in
its server info. A CLI from before the revision prints no revision, and prints the line of text
also with --json: count it as revision 0.
An app on an older protocol ignores a request field or a query parameter that its protocol does
not have, and answers 200. So a command with one of these options reads protocolVersion from
_meta first, and when the app is older, refuses the command before it sends anything, with exit
status 1 and error: protocol_too_old: --failure needs wire protocol 1.12, and the app uses 1.11,
which ignores it: send --sender (1.7), --regex of net list, net poll, net wait, and
net ws events (1.8), mock add --failure (1.12), and mock sync of a file with a rule that has
failure (1.12). The MCP tools refuse regex of list_requests and failure of
add_mock_rule, and from_ms and to_ms of read_logs when the app's Logs tab, in
tabs[].version of _meta, is older than 1.1. Update Lustro in the app, or leave out the option.
Other commands send no extra request, and work with an older app. mock sync rejects two rules
with the same id itself, with exit status 2: an app before 1.11 keeps the first and loses the
other. Before 1.16, mock toggle and mock delete answer 200 for an id that no rule has, and
net throttle takes any delay, so check the result with mock list or net state.
Keep the output small¶
An agent reads all of the output, so ask for only what you need:
lustro net list --errors --last 20: the 20 newest requests that failed or got a status of 400 or higher.lustro net get <id> --no-body: one transaction with its headers, without its bodies. Without--no-body,net getcuts each body at 2 KiB and ends it with a marker such as[... 18251 more bytes: lustro net body <id> response].--fullprints the bodies whole.lustro net body <id> | head -c 4000: the first 4,000 bytes of the response body.
net list says on stderr how many transactions it left out, and --last N or --all prints more.
With --json, a list prints as JSON Lines, one compact object per transaction, so head and jq
can cut it, and --fields id,statusCode,url keeps only those keys. A single JSON object prints
compact when stdout is not a terminal. lustro net state prints the capture state: pause,
overwrite mode, throttle, and the capture filter.
Wait for a request¶
lustro net wait takes the same filters as net list. It polls until a matching request
finishes, prints it, and exits 0, or exits 1 after --timeout seconds (30 by default). It ignores
the requests that finished before it started, and a mocked request finishes in a few
milliseconds. So give the command that makes the app send the request after --, as above:
net wait runs it after its first poll. When the action is not a shell command, start
lustro net wait in the background before the action.
Search¶
--search TEXT finds the transactions in which the text is found, ignoring case: in the URL, the
final URL, the method, a request or response header (as the line Name: value), or a body. The
text has no syntax: a|b, -1, and /api/v1/ are found as typed. Headers and bodies are
searched as stored, so a redacted value is found as [REDACTED], not as the secret.
--regex makes each word of the text, up to a space, a Java regular expression found ignoring
case. Every word must be found, each in any of those fields, and a word that starts with - must
be found in none:
--search with --regex |
Finds |
|---|---|
'featured\|popular' |
either word |
'lists json' |
both words, each in any field |
'podcasts -analytics', '-analytics' |
the first, but not the second; not the word |
'^content-type:\s.*json' |
a header with a value (a space in a regex is \s) |
'/v\d+/ -status/5' |
a versioned path, without the 5xx status paths |
A regex that doesn't compile makes the command print the reason and exit 2, and so does a
search that takes longer than 5 s. --url is always plain text. net ws events --search and
--regex work the same way over the text of the messages. The Network tab's search fields have a
Regex button that does the same, and a ? button that lists common regular expressions. The header search
and regex arrived in protocol 1.8.
lustro net poll prints transactions as they arrive. When a request that was in flight finishes
or fails, it prints its row again, marked [update]; with --json, the later line for an id
replaces the earlier one.
WebSocket messages¶
lustro net ws list prints one row for each connection: a short id, the start time, the state
(open, closed 1000, failed 403, canceled), the counts of sent and received messages, and
the URL. lustro net ws get <id> prints one connection with the headers of its handshake.
lustro net ws events <id> prints the connection's log, oldest first, the last 50 events by
default:
1 14:22:17.243 -- open 101
2 14:22:17.250 -> text 36B {"type":"auth","token":"[REDACTED]"}
3 14:22:17.391 <- text 16B {"type":"ready"}
4 14:22:18.004 -> binary 4B deadbeef
-> is a message the app sent, and <- one it received. -- is a lifecycle event: open,
close sent (the app called close()), close received (the server's close frame), closed,
cancel, and failure. A sent message means that OkHttp queued it; it does not show that the
server received it. [not sent] marks a message that send() refused. A long text ends with a
marker that names the command for the rest, such as
[... 299961 more bytes: lustro net ws payload 3d2a7f10 5], and lustro net ws payload <id> <seq>
[-o FILE] prints or saves a payload as it is stored. --sent, --received, and --search TEXT
(with --regex, a regular expression) select events on the server, --last N or --all sets
how many, and --follow then prints each new event as it comes. --json prints JSON Lines, and
--fields seq,kind,preview keeps only those keys.
A connection is listed only when the app creates its socket with the factory from
Lustro.webSocketFactory. For any other socket, lustro net list shows the handshake, as a
request with the status 101.
The MCP server, for agents without a shell¶
An agent that can run shell commands, such as Claude Code, Codex, Cursor, or Gemini CLI, should
use the lustro CLI. An agent that can only call MCP tools,
such as Claude Desktop, can use lustro mcp: an MCP server on stdin and stdout. Add it to the
client's MCP config as {"command": "lustro", "args": ["mcp"]}; With a coding
agent has the config of each
client. The client starts the server when a session starts and stops it when the session ends,
so nothing runs between sessions. The tools call the routes below through the CLI's own discovery
and adb forward, so the app needs nothing new.
The client puts the description of each tool into the agent's context in every session, and a CLI command costs context only when the agent runs it. So the server has few tools: about 2,000 tokens for all of them.
| Tool | Changes the app | What it does |
|---|---|---|
list_requests |
no | GET network/transactions: the capture state, then the newest 50 requests as lustro net list prints them. Takes search, regex, url, method, status, errors, and last |
get_request |
no | GET network/transactions/<id>, with each body cut at 2 KB, as lustro net get. The id can be a row's short id |
list_mock_rules |
no | GET network/rules, with each response body cut at 2 KB |
add_mock_rule |
yes | POST network/rules: adds a rule on top of the list, or replaces the rule with the same id. failure fails the request with a connection error, as lustro mock add --failure |
delete_mock_rule |
yes | POST network/rules/delete |
set_throttle |
yes | POST network/throttle |
read_logs |
no | GET logs/text: the newest 100 entries that pass the filters, as logcat's threadtime text, cut to its newest 20 KB (max_bytes). An entry that the app's logger appended can have many lines |
call_api |
when the route writes | any route, as lustro api, with the response cut at 20 KB |
get_schema |
no | GET _meta without a tab, and GET <tab>/_schema with one, as lustro schema |
call_api and get_schema reach every tab without a tool of its own: the Preferences, SQLite,
WorkManager, and Screen tabs, and the app's own tabs. Each tool says whether it changes the app,
in its annotations (readOnlyHint, and destructiveHint for a tool that changes the app) and in
the first words of its description. A tool that fails, for example because the app is not in the
foreground, returns the CLI's error message with isError: true. A warning from the app, such as
warning: unknown query parameter "uniqueName" for a call_api with a parameter that the route
does not declare, is a text block of its own after the output, and so is the note for a call_api
with query parameters to an app older than protocol 1.15. regex of list_requests and failure
of add_mock_rule against an app whose protocol is older than the one that added them (1.8 and
1.12), and from_ms and to_ms of read_logs against a Logs tab older than 1.1, are a tool error,
and the tool changes nothing.
The server takes the global flags: lustro mcp --device SERIAL selects the device for every call,
as ANDROID_SERIAL in the server's environment does. It serves the protocol versions from
2024-11-05 to 2026-07-28: a client that opens with initialize, and a client that sends the
version in the _meta of each request. Only protocol messages go to stdout, and its own messages
go to stderr. When adb is not on the server's PATH, as for a desktop app that starts it with a
short PATH, the server looks for it in $ANDROID_HOME/platform-tools, then in the default place
of the Android SDK.
Auth and token discovery¶
Token auth is always on. Every /api/v1/* route except /api/v1/_auth requires a valid
token; unauthenticated requests get an enveloped 401.
Programmatic clients send the token as a Bearer header:
Discovering the token and endpoint. On every successful bind, Lustro logs exactly one
machine-parseable line at logcat tag LustroToken, level INFO:
It is the first place to look for host, port, and token. Lustro logs it again after each
bind, so the last line is the current one, unless the device dropped the newer lines (see below). -d prints the log and exits instead of waiting for
new lines:
When the log has no ready line. A device can drop Info logs: with adb shell getprop log.tag
set to E, the line never reaches logcat (adb shell setprop log.tag.LustroToken I lets it
through until the device restarts). The token, and the host and port of the app's last bind, are
also in the app's prefs file, which a debuggable app lets you read:
adb shell run-as <package> cat shared_prefs/lustro_debug.xml
# <string name="lustro_token">…</string> <string name="lustro_host">127.0.0.1</string> <int name="lustro_port" value="8080" />
Lustro listens only while its app is in the foreground, so the package is that of the resumed
activity (adb shell "dumpsys activity activities | grep ResumedActivity"). The last line in the
log can also be stale, from an earlier install of the app, when the device dropped the newer one:
a 401 to a token from the log means read the prefs.
A no-op build has no ready line. A build with the -noop artifacts, such as a release-like
build with the package of the debug build, has no server and logs nothing. Its APK has no entry
under assets/lustro/, which a build with the Lustro runtime always has. API 28 emulator images
have no unzip, and the grep of API 30 to 33 does not find the entry names in the binary file,
so list the entries on the computer:
adb pull "$(adb shell pm path <package> | grep base.apk | cut -d: -f2 | tr -d '\r')" app.apk
unzip -l app.apk | grep -c ' assets/lustro/' # 0: a no-op build
The CLI reads only the central directory at the end of the APK, so it does not copy the whole file.
A build from before the app added Lustro has no such entry either. When the CLI finds no token,
or the app's port does not answer, it checks, with adb, that there is a device, that the app of
--package is installed, that its build contains the Lustro runtime, that it runs, and that it is
in the foreground. The error then names the first check that fails, and the exit code says which
one it is (see Exit codes).
Conventions a client should follow:
- Honor a LUSTRO_TOKEN environment variable when present. For a known package, read the app's
prefs next, and the log line of its current process only for what they do not give. Without a
package, fall back to the parsed log line, then to the prefs of the app in the foreground.
- The port can differ from the configured one: if bindFallback is enabled and the configured
port was taken, the server binds a port that the system chooses. The endpoint= field gives
the port in use, so always use the log line, not the configured port.
(Browsers authenticate in a different way: with the HttpOnly; SameSite=Strict lustro_token
cookie that POST /api/v1/_auth sets, or by opening a URL with the #lustro_token=<token>
fragment. Agents should use the Bearer header.)
Endpoint and host/device¶
The server binds to 127.0.0.1:8080 by default and only listens while the app is foregrounded.
- From a desktop, forward the device port first.
--no-rebindstops adb from taking over a forward that a different tool set up for a different device on the same local port:
Then talk to http://localhost:8080. If the local port is taken ("Address already in use", or
"cannot rebind existing socket" for a forward that adb forward --list doesn't show for your
device), forward a free local port to the same device port, for example
adb forward --no-rebind tcp:18080 tcp:8080, and use http://localhost:18080. The lustro
CLI finds such a forward without --port, and makes one when there is none.
- With more than one device connected, use the device in ANDROID_SERIAL, or pass
adb -s <serial>; don't choose one that other tools may be using. Don't clear the device log
(adb logcat -c) to find the LustroToken line: read it with -d and take the last one.
Local port 8080 can be another device's forward: find your device's forward in
adb forward --list before you send a request with curl.
- If you can't reach the default port, parse the
endpoint=field from theLustroTokenlog line (see above) to learn the real host and port, and forward that port instead. - LAN exposure (
bindAddress = "0.0.0.0") is an opt-in the app developer sets; do not assume it. With it, theLustroTokenline addslan=and the device's network URLs after the token, and the token changes each time the app's process starts: after a401, read the lastLustroTokenline again. The CLI does that through adb on each call, but not with--tokenorLUSTRO_TOKEN, which it uses as given. - A client in the app's process, such as an instrumentation test, needs no forward and no log:
lustro.endpoint()gives the URL on127.0.0.1, the port, and the token, ornullwhile the server does not listen (the app is not in the foreground). SendGET transactions?since=<ms>with the time before the step under test to get only the requests of that step. Lustro's default port 8080 is also WireMock's: see Use Lustro from your app's code.
Wire protocol¶
All routes are under /api/v1/. The major version lives in the path; the minor version is
reported as _meta.protocolVersion.
Framework routes
| Route | Purpose |
|---|---|
GET /api/v1/_meta |
{ libraryVersion, protocolVersion, tabs: [{ id, title, schemaUrl, version }] }. Only the tabs that have an OpenAPI document are listed. A tab's version is the info.version of its own schema, and the protocol version for a schema without one. |
GET /api/v1/_schema |
JSON Schema for the shared envelopes. |
GET /api/v1/<id>/_schema |
A tab's OpenAPI document (enveloped 404 if it has none). |
Shared envelopes
- Error (any failing route):
{ error, message, code?, field?, hint? }.erroris a stable machine-readable type that follows from the status:bad_request(400),unauthorized(401),forbidden(403),not_found(404),method_not_allowed(405),conflict(409),payload_too_large(413),unprocessable_entity(422),too_many_requests(429),internal_error(500),unavailable(503),timeout(504). Any other status has the typeerror. Lustro's own tabs do not answer 409, 422, or 429, but an app's tab can. - Pagination (collection routes):
{ items: [...], nextCursor: "<opaque>" | null }. - Cursor (observable routes):
{ cursor, status, items?, state? }wherestatusisdelta,unchanged, orreset. Echocursorback on the next poll; treat any unknownstatusasresetand re-sync the full list. The cursor advances when the route's list changes, and a cursor from before an app restart gets areset. - Warning header: see Unknown query parameters.
- Wrong method: see A method that a route does not take.
- Stream (routes whose list only grows at its end):
{ cursor, status, items?, dropped?, state? }, with the same statuses. Here adeltacarries only the entries after the cursor, oldest first: append them. Aresetcarries the last entries of the list: replace what you have.droppedcounts the entries the list evicted before you got them. Treat any unknownstatusasreset.
Unknown query parameters¶
A route ignores a query parameter that it does not know: GET work/items?uniqueName=X returns
every item, because the parameter is name. So the server compares a request's query parameters
with those that the tab's OpenAPI document declares for the route ("in": "query"), and names
each one that it does not declare in a Lustro-Warning response header (protocol 1.15):
More than one is a comma-separated list in one header. A name is a quoted string, in which \
escapes " and \, and \uXXXX stands for a character outside printable ASCII. The status and
the body do not change, so a client that sends an extra parameter keeps working; read the header.
There is no check for a tab without an OpenAPI document, nor for a route that its document does
not describe. Each lustro command prints the warning on stderr.
A method that a route does not take¶
A request with a method that the route does not take, such as GET network/pause, gets a 405
with the type method_not_allowed and an Allow header that lists the methods of the path
(protocol 1.16):
HTTP/1.1 405 Method Not Allowed
Allow: POST
{"error":"method_not_allowed","message":"network/pause takes POST, not GET"}
The server reads the methods from the tab's OpenAPI document, so every tab with a document
answers it, an app's own tab too. A 404 means that the document does not declare the path, or
that the tab has no document: then a wrong method is a 404 too. Send the request again with a
method from Allow. From protocol 1.17, the tab root, such as PUT /api/v1/journals, gets the
405 too, with a message that names the tab alone (journals takes GET or POST, not PUT), and
one slash at the end of a path does not count, so GET network/transactions/ reaches
GET network/transactions.
Network tab operations¶
Base path /api/v1/network. The authoritative contract is network.openapi.json; the table
below summarizes it. All routes are token-authenticated and use the shared error envelope.
| Operation | Route | Notes |
|---|---|---|
| Poll transactions | GET transactions?cursor=&search=®ex=&since= |
Cursor envelope. First poll (no/invalid cursor) → reset with the full list; cursor unchanged → unchanged (items omitted); after a change → delta. search filters case-insensitively over the URL, the method, the headers (each as the line Name: value), and the bodies; with regex=true, it is a Java regular expression, and one that doesn't compile gets a 400 with field: search. since (milliseconds since the Unix epoch, device clock) keeps the transactions with startedAt at or after it. Carries a top-level state { paused, overwriteMode, throttleDelayMs, mockRules, captureFilter }. |
| Transaction detail | GET transactions/{id} |
Full object (headers + bodies, with truncation flags). Enveloped 404 if missing. |
| Transaction body | GET transactions/{id}/body/{request\|response} |
One body as it is stored: the bytes of an image, or the redacted text as UTF-8. Not JSON. Enveloped 404 when no body was kept. See below. |
| Export as HAR | GET transactions/_/export?format=har&ids= |
A HAR 1.2 document of the transactions in ids (comma-separated, or the parameter repeated), or of every one. See below. |
| Poll WebSocket connections | GET websockets?cursor= |
Cursor envelope, newest first, with the same state as the transactions poll. See below. |
| WebSocket connection detail | GET websockets/{id} |
One connection with requestHeaders, responseHeaders, and protocol. Enveloped 404 if missing. |
| Poll a connection's events | GET websockets/{id}/events?cursor=&limit=&direction=&search=®ex= |
Stream envelope: the messages and lifecycle events, in order. See below. |
| Message payload | GET websockets/{id}/events/{seq}/payload |
One message's payload as it is stored: bytes, or the redacted text as UTF-8. Not JSON. |
| Clear | POST clear |
Clears the captured list and the WebSocket connections, and starts the capture filter's counts again; mock rules and settings are preserved. |
| List rules | GET rules |
{ items: [MockRule...] }, in the order the rules are tried. |
| Add / upsert rule | POST rules |
Body MockRuleInput (urlPattern required). Supplying a stable id makes the write idempotent (upsert by id); omitting it generates one. A new rule goes first; a rule replaced by id keeps its place. Returns { status: "ok", id }. |
| Sync rules | POST rules/_/sync |
Atomic full replacement: posts an array; the resulting list equals it, in that order, with no empty window observed by the interceptor. A rule without an id gets a new one. Two posted rules with the same id are a 400 with field: "id", and the rules stay as they were (protocol 1.11). Returns { status: "ok", count }, where count is the number of rules set. |
| Delete rule | POST rules/delete |
Body { id }. An id that no rule has is a 404 with field: "id", and changes nothing. |
| Toggle rule | POST rules/toggle |
Body { id }; flips enabled. An id that no rule has is a 404 with field: "id", and changes nothing. |
| Pause capture | POST pause |
Toggles capture-only pause. While paused, mocks and throttle still apply; only recording into the list stops, for requests and for WebSocket messages. Returns { status: "ok", paused }. |
| Overwrite mode | POST overwrite-mode |
Toggles overwrite mode (a new request evicts earlier completed transactions with the same method + URL path; in-flight ones are never evicted). The new transaction's replacedCount says how many copies it evicted, with the ones those had evicted (protocol 1.10). Returns { status: "ok", overwriteMode }. |
| Throttle | POST throttle |
Body { delayMs }, a whole number from 0 (off) to 600000 (10 minutes); a missing or other value is a 400 with field: "delayMs", and the delay stays as it was. A global pre-request sleep applied to mocked and real OkHttp requests alike; platform HttpURLConnection requests are not held. A throttled transaction is listed while it waits and records the wait in throttledMs. Returns { status: "ok", delayMs }. |
| List senders | GET senders |
{ items: [{ name, baseUrl }] }: the OkHttp clients the app registered for send, in order; the first is the default. Empty when there are none. |
| Send request | POST send |
Synchronous send through one of the senders. See below. |
Mock rule semantics. urlPattern is looked for anywhere in the URL: a substring, or a regular
expression when prefixed with regex: (found, not matched against the whole URL, so anchor it with
^ and $ when it must match all of it). method is null to match any method. The rules are
tried in the order GET rules lists them, and the first enabled rule that matches answers the
request: a new rule goes first, so the rule added last wins when two match, a rule replaced by id
keeps its place, and a sync sets the order as posted. hitCount is a runtime-only counter (not
persisted). Rules answer the calls of Lustro's OkHttp interceptor, and the calls of an app adapter
that asks for a rule with findMockRule. A platform HttpURLConnection request is captured, but
no rule matches it, so a rule for one keeps hitCount at 0. A transaction's source says which
adapter captured it (see "Capture source" below).
Failure rules. A rule with failure fails each request that it matches with a connection error
instead of answering it: timeout, unknownHost, connectionRefused, connectionReset, or tls.
The app's OkHttp call throws SocketTimeoutException, UnknownHostException, ConnectException,
SocketException, or SSLHandshakeException, whose message ends with
(mocked by Lustro rule '<id>'), so the app takes its path for a failed network, not for an HTTP
error. The rule's statusCode, responseHeaders, and responseBody are ignored. The transaction
has error set, statusCode: null, isMocked: true, and the rule's mockRuleId, and the hit
counts. The call fails at once; set a throttle as well to fail it after a wait. failure is null
for a rule that answers, and any other name gets a 400 with field: "failure". A rule that the
interceptor can't serve also fails its request, as an IOException that names the rule, with the
same isMocked and mockRuleId. An app's own adapter reports such a failure with
failRequest(id, durationMs, error, rule). This arrived in protocol 1.12.
Which rule answers a request. Don't match the rules yourself: the app does, as the interceptor
does, and puts the result in each transaction. activeMockRuleId, in the list and the detail, is
the rule that answers the next request with that method and URL, or null; it follows the rules as
they change, so it is set on a request captured before its rule existed. The detail's
matchingMockRuleIds lists every rule whose pattern and method match, enabled or not, in the order
they are tried. mockRuleId is the rule that answered a mocked transaction, recorded when it did;
that rule can have changed or been deleted since. The rules are matched against the URL as
captured, which is redacted, so a pattern that names a redacted value doesn't match there. A
platform transaction has no matching rule. state.mockRules has enabled, the number of enabled
rules, and revision, which changes with every change to the rules but a hit: fetch GET rules
again when it does. These fields arrived in protocol 1.9.
Rules are validated on the way in. A regex: pattern must compile and must not be empty,
statusCode must be from 100 to 599, responseHeaders must
be header names and values OkHttp accepts, and a Content-Type among them must parse as a media
type: the interceptor builds a real response from the rule inside the app's own call. A rule that
fails any of these gets an enveloped 400 whose field names what to fix (urlPattern,
statusCode, or responseHeaders; a blank or missing id gets a new id, so it is never an
error); for rules/_/sync the message also carries the array index, and the whole batch is
rejected. A sync also rejects two rules with the same id, with field: "id" and the indexes of
both in the message. POST rules replaces a rule with the same id wholesale, so send
enabled and responseHeaders when editing one or they fall back to true and empty.
Send request semantics. Body { url, sender?, method?="GET", headers?, body? }. sender is
a name from GET senders; without it, the first sender sends, and an unknown name is a 400 with
field: "sender". Each sender is one of the app's OkHttp clients, so pick the one whose
interceptors (auth, for one) and host fit the request. An absolute url is sent as given; a
relative one is appended to the sender's baseUrl, path and all, and is a 400 with
field: "url" when the sender has none. The app can give a baseUrl as a function that follows
its server picker, so read GET senders again before you rely on it; a 400 with
field: "baseUrl" means that the function failed or gave a URL that is not absolute. Blocks until the sender returns, within the per-request
timeout. The response is { transactionId, sender, url, statusCode, ok, error? }: url is where
the request went, and ok is true whenever a response came back, a 401 included, so read
statusCode. transactionId names the transaction the Lustro interceptor recorded for the
request, and is null when the sender's client has no interceptor or the request wasn't captured.
The response body is never returned, and the sender reads at most maxBodyCaptureBytes of it, so
large or endless responses are safe to send. A send that outlives the per-request timeout gets the
enveloped 504, and its call is cancelled. Requests to the debug server's own bind host:port
are rejected. Send is only available when the app registered a sender: if not, GET senders
is empty, POST send returns an enveloped 404, GET network/_schema has no send route, and
the console has no Send form. The body is strict JSON, and each field must have its type: a
body that is not a JSON string gets a 400 with field: "body". Senders,
sender, the send result's sender and url, and a set transactionId arrived in protocol 1.7.
What advances the cursor. Changes to the captured list advance the transactions cursor: a
new request, its response or streaming progress, a failure, an eviction, or clear. So does a
change to the mock rules, because each transaction says which rule answers it; a hit on a rule
doesn't. Pause, overwrite mode, throttle, and the capture filter's counts don't. Every poll
response carries the current state, unchanged ones included, and GET rules returns the
rules with their hit counts.
Times, protocol, and content types. Every transaction, in the list and in the detail, has
startedAt and completedAt in milliseconds since the Unix epoch. Sort and correlate by those,
with logcat or a server log: timestamp is an HH:mm:ss.SSS display time in the device's zone.
completedAt is null while the request is in flight. A response with a status can still be in
flight (responseComplete: false): the app is still reading a body that capture didn't read
whole, such as a download, a body past the capture cap, or a stream. It completes when the app
reads to the end of the body or closes it, and durationMs then covers the whole body, and
responseBodyBytes is counted when the response had no Content-Length. A body that fails while
the app reads it sets error and keeps statusCode. Take a request's duration from
durationMs: completedAt can be later by the time the capture took to record it. protocol (http/1.1, h2, h3) is
null before a response and for a mocked one. Platform HttpURLConnection capture reads it from
X-Android-Selected-Protocol, a header that the platform adds to the response, and leaves the
platform's X-Android-* headers out of responseHeaders, since the server didn't send them.
requestContentType and responseContentType give the media type as captured, so a client can
tell JSON from an image without reading the headers. These fields arrived in protocol 1.2; a 1.1
server leaves them out.
Throttled requests. When the global throttle holds a request, the transaction is listed from
the moment the app made the call, so startedAt is the call time, and throttledMs says how long
the throttle held it before it was sent. durationMs leaves that wait out, and completedAt
comes at least throttledMs plus durationMs after startedAt. throttledMs is null for a
request that wasn't throttled. In the HAR export, the wait is the entry's timings.blocked, and
time is the sum. This field arrived in protocol 1.4.
Redirects. OkHttp follows a redirect inside the call, so a redirected request is one
transaction: url is what the app requested, and finalUrl is where the response came from,
null when that is url. The detail's priorResponses lists the responses OkHttp answered with
another request, oldest first: each redirect, and each authentication challenge that an
Authenticator answered, with its url and statusCode. Search finds a transaction by its
finalUrl too. Platform HttpURLConnection capture reports finalUrl but no prior responses, which
the platform doesn't show. These fields arrived in protocol 1.5.
Capture source. Every transaction has source, the adapter that captured it. okhttp is
Lustro's OkHttp interceptor: mock rules and the throttle apply to its requests. platform is
platform HttpURLConnection capture, which only records: no rule answers the request and the
throttle doesn't hold it, so don't make a mock rule from one. app is the app's own adapter,
through Lustro.networkCaptureSink(): a rule answers its request only if the adapter asks for it
with findMockRule, and the throttle doesn't hold it. Treat a value you don't know as one that no
rule or throttle reaches. The CLI row ends with [platform] or [app]. This field arrived in
protocol 1.6.
Multipart request bodies. An OkHttp MultipartBody is captured as text: the parts in order,
each with its headers (Content-Disposition, and Content-Type and Content-Length when known),
then the value of a text part. A part that is not text, such as a file, is not read: its content is
one line, [Lustro did not store this part: <type>, <n> bytes], or size unknown. The
requestContentType carries the boundary. requestBodyBytes is the size of the whole body on the
wire, and the stored text is cut at the capture cap like any other body. The default redactor masks
a part whose field name is sensitive, redacts any other part as a body of its own type, and masks a
part's own headers as it masks a request's. A file part with no type is not read either.
Image bodies and the body route. A body is captured as text, or, for an image, as bytes; SVG
is text. The detail's requestBodyBinary and responseBodyBinary are true when that body was
kept as bytes, and its requestBody or responseBody is then null.
GET transactions/{id}/body/{request|response} returns either kind as it is stored, so it is also
how to save a large text body to a file. A body cut at the capture cap comes back as the part that
was kept, and the detail's ...BodyTruncated flag says when. Content-Type is the captured media
type without its parameters, plus charset=utf-8 for text. The route answers an enveloped 404
when the request or response had no body, or when capture kept none: a one-shot or duplex request
body, or a binary type other than an image. The redactor never sees an image, so treat it as
unredacted. lustro net body <id> [request|response] -o FILE wraps the route. These fields and
the route are part of protocol 1.2.
Export as HAR. GET transactions/_/export?format=har&ids=<id>,<id> returns the transactions as a
HAR 1.2 document, oldest first, which browser devtools, proxies, and HAR viewers import. It is
built from the store, so it has the same redacted values as the detail. Without ids it has every
transaction; an id the app no longer has is left out. Each entry's _lustro has the transaction
id, isMocked, source, categories, requestBodyTruncated, responseBodyTruncated,
responseComplete, finalUrl, priorResponses ([{ url, statusCode }], the responses that the
client answered with another request, such as the redirects it followed, which have no HAR entry
of their own), and error. The capture has no phase timings, so each entry spends its whole
durationMs in timings.wait and the throttle's wait in timings.blocked, and _resourceType
(fetch, or image for an image) tells Chrome DevTools how to file it. A body kept as bytes is base64: content.encoding says so for a
response, and postData._encoding for a request. The request line and its headers must stay
under 8 KiB, so send many ids in batches; lustro net export --har FILE [--ids ID ...] does that,
and --har - writes the document to stdout. This route is part of protocol 1.2. From protocol 1.3,
the entry of a WebSocket's handshake has _resourceType: "websocket", the socket's messages in
_webSocketMessages (type send or receive, time in seconds, opcode 1 for text and 2 for
base64 bytes, data), which Chrome DevTools reads, and the connection in _lustro.webSocket.
WebSocket connections. GET websockets lists the sockets that the app creates with the
factory from Lustro.webSocketFactory, in a cursor envelope; the cursor advances when a connection
is listed, changes state, or gets an event. A connection has url (with the ws or wss scheme,
redacted), state (connecting, open, closing, closed, failed), startedAt, openedAt,
and closedAt in epoch milliseconds, statusCode of the handshake response, closeCode,
closeReason, and closedBy (app or server: whose close frame came first), canceled,
error (the exception of a failed socket), and the counts sentCount, sentBytes,
receivedCount, and receivedBytes. transactionId is the handshake's transaction, when the
interceptor on the same client captured it, and that transaction has webSocketId: the
transactions list shows the same handshake with an https URL, as OkHttp holds it. A socket
created in another way has no connection, only the handshake transaction, with webSocketId: null.
WebSocket events. GET websockets/{id}/events is the connection's log in a stream envelope.
Poll it first without a cursor: reset has the last limit events (100 by default). Then echo
the cursor: delta has only the events after it, oldest first, and unchanged has none. Each event
has seq, at (epoch milliseconds), timestamp, and kind, and only the other keys of its kind:
message:direction(sentorreceived),type(textorbinary),payloadBytes(the whole payload),truncated(the capture cap cut it),stored, andpreviewwithpreviewCompletefor text (the first 512 characters, redacted) orhexPreviewfor binary (the first 32 bytes). A sent message hasenqueued, the return value ofsend():truemeans that OkHttp queued it, which does not show that the server received it, andfalsemeans that it was not sent.open:statusCode.close:direction,code,reason, andenqueuedfor the app's ownclose().closed:code,reason.cancel: nothing more.failure:error,statusCode.
seq orders the events and names one in the payload route; a number can be missing. direction
and search (over the stored text, case-insensitive, or a regular expression with regex=true) leave events out of items. When
previewComplete is false, GET websockets/{id}/events/{seq}/payload returns the stored text;
for a binary message it returns the bytes. A connection keeps its last 1000 events by default:
evictedEvents on the connection counts the ones it no longer has, dropped in a delta counts
the ones evicted before you got them, and droppedEvents counts messages that were never stored
because capture was behind. While capture is paused, no message is recorded and no new socket is
listed. POST clear removes the connections; a socket that is still open is listed again with its
next message, with a new log, so a cursor from before the clear gets a reset. These routes and
webSocketId are part of protocol 1.3.
Compressed bodies. A body sent or received with Content-Encoding: gzip, x-gzip, or
deflate is stored inflated: requestBody and responseBody hold the text, and
...BodyTruncated says whether the inflated body passed the capture cap. The headers still name
the encoding, and requestBodyBytes and responseBodyBytes are the size on the wire, before
inflating, so drop Content-Encoding when you send a stored body again. A body in another
encoding, such as br, is not stored: its body is null, and its size is kept. Event streams are
stored as they arrive, without decoding, and so are JSON streams (application/x-ndjson,
application/ndjson, JSON Lines, application/json-seq, application/stream+json): poll the
transaction while it is in flight to see each line as the app reads it.
Request bodies arrive after the request. OkHttp capture copies a request body while OkHttp
sends it, so a transaction is listed first with requestBodyBytes alone and gets its
requestBody once the body is sent; a request that fails before that keeps the size alone. A
request body with no Content-Type is stored as text, and its requestContentType is null.
Logs tab operations¶
Base path /api/v1/logs, when the app registers the Logs plugin (LogsDebugTab.create(); without
it, the routes are an enveloped 404 Unknown tab: logs). The authoritative contract is
lustro-logs/openapi/logs.openapi.json, version 1.1 (1.1 added from and to). The tab runs
logcat -b main -b system -b crash -v threadtime -v UTC --pid=<the app's pid> while Lustro is started, also in the background, from
the start of the app's process, and holds the newest lines in a buffer of a fixed size (4 MiB by
default). The app's own logger can also append its lines in full (LogsDebugTab.append), and
then the tab drops the logcat copies of those tags: such a line has the whole message, up to
65,536 characters, where logcat keeps about 4 KB, and can hold line breaks. The CLI has no logs
commands: use lustro api.
| Operation | Route | Notes |
|---|---|---|
| Poll the log | GET entries?cursor=&level=&tag=&q=&mq=&from=&to=&limit= |
Stream envelope. The first poll gets reset with the last limit lines (default 500, at most 5000) that pass the filters; a poll with the cursor gets delta with the lines after it, oldest first, in pages of limit, or unchanged. state is { reader, readerError?, paused, compact } on every response. |
| Export as text | GET text?cursor=&level=&tag=&q=&mq=&from=&to=&limit= |
text/plain: the held lines as adb logcat -v threadtime prints them, oldest first, every one that passes the filters, or the last limit. A repeated line prints once with [×N]. With a cursor from entries, only the lines after it. |
| Clear | POST clear |
Empties the buffer and returns { status: "ok", cursor }: poll with that cursor to get only the later lines, with no dropped count. A cursor from before the clear gets a reset. |
| Pause | POST pause |
Body { "paused": true } or false; without a body it toggles. While paused, the tab drops new lines. Returns { status: "ok", paused }. |
| Compact | POST compact |
Body { "compact": true } or false; without a body it toggles. On by default: a line that repeats the line before (same level, tag, pid, tid, and message) folds into it. Returns { status: "ok", compact }. |
Bodies. POST pause and POST compact take one JSON object in strict JSON (RFC 8259).
Unquoted names, single quotes, comments, and text after the object are a 400 with
field: "body", and so is a body that is not a JSON object, such as [true]. A field of the wrong
type is a 400 with the field's name in field, such as { "paused": "yes" }. Without a body, or
without the key, the flag toggles.
An item. { seq, at, timestamp, pid, tid, level, tag, message }, and count and lastAt for a
repeated line. at and lastAt are epoch milliseconds, and timestamp is at as logcat prints
it, MM-dd HH:mm:ss.SSS in the device's time zone. seq identifies the line. A repeated line
comes again in a later delta with the same seq and a larger count: replace the row you
have with that seq, do not add a second one.
Filters. level is the lowest level, one of V D I W E F (W gives W, E, and F). tag and
mq are Java regular expressions found in the tag and in the message, case-sensitive (prefix
(?i) to ignore case, anchor with ^ and $), each at most 200 characters. q is text the
message contains, ignoring case. from and to are a time range in epoch milliseconds, both
ends included, such as the run of a worker from its started to its finished event; a repeated
line counts from its at to its lastAt. They combine. The cursor moves past the lines they leave out, so
keep the same filters while you follow one cursor. A bad value gets a 400 with field set to
the parameter. The filters check the time between lines and stop with a 400 after 5 s; one match
can't be stopped, so a regex that backtracks a lot, such as (a+)+$, can hold the request for
long. Keep tag and mq simple.
Reader status. state.reader is running; restarting, for the second after logcat ended
before the tab starts it again; failed, after logcat ended four times in a row without a line,
with the reason in readerError (the buffer keeps what it has, and entries still serves it); or
stopped, between Lustro.stop() and start().
Preferences tab operations¶
Base path /api/v1/prefs, when the app registers the Preferences plugin
(PrefsDebugTab.create(context, ...); without it, the routes are an enveloped
404 Unknown tab: prefs). The authoritative contract is
GET /api/v1/prefs/_schema, made from the tab's route declarations, and its copy
lustro-prefs/openapi/prefs.openapi.json, version 1.2 (1.1 sends a long past 2^53 - 1 as a string; 1.2 adds redacted, and refuses an empty key in POST edit). The CLI has no prefs
commands: use lustro api.
| Operation | Route | Notes |
|---|---|---|
| List the files | GET files |
{ items: [{ name, store, registered, policy, readOnly, encrypted, keyCount, cursor, error? }] }: the SharedPreferences files and then the Preferences DataStores that the app registered, in its order, then the files that the tab found in shared_prefs and files/datastore, by name. store is shared_prefs or preferences_datastore. cursor is the file's cursor now; compare it with the one you polled with to see that the file changed. error says why a file's instance can't read it. |
| Poll a file | GET entries?store=&file=&cursor= |
Cursor envelope. reset or delta carries every entry of the file, by key; unchanged carries none. A cursor of another file, or from before an app restart, gets a reset. |
| Read one value whole | GET entry?store=&file=&key= |
{ item }, after the value policy, never cut. 404 with field: "key" when the file has no such key. |
| Write a value | POST edit |
Body { store?, file, key, type, value }; an empty key is a 400 with field: "key", which POST delete takes. Returns { status: "ok", item }: the entry as the file now holds it, cut at 4096 characters as in entries. |
| Remove a key | POST delete |
Body { store?, file, key }. Returns { status: "ok", deleted }, false when the key was not there. |
| Empty a file | POST clear |
Body { store?, file, confirm: true }; without confirm: true, a 400 with field: "confirm". Returns { status: "ok", removed }. |
Bodies. The POST routes take one JSON object in strict JSON (RFC 8259). Unquoted names,
single quotes, comments, and text after the object are a 400 with field: "body". A missing or
wrong field is a 400 with the field's name in field, and this check comes before the checks of
the file: a body without key for a read-only file gets a 400 with field: "key", not a 403.
Stores. A SharedPreferences file and a Preferences DataStore can have the same name, so
store picks the kind: shared_prefs, the default when a request leaves it out, or
preferences_datastore. Any other value is a 400 with field: "store". The tab reads and
writes a registered DataStore through the app's own instance. A DataStore that the tab found in
files/datastore is read from its file, and it is always read-only.
An item. { key, type, value?, bytes, masked?, redacted?, truncated? }. type is string, int,
long, float, double, boolean, string_set, bytes, or unknown (a value that only a
custom SharedPreferences implementation can hold). double and bytes come only from a
DataStore. value is a JSON string, number, boolean, or, for string_set, a sorted array of
strings; a long beyond 2^53 - 1 either way is the string of its digits, as in the SQLite and
WorkManager routes; a float or a double that is not finite is the string "NaN", "Infinity", or
"-Infinity", and bytes is padded base64. bytes (the field) is the size of the whole value:
a string's UTF-8 bytes, the sum of those of a set's strings, a byte array's length, or 4, 8, 4,
8, and 1 for int, long, float, double, and boolean.
masked: true comes instead of value when the policy leaves it out. redacted: true comes
with a string that is a JSON object or array, under mask_sensitive, when the values of its
sensitive fields, at any depth, are replaced by [REDACTED]: do not write such a value back. In entries, and in the
item of the POST edit response, a value longer than 4096 characters (for a set, all its strings
together) is cut and has truncated: true; read it with GET entry.
Policies. policy is visible (every value), mask_sensitive (every value but those of keys
that look like they hold a secret, such as auth_token, apiKey, or password, by the network
redaction's key check; a boolean, float, or double value always shows, as an app does not
use it for a secret), or keys_only (no value). The keys always show. Under mask_sensitive,
the app can list keys whose values show although the check finds them sensitive, such as
auth_method, by their exact names in any case; files does not list them, and such an item
has its value and no masked. The app can also list keys that every policy masks, such as
account_info with a token in its JSON. A discovered file is mask_sensitive, with no such keys. encrypted is true when the file on disk is encrypted: the app registered an
EncryptedSharedPreferences, which shows plain values as its policy lets it, or the file has the
keysets of one and a plain instance reads it, which is always keys_only and read-only.
Writing. type picks the setter: string, int, long, float, boolean, or
string_set, and for a DataStore also double and bytes (base64; a DataStore before 1.1
can't write it, and answers a 500). Another type is a 400 with field: "type". For a
number or a boolean, value can also be a string, as a text field holds it ("42", "true");
int and long take whole numbers in their range, float a number in a float's range or
"NaN", "Infinity", "-Infinity", double the same in a double's range, and string_set a
JSON array of strings. A wrong value is a 400 with field: "value". An edit can give a key
another type: the app's getter of the old type then throws ClassCastException. A masked value can still be written. All
three mutations return when the file on disk has the change, and move its cursor when they
change it. A read-only file answers
403 with code: "read_only" and field: "file": a file that the app registered with
readOnly = true, a discovered file unless the app made them writable, Lustro's own
lustro_debug, an encrypted file read plain, and every discovered DataStore. A 500 after a
write means the disk write failed: a SharedPreferences instance's memory holds the change, and a
DataStore keeps what it had.
What moves a cursor. The tab's own changes, at once, and the app's changes, through a
listener, while Lustro is started. Before API 30, clear() calls no listener, so a clear by the
app shows only with the next change to the file. Another process that writes the file is not seen.
A registered DataStore moves its cursor when its data changes, while Lustro is started, and a
discovered one when the bytes of its file change, on the next poll.
A file that names no file is a 404, and one with / or \ a 400, both with
field: "file"; the tab never creates a file.
SQLite tab operations¶
Base path /api/v1/sqlite, when the app registers the SQLite plugin
(SqliteDebugTab.create(databases, discoverFrom); without it, the routes are an enveloped
404 Unknown tab: sqlite). The authoritative contract is
lustro-sqlite/openapi/sqlite.openapi.json, the document that the tab's route declarations make, version 1.2 (1.1 adds walBytes; 1.2 refuses a pragma with a value in POST query). The CLI has no
sqlite commands: use lustro api. The GET routes and POST query only read. POST exec,
edit, and delete write, and only to a database that GET databases lists as writable.
| Operation | Route | Notes |
|---|---|---|
| List the databases | GET databases |
{ items: [{ name, registered, source, writable, policy, path, sizeBytes, walBytes, schemaVersion, error? }] }: the databases that the app registered, in its order, then the files that the tab found in the app's databases directory, by file name, and then those in noBackupFilesDir, such as WorkManager's androidx.work.workdb, also by file name, or as no_backup/<file name> when a registration or a file in databases has that name. source is support (the app's SupportSQLiteDatabase, such as Room's), framework (the app's SQLiteDatabase), or file (opened read-only for each request). schemaVersion is PRAGMA user_version; Room and SQLiteOpenHelper set it to the schema's version. policy is the value policy, visible or mask_sensitive (see below). path and sizeBytes are null for a database in memory; sizeBytes leaves out the -wal file, and walBytes is that file's size, or null when there is none. In WAL mode, as Room keeps a database, the -wal file holds the changes until SQLite copies them into the database file at a checkpoint, so it can be the larger one. error says why a database does not open. |
| List the tables | GET tables?db= |
{ database, writable, items: [{ name, type, internal, hasRowId?, rowCount?, entity?, purpose?, error? }] }, by name. type is table or view. A view has no rowCount: counting runs its query. A table that the tab can't read, such as a view on a table that is gone, or whose count stops at the 2 s limit (see below), has error with the reason and can have no hasRowId and no rowCount; the route still answers 200. internal flags sqlite_*, android_metadata, room_master_table, and the shadow tables of a full-text or R*Tree index. entity and purpose are the app's hint. |
| Read a schema | GET schema?db=&table= |
{ database, table, type, internal, hasRowId, rowCount, sql, entity?, purpose?, columns: [{ name, type, notNull, defaultValue, primaryKey, generated, masked }], foreignKeys: [{ table, from, to, onUpdate, onDelete }] }. primaryKey is the column's place in the key, from 1, or 0. generated is true for a column that SQLite computes (GENERATED ALWAYS AS). masked is true for a column whose values the value policy leaves out. A key over several columns has them in order in from and to; a null in to stands for the other table's primary key. |
| Read rows | GET rows?db=&table=&limit=&cursor=&filter=&sort=&dir= |
Pagination envelope { items, nextCursor }. 50 rows by default, limit 1 to 500. Pass nextCursor as cursor for the next page; it is null on the last one. |
| Run a statement that reads | POST query { db, sql } |
{ database, columns, rows: [[cell]], truncated }: a row is an array of cells in the order of columns, which can repeat a name. At most 1000 rows, and fewer when their texts pass 4 Mi characters in all; truncated says that rows were left out. A text comes whole; a blob is its size. |
| Run a statement that writes | POST exec { db, sql } |
{ status: "ok", changes }: the rows that the statement inserted, updated, or deleted, without those of triggers and foreign key actions. Writable databases only. |
| Change one row | POST edit { db, table, rowid \| key, values } |
{ status: "ok" }. values maps columns to a string, a number, or null. Writable databases only. |
| Delete one row | POST delete { db, table, rowid \| key } |
{ status: "ok" }. Writable databases only. |
Bodies. The POST routes take one JSON object in strict JSON (RFC 8259). Unquoted names,
single quotes, comments, and text after the object are a 400 with field: "body". A missing or
wrong field is a 400 with the field's name in field, and this check comes before the checks of
the database, also for a query parameter that is missing, empty, or out of range: GET rows?db=nope
without table gets a 400 with field: "table", not a 404 with field: "db". An empty sql
or table in a body is checked after the database, as every other value is: so a write to a
database that is not writable gets the 403 that the write routes below describe, also with an
empty sql or a rowid of "one".
A row. { rowid?, cells: { <column>: cell } }, with a cell for each column of GET schema,
in its order. rowid is a string, so that a JavaScript client keeps every digit; a view and a
table WITHOUT ROWID have none. SQLite stores any type in any column, so each cell says its
own: { type: "null" }, { type: "integer", value }, { type: "real", value },
{ type: "text", value, truncated?, length? }, or { type: "blob", bytes }. An integer beyond
2^53 - 1 either way is a string of its digits, and an infinite real the string "Infinity" or
"-Infinity". A text longer than 4096 characters is cut, with truncated: true and the whole
length in characters. A blob is only its size, in any column, also in a TEXT one.
The value policy. A database's policy is mask_sensitive, the default and always for a
discovered file, or visible. With mask_sensitive, a cell of a column whose name looks like it
holds a secret, such as access_token, clientSecret, or password (the network redaction's
name check), is { type, masked: true }, with its storage class and no value, length, or size; a
NULL stays { type: "null" }. A column named only key, the name column of a key-value table, is not masked. GET rows masks by the table's column, as GET schema marks it,
and its filter does not search a masked column; a sort on one orders the rows by its values.
POST query masks by the result's column name: SQLite names an expression without an alias by its
text, so length(access_token) is masked, but SELECT access_token AS t shows the value, because
Android does not say which table column a result column comes from. The policy keeps secrets out
of what you read by accident; it does not stop a client that wants them. edit can write a
masked column. The app can list columns whose values show under mask_sensitive although their
names look like they hold a secret, such as oauth_scopes, by their exact names in any case:
GET schema has masked: false for such a column, GET rows sends and filters its values, and
POST query shows a result column of that name, but not an expression of it, such as
length(oauth_scopes). GET databases does not list these names; a discovered file has none.
Order, sort, and filter. Without sort, a table's rows come by rowid, or by the primary key
for a table WITHOUT ROWID, and a view's as SQLite gives them; dir=desc turns the order
around. sort names a column as GET schema does (another case finds it too), or rowid when
the table has one and no column has that name; a sort also sorts by the row's key, so rows with
the same value keep their order from page to page. filter keeps the rows where a cell, as text,
contains the filter: % and _ are plain characters, case does not matter for ASCII letters,
and a blob never matches. A cursor holds a place in the rows: when the app adds or removes rows
between two pages, the next page can repeat or skip a row.
What the GET routes run. Only statements that the tab builds: each db, table, and sort
is checked against the database's schema and quoted, and the filter is a bound parameter. A
file database is opened with OPEN_READONLY for one request and closed after it. Each read
stops at the request timeout, and the client then gets a 504. On a file database, registered
or discovered, that is not in WAL mode, a statement also stops after 2 s (504,
code: "read_limit"), because the app's writes wait for the lock of the tab's connection, and
Android fails a write that waited 2.5 s with SQLITE_BUSY. In GET tables, a count that stops
gives its table an error, and the other tables are still listed. A database through the app's handle
has no such limit: there a read and the app's writes share the app's connection pool.
POST query is read-only for every database, and SQLite enforces it. The statement runs on a
connection that SQLite opens with OPEN_READONLY to the database's file, for this request only,
never on the app's handle. A statement that writes, also one inside a WITH, is a 403 with
code: "read_only" and changes nothing. A pragma with a value, such as PRAGMA user_version(9) or
PRAGMA journal_mode=DELETE, sets it, so query refuses it before it runs: a 400 with
code: "statement_refused". A pragma that reads works: PRAGMA user_version,
PRAGMA table_info(notes), SELECT * FROM pragma_table_info('notes').
A database in memory, and a live handle on another copy of SQLite (such as SQLCipher's), take no
query: 400 with code: "query_unavailable"; read them with GET rows. Android's cursor steps
through the whole result once to count it, so put a LIMIT on a statement over a large table. On
a database that is not in WAL mode, a statement stops after 2 s (504, code: "read_limit"),
because a longer read would make the app's writes fail with SQLITE_BUSY.
POST exec, edit, and delete write through the app's handle, in a transaction of their
own, and only to a database that the app registers with writable = true: any other answers
403 with code: "read_only" and field: "db", after the strict JSON and the field checks of
Bodies above, and before every other check of the body. exec takes
a statement that returns no rows: one that returns rows, such as a SELECT or a write with
RETURNING, is a 400 with code: "statement_refused", and does not run; read it with query. edit and delete name one row by
rowid (as GET rows gives it) or by key, an object with each primary key column of the table
and its value; a table WITHOUT ROWID takes key only. The row must be the only one that
matches: 404 when none does, 400 when more than one does. A value binds by its JSON type, and
the column's type converts a text, so "42" in an INTEGER column is stored as 42; a blob is
written with exec and a blob literal such as x'00ff'. A write that SQLite refuses, such as for
a constraint, is rolled back. SQLite can't stop a write at the request timeout: it runs to its
end and is then rolled back. Only a timeout during the commit itself can leave the change
committed, so read the data again after a 504 before you send a write again. Room's observers, such as a
Flow of a DAO, see the change at once when the app registers the database with
onWrite = { db.invalidationTracker.refreshVersionsAsync() }, and otherwise at the app's next write
through Room.
The statements that both routes refuse. BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT,
RELEASE, ATTACH, DETACH, and VACUUM, in exec also every PRAGMA, and in query a
pragma with a value (= value or (value)), but for those whose value names what to read
(table_info, table_xinfo, table_list, index_info, index_xinfo, index_list,
foreign_key_list, foreign_key_check, integrity_check, quick_check), and the
pragmas that set a value for the whole process (hard_heap_limit, soft_heap_limit,
temp_store_directory, data_store_directory), also without a value: a transaction would stay open on a pooled
request thread and block the app's writes, a pragma would change a setting of the app's
connection, or of every connection of the app, query only reads (a set of the journal mode
failed on its read-only connection with a lock error), ATTACH changes the connection's
databases, and VACUUM INTO writes a file. The tab finds the statement's first keyword past comments, white space (a byte order
mark too, as SQLite reads it), empty statements, and EXPLAIN, and answers 400 with code: "statement_refused". exec also rolls
back, with the same error, a statement that creates or drops a TEMP table, view, index, or
trigger, which would stay on the app's connection. A TEMP trigger that SQLite drops or rewrites
with its table, such as one that Room keeps on a table that it observes, does not count, so
DROP TABLE and ALTER TABLE work there. SQLite runs only the first statement of sql
and ignores the rest: send one statement for each request.
A deferred foreign key. SQLite checks a DEFERRABLE INITIALLY DEFERRED key (Room's
@ForeignKey(deferred = true)) at the commit, and a commit that fails keeps the transaction open
on the app's connection. So when the app has the keys on, exec, edit, and delete compare
PRAGMA foreign_key_check before and after the statement, and roll back a statement that adds a
violation: 400 with code: "sqlite_error". A violation that the database had before does not
count.
WorkManager tab operations¶
Base path /api/v1/work, when the app registers the WorkManager plugin
(WorkDebugTab.create(context, uniqueNames), or createWithMetrics(context, metrics, uniqueNames) with a
work-analytics repository; without it, the routes are an enveloped 404 Unknown tab: work). The
authoritative contract is lustro-work/openapi/work.openapi.json, version 1.3 (1.1 names the unique work of every work request, 1.2 adds the networkRequest of a work's constraints, and 1.3 the prerequisites of a work).
The CLI has no work commands: use lustro api. Only POST cancel and POST prune change
anything. The app needs WorkManager 2.12.0 or newer: with an older one, every route answers 503
with code: "work_unsupported", after the checks of the request's parameters and body, so a bad
parameter, or a cancel without a body, still gets its 400.
| Operation | Route | Notes |
|---|---|---|
| Poll the work | GET items?cursor=&state=&tag=&class=&name= |
Cursor envelope: every work request that WorkManager has, as WorkInfo has it now, in WorkManager's order. The cursor stands for the list's content, so a poll with it is unchanged until any item changes, then delta with the whole list. state takes one or more states, comma-separated (FAILED,CANCELLED); class the worker's full or simple class name; name any unique work name. state is the tab's state on every response (see below). |
| Read one work request | GET items/{id} |
{ item, events, metrics?, state }: the item, the events that the buffer holds of it, oldest first, and with work-analytics its periods. item is null after WorkManager deleted the work (a prune) while the tab still has its events; 404 with field: "id" when neither has it. |
| Poll the events | GET events?cursor=&id=&class=&type=&limit= |
Stream envelope over the events that the tab's listeners recorded. The first poll gets reset with the last limit events (default 500, at most 5000) that pass the filters; a poll with the cursor gets delta with the events after it, oldest first, in pages of limit, with dropped for events that the buffer evicted first, or unchanged. type takes one or more event types, comma-separated. |
| Read the history | GET metrics?id=&tag=&class=&state=&from=&to= |
{ items: [period] } from work-analytics, oldest first by enqueue time; from and to are enqueue times in epoch ms. 404 with code: "metrics_off" when the app passed no repository. |
| Cancel | POST cancel { id } or { name } or { tag } |
Exactly one key, and no other (400 with the key as field): WorkManager.cancelWorkById, cancelUniqueWork, or cancelAllWorkByTag. Returns { status: "ok", cancelled }, the number of matched requests that were not finished; finished work stays as it is, and the work that depends on cancelled work is cancelled too, uncounted. 404 with the key as field when nothing matches. Cancelling work that is RUNNING in an app whose listeners are a work-analytics 2.12.0 repository (state.metrics is a hint) ends the app's process, through a bug of work-analytics, unless the app catches it. |
| Prune | POST prune |
WorkManager.pruneWork(): deletes finished work that no unfinished work depends on. Returns { status: "ok", pruned }. The events stay in the buffer. |
Bodies. POST cancel takes one JSON object. An empty body, or one that is not a JSON object,
is a 400 with field: "body". Unlike the bodies of the Preferences and SQLite routes, the JSON
is not strict: the tab reads it with Android's JSONObject, as the Network tab's rules routes
do, so it takes unquoted names, single quotes, and comments. The checks of its members come
after the 503 with code: "work_not_initialized": while the app has not initialized
WorkManager, a body with a wrong member, such as { "nmae": "x" }, gets the 503, not a 400.
A work item. { id, workerClass, state, tags, uniqueName?, prerequisites?, runAttempts, generation,
stopReason: { code, name }, output, progress, constraints, initialDelayMillis, periodicity?,
nextScheduleTimeMillis? }. state is a WorkInfo.State name: ENQUEUED, RUNNING,
SUCCEEDED, FAILED, BLOCKED (waiting for the work before it in a chain), or CANCELLED.
tags includes the worker's class name, which WorkManager adds. runAttempts is
WorkInfo.runAttemptCount, how often the work started; for periodic work it counts only the
current period, because WorkManager sets it back to 0 when a period ends, so the finished event
of a periodic run has 0 and its started event has the attempt. uniqueName is the name that
the app enqueued the work with, such as the URL of a download; WorkInfo does not have it, so
the tab reads it from WorkManager's own database. When the app's WorkManager does not have the
call that reads it, uniqueName is there only for a name that the app registered, or the one
that name= asked for. prerequisites are the ids of the work that this work waits for, the work
before it in a chain of beginWith() and then(), sorted: BLOCKED work runs when all of them
have succeeded. The tab reads them from WorkManager's database in the same way, once for each
work, as WorkManager records them when the app enqueues it, and leaves the field out for work
that has none, and when the app's WorkManager does not have the call.
stopReason.name is the WorkInfo.STOP_REASON_* constant without the prefix: NOT_STOPPED
when the work never stopped, UNKNOWN when WorkManager does not know why, as after the app's
process died. output and progress are Data as JSON: a long beyond 2^53 - 1 and a NaN or an
infinity are strings. Periodic work loses its output when its period ends, so read a run's output
from its finished event. nextScheduleTimeMillis is left out when there is no next run; a time
in the past on ENQUEUED work means that WorkManager waits for its constraints, such as a content
URI trigger, or for the system to run it. constraints is { network, requiresCharging,
requiresDeviceIdle, requiresBatteryNotLow, requiresStorageNotLow, contentUriTriggers?,
networkRequest? }: network is the NetworkType name, and networkRequest, { transports,
capabilities } by the names of their NetworkCapabilities constants, comes when the app set a
NetworkRequest with setRequiredNetworkRequest, which takes the place of network from API 28,
so that network is then NOT_REQUIRED.
An event. { seq, at, type, id, workerClass, state, runAttempts, generation } and what the
type adds: finished has result (success, failure, or retry) and output; stopped has
stopReason; exception has exception: { type, message?, stackTrace, truncated? }, the message
at most 4096 characters and the stack trace at most 16384; updated has previousGeneration. state and runAttempts are
the work's at the event. The schedule listener gives enqueued, unblocked (the work waits for
no work before it: WorkManager sends it at the time of enqueued for work that has no
prerequisites, or whose prerequisites all succeeded, and else when the last one succeeds),
updated, cancelled, and prerequisiteFailed (the work before it failed or was cancelled, so
this work fails without a run); the execution listener gives started,
stopped, finished, and exception. A worker that throws ends its run with exception, not
finished. WorkManager also sends cancelled for finished work: when the app enqueues work of a
unique name with APPEND_OR_REPLACE while some of that name's work failed or was cancelled,
WorkManager deletes all of it and starts a new chain, and the cancelled event of each deleted
work has state: "CANCELLED", also after its finished event. The work is then gone from
items, and items/{id} has its events with item: null. A finished with retry leaves the work ENQUEUED, as does the end of a period of
periodic work.
A period. { id, generation, workerClass, tags, state, enqueueTimeMillis?, unblockTimeMillis?,
firstStartTimeMillis?, finishTimeMillis?, workerDurationMillis?, totalRuntimeMillis?, runAttempts,
explicitRetries, stopReasons: [{ code, name, count }] }, one run of one-time work or one period of
periodic work. state is a WorkMetricsInfo.State name (ENQUEUED_BLOCKED, ENQUEUED_PENDING,
RUNNING, SUCCEEDED, FAILED, CANCELLED, OBSOLETE_UPDATED). A time that work-analytics
has not seen yet is left out. work-analytics keeps periods 7 days by default, also of the runs of
earlier processes.
The tab's state. Every items and events response, and items/{id}, has state:
{ listeners, reason?, initialized, metrics, uniqueNames, bufferBytes }. listeners is
installed when WorkManager runs with the tab's listeners; missing when the app's
configuration did not go through WorkDebugTab.configure() or WorkManager runs with another one,
such as the default initializer's; unsupported when the app's WorkManager has listener methods
that this version of the tab does not forward. Then reason says what to change, and events is
empty. initialized is false until the app calls WorkManager.getInstance: the tab never
initializes WorkManager, so until then items, items/{id}, cancel, and prune answer 503
with code: "work_not_initialized", except a cancel without a body or with one that is not a
JSON object, which gets its 400 first.
Events live on the heap. The tab records events in the app's process from Lustro.start()
to Lustro.stop(), also in the background, and keeps the newest ones in a buffer of
bufferBytes (1 MiB by default). The
server answers only while the app is in the foreground. When the system starts the app in the
background to run a worker and stops the process before you open the app, the events of that run
are gone: the item still has the state, runAttempts, the last stopReason, and the output, the
history has the run's times, and logcat has the exception (lustro api GET logs/entries --param
tag=WM-WorkerWrapper while the Logs plugin is registered and the process lives, or adb logcat).
A new process starts a new stream: a cursor from before gets a reset.
Screen tab operations¶
Base path /api/v1/screen, when the app registers the Screen plugin
(ScreenDebugTab.create(context), or create(context) { contextJson } with a context provider;
without it, the routes are an enveloped 404 Unknown tab: screen). The authoritative contract is
lustro-screen/openapi/screen.openapi.json, version 1.0. The tab only reads: it
has no route that changes the app.
| Operation | Route | Notes |
|---|---|---|
| Read the screen | GET tree?merged=&settle= |
{ windows, merged, density, compose, windowSource, context, settle?, contextError?, composeError? }. merged=false gives the unmerged semantics tree, in which each text is a node of its own; a node has the same id in both. settle=MS, from 0 to 10000, reads on each frame until two reads in a row are the same and the window focus is at rest (the top visible window that can take the focus has it, and no other window does), for up to MS, and adds settle: { requestedMs, settled, waitedMs, frames }. settle=0, the default, reads once and adds no settle. |
A window. { id, type, kind, title, hasWindowFocus, focusable, visible, bounds, nodes }, in the order the
app added the windows: the activity first, then each dialog, popup, and bottom sheet over it.
kind is activity, dialog, popup, system, or other, from the window type of the root
View's WindowManager.LayoutParams. id is the id of the window's first node, its root View.
hasWindowFocus is true for the window that gets the keys and the touches first, and focusable is false for a window that can't take the focus, such as a popup that does not take the keys. The window manager moves the focus some frames after a dialog opens or closes, 200 ms and more on a physical device, so a read right after a tap can still have it on the window under the dialog: read with settle after a tap. The server
answers while the app's process is started, so it also answers while a permission dialog, the
chooser, or a translucent activity of another app covers the app, and for at least 700 ms after a
full-screen activity of another app covers it. Then no window of the app has the focus: read that
window with uiautomator.
A node. { id, parent?, kind, bounds, screenBounds, visibleBounds } and what it has:
className and resourceId (Views), testTag, text (a list: a merged node carries the text
of each child), contentDescription (a list), editableText (a field's text), password: true,
role (Compose's Role: Button, Checkbox, Switch, RadioButton, Tab, Image,
DropdownList), stateDescription, error, enabled: false, focused: true, selected,
toggle (on, off, or indeterminate), clickable: true, actions (OnClick,
OnLongClick, SetText, PerformImeAction, ScrollBy, ScrollToIndex, the page and progress
actions, Expand, Collapse, and Dismiss), horizontalScroll and verticalScroll
({ value, max, reverse, forward, backward }, with max: null for a View that does not say), and
collection ({ rows, columns } of a Compose list or grid). A key that the node does not have is
left out. The nodes of a window come in a list, each parent before its children. kind is view
or compose: a View's id is v and a number that stays the same while the View lives, and a
Compose node's id is c, the number of its host's View, a dot, and its semantics id, such as
c5.23 under the host v5. The Views of an AndroidView in a Compose host come after the host's
semantics nodes, with the host as their parent. All rectangles are { left, top, right, bottom }
in pixels; bounds is in the window, and screenBounds and visibleBounds are on the screen.
visibleBounds is the part of the node that its parents and its window leave on the screen,
null when they leave none, and clipped: true says that they cut a part of it. A lazy list
composes the rows in view only, and a few more, so a row that is not in the tree needs a scroll
first. The text of a password field has one dot for each character, as the screen shows it.
The context. context is the JSON that the app's ScreenContextProvider returned after the
read, such as {"route":"settings","stack":["home","settings"]}, or null when the app has none.
A provider that throws, or returns text that is not JSON, gives context: null and the reason in
contextError.
The CLI. lustro screen tree prints each window, and each node on the screen that has a text,
a tag, a role, an action, or a state, one line each: its id, its role or class, its text, #tag,
its states and actions, and its visible bounds as [left,top][right,bottom], as
uiautomator dump writes them. --all prints every node, --unmerged reads the unmerged tree,
--settle MS waits as above, and --json prints the response.
Read the screen in a loop. The CLI looks up the token and the port on every call, with
adb logcat -d -s LustroToken, adb forward --list, and adb get-serialno, so each
lustro screen tree costs three adb calls and a Python start. A script that reads the tree many times, such as a step runner,
reads the token and makes the forward once, keeps both, and sends the GET itself:
TOKEN=$(adb logcat -d -s LustroToken | tail -1 | sed -n 's/.*token=\([^ ]*\).*/\1/p')
adb forward --no-rebind tcp:18080 tcp:8080
curl -s -H "Authorization: Bearer $TOKEN" "http://localhost:18080/api/v1/screen/tree?settle=500"
When the app goes to the background, the server closes its socket, and binds again when the app
comes back: the first read after that can get a refused connection, and with bindFallback the
port can change. On a refused connection or a 401, look up the token and the port once more, and
then read the screen with uiautomator dump. Read it with uiautomator dump too when no window
has hasWindowFocus.
Tap what a user taps. To press a node, tap the middle of its visibleBounds with
adb shell input tap X Y. That goes through the system's hit test, as a finger does: a node that
a dialog or a sheet covers gets no tap, so a check that the tap worked tells you what a user would
see. A null visibleBounds means that a user can't tap the node now: scroll first. To scroll,
swipe inside the list's visibleBounds with adb shell input swipe X1 Y1 X2 Y2 300: a swipe from a
lower point to a higher one scrolls down. To type, tap the field, then send adb shell input text.
It takes ASCII text only, and %s for a space.
Common workflows¶
Mock a 500 for an endpoint
TOKEN=...; BASE=http://localhost:8080
curl -s -X POST "$BASE/api/v1/network/rules" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"id":"orders-500","urlPattern":"/v1/orders","method":"GET","statusCode":500,
"responseHeaders":{"Content-Type":"application/json"},
"responseBody":"{\"error\":\"boom\"}"}'
With the CLI, the same rule is:
lustro mock add --id orders-500 --url-pattern /v1/orders --method GET --status 500 \
--header 'Content-Type: application/json' --body '{"error":"boom"}'
Reusing the same id updates the rule in place (idempotent). Remove it with
POST rules/delete {"id":"orders-500"}, or lustro mock delete orders-500.
Make a request fail as a bad network does
lustro mock add --id feed-offline --url-pattern /v1/feed --failure unknownHost
lustro net throttle 3000 # optional: fail after 3 s, as a slow timeout does
The app's call throws UnknownHostException, and the transaction has the error, isMocked:
true, and mockRuleId: "feed-offline". Check what the app shows, then undo both:
lustro mock delete feed-offline and lustro net throttle 0.
Capture and inspect
- Poll
GET transactionswith no cursor →resetsnapshot; keep the returnedcursor. - Re-poll with
?cursor=<cursor>;unchangedmeans no new traffic,delta/resetmeans re-readitems. - Fetch
GET transactions/<id>for full headers and bodies (values are already redacted).
A request is listed once its capture is redacted, which happens off the app's call: usually
milliseconds after the call returns, longer for large bodies. Right after making a request, keep
polling rather than reading the list once. lustro net wait does this.
The app can also leave requests out with a capture filter, set in its code. Such a request is
never listed, but mock rules and the throttle still apply to it. state.captureFilter says
whether the app set one: null when it didn't, or { description, skipped, failed }, where
skipped counts the requests it left out and failed the ones it threw on, which were captured.
Both count since the list was last cleared. So when a request never shows up while capture isn't
paused, check skipped and read description.
Watch a WebSocket
lustro net ws list(orGET websockets) and take the id of the connection.lustro net ws events <id> --follow, or pollGET websockets/<id>/eventswith the cursor, and append eachdelta.- For a message whose preview is cut,
lustro net ws payload <id> <seq>.
To test how the app handles a refused upgrade, add a mock rule for the handshake: its URL has
https for wss, and any status but 101 makes OkHttp fail the socket with that response. A rule
with a failure, such as connectionRefused, fails the socket with the exception and no response,
as a network that drops the connection does.
Send a request
lustro senders # the app's senders, the default first
lustro send --url /v1/orders --sender "API (signed in)"
curl -s -X POST "$BASE/api/v1/network/send" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"url":"/v1/orders","sender":"API (signed in)","method":"GET"}'
Check url in the result before you trust the status: a 401 or a 404 often means that the
request went through a sender with the wrong auth or the wrong base URL. A sent request is captured,
as its own transaction, only when the sender's client carries lustro.networkInterceptor(); then
transactionId names it, and GET transactions/{id} has the response.
Tail the app's log
lustro api GET logs/entries --param level=W --param limit=50 > page.json # the last 50 warnings and errors
cursor=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["cursor"])' < page.json)
lustro api GET logs/entries --param level=W --param cursor="$cursor" # only what came since
Keep the same filters with a cursor. Poll again while a delta is a full page of limit lines. A
reset means the log was cleared or the app restarted: replace what you have.
Export the log for a bug report
lustro api POST logs/clear # start from an empty log
adb shell input tap 540 1200 # reproduce the problem
lustro api GET logs/text > repro.txt # every line since the clear
lustro api GET logs/text --param tag='^(OkHttp|SyncWorker)$' --param level=I
Read and change a SharedPreferences or DataStore value
lustro api GET prefs/files # names, policies, read-only flags
lustro api GET prefs/entries --param file=settings > page.json
cursor=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["cursor"])' < page.json)
lustro api POST prefs/edit --body '{"file":"settings","key":"onboarding_done","type":"boolean","value":false}'
lustro api GET prefs/entries --param file=settings --param cursor="$cursor" # delta: the file again
lustro api GET prefs/entries --param store=preferences_datastore --param file=app_state
lustro api POST prefs/edit --body '{"store":"preferences_datastore","file":"app_state","key":"zoom","type":"double","value":1.5}'
The app reads the new value at its next get. Code that read the value before, such as a cached
field, keeps the old one until the app reads it again; restart the app when in doubt
(adb shell am force-stop <package>): the value is on disk.
Find a table and page through its rows
lustro api GET sqlite/databases # names, sources, schema versions
lustro api GET sqlite/tables --param db=app # tables, row counts, hints
lustro api GET sqlite/schema --param db=app --param table=notes
lustro api GET sqlite/rows --param db=app --param table=notes --param sort=created_at --param dir=desc --param limit=20 > page.json
next=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["nextCursor"] or "")' < page.json)
lustro api GET sqlite/rows --param db=app --param table=notes --param sort=created_at --param dir=desc --param limit=20 --param cursor="$next"
lustro api GET sqlite/rows --param db=app --param table=notes --param filter=invoice
Keep the same sort, dir, filter, and limit from page to page: a cursor is a place in one
order. To read a text cell whole, use POST query. To read a blob's bytes, use
adb shell run-as <package> with the database file that GET databases names as path.
Read with a statement of your own, and change a row
lustro api POST sqlite/query --body '{"db":"app","sql":"SELECT folder_id, count(*) FROM notes GROUP BY folder_id"}'
lustro api POST sqlite/query --body '{"db":"app","sql":"SELECT body FROM notes WHERE id = 42"}' # the whole text
lustro api POST sqlite/query --body '{"db":"app","sql":"PRAGMA index_list(notes)"}'
lustro api POST sqlite/edit --body '{"db":"app","table":"notes","rowid":"42","values":{"title":"Renamed","score":null}}'
lustro api POST sqlite/delete --body '{"db":"app","table":"note_tags","key":{"note_id":42,"tag":"old"}}'
lustro api POST sqlite/exec --body '{"db":"app","sql":"UPDATE notes SET pinned = 0 WHERE pinned = 1"}' # {"status":"ok","changes":3}
query reads every database; the three that write need a writable one.
Atomically sync a rule set (declarative: the resulting set equals what you post; give each
rule its own id, because a set with a repeated id is rejected with a 400):
curl -s -X POST "$BASE/api/v1/network/rules/_/sync" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '[{"id":"a","urlPattern":"/a","statusCode":200,"responseBody":"{}"},
{"id":"b","urlPattern":"/b","statusCode":404,"responseBody":"{}"}]'
Wait for a worker to finish, and see why it failed
# The work of one unique name, and its state now
lustro --json api GET work/items --param name=sync
# Follow the events of the run: poll with the cursor until a finished or exception event comes
lustro --json api GET work/events --param type=finished,exception,stopped,prerequisiteFailed
lustro --json api GET work/events --param cursor=<cursor> --param type=finished,exception,stopped,prerequisiteFailed
# Everything the tab has about one work request: its item, its events, and with work-analytics its runs
lustro --json api GET work/items/<id>
A finished event with result: "failure" has the worker's output; an exception event has the
stack trace; prerequisiteFailed says that the work before it in a chain failed, so look at that
work. When there are no events, read state.listeners and state.reason first.
A worker that returns Result.failure() without output says why only in its log lines. With the
Logs plugin registered, read the app's lines of the run, from its started event to the event that
ended it, with a second of margin on each side:
lustro api GET logs/text --param from=<started at - 1000> --param to=<finished at + 1000> --param level=W
Cancel work and clear the finished history
Failure modes¶
Errors use the shared envelope; key statuses:
401 unauthorized: the token is missing or not valid. SendAuthorization: Bearer <token>.403 forbidden: the Origin /Sec-Fetch-Sitecheck refused the request, on any method (a cross-origin, non-allowed Origin; only the server's own origin and configuredallowedOriginspass). Missing Origin/Sec-Fetch-Siteheaders are accepted, so plain CLI clients are unaffected.400 bad_request: the input is not valid. Also a body sent with aTransfer-Encodingor a malformedContent-Length: chunked request bodies are not supported. Also any request, on any route, whose request line and headers exceed 8 KiB (Request headers too large); its connection then closes. Browsers get there with large cookies that other local servers set on the same host.413 payload_too_large: the request body is larger thanmaxRequestBodyBytes(1 MiB by default; 1 KiB forPOST /api/v1/_auth).503 unavailable: the server is at its limit of concurrent and queued requests. Wait, and then try again.504 timeout: a handler, such as a slowsend, ran longer than the request timeout. Onscreen/tree, withcode: "main_thread_blocked": the app's main thread did not start and finish the read within 5 s plus the settle time, because the app is busy or does not respond. Try again, or look for an ANR in the log.500 internal_errorwithcode: "read_failed"onscreen/tree: the read threw on the main thread, as with a View of the app whose getter throws. The message names the exception; the app goes on.405 method_not_allowed: the route takes another method;Allowlists the methods (see A method that a route does not take).404 not_found: an unknown route, missing transaction, a body that wasn't kept, orsendwith no sender configured. Also a mock rule id that no rule has, onrules/toggleandrules/delete. Also a WebSocket connection that the app cleared or evicted, and a message with no stored payload. Also everynetwork/route when the app did not register the Network tab (Unknown tab: network), everylogs/route without the Logs plugin (Unknown tab: logs), everyprefs/route without the Preferences plugin (Unknown tab: prefs), everysqlite/route without the SQLite plugin (Unknown tab: sqlite), everywork/route without the WorkManager plugin (Unknown tab: work), and everyscreen/route without the Screen plugin (Unknown tab: screen). Onsqlite/routes, also adbthat the tab does not list, and atablethat the database does not have, each with itsfield.403 forbiddenwithcode: "read_only"onprefs/edit,delete, orclear: the file is read-only.GET prefs/filessays which files are, and the app decides it inPrefsDebugTab.create(...). Onsqlite/exec,edit, ordelete, withfield: "db": the database is not writable (GET sqlite/databasessays which are; the app decides it inSqliteDb). Onsqlite/query, withfield: "sql": SQLite refused a write, becausequeryonly reads. A pragma with a value is a400withcode: "statement_refused"instead.400 bad_requestonsqlite/queryorexec:code: "statement_refused"for a statement that the tab does not run (see above), and inexecfor a statement that returns rows;code: "sqlite_error"with SQLite's message for one that SQLite can't run, such as a syntax error or a broken constraint;code: "query_unavailable"for a database that has no file forqueryto open read-only;code: "row_too_big"for a row that does not fit Android's cursor window, about 2 MB: read the value in parts withsubstr().504withcode: "read_limit"onquery, and on aGETroute of afiledatabase (GET tablesputs it in theerrorof the table whose count stopped, and answers200): the database is not in WAL mode, and a statement ran for 2 s. Read less in one statement: aLIMIT, aWHEREthat an index serves, or a smaller page without a filter.500withcode: "open_failed"on asqlite/route: the database did not open. The message has the reason, such as a file that is not there yet, a handle that the app closed, or the exception of the app's function that returns the handle.GET sqlite/databaseslists such a database witherror.500withcode: "sqlite_error": SQLite refused a statement that the tab built, such as on a corrupt file or a view whose table is gone, or a client's statement failed on the file or the device; the message is SQLite's.503on awork/route:code: "work_unsupported"when the app's WorkManager is older than 2.12.0 or missing, with the app's version in the message when the APK has WorkManager's version file (META-INF/androidx.work_work-runtime.version), which a build can leave out;code: "work_not_initialized"onitems,items/{id},cancel, andpruneuntil the app initializes WorkManager.404withcode: "metrics_off"onwork/metricswhen the app passed no work-analytics repository. No work events: checkstate.listenersandstate.reason(see WorkManager tab operations).- No log lines: check
state.readerinGET logs/entries:failedwithreaderErrorwhen logcat could not run,stoppedwhen Lustro is stopped, andstate.pausedwhen the capture is paused. Lines from other processes are never shown: the tab reads the app's own process only. - The CLI exits 3 to 6: it can't reach the app, and the error names the cause (see Exit
codes). Exit 5 says that the installed build does
not contain the Lustro runtime: a build with the
-noopartifacts, or one from before the app added Lustro. Exit 6 withno tokensays that discovery found noLustroTokenline and no token in the app's prefs (see Auth and token discovery). - Connection refused / no response: the app is in the background (the server listens only
while the app is in the foreground), or there is no
adb forward. Re-check theLustroTokenlog line for the live endpoint. A connection closed without a response can also mean the server is at its open-connection limit (concurrency + queue + 16, 96 by default); close idle connections and retry. The CLI reports both cases asconnection_failed, with a hint, and exit 6, or with the cause that adb finds, such as an app that is not running.