From d7d6a17efcfe64929e095166244b4689846a4811 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 22 Oct 2026 06:31:49 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20feat:=20settings=20pages=20update?= =?UTF-8?q?=20live,=20and=20the=20theme=20follows=20into=20every=20open=20?= =?UTF-8?q?tab?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-web/src/api/mod.rs | 1 + crates/forge-web/src/api/packages.rs | 1 + crates/forge-web/src/auth.rs | 4 + crates/forge-web/src/boot.rs | 1 + crates/forge-web/src/git_auth.rs | 1 + crates/forge-web/src/live.rs | 4 + crates/forge-web/src/pages/admin_mail.rs | 4 + crates/forge-web/src/pages/admin_server.rs | 1 + crates/forge-web/src/pages/ci_tests.rs | 17 +- crates/forge-web/src/pages/mod.rs | 1 + crates/forge-web/src/pages/settings_live.rs | 236 ++++++++++++++++++++ crates/forge-web/src/ssh_backend.rs | 1 + crates/forge-web/src/test_support.rs | 1 + crates/forge-web/src/views/mod.rs | 22 +- docs/architecture.md | 3 + 15 files changed, 291 insertions(+), 7 deletions(-) create mode 100644 crates/forge-web/src/pages/settings_live.rs diff --git a/crates/forge-web/src/api/mod.rs b/crates/forge-web/src/api/mod.rs index f3db2ec..95a4b4a 100644 --- a/crates/forge-web/src/api/mod.rs +++ b/crates/forge-web/src/api/mod.rs @@ -114,6 +114,7 @@ pub async fn authenticate( if let Err(e) = state.store.touch_token(&token_id).await { return Err(internal(e)); } + crate::pages::settings_live::bump_account(state, &user.id); Ok(Some(user)) } diff --git a/crates/forge-web/src/api/packages.rs b/crates/forge-web/src/api/packages.rs index c458085..319d99f 100644 --- a/crates/forge-web/src/api/packages.rs +++ b/crates/forge-web/src/api/packages.rs @@ -59,6 +59,7 @@ async fn caller(cx: &Cx, scope_required: bool) -> Result, Refusal> if let Err(e) = state.store.touch_token(&token_id).await { return Err(Box::new(failure(PackageError::Internal(e.to_string())))); } + crate::pages::settings_live::bump_account(state, &user.id); Ok(Some(user)) } diff --git a/crates/forge-web/src/auth.rs b/crates/forge-web/src/auth.rs index 496cf20..6bcf2a7 100644 --- a/crates/forge-web/src/auth.rs +++ b/crates/forge-web/src/auth.rs @@ -83,6 +83,10 @@ pub async fn login(cx: &Cx, user: &User) -> forge_core::Result { user_agent(cx).as_deref(), ) .await?; + // A new sign-in shows up in the user's session list in their other open tabs. + app_context::(cx) + .live + .bump(&crate::live::Topic::Account(user.id.clone())); let max_age = time::Duration::seconds(i64::try_from(SESSION_TTL.as_secs()).unwrap_or(i64::MAX)); session_jar(cx).add( Cookie::build((SESSION_COOKIE, token)) diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 0b3520c..335d2a1 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -165,6 +165,7 @@ pub async fn serve( let public: Router = Router::builder() .discover() .app_context(state.clone()) + .layer(crate::pages::settings_live::AccountWriteLayer) .cookies() .layer(crate::pages::settings_profile::avatar_body_limit()) .layer(crate::pages::repo_ctx::RepoMovedLayer) diff --git a/crates/forge-web/src/git_auth.rs b/crates/forge-web/src/git_auth.rs index 5fd825c..be5c907 100644 --- a/crates/forge-web/src/git_auth.rs +++ b/crates/forge-web/src/git_auth.rs @@ -72,6 +72,7 @@ pub async fn user_from_basic( .touch_token(&access.id) .await .map_err(internal)?; + crate::pages::settings_live::bump_account(state, &user.id); Ok(Some(user)) } diff --git a/crates/forge-web/src/live.rs b/crates/forge-web/src/live.rs index 41e3225..660a1e1 100644 --- a/crates/forge-web/src/live.rs +++ b/crates/forge-web/src/live.rs @@ -103,6 +103,10 @@ pub enum Topic { /// replaced or removed, or an asset was downloaded (its count). Keyed by repo id. The release /// list and the release pages follow it. Bumped by [`crate::release_ops`]. RepoReleases(String), + /// A user's own settings: a profile, key, token, passkey, session, notification or appearance + /// setting changed, or a sign-in or a key or token use happened. Keyed by user id. Streamed only + /// to that user, never to the public profile viewers who follow [`Topic::User`]. + Account(String), } /// The hub of the admin pages. It is process-wide, not part of [`crate::state::AppState`]: the diff --git a/crates/forge-web/src/pages/admin_mail.rs b/crates/forge-web/src/pages/admin_mail.rs index 86fdc02..e353987 100644 --- a/crates/forge-web/src/pages/admin_mail.rs +++ b/crates/forge-web/src/pages/admin_mail.rs @@ -948,6 +948,10 @@ mod tests { settings.contains(r#"data-live="/admin/mail/events""#), "the settings tab is live too" ); + assert!( + settings.contains(r#"data-live="/settings/theme/events""#), + "the theme follows into the admin pages" + ); assert!( !settings.contains("Reset your password"), "the queue is on its own tab" diff --git a/crates/forge-web/src/pages/admin_server.rs b/crates/forge-web/src/pages/admin_server.rs index 83d6be8..b871825 100644 --- a/crates/forge-web/src/pages/admin_server.rs +++ b/crates/forge-web/src/pages/admin_server.rs @@ -886,6 +886,7 @@ mod tests { let page = admin_get(&fx, "/admin/server?restarting=an-older-boot").await; assert!(!page.contains("Restarting...")); assert!(page.contains(r#"data-live="/admin/server/events""#)); + assert!(page.contains(r#"data-live="/settings/theme/events""#)); assert!(page.contains("The server restarted")); } diff --git a/crates/forge-web/src/pages/ci_tests.rs b/crates/forge-web/src/pages/ci_tests.rs index 66f6d3a..e0d1102 100644 --- a/crates/forge-web/src/pages/ci_tests.rs +++ b/crates/forge-web/src/pages/ci_tests.rs @@ -340,7 +340,10 @@ async fn pages_are_live_while_not_finished_and_never_meta_refresh() { finish_job(&fx).await; let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; assert!( - !done.text().contains("data-live="), + !done + .text() + .replace(r#"data-live="/settings/theme/events""#, "") + .contains("data-live="), "job not live when finished" ); assert!( @@ -504,7 +507,13 @@ async fn run_list_is_live_on_page_one_only() { Some(&cookie_for("tahinli-token")), ) .await; - assert!(!second.text().contains("data-live="), "page 2 is not live"); + assert!( + !second + .text() + .replace(r#"data-live="/settings/theme/events""#, "") + .contains("data-live="), + "page 2 is not live" + ); let run = get( &fx.app, &format!("{RUN_BASE}/runs/30?page=2"), @@ -512,7 +521,9 @@ async fn run_list_is_live_on_page_one_only() { ) .await; assert!( - !run.text().contains("data-live="), + !run.text() + .replace(r#"data-live="/settings/theme/events""#, "") + .contains("data-live="), "a run on page 2 is not live" ); } diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 4247395..3be7745 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -121,6 +121,7 @@ pub mod settings_gpg; #[cfg(test)] mod settings_gpg_tests; pub mod settings_keys; +pub mod settings_live; pub mod settings_notifications; pub mod settings_profile; pub mod settings_security; diff --git a/crates/forge-web/src/pages/settings_live.rs b/crates/forge-web/src/pages/settings_live.rs new file mode 100644 index 0000000..b8d862e --- /dev/null +++ b/crates/forge-web/src/pages/settings_live.rs @@ -0,0 +1,236 @@ +//! Live settings. The signed-in user's own settings pages (`/settings/...`) follow +//! [`Topic::Account`] of their own user through `GET /settings/events`. The settings section of the +//! sidebar names that stream (see `views::section_for`), so every page under `/settings` follows it +//! without an attribute of its own. Public profile viewers follow [`Topic::User`] and never wake. +//! +//! Writes reach the topic two ways: +//! - A POST under `/settings/` (a profile, key, token, passkey, session, notification, appearance +//! or security change): [`AccountWriteLayer`] bumps the viewer's topic after the handler ran, so +//! no route calls a bump itself. A refused write bumps too: the page re-reads and agrees. +//! - Anything outside those paths that changes what the pages show: a sign-in (`auth::login`), and +//! a key or token used by git, the API, SSH or a package client. Those call [`bump_account`]. +//! +//! The stream sends `changed` on each wake and carries no data: the page re-reads itself. A session +//! revoked elsewhere is caught the same way. The re-read finds no session, so the page leaves for +//! the login page. + +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::{method, uri}; +use topcoat::router::response::Response; +use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode, route}; + +use crate::auth::current_user; +use crate::live::{LiveHub, Topic, stream_changes, stream_wakes}; +use crate::state::AppState; + +/// Wakes the settings pages of `user_id`. Called after a write that changes what they show. +pub fn bump_account(state: &AppState, user_id: &str) { + state.live.bump(&Topic::Account(user_id.to_owned())); +} + +/// The change stream of the viewer's settings. The viewer comes from the session only, so a user +/// can follow only their own settings. Without a session: 401. +#[route(GET "/settings/events")] +async fn settings_events(cx: &Cx) -> Result { + let Some((user, _)) = current_user(cx).await? else { + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(res); + }; + let hub: &LiveHub = &app_context::(cx).live; + stream_wakes(cx, hub, &[Topic::Account(user.id)]) +} + +/// The appearance stream of a signed-in user's tabs. The shell of every signed-in page follows it, +/// so a theme, accent, base, language or sidebar change made in one tab reaches the others. It +/// sends `changed` only when the appearance differs from what the page shows. +#[route(GET "/settings/theme/events")] +async fn theme_events(cx: &Cx) -> Result { + let Some((user, _)) = current_user(cx).await? else { + let mut res = Response::new(Body::empty()); + *res.status_mut() = StatusCode::UNAUTHORIZED; + return Ok(res); + }; + let state = app_context::(cx).clone(); + let topics = [Topic::Account(user.id.clone())]; + let user_id = user.id; + stream_changes(cx, &state.live.clone(), &topics, move || { + let state = state.clone(); + let user_id = user_id.clone(); + async move { appearance_fingerprint(&state, &user_id).await } + }) + .await +} + +/// The appearance fields of a user, as one line. Compared, never sent. +async fn appearance_fingerprint(state: &AppState, user_id: &str) -> Result { + let Some(user) = state.store.user_by_id(user_id).await? else { + return Ok(String::new()); + }; + Ok(format!( + "{}|{}|{}|{}|{}|{}|{}", + user.theme, + user.language, + user.accent, + user.accent_dark, + user.base_light, + user.base_dark, + user.sidebar_side + )) +} + +/// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router +/// in `boot.rs` and the test router. It sits on a path, so it runs inside the cookie layer (a +/// pathless layer would run outside it, where the session cannot be read). +pub struct AccountWriteLayer; + +impl Layer for AccountWriteLayer { + fn path(&self) -> Option<&Path> { + Some(Path::new("/settings")) + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(bump_after_settings_write(cx, body, next)) + } +} + +/// Bumps the viewer's topic once the handler has run. The viewer is read before the handler, so a +/// write that ends the viewer's own session (a revoke of the current one) still wakes the tabs. +async fn bump_after_settings_write(cx: &Cx, body: Body, next: Next<'_>) -> Result { + if *method(cx) != Method::POST || !uri(cx).path().starts_with("/settings/") { + return next.run(cx, body).await; + } + let viewer = current_user(cx) + .await + .ok() + .flatten() + .map(|(user, _)| user.id); + let result = next.run(cx, body).await; + if let Some(user_id) = viewer { + bump_account(app_context::(cx), &user_id); + } + result +} + +#[cfg(test)] +mod tests { + use futures_util::StreamExt; + use topcoat::router::request::Request; + use topcoat::router::{Body, to_bytes}; + + use crate::auth::SESSION_COOKIE; + use crate::live::Topic; + use crate::test_support::{app_router, create_session, test_state}; + + const CSRF: &str = "settings-live-csrf"; + + #[tokio::test] + async fn the_stream_needs_a_session() { + let dir = tempfile::tempdir().expect("tempdir"); + let router = app_router(test_state(dir.path()).await); + let request = Request::builder() + .method("GET") + .uri("/settings/events") + .body(Body::empty()) + .expect("request"); + assert_eq!(router.handle(request).await.status().as_u16(), 401); + } + + #[tokio::test] + async fn the_theme_stream_needs_a_session_and_the_settings_name_their_streams() { + let dir = tempfile::tempdir().expect("tempdir"); + let state = test_state(dir.path()).await; + let store = state.store.clone(); + let owner = store + .create_user("tahinli", None, "h", false) + .await + .expect("user"); + create_session(&store, &owner.id, "owner-token", CSRF).await; + let router = app_router(state); + + let anon = Request::builder() + .method("GET") + .uri("/settings/theme/events") + .body(Body::empty()) + .expect("request"); + assert_eq!(router.handle(anon).await.status().as_u16(), 401); + + let page = Request::builder() + .method("GET") + .uri("/settings/profile") + .header("cookie", format!("__Host-{SESSION_COOKIE}=owner-token")) + .body(Body::empty()) + .expect("request"); + let res = router.handle(page).await; + let html = + String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.expect("body")) + .into_owned(); + assert!(html.contains(" Some(key.user_id), diff --git a/crates/forge-web/src/test_support.rs b/crates/forge-web/src/test_support.rs index 3fa9ec5..37b7d3b 100644 --- a/crates/forge-web/src/test_support.rs +++ b/crates/forge-web/src/test_support.rs @@ -97,6 +97,7 @@ pub fn app_router(state: AppState) -> Router { Router::builder() .discover() .app_context(state) + .layer(crate::pages::settings_live::AccountWriteLayer) .cookies() .layer(avatar_body_limit()) .layer(RepoMovedLayer) diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index e2f736d..04800e0 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -165,6 +165,8 @@ pub async fn shell( let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned()); let lang = i18n::lang(__cx, viewer.map(|(user, _)| user)); let banner = crate::pages::banner::current(__cx); + // A signed-in tab follows its appearance, so a change in another tab applies here too. + let theme_live = signed_in.then_some("/settings/theme/events"); let banner_back = back.clone().unwrap_or_else(|| "/".to_owned()); let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss); // The admin area and the user settings swap the global links for their own list. Signed-in only. @@ -267,7 +269,7 @@ pub async fn shell( } - +
if signed_in {