forge
Explore
Log in

Don't you dare go Hollow

A session on Settings → Sessions opens its details in a popup (user agent, sign-in and last IP, times) instead of a page, and a session from before IPs were recorded says "Not recorded"

Browse files at this commit

dcdcd272ebe9cfa730d4c78e4125a1d61317c01bAhmet Kaan GümüşParent: c0cdb72
Some checks failed
Show checks
  • feat
    • a session on Settings → Sessions opens its details in a popup (user agent, sign-in and last IP, times) instead of a page, and a session from before IPs were recorded says "Not recorded"
    • the shell's live updates (online, unread, activity, repo side) come over one stream, /-/shell/events, so a page no longer opens six event streams and hangs the next navigation on HTTP/1.1
    • clippy is clean on Rust 1.99
Show full message
✨ feat: a session on Settings → Sessions opens its details in a popup (user agent, sign-in and last IP, times) instead of a page, and a session from before IPs were recorded says "Not recorded"; the shell's live updates (online, unread, activity, repo side) come over one stream, /-/shell/events, so a page no longer opens six event streams and hangs the next navigation on HTTP/1.1; clippy is clean on Rust 1.99
crates/forge-runner/src/executor.rsmodified+1 -2
@@ -1096,8 +1096,7 @@ mod tests {
10961096 #[test]
10971097 fn parallelism_defaults_follow_the_cpu_limit_and_job_env_wins() {
10981098 let mut job = fixture_job("true");
1099- let mut limits = Limits::default();
1100- limits.cpus = "0.5".to_owned();
1099+ let limits = Limits { cpus: "0.5".to_owned(), ..Limits::default() };
11011100 let env = job_env_with_defaults(&job, &limits).expect("env");
11021101 assert!(env.contains(&("CARGO_BUILD_JOBS".to_owned(), "1".to_owned())));
11031102 job.env.insert("CARGO_BUILD_JOBS".to_owned(), "7".to_owned());
crates/forge-web/assets/nav.jsmodified+57 -45
@@ -192,8 +192,6 @@
192192 syncLog();
193193 followTail();
194194 restoreJobs(jobs);
195- syncUnread();
196- syncActivity();
197195 syncLive();
198196 syncPush();
199197 syncTick();
@@ -549,8 +547,10 @@
549547 };
550548 }
551549
552- // Every page holds one stream to /-/alive (no data, no login). Its error means the server, or the
553- // proxy in front of it, is down; its open means it is back.
550+ // Every page holds one stream to /-/shell/events (`/-/alive` for a page from before a deploy, and for
551+ // an anonymous visitor the same alive events). Its error means the server, or the proxy in front of
552+ // it, is down; its open means it is back. Signed-in viewers also get `unread` (the inbox count),
553+ // `activity` (the live strip and ring) and `side` (the sidebar's repo list) on the same connection.
554554 // A `theme` event carries the signed-in user's appearance as `name=value` pairs joined by `;`
555555 // (the `<html>` attributes). An empty value removes the attribute. Only data-* names are applied.
556556 function applyAppearance(data) {
@@ -588,13 +588,19 @@
588588 if (link.down) { armBanner(); }
589589 }
590590 if (window.EventSource) {
591- alive = keepOpen('/-/alive', aliveOpen, aliveDown, {
591+ alive = keepOpen('/-/shell/events', aliveOpen, aliveDown, {
592592 theme: applyAppearance,
593593 language: function () { refreshLive(true); },
594594 // The header's identity (username, avatar, admin rights) or the session changed: the page re-renders.
595595 account: function () { refreshLive(true); },
596596 // A live server setting changed (the banner, registration, limits...): the page re-renders.
597- settings: function () { refreshLive(true); }
597+ settings: function () { refreshLive(true); },
598+ // The inbox count changed (see `unreadChanged` above).
599+ unread: unreadChanged,
600+ // The viewer's activity changed: the strip, ring and chips are fetched again.
601+ activity: function () { refreshActivity(); },
602+ // The sidebar's repo list changed (the sidebar is re-rendered with the page).
603+ side: sideChanged
598604 });
599605 document.addEventListener('visibilitychange', function () { wake(false); });
600606 document.addEventListener('resume', function () { wake(true); });
@@ -1233,12 +1239,10 @@
12331239 // A filtered view asked for in place: the URL is replaced (no history entry per change), fields
12341240 // and caret come through the swap, and the scroll stays put.
12351241 // Live unread count. The profile corner (data-unread-stream) is re-rendered by every swap, so it is
1236- // looked up on each update. One EventSource serves the page and stays open across swaps. It is
1237- // opened only while a corner is shown (signed-in pages) and closed when it is gone. The server
1238- // pushes each change; nothing polls. Each `unread` event also tells the activity stream below to
1239- // refresh. The count shows twice: as a dot on the menu toggle (has-dot), and next to Notifications
1240- // in the sidebar and the phone menu.
1241- var unreadStream = null;
1242+ // looked up on each update. The count arrives as an `unread` event of the shell stream (see
1243+ // `/-/shell/events`, opened with the alive handlers above), which the server pushes on each change;
1244+ // nothing polls. Each `unread` event also refreshes the activity (below). The count shows twice: as
1245+ // a dot on the menu toggle (has-dot), and next to Notifications in the sidebar and the phone menu.
12421246
12431247 // Shows the count in one link the way the server renders it: a span with the number, or no span at zero.
12441248 function setCount(el, cls, n) {
@@ -1264,28 +1268,17 @@
12641268 for (var i = 0; i < links.length; i++) { setCount(links[i], 'count', n); }
12651269 }
12661270
1267- function syncUnread() {
1268- if (!document.querySelector('[data-unread-stream]')) {
1269- if (unreadStream) { unreadStream.close(); unreadStream = null; }
1270- return;
1271- }
1272- if (unreadStream || !window.EventSource) { return; }
1273- unreadStream = new EventSource('/notifications/stream');
1274- unreadStream.addEventListener('unread', function (e) {
1275- setUnread(parseInt(e.data, 10) || 0);
1276- refreshActivity();
1277- });
1271+ // An `unread` event: the count, then the activity is fetched again.
1272+ function unreadChanged(data) {
1273+ setUnread(parseInt(data, 10) || 0);
1274+ refreshActivity();
12781275 }
12791276
1280- syncUnread();
1281-
12821277 // The live activity: the profile corner (heat ring, chips, waiting list) and the live strip after
1283- // the path bar. The server's activity JSON (GET /-/activity) is the source. A `changed` event of
1284- // its stream, and every `unread` event above, fetches it again and redraws whatever is on the page.
1285- // Nothing changes before the JSON says so. The stream stays open across swaps while a strip is
1286- // shown, as the unread one does. A finished run leaves the strip when the server's window ends, so
1287- // while any is listed the JSON is fetched again every 30 s.
1288- var activityStream = null;
1278+ // the path bar. The server's activity JSON (GET /-/activity) is the source. An `activity` event of
1279+ // the shell stream, and every `unread` event, fetches it again and redraws whatever is on the page.
1280+ // Nothing changes before the JSON says so. A finished run leaves the strip when the server's window
1281+ // ends, so while any is listed the JSON is fetched again every 30 s.
12891282 var activitySeq = 0; // a fetch's number: only the newest answer is drawn
12901283 var activityTimer = null; // the next refetch while finished runs are listed
12911284 var SVG_NS = 'http://www.w3.org/2000/svg';
@@ -1516,20 +1509,6 @@
15161509 }).catch(function () { });
15171510 }
15181511
1519- // One EventSource serves the page's strip and stays open across swaps. It is opened only while a
1520- // strip is shown and closed when it is gone.
1521- function syncActivity() {
1522- if (!document.querySelector('.live-strip[data-activity]')) {
1523- if (activityStream) { activityStream.close(); activityStream = null; }
1524- return;
1525- }
1526- if (activityStream || !window.EventSource) { return; }
1527- activityStream = new EventSource('/-/activity/stream');
1528- activityStream.addEventListener('changed', function () { refreshActivity(); });
1529- }
1530-
1531- syncActivity();
1532-
15331512 // The CI log (a job page's [data-live-log]). The server sends the raw text; this turns it into
15341513 // numbered lines (#L12 anchors) with ANSI colours as spans, `::group::name` / `::endgroup::`
15351514 // sections as <details>, and a search box with highlight and next/previous. Streamed bytes go
@@ -2069,6 +2048,15 @@
20692048 return es;
20702049 }
20712050
2051+ // A `side` event of the shell stream: the sidebar's repo list changed. The page is re-rendered with
2052+ // it, as a `changed` event of a data-live stream would, but at most once a second (a code view or a
2053+ // live-now page re-renders at once).
2054+ function sideChanged() {
2055+ if (document.querySelector('[data-live-code], [data-live-now]')) { refreshLive(true); return; }
2056+ if (liveTimer) { return; }
2057+ liveTimer = setTimeout(function () { liveTimer = null; refreshLive(true); }, 1000);
2058+ }
2059+
20722060 // Closes the streams the page no longer names and opens the ones it newly names.
20732061 function syncLive() {
20742062 var want = liveWanted();
@@ -3345,6 +3333,30 @@
33453333 href: function (dlg, path) { return fileHref(dlg, path); }
33463334 };
33473335
3336+ // A link with data-dialog opens the <dialog> whose id it names, in place of following the link.
3337+ // Modifier and non-primary clicks still follow the link (a new tab, say). It listens in the capture
3338+ // phase on window, so it runs before the soft navigation (capture on document) follows the link.
3339+ window.addEventListener('click', function (e) {
3340+ if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return; }
3341+ var t = e.target;
3342+ if (!t || !t.closest) { return; }
3343+ var link = t.closest('[data-dialog]');
3344+ if (!link) { return; }
3345+ var dlg = document.getElementById(link.getAttribute('data-dialog'));
3346+ if (!dlg || dlg.tagName !== 'DIALOG' || typeof dlg.showModal !== 'function') { return; }
3347+ e.preventDefault();
3348+ if (!dlg.open) { dlg.showModal(); }
3349+ // The same function each time, so the listener is added once however often the dialog opens.
3350+ dlg.addEventListener('click', closeOnBackdrop);
3351+ }, true);
3352+
3353+ // A click on a dialog's backdrop (the dialog element itself, outside its box) closes it.
3354+ function closeOnBackdrop(e) {
3355+ var r = this.getBoundingClientRect();
3356+ var inside = e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom;
3357+ if (e.target === this && !inside) { this.close(); }
3358+ }
3359+
33483360 document.addEventListener('click', function (e) {
33493361 var t = e.target;
33503362 if (!t || !t.closest) { return; }
crates/forge-web/src/i18n/mod.rsmodified+8 -0
@@ -267,6 +267,8 @@ pub enum Key {
267267 LastSeenAt,
268268 ExpiresAt,
269269 BackToSessions,
270+ NotRecorded,
271+ Close,
270272
271273 // Metadata lines (see the helpers below for the words in between).
272274 Added,
@@ -485,6 +487,8 @@ pub const ALL: &[Key] = &[
485487 Key::LastSeenAt,
486488 Key::ExpiresAt,
487489 Key::BackToSessions,
490+ Key::NotRecorded,
491+ Key::Close,
488492 Key::Added,
489493 Key::LastUsed,
490494 Key::Created,
@@ -889,6 +893,10 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
889893 (ExpiresAt, Tr) => "Bitiş",
890894 (BackToSessions, En) => "Back to sessions",
891895 (BackToSessions, Tr) => "Oturumlara dön",
896+ (NotRecorded, En) => "Not recorded",
897+ (NotRecorded, Tr) => "Kaydedilmedi",
898+ (Close, En) => "Close",
899+ (Close, Tr) => "Kapat",
892900 (RevokeAllOthers, En) => "Revoke all other sessions",
893901 (RevokeAllOthers, Tr) => "Diğer tüm oturumları iptal et",
894902
crates/forge-web/src/live.rsmodified+26 -5
@@ -28,7 +28,7 @@ use std::future::Future;
2828 use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
2929
3030 use futures_util::future::select_all;
31-use futures_util::stream;
31+use futures_util::{Stream, stream};
3232 use tokio::sync::watch;
3333 use topcoat::Result;
3434 use topcoat::context::Cx;
@@ -216,6 +216,11 @@ fn changed_event() -> Result<Event> {
216216 Ok(Event::new().event("changed").data("1"))
217217 }
218218
219+/// A `name` event with no data the client reads, sent on each change of a page's state.
220+fn named_event(name: &'static str) -> Result<Event> {
221+ Ok(Event::new().event(name).data("1"))
222+}
223+
219224 /// Waits until one of `wakes` is bumped. False when a topic is gone, which ends the stream.
220225 async fn wait_any(wakes: &mut [watch::Receiver<u64>]) -> bool {
221226 let waits = wakes.iter_mut().map(|rx| Box::pin(rx.changed()));
@@ -262,6 +267,23 @@ pub async fn stream_changes_with<F, Fut>(
262267 extra: Vec<watch::Receiver<u64>>,
263268 read: F,
264269 ) -> Result<Response>
270+where
271+ F: Fn() -> Fut + Send + 'static,
272+ Fut: Future<Output = Result<String>> + Send,
273+{
274+ let events = named_changes(hub, topics.to_vec(), extra, "changed", read).await?;
275+ events_response(cx, events)
276+}
277+
278+/// The events of [`stream_changes_with`] as a stream, each named `name`, for a caller that merges
279+/// several streams into one response (see `pages::shell_events`).
280+pub async fn named_changes<F, Fut>(
281+ hub: &LiveHub,
282+ topics: Vec<Topic>,
283+ extra: Vec<watch::Receiver<u64>>,
284+ name: &'static str,
285+ read: F,
286+) -> Result<impl Stream<Item = Result<Event>> + Send + 'static>
265287 where
266288 F: Fn() -> Fut + Send + 'static,
267289 Fut: Future<Output = Result<String>> + Send,
@@ -271,7 +293,7 @@ where
271293 topics.iter().map(|topic| hub.subscribe(topic)).collect();
272294 wakes.extend(extra);
273295 let last = read().await?;
274- let events = stream::unfold(Follow { wakes, read, last }, |mut follow| async move {
296+ Ok(stream::unfold(Follow { wakes, read, last }, move |mut follow| async move {
275297 loop {
276298 if !wait_any(&mut follow.wakes).await {
277299 return None;
@@ -287,10 +309,9 @@ where
287309 continue;
288310 }
289311 follow.last = now;
290- return Some((changed_event(), follow));
312+ return Some((named_event(name), follow));
291313 }
292- });
293- events_response(cx, events)
314+ }))
294315 }
295316
296317 #[cfg(test)]
crates/forge-web/src/pages/activity.rsmodified+14 -4
@@ -15,6 +15,8 @@ use topcoat::router::{Body, HeaderValue, StatusCode, route};
1515
1616 use crate::auth::current_user;
1717 use crate::pages::ci_runs::{changed_stream, events_response, run_href};
18+use futures_util::Stream;
19+use topcoat::router::content::sse::Event;
1820 use crate::state::AppState;
1921 use crate::views::repo_href;
2022
@@ -126,9 +128,18 @@ async fn activity_stream(cx: &Cx) -> Result<Response> {
126128 return Ok(res);
127129 };
128130 let state = app_context::<AppState>(cx).clone();
129- // Subscribed before the first read, so a run change in between is sent.
131+ events_response(cx, activity_changes(state, user, "changed"))
132+}
133+
134+/// The viewer's activity events, each named `name`: one now, then one after each run change that
135+/// alters the JSON. Subscribed when built, before the first read, so a change in between is sent.
136+pub(crate) fn activity_changes(
137+ state: AppState,
138+ user: User,
139+ name: &'static str,
140+) -> impl Stream<Item = Result<Event>> + Send + 'static {
130141 let wake = state.ci_live.subscribe_any_run();
131- let events = changed_stream(wake, true, move || {
142+ changed_stream(wake, true, name, move || {
132143 let state = state.clone();
133144 let user = user.clone();
134145 async move {
@@ -136,8 +147,7 @@ async fn activity_stream(cx: &Cx) -> Result<Response> {
136147 let body = activity_json(&state, &user).await?.to_string();
137148 Ok(Some((body, false)))
138149 }
139- });
140- events_response(cx, events)
150+ })
141151 }
142152
143153 #[cfg(test)]
crates/forge-web/src/pages/ci_runs.rsmodified+9 -7
@@ -1978,13 +1978,15 @@ pub(crate) fn changed_event(status: String) -> Result<Event> {
19781978 Ok(Event::new().event("changed").data(status))
19791979 }
19801980
1981-/// The `changed` events of a CI page. The first event carries the status now. Each later one
1982-/// follows a wake of `wake`: with `only_on_status`, only when the status differs from the last one
1983-/// sent. The stream ends after the terminal status is sent, when the row is gone, or when the signal
1984-/// closes. Subscribe `wake` before the first read, so a change in between is not lost.
1981+/// The events of a CI page, each named `name` (`changed` on a page's own stream). The first event
1982+/// carries the status now. Each later one follows a wake of `wake`: with `only_on_status`, only when
1983+/// the status differs from the last one sent. The stream ends after the terminal status is sent,
1984+/// when the row is gone, or when the signal closes. Subscribe `wake` before the first read, so a
1985+/// change in between is not lost.
19851986 pub(crate) fn changed_stream<F, Fut>(
19861987 wake: watch::Receiver<u64>,
19871988 only_on_status: bool,
1989+ name: &'static str,
19881990 read: F,
19891991 ) -> impl Stream<Item = Result<Event>> + Send + 'static
19901992 where
@@ -2011,7 +2013,7 @@ where
20112013 done: false,
20122014 primed: false,
20132015 },
2014- |mut follow| async move {
2016+ move |mut follow| async move {
20152017 loop {
20162018 if follow.done {
20172019 return None;
@@ -2033,7 +2035,7 @@ where
20332035 let send = changed || !follow.only_on_status;
20342036 follow.last = Some(status.clone());
20352037 if send {
2036- return Some((changed_event(status), follow));
2038+ return Some((Ok(Event::new().event(name).data(status)), follow));
20372039 }
20382040 }
20392041 },
@@ -2156,7 +2158,7 @@ async fn run_events(cx: &Cx) -> Result<Response> {
21562158 let run_id = run.id.clone();
21572159 let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone());
21582160 let repo_id = ctx.repo.id.clone();
2159- let events = changed_stream(wake, false, move || {
2161+ let events = changed_stream(wake, false, "changed", move || {
21602162 let store = store.clone();
21612163 let run_id = run_id.clone();
21622164 let viewer = viewer.clone();
crates/forge-web/src/pages/dashboard.rsmodified+18 -1
@@ -12,6 +12,7 @@ use forge_core::{Notification, Repo, Visibility};
1212 use jiff::{Timestamp, civil};
1313 use topcoat::Result;
1414 use topcoat::context::{Cx, app_context};
15+use topcoat::router::content::sse::Event;
1516 use topcoat::router::response::Response;
1617 use topcoat::router::{Body, StatusCode, page, query_params, route};
1718 use topcoat::view::{View, component, view};
@@ -20,7 +21,7 @@ use crate::auth::{current_user, percent_encode};
2021 use crate::i18n::misc::{self as m, K as MK};
2122 use crate::i18n::orgs::{self as g, K};
2223 use crate::i18n::{self, Lang};
23-use crate::live::{Topic, stream_changes};
24+use crate::live::{Topic, named_changes, stream_changes};
2425 use crate::pages::issue_parts::stamp_unix;
2526 use crate::pages::repo_settings::{notice_banner_for, take_notice};
2627 use crate::state::AppState;
@@ -133,6 +134,22 @@ async fn side_events(cx: &Cx) -> Result<Response> {
133134 .await
134135 }
135136
137+/// The sidebar's change events for `user`, each named `name` (`changed` on `/-/side/events`).
138+pub(crate) async fn side_changes(
139+ state: &AppState,
140+ user: &forge_core::User,
141+ name: &'static str,
142+) -> topcoat::Result<impl futures_util::Stream<Item = topcoat::Result<Event>> + Send + 'static> {
143+ let topics = vec![Topic::User(user.id.clone())];
144+ let (state_for_read, user) = (state.clone(), user.clone());
145+ named_changes(&state.live, topics, Vec::new(), name, move || {
146+ let state = state_for_read.clone();
147+ let user = user.clone();
148+ async move { side_fingerprint(&state, &user).await }
149+ })
150+ .await
151+}
152+
136153 /// The sidebar's repo list as it shows: the names in order, and the total.
137154 async fn side_fingerprint(state: &AppState, user: &forge_core::User) -> Result<String> {
138155 let (listed, total) = state
crates/forge-web/src/pages/mod.rsmodified+1 -0
@@ -135,6 +135,7 @@ pub mod settings_security;
135135 pub mod settings_sessions;
136136 pub mod settings_tokens;
137137 pub mod setup;
138+pub mod shell_events;
138139 pub mod snippet_raw;
139140 pub mod snippets;
140141 pub mod snippets_live;
crates/forge-web/src/pages/notifications.rsmodified+19 -10
@@ -12,7 +12,7 @@ use forge_core::store::admin_alerts::AdminNotice;
1212 use forge_core::store::advisories::AdvisoryNotice;
1313 use forge_core::store::transfers::PendingTransfer;
1414 use forge_core::{Notification, Reason, Role, SubState, User, WatchLevel};
15-use futures_util::{StreamExt, future, stream};
15+use futures_util::{Stream, StreamExt, future, stream};
1616 use serde::Deserialize;
1717 use topcoat::Result;
1818 use topcoat::context::{Cx, app_context};
@@ -725,6 +725,22 @@ fn unread_event(count: u64) -> topcoat::Result<Event> {
725725 Ok(Event::new().event("unread").data(count.to_string()))
726726 }
727727
728+/// The viewer's unread count as `unread` events: one now, then one after each change to the inbox.
729+/// Subscribed before the count is read, so a change in between is pushed again, never missed.
730+pub(crate) async fn unread_changes(
731+ state: &AppState,
732+ user_id: &str,
733+) -> Result<impl Stream<Item = Result<Event>> + Send + 'static> {
734+ let subscription = state.notify_hub.subscribe(user_id);
735+ let count = state.store.unread_count(user_id).await?;
736+ let first = stream::once(future::ready(unread_event(count)));
737+ let changes = stream::unfold(subscription, |mut sub| async move {
738+ let count = sub.next_count().await?;
739+ Some((unread_event(count), sub))
740+ });
741+ Ok(first.chain(changes))
742+}
743+
728744 /// The bell's live count. Sends an `unread` event with the viewer's unread count now, then one
729745 /// after each change to the inbox, until the viewer disconnects or the server shuts down. An
730746 /// anonymous viewer gets a bare 401: an event stream has no login page to redirect to.
@@ -736,15 +752,8 @@ async fn notification_stream(cx: &Cx) -> Result<Response> {
736752 return Ok(res);
737753 };
738754 let state = app_context::<AppState>(cx);
739- let subscription = state.notify_hub.subscribe(&user.id);
740- // Read after subscribing: a change that lands in between is pushed again, never missed.
741- let count = state.store.unread_count(&user.id).await?;
742- let first = stream::once(future::ready(unread_event(count)));
743- let changes = stream::unfold(subscription, |mut sub| async move {
744- let count = sub.next_count().await?;
745- Some((unread_event(count), sub))
746- });
747- events_response(cx, first.chain(changes))
755+ let events = unread_changes(state, &user.id).await?;
756+ events_response(cx, events)
748757 }
749758
750759 /// Subscribes or unsubscribes the viewer from an issue.
crates/forge-web/src/pages/register.rsmodified+2 -3
@@ -423,10 +423,9 @@ async fn verify_resend(cx: &Cx, Form(form): Form<ResendForm>) -> Result<SeeOther
423423 let state = app_context::<AppState>(cx);
424424 if let Some(address) = viewer.0.email.clone()
425425 && !state.store.email_is_verified(&viewer.0.id).await?
426+ && !account::send_verify(state, &viewer.0, &address).await?
426427 {
427- if !account::send_verify(state, &viewer.0, &address).await? {
428- return Ok(see_other("/settings/security?saved=verify_wait"));
429- }
428+ return Ok(see_other("/settings/security?saved=verify_wait"));
430429 }
431430 Ok(see_other("/settings/security?saved=verify_sent"))
432431 }
crates/forge-web/src/pages/repo_side.rsmodified+1 -0
@@ -63,6 +63,7 @@ fn dir_size(path: &Path) -> u64 {
6363 }
6464
6565 /// The tree facts of `repo` at `commit`, read once per commit. `root` is the root entry names.
66+#[allow(clippy::ptr_arg)] // the path is moved into a blocking task, which needs an owned PathBuf
6667 pub async fn tree_facts(
6768 state: &AppState,
6869 repo: &Repo,
crates/forge-web/src/pages/settings_live.rsmodified+13 -2
@@ -24,7 +24,7 @@
2424 use std::collections::VecDeque;
2525
2626 use forge_core::server_settings::{self, FIELDS, Kind};
27-use futures_util::stream;
27+use futures_util::stream::{self, BoxStream, StreamExt};
2828 use tokio::sync::watch;
2929 use topcoat::Result;
3030 use topcoat::context::{Cx, app_context, try_app_context};
@@ -172,6 +172,17 @@ pub async fn alive_response(cx: &Cx) -> Result<Response> {
172172 let viewer = current_user(cx)
173173 .await?
174174 .map(|(user, session)| (user.id, session.id));
175+ let events = alive_stream(state, viewer).await?;
176+ events_response(cx, events)
177+}
178+
179+/// The events of the alive stream for `viewer` (the user and session ids, when signed in). See
180+/// [`alive_response`]. The caller holds the stream slot; `pages::shell_events` merges it with the
181+/// shell's other streams.
182+pub async fn alive_stream(
183+ state: AppState,
184+ viewer: Option<(String, String)>,
185+) -> Result<BoxStream<'static, Result<Event>>> {
175186 // Subscribed before each baseline is read, so a change in between is not lost.
176187 let server_wake = state.live.subscribe(&Topic::ServerSettings);
177188 let settings_last = settings_fingerprint(&state);
@@ -195,7 +206,7 @@ pub async fn alive_response(cx: &Cx) -> Result<Response> {
195206 settings_last,
196207 queue: VecDeque::new(),
197208 };
198- events_response(cx, stream::unfold(alive, next_alive_event))
209+ Ok(stream::unfold(alive, next_alive_event).boxed())
199210 }
200211
201212 /// Waits for the next event of the alive stream. A wake that changes nothing the viewer sees sends
crates/forge-web/src/pages/settings_sessions.rsmodified+84 -23
@@ -65,7 +65,7 @@ async fn sessions_view(
6565 for session in sessions.into_iter() {
6666 <li class="item">
6767 <div class="item-main">
68- <a href=(format!("/settings/sessions/{}", session.id))><strong>(session_label(lang, &session))</strong></a>
68+ <a href=(format!("/settings/sessions/{}", session.id)) data-dialog=(format!("session-{}", session.id))><strong>(session_label(lang, &session))</strong></a>
6969 <span class="muted small">(i18n::dated_label(lang, Key::SignedIn)) " " rel_time(lang: lang, stamp: session.created_at.as_str()) " · " (i18n::dated_label(lang, Key::LastSeen)) " " rel_time(lang: lang, stamp: session.last_seen.as_str()) " · " (i18n::dated_label(lang, Key::ExpiresLabel)) " " rel_time(lang: lang, stamp: session.expires_at.as_str()) (address_text(&session))</span>
7070 if session.id == current_id {
7171 <span class="badge public">(t(lang, Key::ThisSession))</span>
@@ -78,6 +78,15 @@ async fn sessions_view(
7878 <button type="submit" class="danger">(t(lang, Key::Revoke))</button>
7979 </form>
8080 }
81+ <dialog class="session-dialog" id=(format!("session-{}", session.id)) aria-labelledby=(format!("session-{}-title", session.id))>
82+ <div class="session-dialog-head">
83+ <h2 id=(format!("session-{}-title", session.id))>(session_label(lang, &session))</h2>
84+ <form method="dialog">
85+ <button type="submit">(t(lang, Key::Close))</button>
86+ </form>
87+ </div>
88+ session_details(lang: lang, csrf: csrf, session: session.clone(), current: session.id == current_id)
89+ </dialog>
8190 </li>
8291 }
8392 </ul>
@@ -93,8 +102,10 @@ async fn sessions_view(
93102 })
94103 }
95104
105+/// The facts about one session, shared by its dialog on the list and its detail page: the badge
106+/// when it is the current session, the key/value grid, and the revoke button for any other one.
96107 #[component]
97-async fn session_detail_view(
108+async fn session_details(
98109 lang: Lang,
99110 csrf: &str,
100111 session: Session,
@@ -104,34 +115,51 @@ async fn session_detail_view(
104115 .user_agent
105116 .clone()
106117 .unwrap_or_else(|| t(lang, Key::UnknownBrowser).to_owned());
107- let sign_in_ip = session.ip.clone().unwrap_or_else(|| "-".to_owned());
108- let last_ip = session.last_ip.clone().unwrap_or_else(|| "-".to_owned());
118+ // Sessions from before IP recording have no sign-in address.
119+ let sign_in_ip = session
120+ .ip
121+ .clone()
122+ .unwrap_or_else(|| t(lang, Key::NotRecorded).to_owned());
123+ let last_ip = session
124+ .last_ip
125+ .clone()
126+ .unwrap_or_else(|| t(lang, Key::NotRecorded).to_owned());
109127 let id = session.id.clone();
110128 Ok(view! {
111- <section class="page-head">
112- <h1>(session_label(lang, &session))</h1>
113- </section>
114129 if current {
115130 <p><span class="badge public">(t(lang, Key::ThisSession))</span></p>
116131 }
117- <section class="card">
118- <dl class="kv-grid">
119- <div><dt>(t(lang, Key::UserAgent))</dt><dd>(user_agent.as_str())</dd></div>
120- <div><dt>(t(lang, Key::SignInIp))</dt><dd>(sign_in_ip.as_str())</dd></div>
121- <div><dt>(t(lang, Key::LastIp))</dt><dd>(last_ip.as_str())</dd></div>
122- <div><dt>(t(lang, Key::SignedIn))</dt><dd>rel_time(lang: lang, stamp: session.created_at.as_str())</dd></div>
123- <div><dt>(t(lang, Key::LastSeenAt))</dt><dd>rel_time(lang: lang, stamp: session.last_seen.as_str())</dd></div>
124- <div><dt>(t(lang, Key::ExpiresAt))</dt><dd>rel_time(lang: lang, stamp: session.expires_at.as_str())</dd></div>
125- </dl>
132+ <dl class="kv-grid">
133+ <div><dt>(t(lang, Key::UserAgent))</dt><dd>(user_agent.as_str())</dd></div>
134+ <div><dt>(t(lang, Key::SignInIp))</dt><dd>(sign_in_ip.as_str())</dd></div>
135+ <div><dt>(t(lang, Key::LastIp))</dt><dd>(last_ip.as_str())</dd></div>
136+ <div><dt>(t(lang, Key::SignedIn))</dt><dd>rel_time(lang: lang, stamp: session.created_at.as_str())</dd></div>
137+ <div><dt>(t(lang, Key::LastSeenAt))</dt><dd>rel_time(lang: lang, stamp: session.last_seen.as_str())</dd></div>
138+ <div><dt>(t(lang, Key::ExpiresAt))</dt><dd>rel_time(lang: lang, stamp: session.expires_at.as_str())</dd></div>
139+ </dl>
140+ if !current {
141+ <form method="post" action="/settings/sessions/revoke">
142+ <input type="hidden" name="csrf" value=(csrf)>
143+ <input type="hidden" name="id" value=(id.as_str())>
144+ <button type="submit" class="danger">(t(lang, Key::Revoke))</button>
145+ </form>
146+ }
147+ })
148+}
149+
150+#[component]
151+async fn session_detail_view(
152+ lang: Lang,
153+ csrf: &str,
154+ session: Session,
155+ current: bool,
156+) -> Result<impl View> {
157+ Ok(view! {
158+ <section class="page-head">
159+ <h1>(session_label(lang, &session))</h1>
126160 </section>
127161 <section class="card">
128- if !current {
129- <form method="post" action="/settings/sessions/revoke">
130- <input type="hidden" name="csrf" value=(csrf)>
131- <input type="hidden" name="id" value=(id.as_str())>
132- <button type="submit" class="danger">(t(lang, Key::Revoke))</button>
133- </form>
134- }
162+ session_details(lang: lang, csrf: csrf, session: session, current: current)
135163 <p><a href="/settings/sessions">(t(lang, Key::BackToSessions))</a></p>
136164 </section>
137165 })
@@ -254,6 +282,39 @@ mod tests {
254282
255283 const CSRF: &str = "sessions-test-csrf";
256284
285+ #[tokio::test]
286+ async fn sessions_list_renders_a_dialog_per_session() {
287+ let dir = tempfile::tempdir().expect("tempdir");
288+ let state = crate::test_support::test_state(dir.path()).await;
289+ let store = state.store.clone();
290+ let router = crate::test_support::app_router(state.clone());
291+ let tahinli = store
292+ .create_user("tahinli", None, "x", false)
293+ .await
294+ .expect("tahinli");
295+ crate::test_support::create_session(&store, &tahinli.id, "tahinli-token", CSRF).await;
296+ let current = store
297+ .list_sessions(&tahinli.id)
298+ .await
299+ .expect("sessions")
300+ .pop()
301+ .expect("one session");
302+
303+ let req = Request::builder()
304+ .method("GET")
305+ .uri("/settings/sessions")
306+ .header("cookie", format!("__Host-{SESSION_COOKIE}=tahinli-token"))
307+ .body(Body::empty())
308+ .expect("request");
309+ let res = router.handle(req).await;
310+ assert_eq!(res.status().as_u16(), 200);
311+ let body = to_bytes(res.into_body(), usize::MAX).await.expect("body");
312+ let html = String::from_utf8_lossy(&body);
313+ let id = format!("session-{}", current.id);
314+ assert!(html.contains(&format!("<dialog class=\"session-dialog\" id=\"{id}\"")));
315+ assert!(html.contains(&format!("data-dialog=\"{id}\"")));
316+ }
317+
257318 #[tokio::test]
258319 async fn revoking_the_current_session_is_audited() {
259320 let dir = tempfile::tempdir().expect("tempdir");
crates/forge-web/src/pages/shell_events.rsadded+88 -0
@@ -0,0 +1,88 @@
1+//! `GET /-/shell/events`: the one live stream a page holds. It merges the four streams every
2+//! signed-in page used to open (`/-/alive`, `/notifications/stream`, `/-/activity/stream` and
3+//! `/-/side/events`) into one response. Chromium allows six connections per host over HTTP/1.1, and
4+//! a page that held more than that could not load anything else.
5+//!
6+//! The events are named: `settings`, `theme`, `language` and `account` (the alive part, see
7+//! `settings_live::alive_stream`), `unread` (the inbox count), `activity` (the viewer's live strip
8+//! and ring) and `side` (the sidebar's repo list). An anonymous visitor gets the alive part only.
9+//! Each part keeps its own fingerprint, so an event is sent only when that part changed. The old
10+//! routes stay registered for tabs opened before a deploy.
11+
12+use futures_util::StreamExt;
13+use futures_util::stream::{self, BoxStream};
14+use topcoat::Result;
15+use topcoat::context::{Cx, try_app_context};
16+use topcoat::router::content::sse::Event;
17+use topcoat::router::response::Response;
18+use topcoat::router::route;
19+
20+use crate::auth::current_user;
21+use crate::pages::activity::activity_changes;
22+use crate::pages::ci_runs::events_response;
23+use crate::pages::dashboard::side_changes;
24+use crate::pages::notifications::unread_changes;
25+use crate::pages::settings_live::alive_stream;
26+use crate::state::AppState;
27+
28+/// `GET /-/shell/events`: the shell's live events for the viewer, opened once per page. An anonymous
29+/// visitor gets the alive part only. The viewer comes from the session, never from the URL.
30+#[route(GET "/-/shell/events")]
31+async fn shell_events(cx: &Cx) -> Result<Response> {
32+ // A router with no app state (the asset tests) has nothing to follow: the stream only stays open.
33+ let Some(state) = try_app_context::<AppState>(cx).cloned() else {
34+ return events_response(cx, stream::pending::<Result<Event>>());
35+ };
36+ let viewer = current_user(cx).await?;
37+ let ids = viewer
38+ .as_ref()
39+ .map(|(user, session)| (user.id.clone(), session.id.clone()));
40+ let mut parts: Vec<BoxStream<'static, Result<Event>>> =
41+ vec![alive_stream(state.clone(), ids).await?];
42+ if let Some((user, _)) = viewer {
43+ parts.push(unread_changes(&state, &user.id).await?.boxed());
44+ parts.push(activity_changes(state.clone(), user.clone(), "activity").boxed());
45+ parts.push(side_changes(&state, &user, "side").await?.boxed());
46+ }
47+ events_response(cx, stream::select_all(parts))
48+}
49+
50+#[cfg(test)]
51+mod tests {
52+ use topcoat::router::request::Request;
53+ use topcoat::router::{Body, StatusCode};
54+
55+ use crate::auth::SESSION_COOKIE;
56+
57+ /// The shell stream answers `text/event-stream` to an anonymous visitor and to a signed-in one.
58+ #[tokio::test]
59+ async fn shell_events_is_an_event_stream_for_anonymous_and_signed_in_viewers() {
60+ let dir = tempfile::tempdir().expect("tempdir");
61+ let state = crate::test_support::test_state(dir.path()).await;
62+ let store = state.store.clone();
63+ let router = crate::test_support::app_router(state);
64+ let user = store
65+ .create_user("tahinli", None, "x", false)
66+ .await
67+ .expect("user");
68+ crate::test_support::create_session(&store, &user.id, "tok", "csrf").await;
69+
70+ for cookie in [None, Some(format!("__Host-{SESSION_COOKIE}=tok"))] {
71+ let mut builder = Request::builder().method("GET").uri("/-/shell/events");
72+ if let Some(cookie) = &cookie {
73+ builder = builder.header("cookie", cookie.as_str());
74+ }
75+ let res = router
76+ .handle(builder.body(Body::empty()).expect("request"))
77+ .await;
78+ assert_eq!(res.status(), StatusCode::OK, "cookie: {cookie:?}");
79+ assert!(
80+ res.headers()["content-type"]
81+ .to_str()
82+ .expect("header")
83+ .starts_with("text/event-stream"),
84+ "cookie: {cookie:?}"
85+ );
86+ }
87+ }
88+}
crates/forge-web/src/repo_stats.rsmodified+2 -2
@@ -165,7 +165,7 @@ pub fn languages(files: &[(String, u64)], top: usize) -> Vec<LangShare> {
165165 })
166166 .collect();
167167 // Biggest first; equal sizes keep their name order, which the BTreeMap gave.
168- rows.sort_by(|a, b| b.bytes.cmp(&a.bytes));
168+ rows.sort_by_key(|a| std::cmp::Reverse(a.bytes));
169169
170170 if rows.len() > top {
171171 let rest = rows.split_off(top);
@@ -306,7 +306,7 @@ const LICENSE_NAMES: &[&str] = &[
306306
307307 /// The root entry that holds the license, if any: LICENSE, LICENSE.md, LICENSE.txt, LICENCE,
308308 /// COPYING, LICENSE-MIT ... (case-insensitive). The first match in a fixed preference order.
309-pub fn license_file<'a>(root_names: &'a [String]) -> Option<&'a str> {
309+pub fn license_file(root_names: &[String]) -> Option<&str> {
310310 LICENSE_NAMES.iter().find_map(|want| {
311311 root_names
312312 .iter()
crates/forge-web/src/views/mod.rsmodified+1 -1
@@ -868,7 +868,7 @@ async fn side_nav(
868868 (o::t(lang, OK::Settings))
869869 </a>
870870 </nav>
871- <div class="side-group" data-live="/-/side/events">
871+ <div class="side-group" data-shell-live="side">
872872 <h2 class="side-h">(o::t(lang, OK::RecentRepositories))</h2>
873873 if empty {
874874 <p class="side-empty">(o::t(lang, OK::NoReposYet))</p>
style/_account_admin.scssmodified+51 -0
@@ -51,6 +51,57 @@
5151 }
5252 }
5353
54+// A session's details over /settings/sessions, opened from its title. The body is the kv-grid in two
55+// columns; the close button sits at the top right, and the revoke button under the grid.
56+dialog.session-dialog {
57+ width: min(640px, calc(100% - 32px));
58+ max-height: min(80vh, 640px);
59+ margin: 10vh auto 0;
60+ padding: 20px 24px;
61+ overflow: auto;
62+ color: var(--text);
63+ background: var(--surface);
64+ border: 1px solid var(--border);
65+ border-radius: var(--radius-md);
66+ box-shadow: var(--shadow);
67+
68+ &::backdrop {
69+ background: rgba(0, 0, 0, 0.45);
70+ }
71+
72+ .session-dialog-head {
73+ display: flex;
74+ align-items: center;
75+ justify-content: space-between;
76+ gap: 12px;
77+ margin-bottom: 16px;
78+
79+ h2 {
80+ margin: 0;
81+ min-width: 0;
82+ font-size: 1.125rem;
83+ overflow-wrap: anywhere;
84+ }
85+
86+ form {
87+ margin: 0;
88+ flex: none;
89+ }
90+ }
91+
92+ .kv-grid {
93+ grid-template-columns: repeat(2, minmax(0, 1fr));
94+
95+ @media (max-width: 520px) {
96+ grid-template-columns: minmax(0, 1fr);
97+ }
98+ }
99+
100+ > form {
101+ margin-top: 16px;
102+ }
103+}
104+
54105 // Admin user detail. The header: a back link, the avatar, the name with a status dot and a role
55106 // badge, one muted meta line, then one row of small facts. Under it the actions are hairline rows
56107 // (title and one line of help on the left, the button on the right); the destructive ones sit in