web: Keep pages current with Server-Sent Events
CI / Check (pull_request) Successful in 5m43s

Pages polled `/api/version` every three seconds and then fetched the
pending list. Now each page follows one stream from `/events`: the
pending list when the queue changes and the running requests on the
main page, and a request's state and progress on its own page, which
reloads when the request is answered or finishes. The stream starts
with the current state, so a page catches up when the browser
reconnects, and it ends when the approver signs out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jackos1998andClaude Opus 5.5 committed 2026-11-28 22:28:14 +00:00
1 parent 5ad4307626
commit ebba93b685
8 files changed
+286 -130

No files matched your search

+4 -5
View File
@@ -106,10 +106,9 @@ a time: the build, then a copy, comparison and activation for each node, or the
- `runs::Runs` keeps the latest progress of each phase of requests that build, from the build on;
`exec::Output` records each `Progress` message it carries for a tracked request. The web app reads
it, and the request's `finished` or `failed` audit event keeps its phases.
- The web app streams a request's panel (`templates/progress.html`) from `/requests/<id>/events`
and the running list (`templates/running.html`) from `/running/events`, as Server-Sent Events of
rendered HTML that `app.js` swaps in. The bars are `<progress>` elements, since the content
security policy allows no inline styles.
- The web app shows a request's panel (`templates/progress.html`) and the running list
(`templates/running.html`), sent as they change on the page's event stream (`web/events.rs`).
The bars are `<progress>` elements, since the content security policy allows no inline styles.
- `slop` shows it with `Board`: on a terminal, a bar for each running phase, redrawn in place
below other output; otherwise plain lines, every 30 seconds for a running phase and when one
ends, for agents. It holds nothing but a read-only Git key.
@@ -169,7 +168,7 @@ What each request runs, and whose code, decides whether it needs an approval fir
| `src/bin/slop-broker.rs` | Daemon (`serve`); `slop-approve` when run under that name |
| `src/bin/slop.rs` | Agent client; `slop guide` prints `slop-tools.md` |
| `tests/broker.rs` | Handler tests over an in-memory duplex stream with a fake `ssh` |
| `src/web/` | The approvals web app: routes (`mod.rs`), OIDC sign-in and passkey confirmation (`auth.rs`), Web Push (`push.rs`), the audit log by request (`history.rs`), the pages (`page.rs`) and static assets |
| `src/web/` | The approvals web app: routes (`mod.rs`), each page's Server-Sent Events (`events.rs`), OIDC sign-in and passkey confirmation (`auth.rs`), Web Push (`push.rs`), the audit log by request (`history.rs`), the pages (`page.rs`) and static assets |
| `templates/`, `askama.toml` | The web app's HTML, as [askama](https://askama.rs) templates compiled into the broker; `askama.toml` passes everything they show through `ops::printable` before escaping it |
| `nix/` | The package, NixOS modules (`modules/nixos`), home-manager module (`modules/home-manager`), the VM test (`vm-test.nix`, `checks.<system>.vm`), clippy and rustfmt checks (`lints.nix`) and the demo's VMs and repository template (`demo/`, `packages.<system>.demo` and `demo-box`) |
| `devenv.nix` | The development environment, its scripts and the demo's host side (`devenv up`); `nix develop` gives a plainer shell from `flake.nix` without them |
+7 -3
View File
@@ -233,7 +233,7 @@ on a desktop shows what `slop-approve` can only print.
building now) and a row for each node: copying, comparing, ready, activating, done or
failed, with its copy's bar and how long it's taken.
- The pending page lists running requests with one bar each.
- Pages get updates as Server-Sent Events; without JavaScript, a reload shows the latest.
- Without JavaScript, a reload shows the latest.
- Once a request finishes, its page and the audit log keep how each phase ended, such as
`built: 12 derivations in 4m 10s`.
- **Audit log.** The log page groups the audit file by request: who asked, what, the outcome and
@@ -242,8 +242,12 @@ on a desktop shows what `slop-approve` can only print.
- Each request's page shows its full timeline, including the detail approvers saw, so a
notification for a request that's since been answered still leads somewhere useful.
- **Front end.** Server-rendered HTML that works without JavaScript.
- A small script refreshes the list, follows progress and manages notifications, and a service
worker shows them.
- A small script keeps the page current and manages notifications, and a service worker shows
them.
- Each open page follows one stream of Server-Sent Events, which carries the new pending list as
the queue changes, the running requests and a request's progress, as HTML to swap in. It
starts with the current state, so a page that lost its connection catches up when the browser
reconnects.
- Everything shown passes through the same filter as `slop-approve` for control and
bidirectional characters.
- A strict content security policy allows only the app's own scripts.
+36 -42
View File
@@ -25,31 +25,46 @@ setInterval(() => {
}
}, 1000);
// Polls for changes to the pending set while the page is visible.
async function refresh() {
const pending = document.getElementById("pending");
const request = document.getElementById("request");
const container = pending || request;
if (!container || document.hidden) return;
const response = await fetch("/api/version", { credentials: "same-origin" });
if (response.status === 401) return location.reload();
if (!response.ok) return;
const { version } = await response.json();
if (String(version) === container.dataset.version) return;
if (request) return location.reload();
// Swap in the new list, keeping open details open.
// Swaps in a new pending list, keeping open details open.
function showPending(pending, html) {
const open = new Set([...pending.querySelectorAll("article details[open]")].map((d) => d.closest("article").id));
const fragment = await fetch("/pending", { credentials: "same-origin" });
if (!fragment.ok) return;
pending.innerHTML = await fragment.text();
pending.dataset.version = String(version);
pending.innerHTML = html;
for (const id of open) document.getElementById(id)?.querySelector("details")?.setAttribute("open", "");
startCountdowns(pending);
}
// Follows the broker's events for this page: the pending and running requests on the main page;
// a request's progress on its own page, which reloads when the request is answered or finishes.
function listen() {
const pending = document.getElementById("pending");
const request = document.getElementById("request");
if ((!pending && !request) || !("EventSource" in window)) return;
const path = request ? `/events?request=${encodeURIComponent(request.dataset.id)}` : "/events";
const source = new EventSource(path);
source.addEventListener("pending", (event) => showPending(pending, event.data));
source.addEventListener("running", (event) => {
const running = document.getElementById("running");
if (running) running.innerHTML = event.data;
});
source.addEventListener("progress", (event) => {
const progress = document.getElementById("progress");
if (progress) progress.innerHTML = event.data;
});
source.addEventListener("state", (event) => {
if (event.data !== request.dataset.state) location.reload();
});
// Signed out: reloading leads to signing in again.
source.addEventListener("signed-out", () => {
source.close();
location.reload();
});
// The browser reconnects by itself, unless the broker refused; then start again later.
source.addEventListener("error", () => {
if (source.readyState === EventSource.CLOSED) setTimeout(() => location.reload(), 30000);
});
}
function base64urlToBytes(text) {
const base64 = text.replace(/-/g, "+").replace(/_/g, "/");
const binary = atob(base64 + "=".repeat((4 - (base64.length % 4)) % 4));
@@ -128,28 +143,7 @@ function localTimes(root) {
}
}
// Progress of running requests, pushed by the broker as HTML to swap in.
function follow(path, element, ended) {
if (!element || !("EventSource" in window)) return;
const source = new EventSource(path, { withCredentials: true });
source.addEventListener("update", (event) => {
element.innerHTML = event.data;
});
source.addEventListener("end", () => {
source.close();
if (ended) ended();
});
}
const progress = document.getElementById("progress");
if (progress) {
// Once it's finished, the page shows how it ended.
follow(`/requests/${encodeURIComponent(progress.dataset.id)}/events`, progress, () => location.reload());
}
follow("/running/events", document.getElementById("running"));
localTimes(document);
startCountdowns(document);
setInterval(() => refresh().catch(() => {}), 3000);
document.addEventListener("visibilitychange", () => refresh().catch(() => {}));
listen();
setUpPush().catch(() => {});
+211
View File
@@ -0,0 +1,211 @@
//! Keeps open pages current with one stream of Server-Sent Events each, carrying HTML the page
//! script swaps in.
//!
//! - The main page gets `pending` (the pending requests and leases) when the queue changes, and
//! `running` (the running requests) when they change.
//! - A request's page gets `state` (whether it's pending or running; the page reloads when that
//! differs from what it showed) and `progress` (its progress panel) while it runs.
//!
//! Each event comes when the stream starts too, so a page catches up after reconnecting.
use std::collections::HashMap;
use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, Instant};
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::response::{IntoResponse, Response};
use futures_util::StreamExt;
use tokio::sync::watch;
use tower_sessions::Session;
use super::{User, page};
use crate::server::Broker;
/// How often a page gets updates at most.
const INTERVAL: Duration = Duration::from_secs(1);
/// What a request's page shows of it, like `pending running`; the page reloads when it changes.
pub fn request_state(broker: &Broker, id: &str) -> String {
let pending = broker.queue.list().iter().any(|e| e.id == id);
let running = broker.runs.get(id).is_some();
[(pending, "pending"), (running, "running")]
.iter()
.filter(|(on, _)| *on)
.map(|(_, n)| *n)
.collect::<Vec<_>>()
.join(" ")
}
/// The signed-in approver's CSRF token, or `None` once they've signed out.
type SignedIn = Box<dyn FnMut() -> Pin<Box<dyn Future<Output = Option<String>> + Send>> + Send>;
struct Updates {
broker: Arc<Broker>,
signed_in: SignedIn,
/// The request whose page it is, or none for the main page.
request: Option<String>,
queue: watch::Receiver<u64>,
runs: watch::Receiver<u64>,
/// What each event last carried.
sent: HashMap<&'static str, String>,
last: Option<Instant>,
ended: bool,
}
pub fn stream(broker: Arc<Broker>, session: Session, request: Option<String>) -> Response {
let signed_in: SignedIn = Box::new(move || {
let session = session.clone();
Box::pin(async move { session.get::<User>(super::USER).await.ok().flatten().map(|user| user.csrf) })
});
let updates = Updates::new(broker, signed_in, request);
let events = futures_util::stream::unfold(updates, |mut updates| async move {
let events = updates.next().await?;
Some((events, updates))
})
.flat_map(|events| {
let events =
events.into_iter().map(|(name, data)| Ok::<_, Infallible>(Event::default().event(name).data(data)));
futures_util::stream::iter(events)
});
let mut response = Sse::new(events).keep_alive(KeepAlive::default()).into_response();
// Proxies such as nginx would otherwise hold events back.
response.headers_mut().insert("x-accel-buffering", axum::http::HeaderValue::from_static("no"));
response
}
impl Updates {
fn new(broker: Arc<Broker>, signed_in: SignedIn, request: Option<String>) -> Updates {
let (queue, runs) = (broker.queue.subscribe(), broker.runs.subscribe());
Updates { broker, signed_in, request, queue, runs, sent: HashMap::new(), last: None, ended: false }
}
/// The next events, as names and data, once something changes; `None` ends the stream.
async fn next(&mut self) -> Option<Vec<(&'static str, String)>> {
if self.ended {
return None;
}
// Everything at first, then what changed
let mut queue_changed = self.last.is_none();
if let Some(last) = self.last {
queue_changed = tokio::select! {
changed = self.queue.changed() => changed.map(|()| true).ok()?,
changed = self.runs.changed() => changed.map(|()| false).ok()?,
};
tokio::time::sleep(INTERVAL.saturating_sub(last.elapsed())).await;
}
self.last = Some(Instant::now());
queue_changed |= self.queue.has_changed().unwrap_or(false);
self.queue.borrow_and_update();
self.runs.borrow_and_update();
// Signing out, or the session expiring, ends it.
let Some(csrf) = (self.signed_in)().await else {
self.ended = true;
return Some(vec![("signed-out", String::new())]);
};
let mut events = Vec::new();
match self.request.clone() {
None => {
if queue_changed {
let entries = self.broker.queue.list();
let leases = self.broker.queue.all_leases();
events.extend(self.event("pending", page::pending(&csrf, &entries, &leases).0));
}
let running = page::running_list(&self.broker.runs.list());
events.extend(self.event("running", running));
}
Some(id) => {
events.extend(self.event("state", request_state(&self.broker, &id)));
if let Some(run) = self.broker.runs.get(&id) {
events.extend(self.event("progress", page::panel(&run)));
}
}
}
Some(events)
}
/// An event, unless it would repeat the last one of its kind.
fn event(&mut self, name: &'static str, data: String) -> Option<(&'static str, String)> {
if self.sent.get(name) == Some(&data) {
return None;
}
self.sent.insert(name, data.clone());
Some((name, data))
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, Ordering};
use super::*;
use crate::progress::{Counts, Phase, Progress, State};
fn broker() -> Arc<Broker> {
let config = serde_json::from_value(serde_json::json!({
"requesters": {},
"policies": {},
"approve_socket": "/unused",
"approver_group": "root",
}))
.unwrap();
Arc::new(Broker::new(config).unwrap())
}
fn names(events: &[(&'static str, String)]) -> Vec<&'static str> {
events.iter().map(|(name, _)| *name).collect()
}
#[tokio::test]
async fn the_main_page_gets_what_changed() {
let broker = broker();
let signed_out = Arc::new(AtomicBool::new(false));
let check = signed_out.clone();
let signed_in: SignedIn = Box::new(move || {
let out = check.load(Ordering::SeqCst);
Box::pin(async move { (!out).then(|| "token".to_owned()) })
});
let mut updates = Updates::new(broker.clone(), signed_in, None);
// Everything to start with
let events = updates.next().await.unwrap();
assert_eq!(names(&events), ["pending", "running"]);
assert!(events[0].1.contains("Nothing is waiting"), "{events:?}");
// A run starting changes only the running list, and progress updates it
let _tracked = broker.runs.start("abc", "agent", "deploy", "deploy river");
assert_eq!(names(&updates.next().await.unwrap()), ["running"]);
let progress = Progress { phase: Phase::Build, state: State::Running, elapsed: 1, counts: Counts::default() };
broker.runs.record("abc", &progress);
let events = updates.next().await.unwrap();
assert!(events[0].1.contains("building"), "{events:?}");
signed_out.store(true, Ordering::SeqCst);
broker.runs.record("abc", &Progress { elapsed: 2, ..progress });
assert_eq!(names(&updates.next().await.unwrap()), ["signed-out"]);
assert!(updates.next().await.is_none());
}
#[tokio::test]
async fn a_request_page_gets_its_state_and_progress() {
let broker = broker();
let signed_in: SignedIn = Box::new(|| Box::pin(async { Some("token".to_owned()) }));
let mut updates = Updates::new(broker.clone(), signed_in, Some("abc".into()));
assert_eq!(updates.next().await.unwrap(), [("state", String::new())]);
let tracked = broker.runs.start("abc", "agent", "deploy", "deploy river");
let events = updates.next().await.unwrap();
assert_eq!(names(&events), ["state", "progress"]);
assert_eq!(events[0].1, "running");
drop(tracked);
assert_eq!(updates.next().await.unwrap(), [("state", String::new())]);
}
}
+14 -67
View File
@@ -2,6 +2,7 @@
//! for approvers signed in through an OpenID Connect provider, plus Web Push notifications. It
//! sits behind a reverse proxy, which is the only thing that should reach its listener.
mod auth;
mod events;
mod history;
mod page;
mod push;
@@ -24,7 +25,6 @@ use tower_sessions_rusqlite_store::{RusqliteStore, tokio_rusqlite};
use crate::approve;
use crate::config::WebConfig;
use crate::queue::{Decision, PendingInfo};
use crate::runs::Runs;
use crate::server::Broker;
use auth::{Flow, Oidc, Purpose};
use history::History;
@@ -82,12 +82,9 @@ pub async fn run(broker: Arc<Broker>, config: WebConfig, secret: String) -> Resu
let app = Router::new()
.route("/", get(index))
.route("/pending", get(pending_fragment))
.route("/requests/{id}", get(request_page).post(answer))
.route("/requests/{id}/events", get(request_events))
.route("/running/events", get(running_events))
.route("/events", get(page_events))
.route("/log", get(log_page))
.route("/api/version", get(version))
.route("/api/csrf", get(csrf))
.route("/push/key", get(push_key))
.route("/push/subscribe", post(subscribe))
@@ -208,14 +205,7 @@ async fn index(State(web): State<Arc<Web>>, session: Session) -> Result<Response
let entries = web.broker.queue.list();
let leases = web.broker.queue.all_leases();
let runs = web.broker.runs.list();
Ok(page::index(&user.name, &user.csrf, &entries, &leases, &runs, web.broker.queue.version()).into_response())
}
async fn pending_fragment(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
let user = api_user(&session).await?;
let entries = web.broker.queue.list();
let leases = web.broker.queue.all_leases();
Ok(page::pending(&user.csrf, &entries, &leases).into_response())
Ok(page::index(&user.name, &user.csrf, &entries, &leases, &runs).into_response())
}
async fn request_page(
@@ -239,63 +229,25 @@ async fn request_page(
entry: current.as_ref(),
run: run.as_ref(),
past: past.as_ref(),
version: web.broker.queue.version(),
state: events::request_state(&web.broker, &id),
};
Ok(page::request(&user.name, &user.csrf, &view).into_response())
}
/// A running request's progress panel, as Server-Sent Events: the panel as HTML whenever it
/// changes, then `end` once the request finishes.
async fn request_events(
#[derive(Deserialize)]
struct EventsQuery {
/// The request whose page it is.
request: Option<String>,
}
/// Updates for an open page, as Server-Sent Events (see `events.rs`).
async fn page_events(
State(web): State<Arc<Web>>,
session: Session,
Path(id): Path<String>,
Query(query): Query<EventsQuery>,
) -> Result<Response, Failure> {
api_user(&session).await?;
Ok(events(&web, move |runs| runs.get(&id).map(|run| page::panel(&run))))
}
/// The running requests' list, as Server-Sent Events whenever it changes.
async fn running_events(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
api_user(&session).await?;
Ok(events(&web, |runs| Some(page::running_list(&runs.list()))))
}
/// How often pages get progress at most.
const EVENT_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
/// Streams `render`'s HTML as `update` events whenever runs change; when it gives `None`, an
/// `end` event closes the stream.
fn events(web: &Web, render: impl Fn(&Runs) -> Option<String> + Send + Sync + 'static) -> Response {
use axum::response::sse::{Event, KeepAlive, Sse};
let runs = web.broker.runs.clone();
let changes = runs.subscribe();
let render = Arc::new(render);
let stream = futures_util::stream::unfold((changes, true, false), move |(mut changes, first, ended)| {
let (runs, render) = (runs.clone(), render.clone());
async move {
if ended {
return None;
}
if !first {
tokio::time::sleep(EVENT_INTERVAL).await;
changes.changed().await.ok()?;
}
changes.borrow_and_update();
let event = match render(&runs) {
Some(html) => (Event::default().event("update").data(html), false),
None => (Event::default().event("end").data(""), true),
};
Some((Ok::<_, std::convert::Infallible>(event.0), (changes, false, event.1)))
}
});
let mut response = Sse::new(stream).keep_alive(KeepAlive::default()).into_response();
// Proxies such as nginx would otherwise hold events back.
response.headers_mut().insert("x-accel-buffering", HeaderValue::from_static("no"));
response
Ok(events::stream(web.broker.clone(), session, query.request))
}
#[derive(Deserialize)]
@@ -375,11 +327,6 @@ async fn log_page(
Ok(page::log(&user.name, &user.csrf, &view).into_response())
}
async fn version(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
api_user(&session).await?;
Ok(axum::Json(serde_json::json!({ "version": web.broker.queue.version() })).into_response())
}
async fn csrf(session: Session) -> Result<Response, Failure> {
let user = api_user(&session).await?;
Ok(axum::Json(serde_json::json!({ "csrf": user.csrf })).into_response())
+11 -10
View File
@@ -122,7 +122,6 @@ struct Index<'a> {
entries: &'a [PendingInfo],
leases: &'a [(String, String, u64)],
runs: &'a [Run],
version: u64,
}
pub fn index(
@@ -131,9 +130,8 @@ pub fn index(
entries: &[PendingInfo],
leases: &[(String, String, u64)],
runs: &[Run],
version: u64,
) -> Html<String> {
render(Index { name, csrf, entries, leases, runs, version })
render(Index { name, csrf, entries, leases, runs })
}
/// Requests that are running, which the page script swaps in as they change.
@@ -167,7 +165,8 @@ struct Request<'a> {
entry: Option<&'a PendingInfo>,
run: Option<&'a Run>,
past: Option<&'a History>,
version: u64,
id: &'a str,
state: &'a str,
}
pub struct RequestView<'a> {
@@ -175,7 +174,8 @@ pub struct RequestView<'a> {
pub entry: Option<&'a PendingInfo>,
pub run: Option<&'a Run>,
pub past: Option<&'a History>,
pub version: u64,
/// What the page shows of it (`events::request_state`), so the page can tell when it changes.
pub state: String,
}
pub fn request(name: &str, csrf: &str, view: &RequestView) -> Html<String> {
@@ -185,8 +185,8 @@ pub fn request(name: &str, csrf: &str, view: &RequestView) -> Html<String> {
(None, None, Some(past)) if !past.summary.is_empty() => past.summary.clone(),
_ => format!("Request {}", short(view.id)),
};
let RequestView { entry, run, past, version, .. } = *view;
render(Request { name, csrf, heading, entry, run, past, version })
let RequestView { id, entry, run, past, ref state } = *view;
render(Request { name, csrf, heading, entry, run, past, id, state })
}
/// What the log page is filtered by.
@@ -343,7 +343,7 @@ mod tests {
];
let (histories, _) = super::history::gather(records);
let view = RequestView { id: "abc", entry: None, run: None, past: Some(&histories[0]), version: 0 };
let view = RequestView { id: "abc", entry: None, run: None, past: Some(&histories[0]), state: String::new() };
let html = request("broker", "token", &view).0;
assert!(html.contains("<dt>Command</dt><dd class=\"neutral\"><code>uptime</code></dd>"), "{html}");
assert!(html.contains("<span class=\"diff-add\">+a</span>"), "{html}");
@@ -379,8 +379,9 @@ mod tests {
assert!(list.contains("deploy &#60;river&#62;") && list.contains("<progress"), "{list}");
assert!(!running_list(&[]).contains("Running"));
let view = RequestView { id: "abc", entry: None, run: Some(&run), past: None, version: 0 };
let view = RequestView { id: "abc", entry: None, run: Some(&run), past: None, state: "running".into() };
let page = request("broker", "token", &view).0;
assert!(page.contains(r#"id="progress" class="progress" data-id="abc""#), "{page}");
assert!(page.contains(r#"id="request" data-id="abc" data-state="running""#), "{page}");
assert!(page.contains(r#"id="progress" class="progress""#), "{page}");
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
<section id="push" hidden>
<p><span id="push-state"></span> <button type="button" id="push-toggle" class="quiet"></button></p>
</section>
<div id="pending" data-version="{{ version }}">
<div id="pending">
{% include "pending.html" %}
</div>
<section id="running">
+2 -2
View File
@@ -3,12 +3,12 @@
{% block title %}Approval request{% endblock %}
{% block main %}
<h1>{{ heading }}</h1>
<div id="request" data-version="{{ version }}">
<div id="request" data-id="{{ id }}" data-state="{{ state }}">
{% if let Some(entry) = entry %}
{% call m::card(entry, csrf, true) %}{% endcall %}
{% endif %}
{% if let Some(run) = run %}
<section id="progress" class="progress" data-id="{{ run.id }}">
<section id="progress" class="progress">
{% include "progress.html" %}
</section>
{% else if let Some(past) = past %}