From b25287e1147b720659270d1df8fecaf3faee1f59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 17 Oct 2026 21:22:10 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(ci):=20live=20runs=20list,=20j?= =?UTF-8?q?ob=20graph,=20badge=20labels=20and=20a=20one-form=20profile=20s?= =?UTF-8?q?ettings=20page?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Runs list updates live over SSE on page 1 (per-repo change signal), rows are whole-row links. - Run page: compact header and a server-rendered job graph staged by `needs`; job rows are links. - Job log opens at its tail and keeps following unless the reader scrolls up. - Badge label: `?label=`, then the job name, then ci.toml `name`, then "ci"; README badge added. - Profile settings: username, about and timezone in one form, avatar with an Edit menu. --- README.md | 2 + crates/forge-ci/src/config.rs | 74 ++++ crates/forge-ci/src/error.rs | 3 + crates/forge-web/assets/nav.js | 14 +- crates/forge-web/src/ci/api.rs | 2 + crates/forge-web/src/ci/live.rs | 46 +- crates/forge-web/src/ci/reaper.rs | 13 +- crates/forge-web/src/ci/schedule.rs | 13 + crates/forge-web/src/i18n/admin.rs | 5 +- crates/forge-web/src/i18n/mod.rs | 28 +- crates/forge-web/src/i18n/releases_ci.rs | 4 + crates/forge-web/src/pages/ci_badge.rs | 48 +- crates/forge-web/src/pages/ci_runs.rs | 275 +++++++++++- crates/forge-web/src/pages/ci_tests.rs | 292 +++++++++++- .../forge-web/src/pages/settings_profile.rs | 336 +++++++------- docs/ci.md | 23 + style/main.scss | 414 +++++++++++++++++- 17 files changed, 1329 insertions(+), 263 deletions(-) diff --git a/README.md b/README.md index aeaa2d7..cb4fc4c 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # forge +[![build](https://git.tahinli.com/Tahinli/forge/badge.svg?branch=main&label=build)](https://git.tahinli.com/Tahinli/forge/ci) + forge is a self-hosted git forge. You run it on your own server, so your code stays on machines you control and no third-party service sits in the middle. It ships as one binary, `forge`, which serves the web UI, git over HTTPS, and git over SSH. Repositories are plain bare git repositories on disk, and account data lives in one SQLite database. Try the live instance at https://git.tahinli.com. diff --git a/crates/forge-ci/src/config.rs b/crates/forge-ci/src/config.rs index 8e04c22..0d5cc7a 100644 --- a/crates/forge-ci/src/config.rs +++ b/crates/forge-ci/src/config.rs @@ -27,11 +27,16 @@ pub const MAX_JOBS: usize = 20; pub const DEFAULT_TIMEOUT_MINUTES: u32 = 60; /// Smallest and largest allowed job timeout. pub const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive = 1..=360; +/// Longest workflow `name`, in characters, after trimming. +pub const MAX_WORKFLOW_NAME_CHARS: usize = 40; /// A parsed and validated workflow. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct CiConfig { + /// Optional display name, e.g. `"build"`. The CI badge uses it as its label. + #[serde(default)] + pub name: Option, /// The `[on]` table. Optional; defaults to manual runs only. #[serde(rename = "on", default)] pub on: Triggers, @@ -159,6 +164,9 @@ impl CiConfig { } fn validate(&self) -> Result<(), ConfigError> { + if let Some(name) = &self.name { + validate_workflow_name(name)?; + } if self.jobs.is_empty() { return Err(ConfigError::NoJobs); } @@ -215,6 +223,28 @@ fn validate_trigger_glob(kind: &'static str, pattern: &str) -> Result<(), Config .map_err(|e| invalid(e.to_string())) } +/// A workflow name: non-empty after trimming, at most [`MAX_WORKFLOW_NAME_CHARS`] characters, and +/// no control characters. +fn validate_workflow_name(name: &str) -> Result<(), ConfigError> { + let invalid = |reason: &str| ConfigError::InvalidWorkflowName { + name: name.to_string(), + reason: reason.to_string(), + }; + let trimmed = name.trim(); + if trimmed.is_empty() { + return Err(invalid("must not be empty")); + } + if trimmed.chars().count() > MAX_WORKFLOW_NAME_CHARS { + return Err(invalid(&format!( + "must be at most {MAX_WORKFLOW_NAME_CHARS} characters" + ))); + } + if trimmed.chars().any(char::is_control) { + return Err(invalid("must not contain control characters")); + } + Ok(()) +} + /// `^[a-z0-9][a-z0-9_-]{0,39}$` fn is_job_name(name: &str) -> bool { let Some((first, rest)) = name.as_bytes().split_first() else { @@ -659,4 +689,48 @@ artifacts = ["target/release/forge"] let cfg = parse_config(EXAMPLE).unwrap(); assert_eq!(cfg.job_order(), vec!["test", "lint"]); } + + #[test] + fn workflow_name_is_optional_and_kept() { + assert_eq!(parse_config(&job_toml("")).unwrap().name, None); + let cfg = parse_config(&format!("name = \"build\"\n{}", job_toml(""))).unwrap(); + assert_eq!(cfg.name.as_deref(), Some("build")); + } + + #[test] + fn workflow_name_must_not_be_blank() { + for text in ["name = \"\"", "name = \" \""] { + let err = err_of(&format!("{text}\n{}", job_toml(""))); + assert!( + matches!(err, ConfigError::InvalidWorkflowName { .. }), + "{text}: {err:?}" + ); + } + } + + #[test] + fn workflow_name_length_is_capped_after_trimming() { + let at_limit = "n".repeat(MAX_WORKFLOW_NAME_CHARS); + let ok = format!("name = \" {at_limit} \"\n{}", job_toml("")); + assert!(parse_config(&ok).is_ok()); + let over = "n".repeat(MAX_WORKFLOW_NAME_CHARS + 1); + let err = err_of(&format!("name = \"{over}\"\n{}", job_toml(""))); + assert!(matches!(err, ConfigError::InvalidWorkflowName { .. })); + } + + #[test] + fn workflow_name_rejects_control_characters() { + let err = err_of(&format!("name = \"a\\u0007b\"\n{}", job_toml(""))); + assert!(matches!(err, ConfigError::InvalidWorkflowName { .. })); + let err = err_of(&format!("name = \"a\\nb\"\n{}", job_toml(""))); + assert!(matches!(err, ConfigError::InvalidWorkflowName { .. })); + } + + #[test] + fn workflow_name_must_be_a_string() { + assert!(matches!( + err_of(&format!("name = 3\n{}", job_toml(""))), + ConfigError::Toml(_) + )); + } } diff --git a/crates/forge-ci/src/error.rs b/crates/forge-ci/src/error.rs index 0126d53..28985b1 100644 --- a/crates/forge-ci/src/error.rs +++ b/crates/forge-ci/src/error.rs @@ -20,6 +20,9 @@ pub enum ConfigError { #[error("invalid job name {0:?}: must match ^[a-z0-9][a-z0-9_-]{{0,39}}$")] InvalidJobName(String), + #[error("invalid workflow name {name:?}: {reason}")] + InvalidWorkflowName { name: String, reason: String }, + #[error("job {job:?} needs unknown job {need:?}")] UnknownNeed { job: String, need: String }, diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index e73d163..1b7b015 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -144,10 +144,17 @@ old.replaceWith(s); }); if (kept) { restoreFields(kept); } + followTail(); syncUnread(); syncLive(); } + // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place. + function followTail() { + var pre = document.querySelector('[data-live-log]'); + if (pre) { pre.scrollTop = pre.scrollHeight; } + } + function focusMain() { var main = document.querySelector('main'); if (main && main.focus) { main.focus({ preventScroll: true }); } @@ -174,7 +181,7 @@ var saved = history.state; // A live swap keeps the log tail where the reader had it: at the end it stays at the end. var tail = how === 'live' ? document.querySelector('[data-live-log]') : null; - var tailAt = tail ? { top: tail.scrollTop, end: tail.scrollTop + tail.clientHeight >= tail.scrollHeight - 8 } : null; + var tailAt = tail ? { top: tail.scrollTop, end: tail.scrollTop + tail.clientHeight >= tail.scrollHeight - 24 } : null; closeDropdowns(null); adopt(doc, keepFields); if (tailAt) { @@ -425,11 +432,11 @@ } // Appends streamed log text to the tail as a text node, never as HTML. The tail follows the end - // only while the reader is already at the end. + // only while the reader is already at the end (within 24px). Scrolling back down resumes following. function appendLog(text) { var pre = document.querySelector('[data-live-log]'); if (!pre || !text) { return; } - var atEnd = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 8; + var atEnd = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 24; pre.appendChild(document.createTextNode(text)); if (atEnd) { pre.scrollTop = pre.scrollHeight; } } @@ -444,6 +451,7 @@ load({ target: withoutHash(here), dest: here, init: GET_INIT, how: 'live', keep: true, post: false, form: null }); } + followTail(); syncLive(); window.__forgeQuery = function (href) { diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index 6b35cfc..e5ca48d 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -251,6 +251,7 @@ async fn try_claim(state: &AppState, runner: &CiRunner) -> Result watch::Receiver { self.runs.subscribe(run_id) } + /// Subscribes to changes of repo `repo_id`: a run of the repo was created or changed state. + /// Same rules as [`CiLive::subscribe_job`]. + pub fn subscribe_repo(&self, repo_id: &str) -> watch::Receiver { + self.repos.subscribe(repo_id) + } + /// Wakes the subscribers of job `job_id`: its log grew or its state changed. Does nothing when /// nobody is subscribed. pub fn bump_job(&self, job_id: &str) { @@ -43,6 +49,12 @@ impl CiLive { self.runs.bump(run_id); } + /// Wakes the subscribers of repo `repo_id`: a run of the repo was created or changed state. + /// Callers bump it next to the run bump, since the run signal does not know its repo. + pub fn bump_repo(&self, repo_id: &str) { + self.repos.bump(repo_id); + } + /// Wakes the subscribers of job `job_id` once more and drops its signal. Call it when the job /// has reached a terminal state: no change follows, so the signal is not kept. A subscriber /// that waits on a closed signal wakes once and then sees it closed. @@ -135,8 +147,28 @@ mod tests { let live = CiLive::default(); live.bump_job("job-1"); live.bump_run("run-1"); + live.bump_repo("repo-1"); assert!(live.jobs.counters().is_empty()); assert!(live.runs.counters().is_empty()); + assert!(live.repos.counters().is_empty()); + } + + #[tokio::test] + async fn a_repo_bump_wakes_only_the_subscribers_of_that_repo() { + let live = CiLive::default(); + let mut repo = live.subscribe_repo("repo-1"); + let other = live.subscribe_repo("repo-2"); + let run = live.subscribe_run("run-1"); + + live.bump_repo("repo-1"); + + tokio::time::timeout(Duration::from_secs(1), repo.changed()) + .await + .expect("woken") + .expect("open"); + assert_eq!(*repo.borrow_and_update(), 1); + assert!(!other.has_changed().expect("open")); + assert!(!run.has_changed().expect("open")); } #[test] diff --git a/crates/forge-web/src/ci/reaper.rs b/crates/forge-web/src/ci/reaper.rs index 794a37e..183eac8 100644 --- a/crates/forge-web/src/ci/reaper.rs +++ b/crates/forge-web/src/ci/reaper.rs @@ -64,12 +64,15 @@ pub async fn reap_before(state: &AppState, older_than: &str) -> usize { continue; } match state.store.run_by_id(&job.run_id).await { - Ok(Some(run)) => match sync_run_statuses(state, &run).await { - Ok(queued) => wake |= queued, - Err(e) => { - tracing::error!(error = %e, run_id = %run.id, "ci: syncing statuses failed") + Ok(Some(run)) => { + state.ci_live.bump_repo(&run.repo_id); + match sync_run_statuses(state, &run).await { + Ok(queued) => wake |= queued, + Err(e) => { + tracing::error!(error = %e, run_id = %run.id, "ci: syncing statuses failed") + } } - }, + } Ok(None) => {} Err(e) => tracing::error!(error = %e, run_id = %job.run_id, "ci: loading run failed"), } diff --git a/crates/forge-web/src/ci/schedule.rs b/crates/forge-web/src/ci/schedule.rs index 4af755c..f8e6fe6 100644 --- a/crates/forge-web/src/ci/schedule.rs +++ b/crates/forge-web/src/ci/schedule.rs @@ -223,6 +223,7 @@ async fn create( config_error, ) .await?; + state.ci_live.bump_repo(&run.repo_id); if let Some(message) = config_error { let url = format!( "{}/{}/{}/ci/runs/{}", @@ -317,6 +318,18 @@ async fn load(state: &AppState, repo_id: &str, commit: &str) -> Loaded { } } +/// The trimmed workflow `name` in `.forge/ci.toml` at `commit`. `None` when the file is missing, +/// does not parse, or has no name. Reads one git object, so the badge can call it per request. +pub async fn workflow_name(state: &AppState, repo_id: &str, commit: &str) -> Option { + match load(state, repo_id, commit).await { + Loaded::Valid(cfg) => cfg + .name + .map(|name| name.trim().to_owned()) + .filter(|name| !name.is_empty()), + Loaded::Missing | Loaded::Invalid(_) => None, + } +} + /// Whether a pull request needs approval before its jobs run: a fork head, or an author who lacks /// Write on the base repo (or no longer exists). async fn needs_approval( diff --git a/crates/forge-web/src/i18n/admin.rs b/crates/forge-web/src/i18n/admin.rs index 7939794..0fd5edb 100644 --- a/crates/forge-web/src/i18n/admin.rs +++ b/crates/forge-web/src/i18n/admin.rs @@ -810,7 +810,10 @@ mod tests { fn english_text_matches_the_original_phrases() { assert_eq!(t(Lang::En, K::DeleteUser), "Delete user"); assert!(t(Lang::En, K::ReplicationOff).starts_with("Replication is off.")); - assert_eq!(type_to_confirm(Lang::En, "tahinli"), "Type tahinli to confirm"); + assert_eq!( + type_to_confirm(Lang::En, "tahinli"), + "Type tahinli to confirm" + ); assert_eq!( running_line(Lang::En, RunKind::Backup), "A backup run is in progress." diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index f09c625..382d1f4 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -169,18 +169,17 @@ pub enum Key { ErrWrongCode, // Profile. - OkUsernameUpdated, OkAvatarUpdated, OkAvatarRemoved, OkProfileSaved, - CurrentUsername, UsernameHint, Avatar, AvatarAlt, Image, AvatarHint, - RemoveAvatar, - AboutAndTimezone, + Edit, + UploadPhoto, + RemovePhoto, About, AboutHint, Timezone, @@ -371,18 +370,17 @@ pub const ALL: &[Key] = &[ Key::ErrWrongPassword, Key::ErrWrongConfirmCode, Key::ErrWrongCode, - Key::OkUsernameUpdated, Key::OkAvatarUpdated, Key::OkAvatarRemoved, Key::OkProfileSaved, - Key::CurrentUsername, Key::UsernameHint, Key::Avatar, Key::AvatarAlt, Key::Image, Key::AvatarHint, - Key::RemoveAvatar, - Key::AboutAndTimezone, + Key::Edit, + Key::UploadPhoto, + Key::RemovePhoto, Key::About, Key::AboutHint, Key::Timezone, @@ -630,16 +628,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { "Bu kod doğru değil. Doğrulama uygulamanızdaki bir kodu ya da bir kurtarma kodunu kullanın." } - (OkUsernameUpdated, En) => "Username updated.", - (OkUsernameUpdated, Tr) => "Kullanıcı adı güncellendi.", (OkAvatarUpdated, En) => "Avatar updated.", (OkAvatarUpdated, Tr) => "Avatar güncellendi.", (OkAvatarRemoved, En) => "Avatar removed.", (OkAvatarRemoved, Tr) => "Avatar kaldırıldı.", (OkProfileSaved, En) => "Profile saved.", (OkProfileSaved, Tr) => "Profil kaydedildi.", - (CurrentUsername, En) => "Current username: ", - (CurrentUsername, Tr) => "Mevcut kullanıcı adı: ", (UsernameHint, En) => { "Only the capitalization can be changed. Your lookup name stays the same." } @@ -658,10 +652,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (AvatarHint, Tr) => { "PNG, JPEG, WebP ya da GIF, en fazla 5 MiB. Görseller kareye kırpılır ve 256 x 256 piksele küçültülür." } - (RemoveAvatar, En) => "Remove avatar", - (RemoveAvatar, Tr) => "Avatarı kaldır", - (AboutAndTimezone, En) => "About and timezone", - (AboutAndTimezone, Tr) => "Hakkında ve saat dilimi", + (Edit, En) => "Edit", + (Edit, Tr) => "Düzenle", + (UploadPhoto, En) => "Upload a photo…", + (UploadPhoto, Tr) => "Fotoğraf yükle…", + (RemovePhoto, En) => "Remove photo", + (RemovePhoto, Tr) => "Fotoğrafı kaldır", (About, En) => "About", (About, Tr) => "Hakkında", (AboutHint, En) => "At most 2000 characters. Markdown is supported.", diff --git a/crates/forge-web/src/i18n/releases_ci.rs b/crates/forge-web/src/i18n/releases_ci.rs index e937623..bea5551 100644 --- a/crates/forge-web/src/i18n/releases_ci.rs +++ b/crates/forge-web/src/i18n/releases_ci.rs @@ -30,6 +30,7 @@ pub enum K { Runs, NoRunsYet, Jobs, + JobGraph, NoJobs, ColRun, ColState, @@ -175,6 +176,8 @@ pub fn t(lang: Lang, key: K) -> &'static str { (NoRunsYet, Tr) => "Henüz çalıştırma yok.", (Jobs, En) => "Jobs", (Jobs, Tr) => "İşler", + (JobGraph, En) => "Job graph", + (JobGraph, Tr) => "İş grafiği", (NoJobs, En) => "No jobs.", (NoJobs, Tr) => "İş yok.", (ColRun, En) => "Run", @@ -471,6 +474,7 @@ mod tests { K::Runs, K::NoRunsYet, K::Jobs, + K::JobGraph, K::NoJobs, K::ColRun, K::ColState, diff --git a/crates/forge-web/src/pages/ci_badge.rs b/crates/forge-web/src/pages/ci_badge.rs index 1fc24b3..f19d21f 100644 --- a/crates/forge-web/src/pages/ci_badge.rs +++ b/crates/forge-web/src/pages/ci_badge.rs @@ -2,6 +2,9 @@ //! on a branch (`?branch=`, default: the default branch), or of one job of that run (`&job=`). The //! SVG is a flat shields-style image, rendered here with no outside assets. //! +//! The label, the left half, is `?label=` if given, else the job name when `&job=` is given, else +//! the `name` of the run's `.forge/ci.toml`, else "ci". +//! //! Access is the repo's read access: a private repo a viewer cannot read is a 404, like every other //! repo page. A repo with no run on the branch still answers 200 with "no status". @@ -13,6 +16,7 @@ use topcoat::router::request::uri; use topcoat::router::response::Response; use topcoat::router::{Body, HeaderValue, StatusCode, path_param, route}; +use crate::ci::schedule::workflow_name; use crate::pages::repo_ctx::load_repo; use crate::state::AppState; @@ -21,6 +25,8 @@ path_param!(repo); /// Longest label shown, in characters. A longer job name is cut here. const MAX_LABEL_CHARS: usize = 64; +/// The label when neither `?label=`, a job, nor a workflow name gives one. +const DEFAULT_LABEL: &str = "ci"; /// Height of the badge in pixels. const HEIGHT: u32 = 20; /// Padding on each side of a text, in pixels. @@ -158,11 +164,12 @@ pub fn render_badge(label: &str, status: BadgeStatus) -> String { ) } -/// The query values the badge reads. Empty values count as absent. +/// The query values the badge reads. Empty values count as absent. A label is trimmed first. #[derive(Default)] struct BadgeQuery { branch: Option, job: Option, + label: Option, } fn badge_query(cx: &Cx) -> BadgeQuery { @@ -171,13 +178,20 @@ fn badge_query(cx: &Cx) -> BadgeQuery { return query; }; for (key, value) in form_urlencoded::parse(raw.as_bytes()) { - let slot = match key.as_ref() { + let key = key.as_ref(); + let slot = match key { "branch" => &mut query.branch, "job" => &mut query.job, + "label" => &mut query.label, _ => continue, }; + let value: &str = if key == "label" { + value.trim() + } else { + value.as_ref() + }; if !value.is_empty() { - *slot = Some(value.into_owned()); + *slot = Some(value.to_owned()); } } query @@ -200,19 +214,31 @@ async fn ci_badge(cx: &Cx) -> Result { .store .latest_run_on_ref(&ctx.repo.id, &git_ref) .await?; - let (label, status) = match (run, query.job) { - (None, job) => ( - job.unwrap_or_else(|| "ci".to_owned()), - BadgeStatus::NoStatus, - ), - (Some(run), None) => ("ci".to_owned(), status_of_run(run.state)), - (Some(run), Some(job)) => { + let Some(run) = run else { + // No run to read a workflow name from: the label, a job name, or the default. + let label = query + .label + .or(query.job) + .unwrap_or_else(|| DEFAULT_LABEL.to_owned()); + return Ok(svg_response(render_badge(&label, BadgeStatus::NoStatus))); + }; + let (label, status) = match query.job { + Some(job) => { let jobs = state.store.jobs_for_run(&run.id).await?; let status = jobs .iter() .find(|j| j.name == job) .map_or(BadgeStatus::NoStatus, |j| status_of_job(j.state)); - (job, status) + (query.label.unwrap_or(job), status) + } + None => { + let label = match query.label { + Some(label) => label, + None => workflow_name(state, &ctx.repo.id, &run.commit_oid) + .await + .unwrap_or_else(|| DEFAULT_LABEL.to_owned()), + }; + (label, status_of_run(run.state)) } }; Ok(svg_response(render_badge(&label, status))) diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index 7d53645..0a1e070 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -4,7 +4,8 @@ //! 404 for a private repo and a refusal for a change. Every change notifies the job waker and syncs //! the commit status of each job it changed. A run or job page that is not finished stays live: it //! opens a `changed` event stream (`.../events`) and re-renders itself on each event, with no reload -//! and no timer. +//! and no timer. The run list stays live on page 1 the same way, through `/{owner}/{repo}/ci/events`, +//! which fires on every run created or changed in the repo. use std::collections::HashMap; use std::future::Future; @@ -12,7 +13,7 @@ use std::time::Duration; use forge_core::ci::{CiJob, CiRun, RunState}; use forge_core::{Action, Denied, Store, User, authorize}; -use forge_git::browse::{RefInfo, RefKind}; +use forge_git::browse::{RefInfo, RefKind, read_commit}; use futures_util::{Stream, stream}; use serde::Deserialize; use time::OffsetDateTime; @@ -252,6 +253,7 @@ async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> Resul return Ok(()); }; state.ci_live.bump_run(run_id); + state.ci_live.bump_repo(&run.repo_id); for job in state.store.jobs_for_run(run_id).await? { let changed = before .iter() @@ -306,9 +308,36 @@ struct JobRow { message: String, } +/// Layout of the job graph in SVG units. The `.ci-graph-*` rules in main.scss use the same sizes. +const GRAPH_PAD: i64 = 16; +const GRAPH_CARD_W: i64 = 200; +const GRAPH_CARD_H: i64 = 56; +const GRAPH_COL_GAP: i64 = 48; +const GRAPH_ROW_GAP: i64 = 16; + +/// One job card of the graph. `class` is the card's class with its status word. +struct GraphCard { + class: String, + href: String, + name: String, + state: String, + duration: String, +} + +/// The job graph of a run: the cards by stage column, and the connector paths between them. +struct JobGraph { + width: String, + height: String, + columns: Vec>, + paths: Vec, +} + /// The run page's header values. struct RunView { number: i64, + title: String, + commit_href: String, + duration: String, state: String, state_class: String, trigger: String, @@ -365,6 +394,7 @@ async fn runs_body( newer_href: Option, older_href: Option, page_label: String, + live: Option, ) -> Result { Ok(view! { repo_head(head: head) @@ -404,6 +434,7 @@ async fn runs_body( +

(g::t(lang, K::Runs))

if rows.is_empty() { @@ -425,7 +456,7 @@ async fn runs_body( for row in rows.iter() { - "#" (row.number) + "#" (row.number) (row.state.as_str()) (row.trigger.as_str()) (row.git_ref.as_str()) @@ -448,6 +479,7 @@ async fn runs_body( }
+
}) } @@ -481,6 +513,8 @@ async fn runs_list_page(cx: &Cx) -> Result { let newer_href = (page > 1).then(|| format!("{base}?page={}", page - 1)); let older_href = (u64::from(page) < last_page).then(|| format!("{base}?page={}", page + 1)); let page_label = g::page_label(lang, page); + // Page 1 follows the repo's changes, since a new run can appear at any time. Other pages do not. + let live = (page == 1).then(|| format!("{base}/events")); let manual = if can_write(&ctx) { let csrf = match current_user(cx).await? { Some((_, session)) => session.csrf_token.clone(), @@ -502,10 +536,23 @@ async fn runs_list_page(cx: &Cx) -> Result { Ok(view! { shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), runs_body(head: head, lang: lang, notice: notice, manual: manual, badge: badge, rows: rows, - newer_href: newer_href, older_href: older_href, page_label: page_label)) + newer_href: newer_href, older_href: older_href, page_label: page_label, live: live)) }) } +/// The live `changed` stream of a repo's run list. It is sent on each change of the repo: a run was +/// created or changed state. Nothing is sent on connect, since the page was just rendered. +#[route(GET "/{owner}/{repo}/ci/events")] +async fn runs_events(cx: &Cx) -> Result { + let owner = path_param::(cx); + let name = path_param::(cx); + let ctx = load_repo(cx, owner, name).await?; + let state = app_context::(cx); + // Subscribed before the response is sent, so a change after this point is sent. + let wake = state.ci_live.subscribe_repo(&ctx.repo.id); + events_response(cx, repo_changes(wake)) +} + /// Starts a manual run on a branch. Writers only. The branch must be one of the repo's branches. #[route(POST "/{owner}/{repo}/ci")] async fn manual_run_post(cx: &Cx, Form(form): Form) -> Result { @@ -544,10 +591,24 @@ async fn run_view( lang: Lang, ) -> Result { let names = usernames(state, lang, std::iter::once(run.actor_id.as_str())).await?; - let title = title_of(ctx); - let action_base = run_href(&title, run.number); + let repo_title = title_of(ctx); + let action_base = run_href(&repo_title, run.number); + // The commit's first line is the run title. A run whose commit cannot be read shows its trigger. + let path = ctx.path.clone(); + let oid = run.commit_oid.clone(); + let subject = tokio::task::spawn_blocking(move || read_commit(&path, &oid)) + .await?? + .map(|commit| commit.summary) + .filter(|summary| !summary.is_empty()); Ok(RunView { number: run.number, + title: subject.unwrap_or_else(|| run.trigger.clone()), + commit_href: format!("/{repo_title}/commit/{}", run.commit_oid), + duration: duration_text( + lang, + Some(run.created_at.as_str()), + run.finished_at.as_deref(), + ), state: state_text(lang, run.state.as_str()), state_class: format!("ci-state ci-{}", run.state.as_str()), trigger: run.trigger.clone(), @@ -586,6 +647,130 @@ fn job_rows( .collect() } +/// The `needs` of a job spec. A spec that does not read gives no needs. +fn needs_of(spec_json: &str) -> Vec { + #[derive(Deserialize)] + struct Needs { + #[serde(default)] + needs: Vec, + } + serde_json::from_str::(spec_json) + .map(|spec| spec.needs) + .unwrap_or_default() +} + +/// Stage depth of each job, in the order given: 0 with no needs, else 1 plus the largest depth of its +/// needs. A need that names no job of the run is ignored. A cycle (config parsing refuses one) stops +/// at the job that repeats, so the walk always ends. +pub(crate) fn stage_depths(jobs: &[(&str, &[String])]) -> Vec { + let index: HashMap<&str, usize> = jobs + .iter() + .enumerate() + .map(|(i, (name, _))| (*name, i)) + .collect(); + let deps: Vec> = jobs + .iter() + .map(|(_, needs)| { + needs + .iter() + .filter_map(|need| index.get(need.as_str()).copied()) + .collect() + }) + .collect(); + let mut memo = vec![None; jobs.len()]; + let mut active = vec![false; jobs.len()]; + (0..jobs.len()) + .map(|i| depth_of(i, &deps, &mut memo, &mut active)) + .collect() +} + +/// The stage depth of job `i`, memoized in `memo`. `active` marks the jobs on the walk now. +fn depth_of( + i: usize, + deps: &[Vec], + memo: &mut [Option], + active: &mut [bool], +) -> usize { + if let Some(depth) = memo[i] { + return depth; + } + if active[i] { + return 0; + } + active[i] = true; + let depth = deps[i] + .iter() + .map(|&need| depth_of(need, deps, memo, active) + 1) + .max() + .unwrap_or(0); + active[i] = false; + memo[i] = Some(depth); + depth +} + +/// The job graph of a run. Each job sits in the column of its stage depth, below the jobs before it +/// in that column. A connector runs from each needed job to the job that needs it. +fn job_graph(title: &str, jobs: &[CiJob], lang: Lang) -> JobGraph { + let needs: Vec> = jobs.iter().map(|job| needs_of(&job.spec_json)).collect(); + let named: Vec<(&str, &[String])> = jobs + .iter() + .zip(&needs) + .map(|(job, n)| (job.name.as_str(), n.as_slice())) + .collect(); + let depths = stage_depths(&named); + let stages = depths.iter().max().map_or(0, |deepest| deepest + 1); + let mut columns: Vec> = (0..stages).map(|_| Vec::new()).collect(); + let mut slots = Vec::with_capacity(jobs.len()); + for (job, &depth) in jobs.iter().zip(&depths) { + slots.push((depth, columns[depth].len())); + columns[depth].push(GraphCard { + class: format!("ci-graph-card ci-{}", job.state.as_str()), + href: job_href(title, &job.id), + name: job.name.clone(), + state: state_text(lang, job.state.as_str()), + duration: duration_text(lang, job.started_at.as_deref(), job.finished_at.as_deref()), + }); + } + let x = |stage: usize| GRAPH_PAD + stage as i64 * (GRAPH_CARD_W + GRAPH_COL_GAP); + let y = |row: usize| GRAPH_PAD + row as i64 * (GRAPH_CARD_H + GRAPH_ROW_GAP); + let stage_count = stages as i64; + let tallest = columns.iter().map(Vec::len).max().unwrap_or(0) as i64; + let width = + 2 * GRAPH_PAD + stage_count * GRAPH_CARD_W + (stage_count - 1).max(0) * GRAPH_COL_GAP; + let height = 2 * GRAPH_PAD + tallest * GRAPH_CARD_H + (tallest - 1).max(0) * GRAPH_ROW_GAP; + let index: HashMap<&str, usize> = jobs + .iter() + .enumerate() + .map(|(i, job)| (job.name.as_str(), i)) + .collect(); + let bend = GRAPH_COL_GAP / 2; + let mut paths = Vec::new(); + for (i, job_needs) in needs.iter().enumerate() { + let (to_stage, to_row) = slots[i]; + let x2 = x(to_stage); + let y2 = y(to_row) + GRAPH_CARD_H / 2; + for need in job_needs { + let Some(&from) = index.get(need.as_str()) else { + continue; + }; + let (from_stage, from_row) = slots[from]; + let x1 = x(from_stage) + GRAPH_CARD_W; + let y1 = y(from_row) + GRAPH_CARD_H / 2; + paths.push(format!( + "M{x1} {y1} C{} {y1} {} {y2} {x2} {y2}", + x1 + bend, + x2 - bend + )); + } + } + JobGraph { + width: width.to_string(), + height: height.to_string(), + columns, + paths, + } +} + /// How often an idle event stream sends a `: keepalive` comment, so a reverse proxy does not drop /// the connection. This is not a poll: events follow the change signals. const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30); @@ -674,6 +859,15 @@ where ) } +/// One `changed` event per wake of `wake`. The repo list has no status to compare, so each wake is +/// sent. The stream ends when the signal closes. +fn repo_changes(wake: watch::Receiver) -> impl Stream> + Send + 'static { + stream::unfold(wake, |mut wake| async move { + wake.changed().await.ok()?; + Some((changed_event("list".to_owned()), wake)) + }) +} + /// The response of an event stream for a CI page: keep-alive comments while idle, and no buffering /// by a reverse proxy. pub(crate) fn events_response( @@ -700,6 +894,7 @@ async fn run_body( notice: Option<(&'static str, bool)>, run: RunView, jobs: Vec, + graph: JobGraph, writer_csrf: Option, live: Option, ) -> Result { @@ -713,21 +908,26 @@ async fn run_body(
(text)
} } -
-

(g::t(lang, K::RunNumber)) (run.number)

-

- (run.state.as_str()) - " \u{b7} " (run.trigger.as_str()) - " \u{b7} " (run.git_ref.as_str()) - " \u{b7} " (short_oid(&run.commit).to_owned()) - if !run.actor.is_empty() { - " \u{b7} " (run.actor.as_str()) +

+
+

(run.state.as_str())" "(run.title.as_str())

+

+ "#" (run.number) + " \u{b7} " (run.trigger.as_str()) + " \u{b7} " (run.git_ref.as_str()) + " \u{b7} " (short_oid(&run.commit).to_owned()) + if !run.actor.is_empty() { + " \u{b7} " (run.actor.as_str()) + } + " \u{b7} " (run.when.as_str()) + if !run.duration.is_empty() { + " \u{b7} " (run.duration.as_str()) + } +

+ if let Some(message) = run.config_error.as_ref() { +
(message.as_str())
} - " \u{b7} " (run.when.as_str()) -

- if let Some(message) = run.config_error.as_ref() { -
(message.as_str())
- } +
if let Some(csrf) = writer_csrf {
if run.can_approve { @@ -740,6 +940,36 @@ async fn run_body(
}
+ if !jobs.is_empty() { +
+

(g::t(lang, K::JobGraph))

+
+
+ + for stage in graph.columns.iter() { + + } +
+
+
+ }

(g::t(lang, K::Jobs))

if jobs.is_empty() { @@ -759,7 +989,7 @@ async fn run_body( for job in jobs.iter() { - (job.name.as_str()) + (job.name.as_str()) (job.state.as_str()) (job.duration.as_str()) (job.runner.as_str()) @@ -804,6 +1034,7 @@ async fn run_page(cx: &Cx) -> Result { .collect(); let title = title_of(&ctx); let rows = job_rows(&title, &jobs, &runners, lang); + let graph = job_graph(&title, &jobs, lang); let live = (!run_finished(&run.state)).then(|| format!("{}/events", run_href(&title, run.number))); let notice = notice_from_query(cx, lang); @@ -813,7 +1044,7 @@ async fn run_page(cx: &Cx) -> Result { Ok(view! { shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), run_body(head: head, lang: lang, notice: notice, run: header, jobs: rows, - writer_csrf: writer_csrf, live: live)) + graph: graph, writer_csrf: writer_csrf, live: live)) }) } diff --git a/crates/forge-web/src/pages/ci_tests.rs b/crates/forge-web/src/pages/ci_tests.rs index d5b04f1..0f11e25 100644 --- a/crates/forge-web/src/pages/ci_tests.rs +++ b/crates/forge-web/src/pages/ci_tests.rs @@ -301,7 +301,10 @@ async fn run_list_pages_25_at_a_time() { .await; assert_eq!(bogus.status, 200); assert_eq!( - bogus.text().matches("href=\"/tahinli/proj/ci/runs/").count(), + bogus + .text() + .matches("href=\"/tahinli/proj/ci/runs/") + .count(), 25 ); } @@ -463,6 +466,65 @@ async fn live_events_open_with_the_status_and_follow_changes() { assert!(next_event(&mut job_frames).await.is_none(), "stream ends"); } +/// The run list is live on page 1 only: a new run can appear there at any time. Page 2 is a fixed +/// slice, so it carries no live marker. +#[tokio::test] +async fn run_list_is_live_on_page_one_only() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + for _ in 0..30 { + run_with(&fx, &[], false).await; + } + let marker = format!("data-live=\"{RUN_BASE}/events\""); + let first = get(&fx.app, RUN_BASE, Some(&cookie_for("tahinli-token"))).await; + assert!(first.text().contains(&marker), "page 1 is live"); + let second = get( + &fx.app, + &format!("{RUN_BASE}?page=2"), + Some(&cookie_for("tahinli-token")), + ) + .await; + assert!(!second.text().contains("data-live="), "page 2 is not live"); +} + +#[tokio::test] +async fn run_list_events_need_the_same_access_as_the_page() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let url = format!("{RUN_BASE}/events"); + let anon = open(&fx.app, &url, None).await; + assert_eq!(anon.status().as_u16(), 404, "anonymous"); + let outsider = open(&fx.app, &url, Some(&cookie_for("carol-token"))).await; + assert_eq!(outsider.status().as_u16(), 404, "outsider"); + let reader = open(&fx.app, &url, Some(&cookie_for("dave-token"))).await; + assert_eq!(reader.status().as_u16(), 200, "reader"); +} + +/// The list stream sends nothing on connect, then one `changed` event per change of the repo. +#[tokio::test] +async fn run_list_events_follow_repo_changes() { + use futures_util::StreamExt; + + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let mut frames = open( + &fx.app, + &format!("{RUN_BASE}/events"), + Some(&cookie_for("tahinli-token")), + ) + .await + .into_body() + .into_data_stream(); + + let quiet = tokio::time::timeout(Duration::from_millis(200), frames.next()).await; + assert!(quiet.is_err(), "nothing is sent on connect"); + + run_with(&fx, &["build"], false).await; + fx.live.bump_repo(&fx.repo.id); + let first = next_event(&mut frames).await.expect("a repo change"); + assert_eq!(first, b"event: changed\ndata: list\n\n".to_vec()); +} + /// The job's log events: each append is sent as a `log` event with its bytes, the id is the offset /// past them, and the bytes before `?from=` are not sent again. #[tokio::test] @@ -995,3 +1057,231 @@ async fn badge_follows_read_access_and_reports_the_latest_run() { let unknown_repo = get(&fx.app, "/tahinli/nothere/badge.svg", None).await; assert_eq!(unknown_repo.status, 404); } + +/// Writes `.forge/ci.toml` with `text` into a new commit of the bare repo and returns its id. +fn commit_ci_toml(bare: &Path, text: &str) -> String { + fn git(bare: &Path, args: &[&str], stdin: &str) -> String { + let mut child = std::process::Command::new("git") + .arg("--git-dir") + .arg(bare) + .args(args) + .env("GIT_AUTHOR_NAME", "tahinli") + .env("GIT_AUTHOR_EMAIL", "tahinli@example.com") + .env("GIT_COMMITTER_NAME", "tahinli") + .env("GIT_COMMITTER_EMAIL", "tahinli@example.com") + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("spawn git"); + child + .stdin + .take() + .expect("stdin") + .write_all(stdin.as_bytes()) + .expect("write stdin"); + let out = child.wait_with_output().expect("git output"); + assert!( + out.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8(out.stdout) + .expect("utf8") + .trim() + .to_owned() + } + let blob = git(bare, &["hash-object", "-w", "--stdin"], text); + let forge = git(bare, &["mktree"], &format!("100644 blob {blob}\tci.toml\n")); + let root = git(bare, &["mktree"], &format!("040000 tree {forge}\t.forge\n")); + git(bare, &["commit-tree", root.as_str(), "-m", "ci config"], "") +} + +/// Creates a queued run of one job `build` at `commit` on `main`. +async fn run_at(fx: &Fixture, commit: &str) { + let needs: &[String] = &[]; + let specs = [NewJob { + name: "build", + spec_json: SPEC, + needs, + }]; + fx.store + .create_run( + &fx.repo.id, + "push", + "refs/heads/main", + commit, + None, + &fx.tahinli, + false, + &specs, + None, + ) + .await + .expect("run"); +} + +#[tokio::test] +async fn badge_label_comes_from_the_query_job_or_workflow_name() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path"); + let commit = commit_ci_toml( + &bare, + "name = \" release-check \"\n[jobs.build]\nimage = \"i\"\nrun = \"r\"\n", + ); + run_at(&fx, &commit).await; + finish_job(&fx).await; + let path = "/tahinli/proj/badge.svg"; + let reader = Some(cookie_for("dave-token")); + let named = get(&fx.app, path, reader.as_deref()).await.text(); + assert!(named.contains(">release-check"), "name: {named}"); + assert!(named.contains(">passing")); + + let job = get(&fx.app, &format!("{path}?job=build"), reader.as_deref()) + .await + .text(); + assert!(job.contains(">build"), "job beats name: {job}"); + + let label = get(&fx.app, &format!("{path}?label=Ship"), reader.as_deref()) + .await + .text(); + assert!(label.contains(">Ship"), "label beats name: {label}"); + + let both = get( + &fx.app, + &format!("{path}?job=build&label=Ship"), + reader.as_deref(), + ) + .await + .text(); + assert!(both.contains(">Ship"), "label beats job: {both}"); + assert!(both.contains(">passing"), "status is the job's"); +} + +#[tokio::test] +async fn badge_label_is_trimmed_and_empty_means_absent() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + run_with(&fx, &["build"], false).await; + finish_job(&fx).await; + let path = "/tahinli/proj/badge.svg"; + let reader = Some(cookie_for("dave-token")); + let padded = get( + &fx.app, + &format!("{path}?label=%20deploy%20"), + reader.as_deref(), + ) + .await + .text(); + assert!(padded.contains(">deploy"), "{padded}"); + let empty = get(&fx.app, &format!("{path}?label="), reader.as_deref()) + .await + .text(); + assert!( + empty.contains(">ci"), + "empty label is absent: {empty}" + ); + let blank = get(&fx.app, &format!("{path}?label=%20%20"), reader.as_deref()) + .await + .text(); + assert!( + blank.contains(">ci"), + "blank label is absent: {blank}" + ); +} + +#[tokio::test] +async fn badge_label_is_escaped() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + run_with(&fx, &["build"], false).await; + finish_job(&fx).await; + let reader = Some(cookie_for("dave-token")); + let svg = get( + &fx.app, + "/tahinli/proj/badge.svg?label=%3Cb%3E%20a%20%26%20b%20%3E", + reader.as_deref(), + ) + .await + .text(); + assert!(svg.contains("<b> a & b >"), "{svg}"); + assert!(!svg.contains(""), "raw markup must not reach the SVG"); +} + +#[tokio::test] +async fn badge_label_defaults_to_ci_without_a_usable_workflow_name() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path"); + // A run whose config has an empty name: the name is ignored. + let commit = commit_ci_toml( + &bare, + "name = \" \"\n[jobs.build]\nimage = \"i\"\nrun = \"r\"\n", + ); + run_at(&fx, &commit).await; + finish_job(&fx).await; + let reader = Some(cookie_for("dave-token")); + let svg = get(&fx.app, "/tahinli/proj/badge.svg", reader.as_deref()) + .await + .text(); + assert!(svg.contains(">ci"), "{svg}"); +} + +#[tokio::test] +async fn badge_without_any_run_uses_the_label_or_ci() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let reader = Some(cookie_for("dave-token")); + let plain = get(&fx.app, "/tahinli/proj/badge.svg", reader.as_deref()) + .await + .text(); + assert!(plain.contains(">ci"), "{plain}"); + assert!(plain.contains(">no status")); + let labelled = get( + &fx.app, + "/tahinli/proj/badge.svg?label=Nightly", + reader.as_deref(), + ) + .await + .text(); + assert!(labelled.contains(">Nightly"), "{labelled}"); + assert!(labelled.contains(">no status")); +} + +/// Stage depths of a run's jobs, from `(name, needs)` pairs in job order. +fn depths_of(jobs: &[(&str, &[&str])]) -> Vec { + let owned: Vec<(&str, Vec)> = jobs + .iter() + .map(|(name, needs)| (*name, needs.iter().map(|n| n.to_string()).collect())) + .collect(); + let named: Vec<(&str, &[String])> = owned + .iter() + .map(|(name, needs)| (*name, needs.as_slice())) + .collect(); + crate::pages::ci_runs::stage_depths(&named) +} + +#[test] +fn stage_depths_follow_the_longest_chain_of_needs() { + // A chain, a job with two needs one stage past the deeper one, and jobs with no needs. + let depths = depths_of(&[ + ("lint", &[]), + ("build", &[]), + ("test", &["build"]), + ("docs", &["lint"]), + ("deploy", &["test", "lint"]), + ]); + assert_eq!(depths, vec![0, 0, 1, 1, 2]); + // A job that needs a job which needs a job sits two stages down. + let chain = depths_of(&[("c", &["b"]), ("b", &["a"]), ("a", &[])]); + assert_eq!(chain, vec![2, 1, 0]); +} + +#[test] +fn stage_depths_ignore_unknown_needs_and_survive_cycles() { + assert_eq!(depths_of(&[("a", &["ghost"])]), vec![0]); + // Config parsing refuses cycles. The walk must still end. + let cycle = depths_of(&[("a", &["b"]), ("b", &["a"])]); + assert_eq!(cycle.len(), 2); +} diff --git a/crates/forge-web/src/pages/settings_profile.rs b/crates/forge-web/src/pages/settings_profile.rs index f4bd8cf..5b9f2e3 100644 --- a/crates/forge-web/src/pages/settings_profile.rs +++ b/crates/forge-web/src/pages/settings_profile.rs @@ -1,5 +1,6 @@ -//! Page: profile (`/settings/profile`). Username capitalization, avatar upload and removal, -//! the "about" text and the timezone. Every POST checks the CSRF token first. +//! Page: public profile (`/settings/profile`). One form saves the username capitalization, the +//! "about" text and the timezone. The avatar menu beside it posts to its own upload and removal +//! routes. Every POST checks the CSRF token first. use forge_core::AuditAction; use forge_core::names::capitalization_change; @@ -36,18 +37,13 @@ struct ProfileQuery { saved: Option, } +/// The one profile form: username, about and timezone. #[derive(Deserialize)] struct ProfileForm { #[serde(default)] csrf: String, #[serde(default)] username: String, -} - -#[derive(Deserialize)] -struct DetailsForm { - #[serde(default)] - csrf: String, #[serde(default)] about: String, #[serde(default)] @@ -77,12 +73,21 @@ impl Draft { } } -/// Per-section error messages. +/// Per-field error messages, shown under the field they belong to. #[derive(Default)] struct Errors { username: Option, + about: Option, + timezone: Option, avatar: Option, - details: Option, +} + +impl Errors { + /// True when no profile field has an error. The avatar error does not count: it belongs to + /// its own upload. + fn profile_is_clear(&self) -> bool { + self.username.is_none() && self.about.is_none() && self.timezone.is_none() + } } struct Zone { @@ -93,7 +98,6 @@ struct Zone { struct ProfilePage { lang: Lang, csrf: String, - current: String, draft: Draft, errors: Errors, notice: Option<&'static str>, @@ -107,7 +111,6 @@ async fn profile_body(page: ProfilePage) -> Result { let ProfilePage { lang, csrf, - current, draft, errors, notice, @@ -125,71 +128,67 @@ async fn profile_body(page: ProfilePage) -> Result {

(message)

} -
-

(t(lang, Key::Username))

-

(t(lang, Key::CurrentUsername)) (current.as_str())

- if let Some(message) = errors.username { - alert(message: message.as_str()) - } -
+
+ - - - -
-
-

(t(lang, Key::Avatar))

-
- (t(lang, -
- if let Some(message) = errors.avatar { +
+ + + (t(lang, Key::UsernameHint)) + if let Some(message) = errors.username { alert(message: message.as_str()) } -
- - - -
- if has_avatar { -
- - -
+
+
+ + + (t(lang, Key::AboutHint)) + if let Some(message) = errors.about { + alert(message: message.as_str()) }
-
-
-
-

(t(lang, Key::AboutAndTimezone))

- if let Some(message) = errors.details { - alert(message: message.as_str()) - } -
- - - - + if let Some(message) = errors.timezone { + alert(message: message.as_str()) + } + +
+ +
-
+ + }) } @@ -213,7 +212,6 @@ async fn page_data( Ok(ProfilePage { lang, csrf: viewer.1.csrf_token.clone(), - current: viewer.0.username.clone(), draft, errors, notice, @@ -225,23 +223,31 @@ async fn page_data( fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> { match saved { - Some("1") => Some(t(lang, Key::OkUsernameUpdated)), + Some("1") => Some(t(lang, Key::OkProfileSaved)), Some("avatar") => Some(t(lang, Key::OkAvatarUpdated)), Some("avatar-removed") => Some(t(lang, Key::OkAvatarRemoved)), - Some("details") => Some(t(lang, Key::OkProfileSaved)), _ => None, } } -/// Checks the "about" length and the timezone name. Returns the message-carrying error. -fn check_details(lang: Lang, about: &str, timezone: &str) -> forge_core::Result<()> { +/// Checks the "about" length. The timezone is checked with `validate_timezone`. +fn check_about(lang: Lang, about: &str) -> forge_core::Result<()> { if about.chars().count() > MAX_ABOUT_CHARS { return Err(forge_core::Error::Invalid(about_too_long( lang, MAX_ABOUT_CHARS, ))); } - validate_timezone(timezone) + Ok(()) +} + +/// The message to show under a field whose check failed. An internal failure is not a form +/// error, so it propagates as a server error. +fn field_message(err: forge_core::Error) -> Result { + match user_facing_message(&err) { + Some(message) => Ok(message), + None => Err(err.into()), + } } /// Stores a processed avatar, or removes it if no image was sent. @@ -283,89 +289,66 @@ async fn profile_page(cx: &Cx) -> Result { }) } +/// Saves the username, the "about" text and the timezone together. Nothing is written unless +/// every field passes, so one bad field keeps the old values for all of them. The username is +/// written only when its capitalization differs from the stored one. #[page(POST "/settings/profile")] async fn profile_save(cx: &Cx, Form(form): Form) -> Result { let viewer = require_csrf(cx, &form.csrf).await?; let lang = i18n::lang(cx, Some(&viewer.0)); let store = &app_context::(cx).store; + let about = form.about.replace("\r\n", "\n"); - let result = match capitalization_change(&viewer.0.username, &form.username) { - Ok(display) => store.set_username_display(&viewer.0.id, &display).await, - Err(e) => Err(e), - }; - let message = match result { - Ok(()) => { - audit::record( - store, - Some(cx), - Actor::User(&viewer.0), - AuditAction::UsernameChanged, - Target { - kind: "user", - id: &viewer.0.id, - name: form.username.trim(), - }, - serde_json::json!({ "from": viewer.0.username }), - ) - .await; - return Err(see_other("/settings/profile?saved=1").into()); + let mut errors = Errors::default(); + let display = match capitalization_change(&viewer.0.username, &form.username) { + Ok(display) => Some(display), + Err(e) => { + errors.username = Some(field_message(e)?); + None } - Err(e) => match user_facing_message(&e) { - Some(message) => message, - None => return Err(e.into()), - }, }; + if let Err(e) = check_about(lang, &about) { + errors.about = Some(field_message(e)?); + } + if let Err(e) = validate_timezone(&form.timezone) { + errors.timezone = Some(field_message(e)?); + } - let draft = Draft { - username: form.username, - ..Draft::from_user(&viewer.0) - }; - let errors = Errors { - username: Some(message), - ..Errors::default() - }; - let page = page_data(&viewer, lang, draft, errors, None).await?; - Ok(view! { - shell(title: "Profile", viewer: Some(&viewer), profile_body(page: page)) - }) -} - -#[page(POST "/settings/profile/details")] -async fn details_save(cx: &Cx, Form(form): Form) -> Result { - let viewer = require_csrf(cx, &form.csrf).await?; - let store = &app_context::(cx).store; - let lang = i18n::lang(cx, Some(&viewer.0)); - let about = form.about.replace("\r\n", "\n"); - - let result = match check_details(lang, &about, &form.timezone) { - Ok(()) => { - store - .set_profile(&viewer.0.id, &about, &form.timezone) - .await + let display = match display { + Some(display) if errors.profile_is_clear() => display, + _ => { + let draft = Draft { + username: form.username, + about, + timezone: form.timezone, + }; + let page = page_data(&viewer, lang, draft, errors, None).await?; + return Ok(view! { + shell(title: "Profile", viewer: Some(&viewer), profile_body(page: page)) + }); } - Err(e) => Err(e), - }; - let message = match result { - Ok(()) => return Err(see_other("/settings/profile?saved=details").into()), - Err(e) => match user_facing_message(&e) { - Some(message) => message, - None => return Err(e.into()), - }, }; - let draft = Draft { - username: viewer.0.username.clone(), - about, - timezone: form.timezone, - }; - let errors = Errors { - details: Some(message), - ..Errors::default() - }; - let page = page_data(&viewer, lang, draft, errors, None).await?; - Ok(view! { - shell(title: "Profile", viewer: Some(&viewer), profile_body(page: page)) - }) + store + .set_profile(&viewer.0.id, &about, &form.timezone) + .await?; + if display != viewer.0.username { + store.set_username_display(&viewer.0.id, &display).await?; + audit::record( + store, + Some(cx), + Actor::User(&viewer.0), + AuditAction::UsernameChanged, + Target { + kind: "user", + id: &viewer.0.id, + name: &display, + }, + serde_json::json!({ "from": viewer.0.username }), + ) + .await; + } + Err(see_other("/settings/profile?saved=1").into()) } /// Reads the multipart body. The CSRF field is checked before the image is decoded. @@ -584,9 +567,10 @@ pub(crate) mod tests { } #[tokio::test] - async fn tahinli_to_capitalized_succeeds_and_dashboard_shows_it() { + async fn one_save_changes_capitalization_about_and_timezone() { let fx = fixture().await; - let form = format!("csrf={CSRF}&username=Tahinli"); + let form = + format!("csrf={CSRF}&username=Tahinli&about=Hello+*world*&timezone=Europe%2FIstanbul"); let (status, location, _) = send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await; assert_eq!(status, 303); @@ -594,6 +578,8 @@ pub(crate) mod tests { let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); assert_eq!(stored.username, "Tahinli"); + assert_eq!(stored.about, "Hello *world*"); + assert_eq!(stored.timezone, "Europe/Istanbul"); let (status, _, body) = send(&fx.router, "GET", "/", true, None).await; assert_eq!(status, 200); @@ -602,13 +588,13 @@ pub(crate) mod tests { let (status, _, body) = send(&fx.router, "GET", "/settings/profile?saved=1", true, None).await; assert_eq!(status, 200); - assert!(body.contains("Username updated."), "{body}"); + assert!(body.contains("Profile saved."), "{body}"); } #[tokio::test] async fn a_different_name_is_rejected_and_nothing_is_saved() { let fx = fixture().await; - let form = format!("csrf={CSRF}&username=other"); + let form = format!("csrf={CSRF}&username=other&about=kept&timezone=UTC"); let (status, _, body) = send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await; assert_eq!(status, 200); @@ -618,16 +604,17 @@ pub(crate) mod tests { ); let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); assert_eq!(stored.username, "tahinli"); + assert_eq!(stored.about, ""); } #[tokio::test] async fn post_without_a_valid_csrf_token_is_rejected() { let fx = fixture().await; - let forged = "csrf=wrong&username=Tahinli"; + let forged = "csrf=wrong&username=Tahinli&about=&timezone=UTC"; let (status, _, _) = send(&fx.router, "POST", "/settings/profile", true, Some(forged)).await; assert_eq!(status, 403); - let missing = "username=Tahinli"; + let missing = "username=Tahinli&about=&timezone=UTC"; let (status, _, _) = send(&fx.router, "POST", "/settings/profile", true, Some(missing)).await; assert_eq!(status, 403); @@ -654,19 +641,15 @@ pub(crate) mod tests { #[tokio::test] async fn about_and_timezone_round_trip() { let fx = fixture().await; - let form = format!("csrf={CSRF}&about=Hello+*world*&timezone=Europe%2FIstanbul"); - let (status, location, _) = send( - &fx.router, - "POST", - "/settings/profile/details", - true, - Some(&form), - ) - .await; + let form = + format!("csrf={CSRF}&username=tahinli&about=Hello+*world*&timezone=Europe%2FIstanbul"); + let (status, location, _) = + send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await; assert_eq!(status, 303); - assert_eq!(location.as_deref(), Some("/settings/profile?saved=details")); + assert_eq!(location.as_deref(), Some("/settings/profile?saved=1")); let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); + assert_eq!(stored.username, "tahinli"); assert_eq!(stored.about, "Hello *world*"); assert_eq!(stored.timezone, "Europe/Istanbul"); @@ -682,36 +665,27 @@ pub(crate) mod tests { #[tokio::test] async fn a_bad_timezone_is_rejected_and_nothing_is_saved() { let fx = fixture().await; - let form = format!("csrf={CSRF}&about=kept&timezone=Mars%2FOlympus"); - let (status, location, body) = send( - &fx.router, - "POST", - "/settings/profile/details", - true, - Some(&form), - ) - .await; + let form = format!("csrf={CSRF}&username=Tahinli&about=kept&timezone=Mars%2FOlympus"); + let (status, location, body) = + send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await; assert_eq!(status, 200); assert!(location.is_none()); assert!(body.contains(r#"role="alert""#), "{body}"); + // The valid username and about text wait for the timezone to be fixed too. let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); + assert_eq!(stored.username, "tahinli"); assert_eq!(stored.timezone, "UTC"); assert_eq!(stored.about, ""); } #[tokio::test] - async fn details_post_without_csrf_is_rejected() { + async fn profile_post_without_csrf_is_rejected() { let fx = fixture().await; - let form = "about=x&timezone=UTC"; - let (status, _, _) = send( - &fx.router, - "POST", - "/settings/profile/details", - true, - Some(form), - ) - .await; + let form = "username=tahinli&about=x&timezone=UTC"; + let (status, _, _) = send(&fx.router, "POST", "/settings/profile", true, Some(form)).await; assert_eq!(status, 403); + let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap(); + assert_eq!(stored.about, ""); } #[tokio::test] @@ -771,6 +745,7 @@ pub(crate) mod tests { // The page shows the new avatar with the hash as its version. let (_, _, body) = send(&fx.router, "GET", "/settings/profile", true, None).await; assert!(body.contains(&format!("?v={stored_hash}")), "{body}"); + assert!(body.contains("Remove photo"), "{body}"); // The top-nav avatar uses the real hash too, not the default URL. let (_, _, body) = send(&fx.router, "GET", "/", true, None).await; @@ -829,6 +804,9 @@ pub(crate) mod tests { body.contains(r#"src="/avatars/tahinli?v=default""#), "{body}" ); + // With no photo there is nothing to remove, so the menu leaves that item out. + let (_, _, body) = send(&fx.router, "GET", "/settings/profile", true, None).await; + assert!(!body.contains("Remove photo"), "{body}"); let default = send_full( &fx.router, diff --git a/docs/ci.md b/docs/ci.md index ba18659..43265e7 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -18,6 +18,12 @@ The file is limited to 64 KiB. Unknown keys are an error at every level (`deny_u A file with a parse error still creates a run, in state `error`, with the message shown on the run page and a `ci/config` status set to `error`. +### Top level + +| Key | Type | Default | Meaning | +|--------|--------|---------|---------| +| `name` | string | none | The workflow's name, used as the label of the [status badge](#status-badge). 1 to 40 characters after trimming, no control characters. | + ### `[on]` | Key | Type | Default | Meaning | @@ -111,6 +117,23 @@ config failed to parse reports `ci/config`. Pull request runs from forks, or from authors without write access, wait for approval. Their statuses are pending with the description `Waiting for approval`. +### Status badge + +`/{owner}/{repo}/badge.svg` shows the newest run on a branch: `?branch=` picks the branch, and the +default is the default branch. Add `&job=` to show one job's state instead. A private repo's +badge needs read access, like the rest of the repo. + +The left half of the badge, its label, is picked in this order: + +1. `?label=`, for example `?label=Nightly`. Spaces around it are dropped. An empty value is + ignored. Labels are cut at 64 characters. +2. The job name, when `&job=` is given. +3. The `name` from `.forge/ci.toml` at the run's commit. +4. `ci`. + +With no run on the branch the badge says `no status`, and the label is `?label=`, or the job name, +or `ci`. + ## Security model ### Fork pull requests need approval and get no secrets diff --git a/style/main.scss b/style/main.scss index 556d83f..d083861 100644 --- a/style/main.scss +++ b/style/main.scss @@ -1881,18 +1881,6 @@ code { margin-right: 0.4em; } -.avatar-lg { - width: 96px; - height: 96px; -} - -.avatar-row { - display: flex; - flex-wrap: wrap; - gap: 1.25rem; - align-items: flex-start; -} - // Settings pages: the card stack and the form field widths. .settings-layout { display: grid; @@ -1909,12 +1897,6 @@ code { max-width: 24rem; } -@media (max-width: 600px) { - .avatar-row { - flex-direction: column; - } -} - // branch protection // Settings page: rules table with a Remove form per row, then the add/update form. .branch-rules { @@ -3592,6 +3574,214 @@ span.reaction { padding-left: 20px; } +// CI runs list: whole-row links. +// The run number link stretches over its row (no JS). Other controls in the row sit above it. +.ci-runs tbody tr { + position: relative; + cursor: pointer; + + &:hover { + background: var(--surface-2); + } +} + +.ci-runs .ci-run-link::after { + content: ""; + position: absolute; + inset: 0; +} + +.ci-runs tbody a:not(.ci-run-link), +.ci-runs tbody button, +.ci-runs tbody input, +.ci-runs tbody select, +.ci-runs tbody textarea { + position: relative; + z-index: 1; +} + +// CI run page: header and job graph. +// Sizes below match the GRAPH_* constants in crates/forge-web/src/pages/ci_runs.rs: the card is +// 200x56, columns are 48px apart, cards in a column 16px apart, and the box is padded 16px. +.ci-run-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + flex-wrap: wrap; + gap: 16px; + + .ci-actions { + margin-top: 0; + } +} + +.ci-run-head-main { + flex: 1 1 320px; + min-width: 0; +} + +.ci-run-title { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; + margin: 0 0 6px; + overflow-wrap: anywhere; + + .ci-state { + font-size: 0.8rem; + } +} + +.ci-run-meta { + margin: 0; + overflow-wrap: anywhere; +} + +.ci-graph { + max-width: 100%; + overflow-x: auto; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--bg); + + &:focus-visible { + outline: 2px solid var(--focus); + outline-offset: 2px; + } +} + +.ci-graph-canvas { + position: relative; + display: flex; + gap: 48px; + width: max-content; + padding: 16px; +} + +.ci-graph-col { + display: flex; + flex-direction: column; + flex-shrink: 0; + gap: 16px; + width: 200px; +} + +// Connectors sit under the cards: the SVG comes first and the cards are positioned. +.ci-graph-lines { + position: absolute; + top: 0; + left: 0; + overflow: visible; + pointer-events: none; + + path { + fill: none; + stroke: var(--border-strong); + stroke-width: 2; + } +} + +.ci-graph-card { + --ci-icon: var(--muted); + + position: relative; + display: flex; + flex-direction: column; + justify-content: center; + flex-shrink: 0; + gap: 2px; + box-sizing: border-box; + width: 200px; + height: 56px; + padding: 6px 12px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface); + color: var(--text); + text-decoration: none; + + &:hover { + border-color: var(--border-strong); + background: var(--surface-2); + } + + &:focus-visible { + outline: 2px solid var(--focus); + outline-offset: 2px; + } + + &.ci-success { + --ci-icon: var(--public-text); + } + + &.ci-queued, + &.ci-running, + &.ci-blocked, + &.ci-waiting_approval { + --ci-icon: var(--warning); + } + + &.ci-failure, + &.ci-error { + --ci-icon: var(--danger); + } +} + +.ci-graph-name { + overflow: hidden; + font-size: 0.9375rem; + font-weight: 600; + line-height: 1.5; + text-overflow: ellipsis; + white-space: nowrap; +} + +.ci-graph-meta { + display: flex; + align-items: center; + gap: 6px; + overflow: hidden; + color: var(--muted); + font-size: 0.75rem; + line-height: 1.4; + white-space: nowrap; +} + +.ci-graph-icon { + flex-shrink: 0; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--ci-icon); +} + +// CI run page: job rows link through the whole row (no JS). The name link stretches over its row +// and the other controls in the row sit above it. +.ci-jobs tbody tr { + position: relative; + cursor: pointer; + + &:hover { + background: var(--surface-2); + } +} + +.ci-jobs .ci-job-link::after { + content: ""; + position: absolute; + inset: 0; +} + +.ci-jobs tbody a:not(.ci-job-link), +.ci-jobs tbody button, +.ci-jobs tbody input, +.ci-jobs tbody select, +.ci-jobs tbody textarea { + position: relative; + z-index: 1; +} + /* Theme and language preferences (T1). The palettes live at the top of this file: the dark variables apply under :root:not([data-theme="light"]) and under :root[data-theme="dark"]. */ .theme-picker { @@ -4171,3 +4361,191 @@ span.reaction { } } } + +// --------------------------------------------------------------------------- +// Settings: public profile (/settings/profile). One form on the left, the avatar with its +// Edit menu on the right. Below 48rem the avatar sits above the form. +// --------------------------------------------------------------------------- + +.profile-settings { + display: grid; + grid-template-columns: minmax(0, 1fr) 220px; + gap: 40px; + align-items: start; + max-width: 920px; +} + +.profile-form { + display: flex; + flex-direction: column; + gap: 22px; + min-width: 0; + max-width: 600px; +} + +.profile-field { + display: flex; + flex-direction: column; + gap: 6px; + min-width: 0; + + > label { + font-size: 0.875rem; + font-weight: 600; + color: var(--text); + } + + input[type="text"], + textarea, + select { + box-sizing: border-box; + max-width: 100%; + } + + input[type="text"], + select { + width: 100%; + max-width: 320px; + } + + textarea { + width: 100%; + resize: vertical; + } + + small { + font-size: 0.8125rem; + line-height: 1.45; + } + + .alert { + margin: 0; + } +} + +.profile-actions { + margin-top: 4px; +} + +.profile-settings-avatar { + display: flex; + flex-direction: column; + gap: 10px; + min-width: 0; + + small { + font-size: 0.8125rem; + line-height: 1.45; + } +} + +.profile-settings-avatar-frame { + position: relative; + width: 180px; + height: 180px; +} + +.profile-settings-avatar-img { + display: block; + width: 180px; + height: 180px; + box-sizing: border-box; + border: 1px solid var(--border); +} + +// The Edit pill sits over the bottom-left edge of the circle. +.profile-settings-avatar-menu { + position: absolute; + left: 6px; + bottom: 10px; + + > summary { + display: inline-flex; + align-items: center; + height: 32px; + padding: 0 14px; + border: 1px solid var(--border-strong); + border-radius: 999px; + background: var(--surface); + box-shadow: var(--shadow); + color: var(--text); + font-size: 0.8125rem; + font-weight: 500; + cursor: pointer; + + &:hover { + background: var(--surface-2); + } + } + + &[open] > summary { + border-color: var(--accent); + } +} + +.profile-settings-avatar-list { + left: 0; + right: auto; + top: calc(100% + 8px); + min-width: 220px; +} + +.profile-settings-avatar-upload { + display: flex; + flex-direction: column; + align-items: stretch; + margin: 0; + + > button { + margin: 4px 14px 10px; + } +} + +// The file input stays in the tab order but is visually hidden. Its label is the visible item. +.profile-settings-avatar-upload .profile-settings-avatar-file { + position: absolute; + width: 1px; + height: 1px; + margin: 0; + padding: 0; + border: 0; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + opacity: 0; +} + +.profile-settings-avatar-item { + display: block; + padding: 8px 14px; + color: var(--text); + font-size: 0.875rem; + white-space: nowrap; + cursor: pointer; + + &:hover { + background: var(--surface-2); + } +} + +.profile-settings-avatar-upload .profile-settings-avatar-file:focus-visible + .profile-settings-avatar-item { + outline: 2px solid var(--accent); + outline-offset: -2px; +} + +.profile-settings-avatar-remove { + margin: 0; + padding-top: 6px; + border-top: 1px solid var(--border); +} + +@media (max-width: 48rem) { + .profile-settings { + grid-template-columns: minmax(0, 1fr); + gap: 24px; + } + + .profile-settings-avatar { + order: -1; + } +}