Custom tabs¶
DebugTab is the only public extension point for adding a tab. Other public types, such as
Redactor, MockRuleStorage, and the sink from Lustro.networkCaptureSink(), change how the
Network tab works, but they add no tab. A tab must have an id, a title, and an icon. All the
other members have a default, such as routes(routes) for the JSON routes and renderContent()
for the HTML view. A tab without a view is valid: agents and scripts use its routes.
The id is the part of the routes after /api/v1/. Two rules apply to it:
- It must match
[a-z][a-z0-9-]{0,30}.Lustro.Builder.addTab()throws anIllegalArgumentExceptionat once for an id that does not match. - It must be different from the id of every other tab. The builder does not check this. Then
start()finds two tabs with the same id, does not open the server, logs the warningFailed to arm the debug serverat theLustrotag, with an exception whose message isDuplicate debug tab id '<id>', and returnsLustroStatus.DISABLED. It does not throw. The ids of Lustro's own tabs arenetwork,logs,prefs,sqlite,work, andscreen, so do not use them.
A tab is your code, and it reads your app's internals, so put it in src/debug. The release build
fails on a DebugTab subclass in src/main or src/release: see
Release safety. Write a tab builds
a complete tab step by step.
@OptIn(ExperimentalDebugRoutes::class)
class FlagsTab(private val flags: FeatureFlagRepository) : DebugTab() {
override val id = "flags"
override val title = "Feature Flags"
override val icon = "🚩"
override fun renderContent() = """<div id="flags-list"></div>"""
// GET /api/v1/flags/list. Another method gets 405, another path 404, and anything
// thrown, even TODO(), an enveloped 500 (it never escapes into your app).
override fun routes(routes: DebugRoutes) {
routes.version = "1.0"
routes.get("list") {
summary = "The flags."
handle { DebugResponse.ok(flags.toJson()) }
}
}
}
Register it with the other tabs:
Lustro.builder(application)
.addTab(NetworkDebugTab.create(senderClient = client))
.addTab(FlagsTab(flagsRepo))
.build()
Declared routes¶
A tab declares its routes in routes(routes): for each route, its method, its path, its
parameters and body, its response, and its handler. Lustro routes each request, checks its
parameters, and makes the tab's OpenAPI document from the same declarations, so the routes and
the document can't drift apart, and GET /api/v1/_meta lists the tab.
@OptIn(ExperimentalDebugRoutes::class)
override fun routes(routes: DebugRoutes) {
routes.version = "1.0" // the info.version of the document; change it when a route changes
routes.get("items/{id}") {
summary = "One item."
val id = path.long("id")
val full = query.boolean("full").withDefault(false)
errors(404)
handle { call -> item(call[id], call[full]) }
}
routes.post("toggle") {
acceptsForm = true // also id=... from curl -d
val id = body.string("id") { minLength = 1 }.required()
handle { call -> toggle(call[id]) }
}
}
- The API needs an opt-in. Its shape can still change in a way that breaks the code that
uses it, so it is marked
@ExperimentalDebugRoutes, and the compiler stops a tab without@OptIn(ExperimentalDebugRoutes::class). It is a Kotlin API: Java is not a target. - Parameters.
path,query, andbodydeclare them, as astring,int,long, orboolean. The query and the body also takedouble, a decimal such as0.35, for a threshold or a ratio: the router refusesNaN, the infinities, and text that is not a JSON number, such as0x1p3. A body also takesjson, which gives the handler the value's JSON text: use it for an object, or for a field that takes more than one JSON type, such as the SQLite tab'srowid, a whole number or a string of one, and describe it withschema. In the query and the body,stringsdeclares a parameter that the request can repeat, such as?ids=a&ids=b: its value is the list of every value, and in a JSON body a JSON array of strings. Each returns a handle, and the handler reads the value with it:call[id]. A parameter is optional (nullwhen absent) until.required()or.withDefault(value). Options:description,minLength,maxLength, andvaluesfor a string,minandmaxfor a number (aLongfor an int or a long, aDoublefor a double), andschema, a JSON Schema that describes it in the document in place of the one made from its type, such asDebugRoutes.ref("Store"). - Empty values. In the query or a form, an empty int, long, double, or boolean takes its default,
and without a default gets a
400:?since=usually comes from a variable with no value. An empty string is a string, whichminLength = 1andvaluesrefuse. - Paths. A path is relative to the tab, such as
items/{id}. The path""declares a route at the tab root,/api/v1/<tab id>, such asroutes.get("")to list a collection androutes.post("")to add to it. Its path in the document is/api/v1/<tab id>, and its405names the tab alone, such asjournals takes GET or POST, not PUT. Its defaultoperationIdis the method andRoot, such asgetRoot. The router ignores one slash at the end of a request's path, soPOST /api/v1/<tab id>/seed/reaches the routeseed. A path with two slashes at the end, such asseed//, gets404. - Path parameters. For the route's own method, a segment that its parameter does not take,
such as
items/xfor apath.long("id")or a value outsidevalues, matches no route, so the client gets404, as for an id that names nothing. The router checks the method before the path parameters, so another method gets405with anAllowheader: withroutes.get(""),routes.post(""), androutes.delete("{id}")withpath.int("id"),DELETE journals/abcgets404, butGET journals/abcgets405,Allow: DELETE, andjournals/abc takes DELETE, not GET. - Bodies. Body fields come from a JSON object in strict JSON (RFC 8259), with strict JSON
types, and
nullcounts as absent. WithacceptsForm = true, a route also takes them as anapplication/x-www-form-urlencodedform. A route with a required field gets a400for an empty body. For a body that is not a set of fields, such as an uploaded file, userawBody(contentType, schema)and readcall.request.bodyin the handler. - Answers. A path that no route declares gets
404. A declared path with another method gets405 method_not_allowedwith anAllowheader. A missing or wrong query parameter or body field gets400 bad_requestwith the parameter's name infield, and the message says what the request gave, and a body that is not a JSON object getsfield: "body". For an error that depends on data, such as an unknown id, the handler returnsDebugResponse.error(...), or a helper deep in its code throwsDebugResponseException(response). The server answers that exception for a tab that routes by hand too. - The document. It has the paths, methods, parameters, bodies, and responses, the shared
ErrorEnvelope, and the descriptions:summary,description,bodyDescription, and the parameters'description.response(description, schema)adds the success response's JSON Schema, and a block after it describes a body that is not JSON, such asresponse("The file.") { content("image/png"); header("Content-Disposition", "attachment.") }. The success response is200;statusin the block names another success status, from200to299, such asresponse("The new item.", schema) { status = 201 }, and the handler answers it withDebugResponse.ok(json, status = 201). Nothing compares the declared status with the status that the handler answers: a handler that answersDebugResponse.ok(json)sends200while the document says201. Use one constant for both, and check the status in a unit test that callstab.handle(). A204or205has no body, so it declares no schema, and its handler answersDebugResponse.ok("", status = 204).component(name, schema)adds a schema undercomponents/schemas, andDebugRoutes.ref(name)refers to it; a$refcan also point into one, such as#/components/schemas/Envelope/properties/state.errors(404, 409)lists the error statuses that the handler answers; the document already lists400when the router can refuse a query parameter or the body, and404for a path parameter that does not take every segment. - Your own document or routing. Override
schema()to give your own document; the declared routes still route.super.schema()gives the generated one, to change. Overridehandle()to route some paths by hand, and callsuper.handle(request)for the declared ones. - Mistakes. A mistake in the declarations, such as a path parameter that the route does not
declare, two routes with the same method and path, a schema that is not valid JSON, or a
missing
version, throwsIllegalStateExceptionfrom the firsthandle()orschema()call. A unit test that callstab.schema()finds it. The server then leaves the tab out of_metaand answers its routes with500. - Release builds.
routes()runs only when the runtime callshandle()orschema()for the first time, never in a no-op build, and the declarations need no reflection and no keep rules.
Asset and rendering conventions:
- Static assets live at
assets/lustro/<id>.{js,css,openapi.json}and are resolved by id at runtime. Returning non-empty strings fromrenderScript()/renderStyles()overrides the static.js/.css; returning a non-nullschema()overrides the static.openapi.json. A tab that declares its routes inroutes()needs no.openapi.json: its defaultschema()returns the document of the declarations. - The console loads the tab's JS as an external script after
shared.js(CSP:script-src 'self'). Usedata-actionattributes and one event listener on a parent element. Do not use inlineonclickhandlers or<script>elements. Send data withfetch(), not with an HTML<form>: the CSP setsform-action 'none'. - Escape every value you render.
String.escapeHtml()makes a value safe as HTML text and inside a quoted attribute; the browser-sidedebugEscapeHtml(text)does the same in tab JS. Anything the app stores or a request carries is untrusted input to your tab. - Use the console's styles. Every tab page loads
shared.css, the console's design system. It has design tokens (surfaces, text colors, and the colors of methods, statuses, log levels, and categories, in the dark and the light theme) and the.dc-*components. A tab that uses them looks like the console in both themes, without CSS of its own. The custom tab styleguide gives the rules, and the sample's flags tab is a working example. - A tab that routes by hand in
handle(request)returnsnullfor a method that a route does not take, as for a route that the tab does not have. When the tab's OpenAPI document declares the path with other methods, the client gets a405with anAllowheader that lists them, and otherwise a404. The server reads the document's paths as the declared routes do: the path/api/v1/<tab id>is the tab root, which the tab gets as the path"", and one slash at the end of a path does not count. The tab itself gets the path as the request gave it, such asseed/, so a tab with a document treats one slash at the end as no slash, as the declared routes do. OtherwisePOST items/gets a405that namesGET, and thenGET items/gets404. - Make the responses with the
DebugResponsefactories (ok,json { ... },text,bytes,notFound,error).error(message, status)gives the error envelope, and itserrortype 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), anderrorfor any other status. - A tab that routes by hand reads a JSON body with
request.bodyAsString(). For anapplication/x-www-form-urlencodedbody, ascurl -d key=valueand old clients send it,request.formParams()gives each name with its values, decoded as the query parameters are. It is empty for another content type. Unlikeorg.json, it needs no Robolectric in a JVM unit test. - For a list that clients poll,
DebugResponse.cursorEnvelope(currentSequence, clientCursor) { /* items */ }gives the cursor envelope'sreset,unchanged, anddeltaanswers, and usesCursorCodecfor the opaque cursors, so a tab does not write that code itself. Increase the sequence only when the list changes, because each increase sends the whole list again. Put the other values that clients poll in itsstate. For a list that only grows at its end, such as a log,DebugResponse.streamEnvelope(...)gives the stream envelope: a poll gets only the entries after its cursor. - Make every cursor with these helpers, also a tab's own
sinceor page cursor. A page keeps its cursor when the app restarts, and sends it again. A cursor of the helpers carries the epoch of the process, so a cursor from before the restart is foreign and gets areset. A tab that sends its own sequence number, such as?since=42, gets the old number from the page, while the new process counts from 1 again: the page then skips the new process's first 42 items.cursorEnvelopeandstreamEnvelopepick the epoch once for each process; a store that the app can make again within one process passes its ownepoch, made when it is created. - Change state only on
POST,PUT,PATCH, orDELETE, never onGETorHEAD. The runtime rejects browser requests from other origins on every method, but for aGETorHEADit can go only bySec-Fetch-Site, which browsers send only to loopback and HTTPS addresses, and older ones not at all. Without that header, an<img>on a page from another port of the same host sends aGETthe runtime can't tell from the console's own, and it carries the console's cookie, since cookies aren't isolated by port. handle()runs off the main thread, and the calls can run at the same time. Keep the tab's mutable state thread-safe. Blocking I/O is permitted: the runtime stops each request at its timeout.- When a request times out, the client gets a
504and the runtime cancels the request:request.isCancelledturnstrue, actions registered withrequest.onCancel { ... }run, and the handler's thread is interrupted. UseonCancelto abort blocking calls that ignore interrupts, such as cancelling theCancellationSignalpassed toSQLiteDatabase.rawQueryor an OkHttpCall. A handler that ignores cancellation keeps its concurrency slot until it returns. For work that takes longer than the timeout, see Long work. - Give the tab an OpenAPI document, so that agents find it.
/api/v1/_metalists only the tabs that have one: the document of the declared routes, a staticassets/lustro/<id>.openapi.json, or aschema()that returns one. A tab without a document works in the console, but agents do not see it in_meta. The document declares each query parameter that a route reads ("in": "query"): the server names every other one in aLustro-Warningresponse header, and the CLI prints it.
Headless tabs¶
A tab with showInTabBar = false is headless: it has routes, and no page. It has no link in the
tab bar, and /tab/<id> answers 404, as for an unknown tab. Its routes, its _schema, and its
_view.js and _view.css work. A headless tab must still set title and icon, because they
are abstract. GET /api/v1/_meta lists the title when the tab has an OpenAPI document, so give
it a name that tells an agent what the routes are for. Nothing shows the icon, so any value,
such as "", works.
Long work¶
The server answers a request that runs longer than requestTimeoutMs, 30 s by default, with a
504, and cancels it. For work that takes longer, such as seeding hundreds of items or labeling a
photo library, do not make the request wait for it. Use two routes:
POST startstarts the work on a thread or a coroutine of the tab, and answers at once with an id for the job, such as{"jobId":"7"}. When a job is already running and the tab runs one at a time, answer409(DebugResponse.error(message, status = 409)gives theconflicttype).GET jobs/<id>reports the progress, and the result when the job is done, such as{"state":"running","done":120,"total":500}. The console polls it withdebugPoll, and an agent polls it withlustro api GET <tab>/jobs/<id>.
The job runs outside the request, so the server does not cancel it, and it does not hold a concurrency slot. Keep the jobs in the tab, give each one a way to stop, and drop old jobs so that they do not stay in memory.
maxRequestBodyBytes and requestTimeoutMs are global: they apply to every tab. A tab that needs
a larger body or a longer timeout raises the value in DebugConfig for the whole server (see
Configuration). The server holds at most
maxConcurrentRequests x maxRequestBodyBytes of request bodies in memory at a time, so a
larger body limit also raises that bound.
The console's helpers¶
The tab's script runs after shared.js, which gives these helpers:
debugPoll(urlOrFunction, intervalMs, callback, options)polls a route, and shows the connection state in the top bar.options.onConnectionChange(connected)runs when the state changes:trueat the first answer and at the first answer after a lost connection, andfalseafter three failed polls in a row. Use it to disable a form or show that the app is gone.options.onRejected(status, envelope)gets a response that is not2xx, and returnstruewhen it handled it. The fourth argument can also beonRejecteditself, as before. The result hasstop().debugFetch(url, options)rejects on a status that is not2xx, witherr.statusanderr.response.debugErrorMessage(err)gives a Promise of the text to show: themessageof the error envelope, or elseerr.message.- The status pill in the top bar shows whether the console reaches the app.
debugFetchsets "Live" at each answer of the app, also at an error answer such as a400or a409: the app answered, and the tab shows the error next to its action.debugPollsets "Live" at each answer that it counts as connected: a2xx, or a rejection thatonRejectedhandled. "Error" means that a request ofdebugFetchgot no answer, that three polls in a row failed, or that the app answered401. The tab does nothing for the pill. - A
401answer to either one shows the console's "Signed out" notice above the tab's content, and the next2xxanswer removes it. The tab does nothing for it. debugModal(id, { onHide })shows and hides a.dc-modal-scrimof the tab's markup.onHideruns each time the dialog is hidden: byhide(), by Escape, or by a click on the scrim. Use it to clear the state of the dialog, such as the id of the item being edited.debugEscapeHtml(text),debugToast(message, type),lustroApiUrl(path), andlustroOnContentReady(fn): see Write a tab.