apalis-tui
The apalis-rtui dashboard, as a ratatui application. One codebase builds a native terminal
binary and a WebAssembly bundle from the same App and draw modules, both plain HTTP clients of
the apalis-rtui JSON API.
Most users of apalis-rtui should not add this crate to their own Cargo.toml. apalis-rtui's
ui feature already serves this crate's web build as a static asset (apalis-rtui/assets/tui-web-dist/),
built once by CI and vendored in. Reach for apalis-tui itself to run the native terminal client
or to work on the dashboard.
Features
native is a default feature, so cargo install apalis-tui builds the terminal client and asks
for no wasm toolchain. web is opt-in, needs the wasm32-unknown-unknown target, and is only ever
requested by build-web.sh. Both feature sets are additive and neither one reaches the other's
target: every web dependency lives under a cfg(target_arch = "wasm32") table and every native
dependency under cfg(not(target_arch = "wasm32")).
Architecture
Every module builds and tests on the host target with no feature enabled. There is no browser, no wasm target, and no running server in the loop:
src/
app.rs App: screens, selection state, the hit-region mouse model, the confirm dialog,
capability-gated actions. Nothing here performs I/O.
data.rs Query constants (PAGE_SIZE, STATUSES), the pure apply_* functions that fold a
fetched wire value into Data, the Compact-args decode, and the DataSource trait a
backend implements against.
theme.rs The Phosphor Slate palette and style helpers. No draw function writes a bare
Color::Rgb.
keymap.rs The keyboard reference App::key and the Help overlay both read from, so the two
cannot drift.
input.rs Backend-agnostic key/mouse event types.
hash.rs The web build's #/<screen>/<queue>/<status>/<page>/<task_id> deep-link format:
Route::parse/Route::format, no web_sys dependency, unit-tested here on the host.
draw/ One draw function per screen (overview, queues, tasks, task_detail, workers, logs,
help), plus the shared tab bar, statusline, and modal overlays in draw/mod.rs.
backend/ The web (wasm32 + ratzilla) and native (crossterm) data/event loops. Both
implement the same contract backend/mod.rs documents: a poll/SSE loop, the
pending-action drain, and the frame loop's needs_redraw gate.
App never touches the network. A backend implementation fetches data, folds it in through
data.rs's apply_* functions, drains App::take_pending_action after every input event to
perform a confirmed retry/reschedule/resume/vacuum call, and reports the result back through
App::set_toast_from_outcome. This is what keeps the whole application logic unit-testable
without a browser or a server, and what lets the native and web builds share every byte of it.
Screens
Five numbered tabs (1-5: Overview, Queues, Tasks, Workers, Logs) plus Task detail, a drill-in
state reached from three different lists (a queue's task table, the cross-queue Tasks table, or
the Overview's Attention pane), each remembered as the screen esc returns to. See app::Origin
for how a Task detail screen tracks where it came from.
The Queue screen's status tabs treat Failed and Killed as one terminal-failure family, in both
the tab count and the task list: the reference SQL backends persist Killed when attempts run
out, apalis-redis persists Failed and never writes Killed, so separate tabs would look empty
on one backend and populated on another for the same outcome.
The Tasks screen (GET /tasks) decodes each row's Compact-encoded args best-effort as UTF-8
JSON, falling back to a (binary payload, N bytes) placeholder when the bytes don't decode
(data::decode_compact_args).
Reschedule, Resume, and Vacuum are gated per queue by GET /capabilities, fetched once per
session (App::set_capabilities). A gated control stays clickable when unsupported. It shows a
muted ✗ marker in its own label and produces a toast naming the missing capability. It never
disappears or silently does nothing.
Web build
# wasm-opt from Binaryen release version_125 on PATH, or WASM_OPT=/path/to/wasm-opt
Every tool is pinned to an exact version and the script refuses any other, because CI rebuilds the
bundle with the same pins and fails the pull request when the bytes differ from the checked-in
copy. The Rust pin fixes the standard library's /rustc/<commit> path that panic locations embed,
and the script remaps the checkout and every cargo registry directory to fixed prefixes, so the
same source produces the same bytes on any machine.
This crate's rust-version is 1.90, above the workspace floor of 1.88 that the server crates keep.
The reason is ratzilla = "=0.3.1": its transitive beamterm-* dependencies declare 1.90 as their
own floor, and the web build needs them. The native build and a plain cargo check --target wasm32-unknown-unknown with no web feature have no such need, so the server crates are unaffected.
build-web.sh (docs/PLAN.md §3.3): checks the Rust toolchain, the installed wasm-bindgen-cli
version against the wasm-bindgen crate resolved in Cargo.lock (a mismatched CLI fails opaquely
inside a browser rather than at build time), and the Binaryen version; builds --release --target wasm32-unknown-unknown --features web with the path remap; runs wasm-bindgen --target web --no-typescript --out-name apalis-tui into apalis-rtui/assets/tui-web-dist/pkg/; runs
wasm-opt -Os and then tools/check-wasm-tables.py on its output; copies web/index.html to
apalis-rtui/assets/tui-web-dist/; and prints every file's raw and gzip size. This is the exact directory apalis-rtui's ui feature
include_dir!s at compile time (§2.4), so re-running this script and rebuilding apalis-rtui is
the whole update cycle; nothing else regenerates that directory.
Measured bundle size (gzip-measured, §3.3's soft budget is 500 KB gzipped total). The checked-in
bundle is built with wasm-opt -Os from Binaryen 125:
| File | Raw | Gzip |
|---|---|---|
index.html |
2.7 KB | 1.4 KB |
pkg/apalis-tui.js |
37.4 KB | 7.5 KB |
pkg/apalis-tui_bg.wasm |
816.5 KB | 320.7 KB |
| Total | 856.6 KB | 329.6 KB |
Without wasm-opt the module is 1025 KB raw and 347 KB gzipped, still inside the soft budget.
Why the Binaryen version is pinned. build-web.sh refuses any wasm-opt other than Binaryen
125 (set WASM_OPT=/path/to/wasm-opt to point at one that is not on PATH). Binaryen 108, the
version Debian and Ubuntu ship as the binaryen apt package, corrupts this module on a plain
-Os round trip: the module has two tables (a fixed funcref call table and a growable anyref
table wasm-bindgen uses for Closure/externref values), and version 108 rewrites the
__wbindgen_externrefs export to point at the wrong one. The result loads and looks fine, then the
first Closure::wrap call (run_web's first line) throws
WebAssembly.Table.grow(): failed to grow table by 4 in a real browser. Nothing on the host target
ever exercises a Closure, so cargo test -p apalis-tui stays green either way. Only tests/e2e
catches it, which is why the pin is enforced at build time and why CI's wasm-build job downloads
the same Binaryen release and diffs its output byte for byte against the checked-in bundle. As a
second guard, build-web.sh runs tools/check-wasm-tables.py after wasm-opt: it reads the
table and export sections back from the binary and fails when __wbindgen_externrefs does not
name a growable externref table, so a wrong wasm-opt cannot ship a broken module even if the
version pin is bypassed. Upstream tracked the bug as
Binaryen issue 4711, closed by pull request
4736 after release 108. Release 125 is the version verified here.
ratzilla 0.3.1 quirks (carried over from prototypes/tui-web/README.md, docs/PLAN.md §7.10)
| Quirk | Mitigation in backend/web.rs |
|---|---|
DomBackend rebuilds its #grid element (losing key/mouse listeners) on every window resize, and on the first draw when given a container id matching its own grid id. |
DomBackend::new() (parent <body>). A manual requestAnimationFrame loop instead of draw_web. Listeners re-attached after any frame where the live grid element has no tabindex. |
Backend::size() is a hardcoded 10×20-CSS-px guess, independent of the real, font-measured cell grid draw() indexes into (self.cells, sized from self.size). Frame::area() desyncs from it. |
SizedDomBackend wraps DomBackend and serves size() from window_size()'s accurate columns_rows (which does report the real self.size), re-read at the end of every draw. backend::clamp_grid floors a 0×0 reading at 1×1. |
A window resize only marks DomBackend uninitialized. It rebuilds #grid, re-measures the cell size and recomputes its grid dimensions inside the next draw() call, then indexes self.cells[y * width + x] with coordinates from a buffer Terminal::flush already diffed against the previous reading. A resize that shrinks the grid panics there (dom.rs:321, index out of bounds), and panic = "abort" kills the tab. |
SizedDomBackend::draw splits every draw in two: an empty first pass lets DomBackend rebuild and re-measure with nothing to index, window_size() then reports the grid that exists, and the content is filtered against it before the second pass paints. The wrapper also reports the rebuild so the frame loop calls Terminal::clear once, since a rebuilt grid is blank and a diffing Terminal would not repaint it when the new grid measures the same as the old. set_cursor_position drops an out-of-grid position for the same reason. tests/resize.rs covers the host-target half. |
Key events are delivered to the grid element (tabindex=0), not window. |
The host page focuses it once it exists and refocuses after resizes/clicks (web/index.html's script). |
critical-section (transitive, via ratatui-core) needs its std feature on wasm32 or the module import fails at instantiation. |
critical-section = { version = "1", features = ["std"] } pinned explicitly (root Cargo.toml). |
No scroll-wheel MouseEventKind variant in 0.3.1. |
j/k/paging cover long lists, same as the spike. |
No web font is loaded (§5.8: system monospace stack only), so there is no font-load race to wait out before the first cell measurement, unlike the spike's document.fonts.load. |
A simplification. Not a workaround. |
Native build
--api defaults to http://127.0.0.1:8080/api/v1. APALIS_TUI_API sets it from the
environment instead. The flag wins when both are given (docs/PLAN.md §3.4). --screen
(overview/queues/tasks/workers/logs), --queue, and --status seed the initial screen
and selection, the CLI equivalent of the web build's #/… hash routes (§3.7) since a terminal has
no address bar to carry that state instead. q or ctrl-c quits. Both are read directly by the
event loop, not by App::key, since keymap.rs only ever binds q to close the Help overlay.
backend/native.rs is backend/web.rs's direct counterpart: same data flow, same poll cadence
(200ms scoped / 2000ms full, or immediately when App::dirty is set), same SSE reconnect, ported
from gloo-net/ratzilla/wasm_bindgen_futures::spawn_local to reqwest/crossterm/
tokio::spawn. App is shared as Arc<Mutex<App>> (web's Rc<RefCell<App>> mirrored for a
backend whose poll loop, two SSE loops, and action calls are real OS-thread-parallel tokio tasks,
not single-threaded JS callbacks). Every critical section on it is a few synchronous field reads or
an apply_* fold, never spanning an .await, so a plain std::sync::Mutex is enough.
Two behaviors are native-only, both documented at their definition:
- The double-click shim (
docs/PLAN.md§3.5):crosstermreports rawDown/Upmouse events with no click concept of its own, unlikeratzilla'sSingleClick/DoubleClick. ADown+Uppair on the same cell and button becomes aSingleClick. A second such pair within 400ms of the first becomes aDoubleClick.backend::native'sClickTrackeris the whole mechanism, unit-tested against syntheticInstants (not real time) for the timing and the same-cell/same-button conditions. RawJson's clipboard fallback (§7.5):Action::RawJson(huge task args' escape hatch) already echoes the raw-route URL in a toast on every non-wasm32 target,App::act's own job vialib.rs'scrate::copy_to_clipboard(currently a no-op there on native). A real system clipboard write (arboard, or shelling out toxclip/wl-copy/pbcopy) is alib.rs-owned enhancement, since that function lives outsidebackend::native. The toast already shows the full URL either way, so a user can select and copy it from the terminal without a programmatic clipboard write.
Terminal state (raw mode, the alternate screen, mouse capture) is restored on every exit path: a
clean q/ctrl-c, a transport error unwinding out of run, and a panic (a std::panic hook
installed before entering raw mode runs the same restore before the default hook prints). An RAII
guard (TerminalGuard) backs the same restore for the ordinary early-return case.
Tests
tests/support/mod.rs: shared, deterministic fixtures (a fixed clock, fixed task ids, no wall-clock reads or ULIDs generated at test time).tests/screens.rs: renders every screen withratatui::backend::TestBackendat two viewport sizes and snapshots the buffer as text viainsta.tests/mouse.rs: after drawing a screen, asserts the hit-region model:App::hit_atresolves to the documented action, andApp::mouseperforms it, including through modal layers.tests/keys.rs: a table-driven keymap test, plus a consistency check that every binding inkeymap::{NAVIGATION, ACTIONS}appears in the rendered Help overlay.tests/resize.rs: the size sweep. Every screen, dialog and overlay drawn at every width from 1 to 200 and a spread of heights, a size change between two frames on oneApp, and clicks on hit regions recorded at a larger size. Nothing may panic. About three minutes in a debug build, the slowest test in the crate.tests/parity.rs(docs/PLAN.md§5.11, gated on the defaultnativefeature): the sametests/supportfixtures through the samedraw_*functions astests/screens.rs, asserted against the exact same committed.snapfiles (aninsta::Settingsoverride turns off the module-name prefix insta would otherwise add, so both files write and checktests/snapshots/screens__….snap).App/drawtake no backend-specific type, so nothing here can actually differ fromscreens.rs's own run. The real check is the compile step itself (drawandbackend::nativecompiling together) plus this assertion catching a stray#[cfg(feature = "native")]insidedrawthe day one ever creeps in.
To update snapshots after an intentional rendering change: cargo insta review, or
INSTA_UPDATE=always cargo test -p apalis-tui to accept them all and a plain cargo test to
confirm they now pass. That run also covers tests/parity.rs and backend::native's own unit
tests, since native is a default feature (the double-click shim's timing, the
crossterm-to-crate::KeyCode translation table, and the SSE byte-stream parser), which need
backend::native's module-private types and so live in its own #[cfg(test)] mod tests rather
than in tests/parity.rs (an integration-test binary sees only this crate's pub surface).
Browser e2e (tests/e2e/, docs/TESTING.md §2.5)
tests/screens.rs/mouse.rs/keys.rs above prove App/draw render and react to input
correctly against a synthetic TestBackend. No browser, no DOM, no real HTTP call is in that
loop, so a regression in backend/web.rs itself (a ratzilla DomBackend quirk, the wasm
bundle's gloo-net/EventSource calls landing on the wrong route, hash routing round-tripping
through a real address bar) would slip through untested. tests/e2e/ closes that gap: a
Node/Playwright driver boots the real apalis-rtui/examples/custom-backend-dashboard.rs server
(the in-memory CustomBackend double, no database) and drives the real, already-built
apalis-rtui/assets/tui-web-dist/ wasm bundle in headless Chromium with real mouse clicks and
real key presses, asserting on rendered grid text, never a screenshot.
&&
See tests/e2e/README.md for the full flow (the walk, mouse-only and keyboard-only modality
checks, capability gating, deep links, and the redraw-only-on-change DOM-mutation count) and its
prerequisites.
The friction loop, if a test run surfaces one, looks like this: npm test fails on a grid-text
assertion, the error names the exact string expected and what was seen, apalis-rtui/examples/ custom-backend-dashboard.rs's own stdout/stderr (captured by tests/e2e/lib/server.mjs and
included in a startup-timeout error) shows what the server actually did, and the failing test's
own screen/action sequence in tests/e2e/test/*.test.mjs reads as plain steps, so the next run
after a fix is npm test again, not a fresh investigation from scratch.
Changes from the prototypes/tui-web spike
The spike's tab 3 recalled whatever single task was currently open. It never called GET /tasks.
This crate implements the real cross-queue Tasks screen instead. Task detail becomes a pure
drill-in state reached from three lists, and tab 3 goes to the real Tasks table.
The spike hard-coded every Reschedule/Resume toast to the same string, since no published backend
implements either trait. This crate reads GET /capabilities and gates each control per queue, so
a deployment against a backend that does implement them sees a working control, not a permanent
toast.
The spike's Retry action computed a PUT /queues/{queue}/tasks push client-side. This crate calls
POST /queues/{queue}/tasks/{task_id}/retry (or the bulk route for a multi-selection) and labels
the result by the response's ActionOutcome mode, so the toast never claims a reschedule happened
when the backend actually pushed a new task.
The Worker screen's layers-chip vocabulary gained four entries: CircuitBreaker, LongRunning,
EventListener, Parallelize.
The confirm dialog clears the hit regions under it before drawing its own buttons, as
docs/PLAN.md §3.5 asks, but the Help overlay gates activation in App::act instead of clearing:
the overlay is read-only and closes on a click anywhere, so leaving the regions under it
registered is what lets a click land at all, and one refusal in act covers every screen without
depending on which draw function ran last.
A needs_redraw flag on App, set by every state-changing method, lets a frame loop skip
terminal.draw() on a frame where nothing changed, instead of redrawing on every animation frame
regardless of whether anything is different. backend/web.rs reads it exactly this way.
The spike had no hash routing at all (docs/PLAN.md §3.7 is new to this plan). hash.rs's
Route/RouteScreen and backend/web.rs's hashchange listener add #/<screen>/… deep links,
History::push_state/replace_state, and page-load seeding, none of which the spike attempted.
The spike trusted DomBackend::size() directly. backend/web.rs's SizedDomBackend does not
(§7.10): it sources Frame::area() from window_size()'s accurate reading, and it filters every
cell it forwards against the grid DomBackend has just rebuilt, so a resize cannot hand
DomBackend::draw a coordinate past its own cell vector. tests/resize.rs is the host-target
half of the same guarantee: every screen, dialog and overlay drawn at every width from 1 to 200
and a spread of heights down to a single row.
data.rs's DataSource trait, as written, is synchronous (fn overview(&self) -> Result<...>).
A browser cannot serve a real network fetch synchronously, so backend/web.rs does not implement
it: it performs its own async gloo-net calls directly and folds results through the same
apply_* functions DataSource's doc comment names, which is what actually keeps native and web
sharing that fold logic. backend/native.rs does not implement it either, and for the same
reason: it chose an async, tokio-driven reqwest::Client over a blocking one (both were open
options, docs/PLAN.md §3.1), so a reqwest::blocking::Client implementing DataSource literally
remains open for a future backend that wants exactly that shape instead.
License
Licensed under either of Apache License, Version 2.0 or the MIT license at your option.