diff --git a/crates/forge-runner/src/executor.rs b/crates/forge-runner/src/executor.rs index b82b6c3..ad44139 100644 --- a/crates/forge-runner/src/executor.rs +++ b/crates/forge-runner/src/executor.rs @@ -1096,8 +1096,7 @@ mod tests { #[test] fn parallelism_defaults_follow_the_cpu_limit_and_job_env_wins() { let mut job = fixture_job("true"); - let mut limits = Limits::default(); - limits.cpus = "0.5".to_owned(); + let limits = Limits { cpus: "0.5".to_owned(), ..Limits::default() }; let env = job_env_with_defaults(&job, &limits).expect("env"); assert!(env.contains(&("CARGO_BUILD_JOBS".to_owned(), "1".to_owned()))); job.env.insert("CARGO_BUILD_JOBS".to_owned(), "7".to_owned()); diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index f06f1a5..12b1aed 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -192,8 +192,6 @@ syncLog(); followTail(); restoreJobs(jobs); - syncUnread(); - syncActivity(); syncLive(); syncPush(); syncTick(); @@ -549,8 +547,10 @@ }; } - // Every page holds one stream to /-/alive (no data, no login). Its error means the server, or the - // proxy in front of it, is down; its open means it is back. + // Every page holds one stream to /-/shell/events (`/-/alive` for a page from before a deploy, and for + // an anonymous visitor the same alive events). Its error means the server, or the proxy in front of + // it, is down; its open means it is back. Signed-in viewers also get `unread` (the inbox count), + // `activity` (the live strip and ring) and `side` (the sidebar's repo list) on the same connection. // A `theme` event carries the signed-in user's appearance as `name=value` pairs joined by `;` // (the `` attributes). An empty value removes the attribute. Only data-* names are applied. function applyAppearance(data) { @@ -588,13 +588,19 @@ if (link.down) { armBanner(); } } if (window.EventSource) { - alive = keepOpen('/-/alive', aliveOpen, aliveDown, { + alive = keepOpen('/-/shell/events', aliveOpen, aliveDown, { theme: applyAppearance, language: function () { refreshLive(true); }, // The header's identity (username, avatar, admin rights) or the session changed: the page re-renders. account: function () { refreshLive(true); }, // A live server setting changed (the banner, registration, limits...): the page re-renders. - settings: function () { refreshLive(true); } + settings: function () { refreshLive(true); }, + // The inbox count changed (see `unreadChanged` above). + unread: unreadChanged, + // The viewer's activity changed: the strip, ring and chips are fetched again. + activity: function () { refreshActivity(); }, + // The sidebar's repo list changed (the sidebar is re-rendered with the page). + side: sideChanged }); document.addEventListener('visibilitychange', function () { wake(false); }); document.addEventListener('resume', function () { wake(true); }); @@ -1233,12 +1239,10 @@ // A filtered view asked for in place: the URL is replaced (no history entry per change), fields // and caret come through the swap, and the scroll stays put. // Live unread count. The profile corner (data-unread-stream) is re-rendered by every swap, so it is - // looked up on each update. One EventSource serves the page and stays open across swaps. It is - // opened only while a corner is shown (signed-in pages) and closed when it is gone. The server - // pushes each change; nothing polls. Each `unread` event also tells the activity stream below to - // refresh. The count shows twice: as a dot on the menu toggle (has-dot), and next to Notifications - // in the sidebar and the phone menu. - var unreadStream = null; + // looked up on each update. The count arrives as an `unread` event of the shell stream (see + // `/-/shell/events`, opened with the alive handlers above), which the server pushes on each change; + // nothing polls. Each `unread` event also refreshes the activity (below). The count shows twice: as + // a dot on the menu toggle (has-dot), and next to Notifications in the sidebar and the phone menu. // Shows the count in one link the way the server renders it: a span with the number, or no span at zero. function setCount(el, cls, n) { @@ -1264,28 +1268,17 @@ for (var i = 0; i < links.length; i++) { setCount(links[i], 'count', n); } } - function syncUnread() { - if (!document.querySelector('[data-unread-stream]')) { - if (unreadStream) { unreadStream.close(); unreadStream = null; } - return; - } - if (unreadStream || !window.EventSource) { return; } - unreadStream = new EventSource('/notifications/stream'); - unreadStream.addEventListener('unread', function (e) { - setUnread(parseInt(e.data, 10) || 0); - refreshActivity(); - }); + // An `unread` event: the count, then the activity is fetched again. + function unreadChanged(data) { + setUnread(parseInt(data, 10) || 0); + refreshActivity(); } - syncUnread(); - // The live activity: the profile corner (heat ring, chips, waiting list) and the live strip after - // the path bar. The server's activity JSON (GET /-/activity) is the source. A `changed` event of - // its stream, and every `unread` event above, fetches it again and redraws whatever is on the page. - // Nothing changes before the JSON says so. The stream stays open across swaps while a strip is - // shown, as the unread one does. A finished run leaves the strip when the server's window ends, so - // while any is listed the JSON is fetched again every 30 s. - var activityStream = null; + // the path bar. The server's activity JSON (GET /-/activity) is the source. An `activity` event of + // the shell stream, and every `unread` event, fetches it again and redraws whatever is on the page. + // Nothing changes before the JSON says so. A finished run leaves the strip when the server's window + // ends, so while any is listed the JSON is fetched again every 30 s. var activitySeq = 0; // a fetch's number: only the newest answer is drawn var activityTimer = null; // the next refetch while finished runs are listed var SVG_NS = 'http://www.w3.org/2000/svg'; @@ -1516,20 +1509,6 @@ }).catch(function () { }); } - // One EventSource serves the page's strip and stays open across swaps. It is opened only while a - // strip is shown and closed when it is gone. - function syncActivity() { - if (!document.querySelector('.live-strip[data-activity]')) { - if (activityStream) { activityStream.close(); activityStream = null; } - return; - } - if (activityStream || !window.EventSource) { return; } - activityStream = new EventSource('/-/activity/stream'); - activityStream.addEventListener('changed', function () { refreshActivity(); }); - } - - syncActivity(); - // The CI log (a job page's [data-live-log]). The server sends the raw text; this turns it into // numbered lines (#L12 anchors) with ANSI colours as spans, `::group::name` / `::endgroup::` // sections as
, and a search box with highlight and next/previous. Streamed bytes go @@ -2069,6 +2048,15 @@ return es; } + // A `side` event of the shell stream: the sidebar's repo list changed. The page is re-rendered with + // it, as a `changed` event of a data-live stream would, but at most once a second (a code view or a + // live-now page re-renders at once). + function sideChanged() { + if (document.querySelector('[data-live-code], [data-live-now]')) { refreshLive(true); return; } + if (liveTimer) { return; } + liveTimer = setTimeout(function () { liveTimer = null; refreshLive(true); }, 1000); + } + // Closes the streams the page no longer names and opens the ones it newly names. function syncLive() { var want = liveWanted(); @@ -3345,6 +3333,30 @@ href: function (dlg, path) { return fileHref(dlg, path); } }; + // A link with data-dialog opens the whose id it names, in place of following the link. + // Modifier and non-primary clicks still follow the link (a new tab, say). It listens in the capture + // phase on window, so it runs before the soft navigation (capture on document) follows the link. + window.addEventListener('click', function (e) { + if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return; } + var t = e.target; + if (!t || !t.closest) { return; } + var link = t.closest('[data-dialog]'); + if (!link) { return; } + var dlg = document.getElementById(link.getAttribute('data-dialog')); + if (!dlg || dlg.tagName !== 'DIALOG' || typeof dlg.showModal !== 'function') { return; } + e.preventDefault(); + if (!dlg.open) { dlg.showModal(); } + // The same function each time, so the listener is added once however often the dialog opens. + dlg.addEventListener('click', closeOnBackdrop); + }, true); + + // A click on a dialog's backdrop (the dialog element itself, outside its box) closes it. + function closeOnBackdrop(e) { + var r = this.getBoundingClientRect(); + var inside = e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom; + if (e.target === this && !inside) { this.close(); } + } + document.addEventListener('click', function (e) { var t = e.target; if (!t || !t.closest) { return; } diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index 61f416a..48a0c36 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -267,6 +267,8 @@ pub enum Key { LastSeenAt, ExpiresAt, BackToSessions, + NotRecorded, + Close, // Metadata lines (see the helpers below for the words in between). Added, @@ -485,6 +487,8 @@ pub const ALL: &[Key] = &[ Key::LastSeenAt, Key::ExpiresAt, Key::BackToSessions, + Key::NotRecorded, + Key::Close, Key::Added, Key::LastUsed, Key::Created, @@ -889,6 +893,10 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (ExpiresAt, Tr) => "Bitiş", (BackToSessions, En) => "Back to sessions", (BackToSessions, Tr) => "Oturumlara dön", + (NotRecorded, En) => "Not recorded", + (NotRecorded, Tr) => "Kaydedilmedi", + (Close, En) => "Close", + (Close, Tr) => "Kapat", (RevokeAllOthers, En) => "Revoke all other sessions", (RevokeAllOthers, Tr) => "Diğer tüm oturumları iptal et", diff --git a/crates/forge-web/src/live.rs b/crates/forge-web/src/live.rs index 64e51b0..db8eec4 100644 --- a/crates/forge-web/src/live.rs +++ b/crates/forge-web/src/live.rs @@ -28,7 +28,7 @@ use std::future::Future; use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; use futures_util::future::select_all; -use futures_util::stream; +use futures_util::{Stream, stream}; use tokio::sync::watch; use topcoat::Result; use topcoat::context::Cx; @@ -216,6 +216,11 @@ fn changed_event() -> Result { Ok(Event::new().event("changed").data("1")) } +/// A `name` event with no data the client reads, sent on each change of a page's state. +fn named_event(name: &'static str) -> Result { + Ok(Event::new().event(name).data("1")) +} + /// Waits until one of `wakes` is bumped. False when a topic is gone, which ends the stream. async fn wait_any(wakes: &mut [watch::Receiver]) -> bool { let waits = wakes.iter_mut().map(|rx| Box::pin(rx.changed())); @@ -262,6 +267,23 @@ pub async fn stream_changes_with( extra: Vec>, read: F, ) -> Result +where + F: Fn() -> Fut + Send + 'static, + Fut: Future> + Send, +{ + let events = named_changes(hub, topics.to_vec(), extra, "changed", read).await?; + events_response(cx, events) +} + +/// The events of [`stream_changes_with`] as a stream, each named `name`, for a caller that merges +/// several streams into one response (see `pages::shell_events`). +pub async fn named_changes( + hub: &LiveHub, + topics: Vec, + extra: Vec>, + name: &'static str, + read: F, +) -> Result> + Send + 'static> where F: Fn() -> Fut + Send + 'static, Fut: Future> + Send, @@ -271,7 +293,7 @@ where topics.iter().map(|topic| hub.subscribe(topic)).collect(); wakes.extend(extra); let last = read().await?; - let events = stream::unfold(Follow { wakes, read, last }, |mut follow| async move { + Ok(stream::unfold(Follow { wakes, read, last }, move |mut follow| async move { loop { if !wait_any(&mut follow.wakes).await { return None; @@ -287,10 +309,9 @@ where continue; } follow.last = now; - return Some((changed_event(), follow)); + return Some((named_event(name), follow)); } - }); - events_response(cx, events) + })) } #[cfg(test)] diff --git a/crates/forge-web/src/pages/activity.rs b/crates/forge-web/src/pages/activity.rs index a45289c..1e70a24 100644 --- a/crates/forge-web/src/pages/activity.rs +++ b/crates/forge-web/src/pages/activity.rs @@ -15,6 +15,8 @@ use topcoat::router::{Body, HeaderValue, StatusCode, route}; use crate::auth::current_user; use crate::pages::ci_runs::{changed_stream, events_response, run_href}; +use futures_util::Stream; +use topcoat::router::content::sse::Event; use crate::state::AppState; use crate::views::repo_href; @@ -126,9 +128,18 @@ async fn activity_stream(cx: &Cx) -> Result { return Ok(res); }; let state = app_context::(cx).clone(); - // Subscribed before the first read, so a run change in between is sent. + events_response(cx, activity_changes(state, user, "changed")) +} + +/// The viewer's activity events, each named `name`: one now, then one after each run change that +/// alters the JSON. Subscribed when built, before the first read, so a change in between is sent. +pub(crate) fn activity_changes( + state: AppState, + user: User, + name: &'static str, +) -> impl Stream> + Send + 'static { let wake = state.ci_live.subscribe_any_run(); - let events = changed_stream(wake, true, move || { + changed_stream(wake, true, name, move || { let state = state.clone(); let user = user.clone(); async move { @@ -136,8 +147,7 @@ async fn activity_stream(cx: &Cx) -> Result { let body = activity_json(&state, &user).await?.to_string(); Ok(Some((body, false))) } - }); - events_response(cx, events) + }) } #[cfg(test)] diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index ceb02be..94ddff4 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -1978,13 +1978,15 @@ pub(crate) fn changed_event(status: String) -> Result { Ok(Event::new().event("changed").data(status)) } -/// The `changed` events of a CI page. The first event carries the status now. Each later one -/// follows a wake of `wake`: with `only_on_status`, only when the status differs from the last one -/// sent. The stream ends after the terminal status is sent, when the row is gone, or when the signal -/// closes. Subscribe `wake` before the first read, so a change in between is not lost. +/// The events of a CI page, each named `name` (`changed` on a page's own stream). The first event +/// carries the status now. Each later one follows a wake of `wake`: with `only_on_status`, only when +/// the status differs from the last one sent. The stream ends after the terminal status is sent, +/// when the row is gone, or when the signal closes. Subscribe `wake` before the first read, so a +/// change in between is not lost. pub(crate) fn changed_stream( wake: watch::Receiver, only_on_status: bool, + name: &'static str, read: F, ) -> impl Stream> + Send + 'static where @@ -2011,7 +2013,7 @@ where done: false, primed: false, }, - |mut follow| async move { + move |mut follow| async move { loop { if follow.done { return None; @@ -2033,7 +2035,7 @@ where let send = changed || !follow.only_on_status; follow.last = Some(status.clone()); if send { - return Some((changed_event(status), follow)); + return Some((Ok(Event::new().event(name).data(status)), follow)); } } }, @@ -2156,7 +2158,7 @@ async fn run_events(cx: &Cx) -> Result { let run_id = run.id.clone(); let viewer = ctx.viewer.as_ref().map(|(user, _)| user.clone()); let repo_id = ctx.repo.id.clone(); - let events = changed_stream(wake, false, move || { + let events = changed_stream(wake, false, "changed", move || { let store = store.clone(); let run_id = run_id.clone(); let viewer = viewer.clone(); diff --git a/crates/forge-web/src/pages/dashboard.rs b/crates/forge-web/src/pages/dashboard.rs index 02fa8ad..cfd8758 100644 --- a/crates/forge-web/src/pages/dashboard.rs +++ b/crates/forge-web/src/pages/dashboard.rs @@ -12,6 +12,7 @@ use forge_core::{Notification, Repo, Visibility}; use jiff::{Timestamp, civil}; use topcoat::Result; use topcoat::context::{Cx, app_context}; +use topcoat::router::content::sse::Event; use topcoat::router::response::Response; use topcoat::router::{Body, StatusCode, page, query_params, route}; use topcoat::view::{View, component, view}; @@ -20,7 +21,7 @@ use crate::auth::{current_user, percent_encode}; use crate::i18n::misc::{self as m, K as MK}; use crate::i18n::orgs::{self as g, K}; use crate::i18n::{self, Lang}; -use crate::live::{Topic, stream_changes}; +use crate::live::{Topic, named_changes, stream_changes}; use crate::pages::issue_parts::stamp_unix; use crate::pages::repo_settings::{notice_banner_for, take_notice}; use crate::state::AppState; @@ -133,6 +134,22 @@ async fn side_events(cx: &Cx) -> Result { .await } +/// The sidebar's change events for `user`, each named `name` (`changed` on `/-/side/events`). +pub(crate) async fn side_changes( + state: &AppState, + user: &forge_core::User, + name: &'static str, +) -> topcoat::Result> + Send + 'static> { + let topics = vec![Topic::User(user.id.clone())]; + let (state_for_read, user) = (state.clone(), user.clone()); + named_changes(&state.live, topics, Vec::new(), name, move || { + let state = state_for_read.clone(); + let user = user.clone(); + async move { side_fingerprint(&state, &user).await } + }) + .await +} + /// The sidebar's repo list as it shows: the names in order, and the total. async fn side_fingerprint(state: &AppState, user: &forge_core::User) -> Result { let (listed, total) = state diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 4d0a1cb..7a467eb 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -135,6 +135,7 @@ pub mod settings_security; pub mod settings_sessions; pub mod settings_tokens; pub mod setup; +pub mod shell_events; pub mod snippet_raw; pub mod snippets; pub mod snippets_live; diff --git a/crates/forge-web/src/pages/notifications.rs b/crates/forge-web/src/pages/notifications.rs index dd223c4..8bba69e 100644 --- a/crates/forge-web/src/pages/notifications.rs +++ b/crates/forge-web/src/pages/notifications.rs @@ -12,7 +12,7 @@ use forge_core::store::admin_alerts::AdminNotice; use forge_core::store::advisories::AdvisoryNotice; use forge_core::store::transfers::PendingTransfer; use forge_core::{Notification, Reason, Role, SubState, User, WatchLevel}; -use futures_util::{StreamExt, future, stream}; +use futures_util::{Stream, StreamExt, future, stream}; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -725,6 +725,22 @@ fn unread_event(count: u64) -> topcoat::Result { Ok(Event::new().event("unread").data(count.to_string())) } +/// The viewer's unread count as `unread` events: one now, then one after each change to the inbox. +/// Subscribed before the count is read, so a change in between is pushed again, never missed. +pub(crate) async fn unread_changes( + state: &AppState, + user_id: &str, +) -> Result> + Send + 'static> { + let subscription = state.notify_hub.subscribe(user_id); + let count = state.store.unread_count(user_id).await?; + let first = stream::once(future::ready(unread_event(count))); + let changes = stream::unfold(subscription, |mut sub| async move { + let count = sub.next_count().await?; + Some((unread_event(count), sub)) + }); + Ok(first.chain(changes)) +} + /// The bell's live count. Sends an `unread` event with the viewer's unread count now, then one /// after each change to the inbox, until the viewer disconnects or the server shuts down. An /// 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 { return Ok(res); }; let state = app_context::(cx); - let subscription = state.notify_hub.subscribe(&user.id); - // Read after subscribing: a change that lands in between is pushed again, never missed. - let count = state.store.unread_count(&user.id).await?; - let first = stream::once(future::ready(unread_event(count))); - let changes = stream::unfold(subscription, |mut sub| async move { - let count = sub.next_count().await?; - Some((unread_event(count), sub)) - }); - events_response(cx, first.chain(changes)) + let events = unread_changes(state, &user.id).await?; + events_response(cx, events) } /// Subscribes or unsubscribes the viewer from an issue. diff --git a/crates/forge-web/src/pages/register.rs b/crates/forge-web/src/pages/register.rs index c0c060c..e1b71cc 100644 --- a/crates/forge-web/src/pages/register.rs +++ b/crates/forge-web/src/pages/register.rs @@ -423,10 +423,9 @@ async fn verify_resend(cx: &Cx, Form(form): Form) -> Result(cx); if let Some(address) = viewer.0.email.clone() && !state.store.email_is_verified(&viewer.0.id).await? + && !account::send_verify(state, &viewer.0, &address).await? { - if !account::send_verify(state, &viewer.0, &address).await? { - return Ok(see_other("/settings/security?saved=verify_wait")); - } + return Ok(see_other("/settings/security?saved=verify_wait")); } Ok(see_other("/settings/security?saved=verify_sent")) } diff --git a/crates/forge-web/src/pages/repo_side.rs b/crates/forge-web/src/pages/repo_side.rs index de4fffd..ea7835d 100644 --- a/crates/forge-web/src/pages/repo_side.rs +++ b/crates/forge-web/src/pages/repo_side.rs @@ -63,6 +63,7 @@ fn dir_size(path: &Path) -> u64 { } /// The tree facts of `repo` at `commit`, read once per commit. `root` is the root entry names. +#[allow(clippy::ptr_arg)] // the path is moved into a blocking task, which needs an owned PathBuf pub async fn tree_facts( state: &AppState, repo: &Repo, diff --git a/crates/forge-web/src/pages/settings_live.rs b/crates/forge-web/src/pages/settings_live.rs index 46e9593..3b6f7fb 100644 --- a/crates/forge-web/src/pages/settings_live.rs +++ b/crates/forge-web/src/pages/settings_live.rs @@ -24,7 +24,7 @@ use std::collections::VecDeque; use forge_core::server_settings::{self, FIELDS, Kind}; -use futures_util::stream; +use futures_util::stream::{self, BoxStream, StreamExt}; use tokio::sync::watch; use topcoat::Result; use topcoat::context::{Cx, app_context, try_app_context}; @@ -172,6 +172,17 @@ pub async fn alive_response(cx: &Cx) -> Result { let viewer = current_user(cx) .await? .map(|(user, session)| (user.id, session.id)); + let events = alive_stream(state, viewer).await?; + events_response(cx, events) +} + +/// The events of the alive stream for `viewer` (the user and session ids, when signed in). See +/// [`alive_response`]. The caller holds the stream slot; `pages::shell_events` merges it with the +/// shell's other streams. +pub async fn alive_stream( + state: AppState, + viewer: Option<(String, String)>, +) -> Result>> { // Subscribed before each baseline is read, so a change in between is not lost. let server_wake = state.live.subscribe(&Topic::ServerSettings); let settings_last = settings_fingerprint(&state); @@ -195,7 +206,7 @@ pub async fn alive_response(cx: &Cx) -> Result { settings_last, queue: VecDeque::new(), }; - events_response(cx, stream::unfold(alive, next_alive_event)) + Ok(stream::unfold(alive, next_alive_event).boxed()) } /// Waits for the next event of the alive stream. A wake that changes nothing the viewer sees sends diff --git a/crates/forge-web/src/pages/settings_sessions.rs b/crates/forge-web/src/pages/settings_sessions.rs index 3df10ae..667c8bc 100644 --- a/crates/forge-web/src/pages/settings_sessions.rs +++ b/crates/forge-web/src/pages/settings_sessions.rs @@ -65,7 +65,7 @@ async fn sessions_view( for session in sessions.into_iter() {
  • - (session_label(lang, &session)) + (session_label(lang, &session)) (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)) if session.id == current_id { (t(lang, Key::ThisSession)) @@ -78,6 +78,15 @@ async fn sessions_view( } + +
    +

    (session_label(lang, &session))

    +
    + +
    +
    + session_details(lang: lang, csrf: csrf, session: session.clone(), current: session.id == current_id) +
  • } @@ -93,8 +102,10 @@ async fn sessions_view( }) } +/// The facts about one session, shared by its dialog on the list and its detail page: the badge +/// when it is the current session, the key/value grid, and the revoke button for any other one. #[component] -async fn session_detail_view( +async fn session_details( lang: Lang, csrf: &str, session: Session, @@ -104,34 +115,51 @@ async fn session_detail_view( .user_agent .clone() .unwrap_or_else(|| t(lang, Key::UnknownBrowser).to_owned()); - let sign_in_ip = session.ip.clone().unwrap_or_else(|| "-".to_owned()); - let last_ip = session.last_ip.clone().unwrap_or_else(|| "-".to_owned()); + // Sessions from before IP recording have no sign-in address. + let sign_in_ip = session + .ip + .clone() + .unwrap_or_else(|| t(lang, Key::NotRecorded).to_owned()); + let last_ip = session + .last_ip + .clone() + .unwrap_or_else(|| t(lang, Key::NotRecorded).to_owned()); let id = session.id.clone(); Ok(view! { -
    -

    (session_label(lang, &session))

    -
    if current {

    (t(lang, Key::ThisSession))

    } -
    -
    -
    (t(lang, Key::UserAgent))
    (user_agent.as_str())
    -
    (t(lang, Key::SignInIp))
    (sign_in_ip.as_str())
    -
    (t(lang, Key::LastIp))
    (last_ip.as_str())
    -
    (t(lang, Key::SignedIn))
    rel_time(lang: lang, stamp: session.created_at.as_str())
    -
    (t(lang, Key::LastSeenAt))
    rel_time(lang: lang, stamp: session.last_seen.as_str())
    -
    (t(lang, Key::ExpiresAt))
    rel_time(lang: lang, stamp: session.expires_at.as_str())
    -
    +
    +
    (t(lang, Key::UserAgent))
    (user_agent.as_str())
    +
    (t(lang, Key::SignInIp))
    (sign_in_ip.as_str())
    +
    (t(lang, Key::LastIp))
    (last_ip.as_str())
    +
    (t(lang, Key::SignedIn))
    rel_time(lang: lang, stamp: session.created_at.as_str())
    +
    (t(lang, Key::LastSeenAt))
    rel_time(lang: lang, stamp: session.last_seen.as_str())
    +
    (t(lang, Key::ExpiresAt))
    rel_time(lang: lang, stamp: session.expires_at.as_str())
    +
    + if !current { +
    + + + +
    + } + }) +} + +#[component] +async fn session_detail_view( + lang: Lang, + csrf: &str, + session: Session, + current: bool, +) -> Result { + Ok(view! { +
    +

    (session_label(lang, &session))

    - if !current { -
    - - - -
    - } + session_details(lang: lang, csrf: csrf, session: session, current: current)

    (t(lang, Key::BackToSessions))

    }) @@ -254,6 +282,39 @@ mod tests { const CSRF: &str = "sessions-test-csrf"; + #[tokio::test] + async fn sessions_list_renders_a_dialog_per_session() { + let dir = tempfile::tempdir().expect("tempdir"); + let state = crate::test_support::test_state(dir.path()).await; + let store = state.store.clone(); + let router = crate::test_support::app_router(state.clone()); + let tahinli = store + .create_user("tahinli", None, "x", false) + .await + .expect("tahinli"); + crate::test_support::create_session(&store, &tahinli.id, "tahinli-token", CSRF).await; + let current = store + .list_sessions(&tahinli.id) + .await + .expect("sessions") + .pop() + .expect("one session"); + + let req = Request::builder() + .method("GET") + .uri("/settings/sessions") + .header("cookie", format!("__Host-{SESSION_COOKIE}=tahinli-token")) + .body(Body::empty()) + .expect("request"); + let res = router.handle(req).await; + assert_eq!(res.status().as_u16(), 200); + let body = to_bytes(res.into_body(), usize::MAX).await.expect("body"); + let html = String::from_utf8_lossy(&body); + let id = format!("session-{}", current.id); + assert!(html.contains(&format!(" Result { + // A router with no app state (the asset tests) has nothing to follow: the stream only stays open. + let Some(state) = try_app_context::(cx).cloned() else { + return events_response(cx, stream::pending::>()); + }; + let viewer = current_user(cx).await?; + let ids = viewer + .as_ref() + .map(|(user, session)| (user.id.clone(), session.id.clone())); + let mut parts: Vec>> = + vec![alive_stream(state.clone(), ids).await?]; + if let Some((user, _)) = viewer { + parts.push(unread_changes(&state, &user.id).await?.boxed()); + parts.push(activity_changes(state.clone(), user.clone(), "activity").boxed()); + parts.push(side_changes(&state, &user, "side").await?.boxed()); + } + events_response(cx, stream::select_all(parts)) +} + +#[cfg(test)] +mod tests { + use topcoat::router::request::Request; + use topcoat::router::{Body, StatusCode}; + + use crate::auth::SESSION_COOKIE; + + /// The shell stream answers `text/event-stream` to an anonymous visitor and to a signed-in one. + #[tokio::test] + async fn shell_events_is_an_event_stream_for_anonymous_and_signed_in_viewers() { + let dir = tempfile::tempdir().expect("tempdir"); + let state = crate::test_support::test_state(dir.path()).await; + let store = state.store.clone(); + let router = crate::test_support::app_router(state); + let user = store + .create_user("tahinli", None, "x", false) + .await + .expect("user"); + crate::test_support::create_session(&store, &user.id, "tok", "csrf").await; + + for cookie in [None, Some(format!("__Host-{SESSION_COOKIE}=tok"))] { + let mut builder = Request::builder().method("GET").uri("/-/shell/events"); + if let Some(cookie) = &cookie { + builder = builder.header("cookie", cookie.as_str()); + } + let res = router + .handle(builder.body(Body::empty()).expect("request")) + .await; + assert_eq!(res.status(), StatusCode::OK, "cookie: {cookie:?}"); + assert!( + res.headers()["content-type"] + .to_str() + .expect("header") + .starts_with("text/event-stream"), + "cookie: {cookie:?}" + ); + } + } +} diff --git a/crates/forge-web/src/repo_stats.rs b/crates/forge-web/src/repo_stats.rs index 6822ef1..69a3e1e 100644 --- a/crates/forge-web/src/repo_stats.rs +++ b/crates/forge-web/src/repo_stats.rs @@ -165,7 +165,7 @@ pub fn languages(files: &[(String, u64)], top: usize) -> Vec { }) .collect(); // Biggest first; equal sizes keep their name order, which the BTreeMap gave. - rows.sort_by(|a, b| b.bytes.cmp(&a.bytes)); + rows.sort_by_key(|a| std::cmp::Reverse(a.bytes)); if rows.len() > top { let rest = rows.split_off(top); @@ -306,7 +306,7 @@ const LICENSE_NAMES: &[&str] = &[ /// The root entry that holds the license, if any: LICENSE, LICENSE.md, LICENSE.txt, LICENCE, /// COPYING, LICENSE-MIT ... (case-insensitive). The first match in a fixed preference order. -pub fn license_file<'a>(root_names: &'a [String]) -> Option<&'a str> { +pub fn license_file(root_names: &[String]) -> Option<&str> { LICENSE_NAMES.iter().find_map(|want| { root_names .iter() diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index 1a8a8a8..be55238 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -868,7 +868,7 @@ async fn side_nav( (o::t(lang, OK::Settings)) -
    +

    (o::t(lang, OK::RecentRepositories))

    if empty {

    (o::t(lang, OK::NoReposYet))

    diff --git a/style/_account_admin.scss b/style/_account_admin.scss index 927a3f0..201b782 100644 --- a/style/_account_admin.scss +++ b/style/_account_admin.scss @@ -51,6 +51,57 @@ } } +// A session's details over /settings/sessions, opened from its title. The body is the kv-grid in two +// columns; the close button sits at the top right, and the revoke button under the grid. +dialog.session-dialog { + width: min(640px, calc(100% - 32px)); + max-height: min(80vh, 640px); + margin: 10vh auto 0; + padding: 20px 24px; + overflow: auto; + color: var(--text); + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-md); + box-shadow: var(--shadow); + + &::backdrop { + background: rgba(0, 0, 0, 0.45); + } + + .session-dialog-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 16px; + + h2 { + margin: 0; + min-width: 0; + font-size: 1.125rem; + overflow-wrap: anywhere; + } + + form { + margin: 0; + flex: none; + } + } + + .kv-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + + @media (max-width: 520px) { + grid-template-columns: minmax(0, 1fr); + } + } + + > form { + margin-top: 16px; + } +} + // Admin user detail. The header: a back link, the avatar, the name with a status dot and a role // badge, one muted meta line, then one row of small facts. Under it the actions are hairline rows // (title and one line of help on the left, the button on the right); the destructive ones sit in