forge
Explore
Log in

Don't you dare go Hollow

Live runs list, job graph, badge labels and a one-form profile settings page

Browse files at this commit

b25287e1147b720659270d1df8fecaf3faee1f59Ahmet Kaan GümüşParent: 590ac38
  • feat
    • live runs list, job graph, badge labels and a one-form profile settings page
Show full message
✨ feat(ci): live runs list, job graph, badge labels and a one-form profile settings page

- 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.

17 changed files +1329 -263

README.mdmodified+2 -0
@@ -1,5 +1,7 @@
1 # forge1 # forge
2 2
3+[![build](https://git.tahinli.com/Tahinli/forge/badge.svg?branch=main&label=build)](https://git.tahinli.com/Tahinli/forge/ci)
4+
3 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.5 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.
4 6
5 Try the live instance at https://git.tahinli.com.7 Try the live instance at https://git.tahinli.com.
crates/forge-ci/src/config.rsmodified+74 -0
@@ -27,11 +27,16 @@ pub const MAX_JOBS: usize = 20;
27 pub const DEFAULT_TIMEOUT_MINUTES: u32 = 60;27 pub const DEFAULT_TIMEOUT_MINUTES: u32 = 60;
28 /// Smallest and largest allowed job timeout.28 /// Smallest and largest allowed job timeout.
29 pub const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive<u32> = 1..=360;29 pub const TIMEOUT_RANGE_MINUTES: std::ops::RangeInclusive<u32> = 1..=360;
30+/// Longest workflow `name`, in characters, after trimming.
31+pub const MAX_WORKFLOW_NAME_CHARS: usize = 40;
30 32
31 /// A parsed and validated workflow.33 /// A parsed and validated workflow.
32 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]34 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33 #[serde(deny_unknown_fields)]35 #[serde(deny_unknown_fields)]
34 pub struct CiConfig {36 pub struct CiConfig {
37+ /// Optional display name, e.g. `"build"`. The CI badge uses it as its label.
38+ #[serde(default)]
39+ pub name: Option<String>,
35 /// The `[on]` table. Optional; defaults to manual runs only.40 /// The `[on]` table. Optional; defaults to manual runs only.
36 #[serde(rename = "on", default)]41 #[serde(rename = "on", default)]
37 pub on: Triggers,42 pub on: Triggers,
@@ -159,6 +164,9 @@ impl CiConfig {
159 }164 }
160 165
161 fn validate(&self) -> Result<(), ConfigError> {166 fn validate(&self) -> Result<(), ConfigError> {
167+ if let Some(name) = &self.name {
168+ validate_workflow_name(name)?;
169+ }
162 if self.jobs.is_empty() {170 if self.jobs.is_empty() {
163 return Err(ConfigError::NoJobs);171 return Err(ConfigError::NoJobs);
164 }172 }
@@ -215,6 +223,28 @@ fn validate_trigger_glob(kind: &'static str, pattern: &str) -> Result<(), Config
215 .map_err(|e| invalid(e.to_string()))223 .map_err(|e| invalid(e.to_string()))
216 }224 }
217 225
226+/// A workflow name: non-empty after trimming, at most [`MAX_WORKFLOW_NAME_CHARS`] characters, and
227+/// no control characters.
228+fn validate_workflow_name(name: &str) -> Result<(), ConfigError> {
229+ let invalid = |reason: &str| ConfigError::InvalidWorkflowName {
230+ name: name.to_string(),
231+ reason: reason.to_string(),
232+ };
233+ let trimmed = name.trim();
234+ if trimmed.is_empty() {
235+ return Err(invalid("must not be empty"));
236+ }
237+ if trimmed.chars().count() > MAX_WORKFLOW_NAME_CHARS {
238+ return Err(invalid(&format!(
239+ "must be at most {MAX_WORKFLOW_NAME_CHARS} characters"
240+ )));
241+ }
242+ if trimmed.chars().any(char::is_control) {
243+ return Err(invalid("must not contain control characters"));
244+ }
245+ Ok(())
246+}
247+
218 /// `^[a-z0-9][a-z0-9_-]{0,39}$`248 /// `^[a-z0-9][a-z0-9_-]{0,39}$`
219 fn is_job_name(name: &str) -> bool {249 fn is_job_name(name: &str) -> bool {
220 let Some((first, rest)) = name.as_bytes().split_first() else {250 let Some((first, rest)) = name.as_bytes().split_first() else {
@@ -659,4 +689,48 @@ artifacts = ["target/release/forge"]
659 let cfg = parse_config(EXAMPLE).unwrap();689 let cfg = parse_config(EXAMPLE).unwrap();
660 assert_eq!(cfg.job_order(), vec!["test", "lint"]);690 assert_eq!(cfg.job_order(), vec!["test", "lint"]);
661 }691 }
692+
693+ #[test]
694+ fn workflow_name_is_optional_and_kept() {
695+ assert_eq!(parse_config(&job_toml("")).unwrap().name, None);
696+ let cfg = parse_config(&format!("name = \"build\"\n{}", job_toml(""))).unwrap();
697+ assert_eq!(cfg.name.as_deref(), Some("build"));
698+ }
699+
700+ #[test]
701+ fn workflow_name_must_not_be_blank() {
702+ for text in ["name = \"\"", "name = \" \""] {
703+ let err = err_of(&format!("{text}\n{}", job_toml("")));
704+ assert!(
705+ matches!(err, ConfigError::InvalidWorkflowName { .. }),
706+ "{text}: {err:?}"
707+ );
708+ }
709+ }
710+
711+ #[test]
712+ fn workflow_name_length_is_capped_after_trimming() {
713+ let at_limit = "n".repeat(MAX_WORKFLOW_NAME_CHARS);
714+ let ok = format!("name = \" {at_limit} \"\n{}", job_toml(""));
715+ assert!(parse_config(&ok).is_ok());
716+ let over = "n".repeat(MAX_WORKFLOW_NAME_CHARS + 1);
717+ let err = err_of(&format!("name = \"{over}\"\n{}", job_toml("")));
718+ assert!(matches!(err, ConfigError::InvalidWorkflowName { .. }));
719+ }
720+
721+ #[test]
722+ fn workflow_name_rejects_control_characters() {
723+ let err = err_of(&format!("name = \"a\\u0007b\"\n{}", job_toml("")));
724+ assert!(matches!(err, ConfigError::InvalidWorkflowName { .. }));
725+ let err = err_of(&format!("name = \"a\\nb\"\n{}", job_toml("")));
726+ assert!(matches!(err, ConfigError::InvalidWorkflowName { .. }));
727+ }
728+
729+ #[test]
730+ fn workflow_name_must_be_a_string() {
731+ assert!(matches!(
732+ err_of(&format!("name = 3\n{}", job_toml(""))),
733+ ConfigError::Toml(_)
734+ ));
735+ }
662 }736 }
crates/forge-ci/src/error.rsmodified+3 -0
@@ -20,6 +20,9 @@ pub enum ConfigError {
20 #[error("invalid job name {0:?}: must match ^[a-z0-9][a-z0-9_-]{{0,39}}$")]20 #[error("invalid job name {0:?}: must match ^[a-z0-9][a-z0-9_-]{{0,39}}$")]
21 InvalidJobName(String),21 InvalidJobName(String),
22 22
23+ #[error("invalid workflow name {name:?}: {reason}")]
24+ InvalidWorkflowName { name: String, reason: String },
25+
23 #[error("job {job:?} needs unknown job {need:?}")]26 #[error("job {job:?} needs unknown job {need:?}")]
24 UnknownNeed { job: String, need: String },27 UnknownNeed { job: String, need: String },
25 28
crates/forge-web/assets/nav.jsmodified+11 -3
@@ -144,10 +144,17 @@
144 old.replaceWith(s);144 old.replaceWith(s);
145 });145 });
146 if (kept) { restoreFields(kept); }146 if (kept) { restoreFields(kept); }
147+ followTail();
147 syncUnread();148 syncUnread();
148 syncLive();149 syncLive();
149 }150 }
150 151
152+ // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place.
153+ function followTail() {
154+ var pre = document.querySelector('[data-live-log]');
155+ if (pre) { pre.scrollTop = pre.scrollHeight; }
156+ }
157+
151 function focusMain() {158 function focusMain() {
152 var main = document.querySelector('main');159 var main = document.querySelector('main');
153 if (main && main.focus) { main.focus({ preventScroll: true }); }160 if (main && main.focus) { main.focus({ preventScroll: true }); }
@@ -174,7 +181,7 @@
174 var saved = history.state;181 var saved = history.state;
175 // A live swap keeps the log tail where the reader had it: at the end it stays at the end.182 // A live swap keeps the log tail where the reader had it: at the end it stays at the end.
176 var tail = how === 'live' ? document.querySelector('[data-live-log]') : null;183 var tail = how === 'live' ? document.querySelector('[data-live-log]') : null;
177- var tailAt = tail ? { top: tail.scrollTop, end: tail.scrollTop + tail.clientHeight >= tail.scrollHeight - 8 } : null;184+ var tailAt = tail ? { top: tail.scrollTop, end: tail.scrollTop + tail.clientHeight >= tail.scrollHeight - 24 } : null;
178 closeDropdowns(null);185 closeDropdowns(null);
179 adopt(doc, keepFields);186 adopt(doc, keepFields);
180 if (tailAt) {187 if (tailAt) {
@@ -425,11 +432,11 @@
425 }432 }
426 433
427 // Appends streamed log text to the tail as a text node, never as HTML. The tail follows the end434 // Appends streamed log text to the tail as a text node, never as HTML. The tail follows the end
428- // only while the reader is already at the end.435+ // only while the reader is already at the end (within 24px). Scrolling back down resumes following.
429 function appendLog(text) {436 function appendLog(text) {
430 var pre = document.querySelector('[data-live-log]');437 var pre = document.querySelector('[data-live-log]');
431 if (!pre || !text) { return; }438 if (!pre || !text) { return; }
432- var atEnd = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 8;439+ var atEnd = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 24;
433 pre.appendChild(document.createTextNode(text));440 pre.appendChild(document.createTextNode(text));
434 if (atEnd) { pre.scrollTop = pre.scrollHeight; }441 if (atEnd) { pre.scrollTop = pre.scrollHeight; }
435 }442 }
@@ -444,6 +451,7 @@
444 load({ target: withoutHash(here), dest: here, init: GET_INIT, how: 'live', keep: true, post: false, form: null });451 load({ target: withoutHash(here), dest: here, init: GET_INIT, how: 'live', keep: true, post: false, form: null });
445 }452 }
446 453
454+ followTail();
447 syncLive();455 syncLive();
448 456
449 window.__forgeQuery = function (href) {457 window.__forgeQuery = function (href) {
crates/forge-web/src/ci/api.rsmodified+2 -0
@@ -251,6 +251,7 @@ async fn try_claim(state: &AppState, runner: &CiRunner) -> Result<Option<JobAssi
251 };251 };
252 state.ci_live.bump_job(&job.id);252 state.ci_live.bump_job(&job.id);
253 state.ci_live.bump_run(&run.id);253 state.ci_live.bump_run(&run.id);
254+ state.ci_live.bump_repo(&run.repo_id);
254 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;255 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
255 let repo = state256 let repo = state
256 .store257 .store
@@ -675,6 +676,7 @@ async fn finish_job(
675 }676 }
676 if any_changed {677 if any_changed {
677 state.ci_live.bump_run(&run.id);678 state.ci_live.bump_run(&run.id);
679+ state.ci_live.bump_repo(&run.repo_id);
678 }680 }
679 if queued {681 if queued {
680 state.ci_waker.notify_waiters();682 state.ci_waker.notify_waiters();
crates/forge-web/src/ci/live.rsmodified+39 -7
@@ -1,8 +1,9 @@
1-//! Change signals for CI jobs and runs. [`CiLive`] keeps one generation counter per job and one per1+//! Change signals for CI jobs, runs and repos. [`CiLive`] keeps one generation counter per job, one
2-//! run. A write that changes a job or a run bumps its counter, and every subscriber wakes on the2+//! per run and one per repo. A write that changes a job or a run bumps its counter, and every
3-//! change. The counter carries no data: a subscriber reads the database or the log file again when3+//! subscriber wakes on the change. The counter carries no data: a subscriber reads the database or
4-//! it wakes. Nothing polls. A signal with no receivers left is removed, so the maps hold only the4+//! the log file again when it wakes. Nothing polls. A signal with no receivers left is removed, so
5-//! jobs and runs somebody is watching. The hub is in-process only, like [`NotifyHub`].5+//! the maps hold only the jobs, runs and repos somebody is watching. The hub is in-process only,
6+//! like [`NotifyHub`].
6 //!7 //!
7 //! [`NotifyHub`]: crate::notify_hub::NotifyHub8 //! [`NotifyHub`]: crate::notify_hub::NotifyHub
8 9
@@ -16,6 +17,7 @@ use tokio::sync::watch;
16 pub struct CiLive {17 pub struct CiLive {
17 jobs: Signals,18 jobs: Signals,
18 runs: Signals,19 runs: Signals,
20+ repos: Signals,
19 }21 }
20 22
21 impl CiLive {23 impl CiLive {
@@ -26,12 +28,16 @@ impl CiLive {
26 }28 }
27 29
28 /// Subscribes to changes of run `run_id`. Same rules as [`CiLive::subscribe_job`].30 /// Subscribes to changes of run `run_id`. Same rules as [`CiLive::subscribe_job`].
29- // No caller yet: the run status stream that waits on this is the next change.
30- #[allow(dead_code)]
31 pub fn subscribe_run(&self, run_id: &str) -> watch::Receiver<u64> {31 pub fn subscribe_run(&self, run_id: &str) -> watch::Receiver<u64> {
32 self.runs.subscribe(run_id)32 self.runs.subscribe(run_id)
33 }33 }
34 34
35+ /// Subscribes to changes of repo `repo_id`: a run of the repo was created or changed state.
36+ /// Same rules as [`CiLive::subscribe_job`].
37+ pub fn subscribe_repo(&self, repo_id: &str) -> watch::Receiver<u64> {
38+ self.repos.subscribe(repo_id)
39+ }
40+
35 /// Wakes the subscribers of job `job_id`: its log grew or its state changed. Does nothing when41 /// Wakes the subscribers of job `job_id`: its log grew or its state changed. Does nothing when
36 /// nobody is subscribed.42 /// nobody is subscribed.
37 pub fn bump_job(&self, job_id: &str) {43 pub fn bump_job(&self, job_id: &str) {
@@ -43,6 +49,12 @@ impl CiLive {
43 self.runs.bump(run_id);49 self.runs.bump(run_id);
44 }50 }
45 51
52+ /// Wakes the subscribers of repo `repo_id`: a run of the repo was created or changed state.
53+ /// Callers bump it next to the run bump, since the run signal does not know its repo.
54+ pub fn bump_repo(&self, repo_id: &str) {
55+ self.repos.bump(repo_id);
56+ }
57+
46 /// Wakes the subscribers of job `job_id` once more and drops its signal. Call it when the job58 /// Wakes the subscribers of job `job_id` once more and drops its signal. Call it when the job
47 /// has reached a terminal state: no change follows, so the signal is not kept. A subscriber59 /// has reached a terminal state: no change follows, so the signal is not kept. A subscriber
48 /// that waits on a closed signal wakes once and then sees it closed.60 /// that waits on a closed signal wakes once and then sees it closed.
@@ -135,8 +147,28 @@ mod tests {
135 let live = CiLive::default();147 let live = CiLive::default();
136 live.bump_job("job-1");148 live.bump_job("job-1");
137 live.bump_run("run-1");149 live.bump_run("run-1");
150+ live.bump_repo("repo-1");
138 assert!(live.jobs.counters().is_empty());151 assert!(live.jobs.counters().is_empty());
139 assert!(live.runs.counters().is_empty());152 assert!(live.runs.counters().is_empty());
153+ assert!(live.repos.counters().is_empty());
154+ }
155+
156+ #[tokio::test]
157+ async fn a_repo_bump_wakes_only_the_subscribers_of_that_repo() {
158+ let live = CiLive::default();
159+ let mut repo = live.subscribe_repo("repo-1");
160+ let other = live.subscribe_repo("repo-2");
161+ let run = live.subscribe_run("run-1");
162+
163+ live.bump_repo("repo-1");
164+
165+ tokio::time::timeout(Duration::from_secs(1), repo.changed())
166+ .await
167+ .expect("woken")
168+ .expect("open");
169+ assert_eq!(*repo.borrow_and_update(), 1);
170+ assert!(!other.has_changed().expect("open"));
171+ assert!(!run.has_changed().expect("open"));
140 }172 }
141 173
142 #[test]174 #[test]
crates/forge-web/src/ci/reaper.rsmodified+8 -5
@@ -64,12 +64,15 @@ pub async fn reap_before(state: &AppState, older_than: &str) -> usize {
64 continue;64 continue;
65 }65 }
66 match state.store.run_by_id(&job.run_id).await {66 match state.store.run_by_id(&job.run_id).await {
67- Ok(Some(run)) => match sync_run_statuses(state, &run).await {67+ Ok(Some(run)) => {
68- Ok(queued) => wake |= queued,68+ state.ci_live.bump_repo(&run.repo_id);
69- Err(e) => {69+ match sync_run_statuses(state, &run).await {
70- tracing::error!(error = %e, run_id = %run.id, "ci: syncing statuses failed")70+ Ok(queued) => wake |= queued,
71+ Err(e) => {
72+ tracing::error!(error = %e, run_id = %run.id, "ci: syncing statuses failed")
73+ }
71 }74 }
72- },75+ }
73 Ok(None) => {}76 Ok(None) => {}
74 Err(e) => tracing::error!(error = %e, run_id = %job.run_id, "ci: loading run failed"),77 Err(e) => tracing::error!(error = %e, run_id = %job.run_id, "ci: loading run failed"),
75 }78 }
crates/forge-web/src/ci/schedule.rsmodified+13 -0
@@ -223,6 +223,7 @@ async fn create(
223 config_error,223 config_error,
224 )224 )
225 .await?;225 .await?;
226+ state.ci_live.bump_repo(&run.repo_id);
226 if let Some(message) = config_error {227 if let Some(message) = config_error {
227 let url = format!(228 let url = format!(
228 "{}/{}/{}/ci/runs/{}",229 "{}/{}/{}/ci/runs/{}",
@@ -317,6 +318,18 @@ async fn load(state: &AppState, repo_id: &str, commit: &str) -> Loaded {
317 }318 }
318 }319 }
319 320
321+/// The trimmed workflow `name` in `.forge/ci.toml` at `commit`. `None` when the file is missing,
322+/// does not parse, or has no name. Reads one git object, so the badge can call it per request.
323+pub async fn workflow_name(state: &AppState, repo_id: &str, commit: &str) -> Option<String> {
324+ match load(state, repo_id, commit).await {
325+ Loaded::Valid(cfg) => cfg
326+ .name
327+ .map(|name| name.trim().to_owned())
328+ .filter(|name| !name.is_empty()),
329+ Loaded::Missing | Loaded::Invalid(_) => None,
330+ }
331+}
332+
320 /// Whether a pull request needs approval before its jobs run: a fork head, or an author who lacks333 /// Whether a pull request needs approval before its jobs run: a fork head, or an author who lacks
321 /// Write on the base repo (or no longer exists).334 /// Write on the base repo (or no longer exists).
322 async fn needs_approval(335 async fn needs_approval(
crates/forge-web/src/i18n/admin.rsmodified+4 -1
@@ -810,7 +810,10 @@ mod tests {
810 fn english_text_matches_the_original_phrases() {810 fn english_text_matches_the_original_phrases() {
811 assert_eq!(t(Lang::En, K::DeleteUser), "Delete user");811 assert_eq!(t(Lang::En, K::DeleteUser), "Delete user");
812 assert!(t(Lang::En, K::ReplicationOff).starts_with("Replication is off."));812 assert!(t(Lang::En, K::ReplicationOff).starts_with("Replication is off."));
813- assert_eq!(type_to_confirm(Lang::En, "tahinli"), "Type tahinli to confirm");813+ assert_eq!(
814+ type_to_confirm(Lang::En, "tahinli"),
815+ "Type tahinli to confirm"
816+ );
814 assert_eq!(817 assert_eq!(
815 running_line(Lang::En, RunKind::Backup),818 running_line(Lang::En, RunKind::Backup),
816 "A backup run is in progress."819 "A backup run is in progress."
crates/forge-web/src/i18n/mod.rsmodified+12 -16
@@ -169,18 +169,17 @@ pub enum Key {
169 ErrWrongCode,169 ErrWrongCode,
170 170
171 // Profile.171 // Profile.
172- OkUsernameUpdated,
173 OkAvatarUpdated,172 OkAvatarUpdated,
174 OkAvatarRemoved,173 OkAvatarRemoved,
175 OkProfileSaved,174 OkProfileSaved,
176- CurrentUsername,
177 UsernameHint,175 UsernameHint,
178 Avatar,176 Avatar,
179 AvatarAlt,177 AvatarAlt,
180 Image,178 Image,
181 AvatarHint,179 AvatarHint,
182- RemoveAvatar,180+ Edit,
183- AboutAndTimezone,181+ UploadPhoto,
182+ RemovePhoto,
184 About,183 About,
185 AboutHint,184 AboutHint,
186 Timezone,185 Timezone,
@@ -371,18 +370,17 @@ pub const ALL: &[Key] = &[
371 Key::ErrWrongPassword,370 Key::ErrWrongPassword,
372 Key::ErrWrongConfirmCode,371 Key::ErrWrongConfirmCode,
373 Key::ErrWrongCode,372 Key::ErrWrongCode,
374- Key::OkUsernameUpdated,
375 Key::OkAvatarUpdated,373 Key::OkAvatarUpdated,
376 Key::OkAvatarRemoved,374 Key::OkAvatarRemoved,
377 Key::OkProfileSaved,375 Key::OkProfileSaved,
378- Key::CurrentUsername,
379 Key::UsernameHint,376 Key::UsernameHint,
380 Key::Avatar,377 Key::Avatar,
381 Key::AvatarAlt,378 Key::AvatarAlt,
382 Key::Image,379 Key::Image,
383 Key::AvatarHint,380 Key::AvatarHint,
384- Key::RemoveAvatar,381+ Key::Edit,
385- Key::AboutAndTimezone,382+ Key::UploadPhoto,
383+ Key::RemovePhoto,
386 Key::About,384 Key::About,
387 Key::AboutHint,385 Key::AboutHint,
388 Key::Timezone,386 Key::Timezone,
@@ -630,16 +628,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
630 "Bu kod doğru değil. Doğrulama uygulamanızdaki bir kodu ya da bir kurtarma kodunu kullanın."628 "Bu kod doğru değil. Doğrulama uygulamanızdaki bir kodu ya da bir kurtarma kodunu kullanın."
631 }629 }
632 630
633- (OkUsernameUpdated, En) => "Username updated.",
634- (OkUsernameUpdated, Tr) => "Kullanıcı adı güncellendi.",
635 (OkAvatarUpdated, En) => "Avatar updated.",631 (OkAvatarUpdated, En) => "Avatar updated.",
636 (OkAvatarUpdated, Tr) => "Avatar güncellendi.",632 (OkAvatarUpdated, Tr) => "Avatar güncellendi.",
637 (OkAvatarRemoved, En) => "Avatar removed.",633 (OkAvatarRemoved, En) => "Avatar removed.",
638 (OkAvatarRemoved, Tr) => "Avatar kaldırıldı.",634 (OkAvatarRemoved, Tr) => "Avatar kaldırıldı.",
639 (OkProfileSaved, En) => "Profile saved.",635 (OkProfileSaved, En) => "Profile saved.",
640 (OkProfileSaved, Tr) => "Profil kaydedildi.",636 (OkProfileSaved, Tr) => "Profil kaydedildi.",
641- (CurrentUsername, En) => "Current username: ",
642- (CurrentUsername, Tr) => "Mevcut kullanıcı adı: ",
643 (UsernameHint, En) => {637 (UsernameHint, En) => {
644 "Only the capitalization can be changed. Your lookup name stays the same."638 "Only the capitalization can be changed. Your lookup name stays the same."
645 }639 }
@@ -658,10 +652,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
658 (AvatarHint, Tr) => {652 (AvatarHint, Tr) => {
659 "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."653 "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."
660 }654 }
661- (RemoveAvatar, En) => "Remove avatar",655+ (Edit, En) => "Edit",
662- (RemoveAvatar, Tr) => "Avatarı kaldır",656+ (Edit, Tr) => "Düzenle",
663- (AboutAndTimezone, En) => "About and timezone",657+ (UploadPhoto, En) => "Upload a photo…",
664- (AboutAndTimezone, Tr) => "Hakkında ve saat dilimi",658+ (UploadPhoto, Tr) => "Fotoğraf yükle…",
659+ (RemovePhoto, En) => "Remove photo",
660+ (RemovePhoto, Tr) => "Fotoğrafı kaldır",
665 (About, En) => "About",661 (About, En) => "About",
666 (About, Tr) => "Hakkında",662 (About, Tr) => "Hakkında",
667 (AboutHint, En) => "At most 2000 characters. Markdown is supported.",663 (AboutHint, En) => "At most 2000 characters. Markdown is supported.",
crates/forge-web/src/i18n/releases_ci.rsmodified+4 -0
@@ -30,6 +30,7 @@ pub enum K {
30 Runs,30 Runs,
31 NoRunsYet,31 NoRunsYet,
32 Jobs,32 Jobs,
33+ JobGraph,
33 NoJobs,34 NoJobs,
34 ColRun,35 ColRun,
35 ColState,36 ColState,
@@ -175,6 +176,8 @@ pub fn t(lang: Lang, key: K) -> &'static str {
175 (NoRunsYet, Tr) => "Henüz çalıştırma yok.",176 (NoRunsYet, Tr) => "Henüz çalıştırma yok.",
176 (Jobs, En) => "Jobs",177 (Jobs, En) => "Jobs",
177 (Jobs, Tr) => "İşler",178 (Jobs, Tr) => "İşler",
179+ (JobGraph, En) => "Job graph",
180+ (JobGraph, Tr) => "İş grafiği",
178 (NoJobs, En) => "No jobs.",181 (NoJobs, En) => "No jobs.",
179 (NoJobs, Tr) => "İş yok.",182 (NoJobs, Tr) => "İş yok.",
180 (ColRun, En) => "Run",183 (ColRun, En) => "Run",
@@ -471,6 +474,7 @@ mod tests {
471 K::Runs,474 K::Runs,
472 K::NoRunsYet,475 K::NoRunsYet,
473 K::Jobs,476 K::Jobs,
477+ K::JobGraph,
474 K::NoJobs,478 K::NoJobs,
475 K::ColRun,479 K::ColRun,
476 K::ColState,480 K::ColState,
crates/forge-web/src/pages/ci_badge.rsmodified+37 -11
@@ -2,6 +2,9 @@
2 //! on a branch (`?branch=`, default: the default branch), or of one job of that run (`&job=`). The2 //! on a branch (`?branch=`, default: the default branch), or of one job of that run (`&job=`). The
3 //! SVG is a flat shields-style image, rendered here with no outside assets.3 //! SVG is a flat shields-style image, rendered here with no outside assets.
4 //!4 //!
5+//! The label, the left half, is `?label=` if given, else the job name when `&job=` is given, else
6+//! the `name` of the run's `.forge/ci.toml`, else "ci".
7+//!
5 //! Access is the repo's read access: a private repo a viewer cannot read is a 404, like every other8 //! Access is the repo's read access: a private repo a viewer cannot read is a 404, like every other
6 //! repo page. A repo with no run on the branch still answers 200 with "no status".9 //! repo page. A repo with no run on the branch still answers 200 with "no status".
7 10
@@ -13,6 +16,7 @@ use topcoat::router::request::uri;
13 use topcoat::router::response::Response;16 use topcoat::router::response::Response;
14 use topcoat::router::{Body, HeaderValue, StatusCode, path_param, route};17 use topcoat::router::{Body, HeaderValue, StatusCode, path_param, route};
15 18
19+use crate::ci::schedule::workflow_name;
16 use crate::pages::repo_ctx::load_repo;20 use crate::pages::repo_ctx::load_repo;
17 use crate::state::AppState;21 use crate::state::AppState;
18 22
@@ -21,6 +25,8 @@ path_param!(repo);
21 25
22 /// Longest label shown, in characters. A longer job name is cut here.26 /// Longest label shown, in characters. A longer job name is cut here.
23 const MAX_LABEL_CHARS: usize = 64;27 const MAX_LABEL_CHARS: usize = 64;
28+/// The label when neither `?label=`, a job, nor a workflow name gives one.
29+const DEFAULT_LABEL: &str = "ci";
24 /// Height of the badge in pixels.30 /// Height of the badge in pixels.
25 const HEIGHT: u32 = 20;31 const HEIGHT: u32 = 20;
26 /// Padding on each side of a text, in pixels.32 /// Padding on each side of a text, in pixels.
@@ -158,11 +164,12 @@ pub fn render_badge(label: &str, status: BadgeStatus) -> String {
158 )164 )
159 }165 }
160 166
161-/// The query values the badge reads. Empty values count as absent.167+/// The query values the badge reads. Empty values count as absent. A label is trimmed first.
162 #[derive(Default)]168 #[derive(Default)]
163 struct BadgeQuery {169 struct BadgeQuery {
164 branch: Option<String>,170 branch: Option<String>,
165 job: Option<String>,171 job: Option<String>,
172+ label: Option<String>,
166 }173 }
167 174
168 fn badge_query(cx: &Cx) -> BadgeQuery {175 fn badge_query(cx: &Cx) -> BadgeQuery {
@@ -171,13 +178,20 @@ fn badge_query(cx: &Cx) -> BadgeQuery {
171 return query;178 return query;
172 };179 };
173 for (key, value) in form_urlencoded::parse(raw.as_bytes()) {180 for (key, value) in form_urlencoded::parse(raw.as_bytes()) {
174- let slot = match key.as_ref() {181+ let key = key.as_ref();
182+ let slot = match key {
175 "branch" => &mut query.branch,183 "branch" => &mut query.branch,
176 "job" => &mut query.job,184 "job" => &mut query.job,
185+ "label" => &mut query.label,
177 _ => continue,186 _ => continue,
178 };187 };
188+ let value: &str = if key == "label" {
189+ value.trim()
190+ } else {
191+ value.as_ref()
192+ };
179 if !value.is_empty() {193 if !value.is_empty() {
180- *slot = Some(value.into_owned());194+ *slot = Some(value.to_owned());
181 }195 }
182 }196 }
183 query197 query
@@ -200,19 +214,31 @@ async fn ci_badge(cx: &Cx) -> Result<Response> {
200 .store214 .store
201 .latest_run_on_ref(&ctx.repo.id, &git_ref)215 .latest_run_on_ref(&ctx.repo.id, &git_ref)
202 .await?;216 .await?;
203- let (label, status) = match (run, query.job) {217+ let Some(run) = run else {
204- (None, job) => (218+ // No run to read a workflow name from: the label, a job name, or the default.
205- job.unwrap_or_else(|| "ci".to_owned()),219+ let label = query
206- BadgeStatus::NoStatus,220+ .label
207- ),221+ .or(query.job)
208- (Some(run), None) => ("ci".to_owned(), status_of_run(run.state)),222+ .unwrap_or_else(|| DEFAULT_LABEL.to_owned());
209- (Some(run), Some(job)) => {223+ return Ok(svg_response(render_badge(&label, BadgeStatus::NoStatus)));
224+ };
225+ let (label, status) = match query.job {
226+ Some(job) => {
210 let jobs = state.store.jobs_for_run(&run.id).await?;227 let jobs = state.store.jobs_for_run(&run.id).await?;
211 let status = jobs228 let status = jobs
212 .iter()229 .iter()
213 .find(|j| j.name == job)230 .find(|j| j.name == job)
214 .map_or(BadgeStatus::NoStatus, |j| status_of_job(j.state));231 .map_or(BadgeStatus::NoStatus, |j| status_of_job(j.state));
215- (job, status)232+ (query.label.unwrap_or(job), status)
233+ }
234+ None => {
235+ let label = match query.label {
236+ Some(label) => label,
237+ None => workflow_name(state, &ctx.repo.id, &run.commit_oid)
238+ .await
239+ .unwrap_or_else(|| DEFAULT_LABEL.to_owned()),
240+ };
241+ (label, status_of_run(run.state))
216 }242 }
217 };243 };
218 Ok(svg_response(render_badge(&label, status)))244 Ok(svg_response(render_badge(&label, status)))
crates/forge-web/src/pages/ci_runs.rsmodified+253 -22
@@ -4,7 +4,8 @@
4 //! 404 for a private repo and a refusal for a change. Every change notifies the job waker and syncs4 //! 404 for a private repo and a refusal for a change. Every change notifies the job waker and syncs
5 //! the commit status of each job it changed. A run or job page that is not finished stays live: it5 //! the commit status of each job it changed. A run or job page that is not finished stays live: it
6 //! opens a `changed` event stream (`.../events`) and re-renders itself on each event, with no reload6 //! opens a `changed` event stream (`.../events`) and re-renders itself on each event, with no reload
7-//! and no timer.7+//! and no timer. The run list stays live on page 1 the same way, through `/{owner}/{repo}/ci/events`,
8+//! which fires on every run created or changed in the repo.
8 9
9 use std::collections::HashMap;10 use std::collections::HashMap;
10 use std::future::Future;11 use std::future::Future;
@@ -12,7 +13,7 @@ use std::time::Duration;
12 13
13 use forge_core::ci::{CiJob, CiRun, RunState};14 use forge_core::ci::{CiJob, CiRun, RunState};
14 use forge_core::{Action, Denied, Store, User, authorize};15 use forge_core::{Action, Denied, Store, User, authorize};
15-use forge_git::browse::{RefInfo, RefKind};16+use forge_git::browse::{RefInfo, RefKind, read_commit};
16 use futures_util::{Stream, stream};17 use futures_util::{Stream, stream};
17 use serde::Deserialize;18 use serde::Deserialize;
18 use time::OffsetDateTime;19 use time::OffsetDateTime;
@@ -252,6 +253,7 @@ async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> Resul
252 return Ok(());253 return Ok(());
253 };254 };
254 state.ci_live.bump_run(run_id);255 state.ci_live.bump_run(run_id);
256+ state.ci_live.bump_repo(&run.repo_id);
255 for job in state.store.jobs_for_run(run_id).await? {257 for job in state.store.jobs_for_run(run_id).await? {
256 let changed = before258 let changed = before
257 .iter()259 .iter()
@@ -306,9 +308,36 @@ struct JobRow {
306 message: String,308 message: String,
307 }309 }
308 310
311+/// Layout of the job graph in SVG units. The `.ci-graph-*` rules in main.scss use the same sizes.
312+const GRAPH_PAD: i64 = 16;
313+const GRAPH_CARD_W: i64 = 200;
314+const GRAPH_CARD_H: i64 = 56;
315+const GRAPH_COL_GAP: i64 = 48;
316+const GRAPH_ROW_GAP: i64 = 16;
317+
318+/// One job card of the graph. `class` is the card's class with its status word.
319+struct GraphCard {
320+ class: String,
321+ href: String,
322+ name: String,
323+ state: String,
324+ duration: String,
325+}
326+
327+/// The job graph of a run: the cards by stage column, and the connector paths between them.
328+struct JobGraph {
329+ width: String,
330+ height: String,
331+ columns: Vec<Vec<GraphCard>>,
332+ paths: Vec<String>,
333+}
334+
309 /// The run page's header values.335 /// The run page's header values.
310 struct RunView {336 struct RunView {
311 number: i64,337 number: i64,
338+ title: String,
339+ commit_href: String,
340+ duration: String,
312 state: String,341 state: String,
313 state_class: String,342 state_class: String,
314 trigger: String,343 trigger: String,
@@ -365,6 +394,7 @@ async fn runs_body(
365 newer_href: Option<String>,394 newer_href: Option<String>,
366 older_href: Option<String>,395 older_href: Option<String>,
367 page_label: String,396 page_label: String,
397+ live: Option<String>,
368 ) -> Result<impl View> {398 ) -> Result<impl View> {
369 Ok(view! {399 Ok(view! {
370 repo_head(head: head)400 repo_head(head: head)
@@ -404,6 +434,7 @@ async fn runs_body(
404 </label>434 </label>
405 </details>435 </details>
406 </section>436 </section>
437+ <div data-live=(live.as_deref())>
407 <section class="card">438 <section class="card">
408 <h2>(g::t(lang, K::Runs))</h2>439 <h2>(g::t(lang, K::Runs))</h2>
409 if rows.is_empty() {440 if rows.is_empty() {
@@ -425,7 +456,7 @@ async fn runs_body(
425 <tbody>456 <tbody>
426 for row in rows.iter() {457 for row in rows.iter() {
427 <tr>458 <tr>
428- <td><a href=(row.href.as_str())>"#" (row.number)</a></td>459+ <td><a class="ci-run-link" href=(row.href.as_str())>"#" (row.number)</a></td>
429 <td><span class=(row.state_class.as_str())>(row.state.as_str())</span></td>460 <td><span class=(row.state_class.as_str())>(row.state.as_str())</span></td>
430 <td>(row.trigger.as_str())</td>461 <td>(row.trigger.as_str())</td>
431 <td><code>(row.git_ref.as_str())</code></td>462 <td><code>(row.git_ref.as_str())</code></td>
@@ -448,6 +479,7 @@ async fn runs_body(
448 }479 }
449 </nav>480 </nav>
450 </section>481 </section>
482+ </div>
451 })483 })
452 }484 }
453 485
@@ -481,6 +513,8 @@ async fn runs_list_page(cx: &Cx) -> Result<impl View> {
481 let newer_href = (page > 1).then(|| format!("{base}?page={}", page - 1));513 let newer_href = (page > 1).then(|| format!("{base}?page={}", page - 1));
482 let older_href = (u64::from(page) < last_page).then(|| format!("{base}?page={}", page + 1));514 let older_href = (u64::from(page) < last_page).then(|| format!("{base}?page={}", page + 1));
483 let page_label = g::page_label(lang, page);515 let page_label = g::page_label(lang, page);
516+ // Page 1 follows the repo's changes, since a new run can appear at any time. Other pages do not.
517+ let live = (page == 1).then(|| format!("{base}/events"));
484 let manual = if can_write(&ctx) {518 let manual = if can_write(&ctx) {
485 let csrf = match current_user(cx).await? {519 let csrf = match current_user(cx).await? {
486 Some((_, session)) => session.csrf_token.clone(),520 Some((_, session)) => session.csrf_token.clone(),
@@ -502,10 +536,23 @@ async fn runs_list_page(cx: &Cx) -> Result<impl View> {
502 Ok(view! {536 Ok(view! {
503 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),537 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
504 runs_body(head: head, lang: lang, notice: notice, manual: manual, badge: badge, rows: rows,538 runs_body(head: head, lang: lang, notice: notice, manual: manual, badge: badge, rows: rows,
505- newer_href: newer_href, older_href: older_href, page_label: page_label))539+ newer_href: newer_href, older_href: older_href, page_label: page_label, live: live))
506 })540 })
507 }541 }
508 542
543+/// The live `changed` stream of a repo's run list. It is sent on each change of the repo: a run was
544+/// created or changed state. Nothing is sent on connect, since the page was just rendered.
545+#[route(GET "/{owner}/{repo}/ci/events")]
546+async fn runs_events(cx: &Cx) -> Result<Response> {
547+ let owner = path_param::<Owner>(cx);
548+ let name = path_param::<Repo>(cx);
549+ let ctx = load_repo(cx, owner, name).await?;
550+ let state = app_context::<AppState>(cx);
551+ // Subscribed before the response is sent, so a change after this point is sent.
552+ let wake = state.ci_live.subscribe_repo(&ctx.repo.id);
553+ events_response(cx, repo_changes(wake))
554+}
555+
509 /// Starts a manual run on a branch. Writers only. The branch must be one of the repo's branches.556 /// Starts a manual run on a branch. Writers only. The branch must be one of the repo's branches.
510 #[route(POST "/{owner}/{repo}/ci")]557 #[route(POST "/{owner}/{repo}/ci")]
511 async fn manual_run_post(cx: &Cx, Form(form): Form<ManualForm>) -> Result<SeeOther> {558 async fn manual_run_post(cx: &Cx, Form(form): Form<ManualForm>) -> Result<SeeOther> {
@@ -544,10 +591,24 @@ async fn run_view(
544 lang: Lang,591 lang: Lang,
545 ) -> Result<RunView> {592 ) -> Result<RunView> {
546 let names = usernames(state, lang, std::iter::once(run.actor_id.as_str())).await?;593 let names = usernames(state, lang, std::iter::once(run.actor_id.as_str())).await?;
547- let title = title_of(ctx);594+ let repo_title = title_of(ctx);
548- let action_base = run_href(&title, run.number);595+ let action_base = run_href(&repo_title, run.number);
596+ // The commit's first line is the run title. A run whose commit cannot be read shows its trigger.
597+ let path = ctx.path.clone();
598+ let oid = run.commit_oid.clone();
599+ let subject = tokio::task::spawn_blocking(move || read_commit(&path, &oid))
600+ .await??
601+ .map(|commit| commit.summary)
602+ .filter(|summary| !summary.is_empty());
549 Ok(RunView {603 Ok(RunView {
550 number: run.number,604 number: run.number,
605+ title: subject.unwrap_or_else(|| run.trigger.clone()),
606+ commit_href: format!("/{repo_title}/commit/{}", run.commit_oid),
607+ duration: duration_text(
608+ lang,
609+ Some(run.created_at.as_str()),
610+ run.finished_at.as_deref(),
611+ ),
551 state: state_text(lang, run.state.as_str()),612 state: state_text(lang, run.state.as_str()),
552 state_class: format!("ci-state ci-{}", run.state.as_str()),613 state_class: format!("ci-state ci-{}", run.state.as_str()),
553 trigger: run.trigger.clone(),614 trigger: run.trigger.clone(),
@@ -586,6 +647,130 @@ fn job_rows(
586 .collect()647 .collect()
587 }648 }
588 649
650+/// The `needs` of a job spec. A spec that does not read gives no needs.
651+fn needs_of(spec_json: &str) -> Vec<String> {
652+ #[derive(Deserialize)]
653+ struct Needs {
654+ #[serde(default)]
655+ needs: Vec<String>,
656+ }
657+ serde_json::from_str::<Needs>(spec_json)
658+ .map(|spec| spec.needs)
659+ .unwrap_or_default()
660+}
661+
662+/// Stage depth of each job, in the order given: 0 with no needs, else 1 plus the largest depth of its
663+/// needs. A need that names no job of the run is ignored. A cycle (config parsing refuses one) stops
664+/// at the job that repeats, so the walk always ends.
665+pub(crate) fn stage_depths(jobs: &[(&str, &[String])]) -> Vec<usize> {
666+ let index: HashMap<&str, usize> = jobs
667+ .iter()
668+ .enumerate()
669+ .map(|(i, (name, _))| (*name, i))
670+ .collect();
671+ let deps: Vec<Vec<usize>> = jobs
672+ .iter()
673+ .map(|(_, needs)| {
674+ needs
675+ .iter()
676+ .filter_map(|need| index.get(need.as_str()).copied())
677+ .collect()
678+ })
679+ .collect();
680+ let mut memo = vec![None; jobs.len()];
681+ let mut active = vec![false; jobs.len()];
682+ (0..jobs.len())
683+ .map(|i| depth_of(i, &deps, &mut memo, &mut active))
684+ .collect()
685+}
686+
687+/// The stage depth of job `i`, memoized in `memo`. `active` marks the jobs on the walk now.
688+fn depth_of(
689+ i: usize,
690+ deps: &[Vec<usize>],
691+ memo: &mut [Option<usize>],
692+ active: &mut [bool],
693+) -> usize {
694+ if let Some(depth) = memo[i] {
695+ return depth;
696+ }
697+ if active[i] {
698+ return 0;
699+ }
700+ active[i] = true;
701+ let depth = deps[i]
702+ .iter()
703+ .map(|&need| depth_of(need, deps, memo, active) + 1)
704+ .max()
705+ .unwrap_or(0);
706+ active[i] = false;
707+ memo[i] = Some(depth);
708+ depth
709+}
710+
711+/// The job graph of a run. Each job sits in the column of its stage depth, below the jobs before it
712+/// in that column. A connector runs from each needed job to the job that needs it.
713+fn job_graph(title: &str, jobs: &[CiJob], lang: Lang) -> JobGraph {
714+ let needs: Vec<Vec<String>> = jobs.iter().map(|job| needs_of(&job.spec_json)).collect();
715+ let named: Vec<(&str, &[String])> = jobs
716+ .iter()
717+ .zip(&needs)
718+ .map(|(job, n)| (job.name.as_str(), n.as_slice()))
719+ .collect();
720+ let depths = stage_depths(&named);
721+ let stages = depths.iter().max().map_or(0, |deepest| deepest + 1);
722+ let mut columns: Vec<Vec<GraphCard>> = (0..stages).map(|_| Vec::new()).collect();
723+ let mut slots = Vec::with_capacity(jobs.len());
724+ for (job, &depth) in jobs.iter().zip(&depths) {
725+ slots.push((depth, columns[depth].len()));
726+ columns[depth].push(GraphCard {
727+ class: format!("ci-graph-card ci-{}", job.state.as_str()),
728+ href: job_href(title, &job.id),
729+ name: job.name.clone(),
730+ state: state_text(lang, job.state.as_str()),
731+ duration: duration_text(lang, job.started_at.as_deref(), job.finished_at.as_deref()),
732+ });
733+ }
734+ let x = |stage: usize| GRAPH_PAD + stage as i64 * (GRAPH_CARD_W + GRAPH_COL_GAP);
735+ let y = |row: usize| GRAPH_PAD + row as i64 * (GRAPH_CARD_H + GRAPH_ROW_GAP);
736+ let stage_count = stages as i64;
737+ let tallest = columns.iter().map(Vec::len).max().unwrap_or(0) as i64;
738+ let width =
739+ 2 * GRAPH_PAD + stage_count * GRAPH_CARD_W + (stage_count - 1).max(0) * GRAPH_COL_GAP;
740+ let height = 2 * GRAPH_PAD + tallest * GRAPH_CARD_H + (tallest - 1).max(0) * GRAPH_ROW_GAP;
741+ let index: HashMap<&str, usize> = jobs
742+ .iter()
743+ .enumerate()
744+ .map(|(i, job)| (job.name.as_str(), i))
745+ .collect();
746+ let bend = GRAPH_COL_GAP / 2;
747+ let mut paths = Vec::new();
748+ for (i, job_needs) in needs.iter().enumerate() {
749+ let (to_stage, to_row) = slots[i];
750+ let x2 = x(to_stage);
751+ let y2 = y(to_row) + GRAPH_CARD_H / 2;
752+ for need in job_needs {
753+ let Some(&from) = index.get(need.as_str()) else {
754+ continue;
755+ };
756+ let (from_stage, from_row) = slots[from];
757+ let x1 = x(from_stage) + GRAPH_CARD_W;
758+ let y1 = y(from_row) + GRAPH_CARD_H / 2;
759+ paths.push(format!(
760+ "M{x1} {y1} C{} {y1} {} {y2} {x2} {y2}",
761+ x1 + bend,
762+ x2 - bend
763+ ));
764+ }
765+ }
766+ JobGraph {
767+ width: width.to_string(),
768+ height: height.to_string(),
769+ columns,
770+ paths,
771+ }
772+}
773+
589 /// How often an idle event stream sends a `: keepalive` comment, so a reverse proxy does not drop774 /// How often an idle event stream sends a `: keepalive` comment, so a reverse proxy does not drop
590 /// the connection. This is not a poll: events follow the change signals.775 /// the connection. This is not a poll: events follow the change signals.
591 const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30);776 const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30);
@@ -674,6 +859,15 @@ where
674 )859 )
675 }860 }
676 861
862+/// One `changed` event per wake of `wake`. The repo list has no status to compare, so each wake is
863+/// sent. The stream ends when the signal closes.
864+fn repo_changes(wake: watch::Receiver<u64>) -> impl Stream<Item = Result<Event>> + Send + 'static {
865+ stream::unfold(wake, |mut wake| async move {
866+ wake.changed().await.ok()?;
867+ Some((changed_event("list".to_owned()), wake))
868+ })
869+}
870+
677 /// The response of an event stream for a CI page: keep-alive comments while idle, and no buffering871 /// The response of an event stream for a CI page: keep-alive comments while idle, and no buffering
678 /// by a reverse proxy.872 /// by a reverse proxy.
679 pub(crate) fn events_response(873 pub(crate) fn events_response(
@@ -700,6 +894,7 @@ async fn run_body(
700 notice: Option<(&'static str, bool)>,894 notice: Option<(&'static str, bool)>,
701 run: RunView,895 run: RunView,
702 jobs: Vec<JobRow>,896 jobs: Vec<JobRow>,
897+ graph: JobGraph,
703 writer_csrf: Option<String>,898 writer_csrf: Option<String>,
704 live: Option<String>,899 live: Option<String>,
705 ) -> Result<impl View> {900 ) -> Result<impl View> {
@@ -713,21 +908,26 @@ async fn run_body(
713 <section class="card notice" role="status">(text)</section>908 <section class="card notice" role="status">(text)</section>
714 }909 }
715 }910 }
716- <section class="card">911+ <section class="card ci-run-head">
717- <h2>(g::t(lang, K::RunNumber)) (run.number)</h2>912+ <div class="ci-run-head-main">
718- <p class="muted small">913+ <h2 class="ci-run-title"><span class=(run.state_class.as_str())>(run.state.as_str())</span>" "(run.title.as_str())</h2>
719- <span class=(run.state_class.as_str())>(run.state.as_str())</span>914+ <p class="muted small ci-run-meta">
720- " \u{b7} " (run.trigger.as_str())915+ "#" (run.number)
721- " \u{b7} " <code>(run.git_ref.as_str())</code>916+ " \u{b7} " (run.trigger.as_str())
722- " \u{b7} " <code>(short_oid(&run.commit).to_owned())</code>917+ " \u{b7} " <code>(run.git_ref.as_str())</code>
723- if !run.actor.is_empty() {918+ " \u{b7} " <a href=(run.commit_href.as_str())><code>(short_oid(&run.commit).to_owned())</code></a>
724- " \u{b7} " (run.actor.as_str())919+ if !run.actor.is_empty() {
920+ " \u{b7} " (run.actor.as_str())
921+ }
922+ " \u{b7} " (run.when.as_str())
923+ if !run.duration.is_empty() {
924+ " \u{b7} " (run.duration.as_str())
925+ }
926+ </p>
927+ if let Some(message) = run.config_error.as_ref() {
928+ <pre class="ci-config-error">(message.as_str())</pre>
725 }929 }
726- " \u{b7} " (run.when.as_str())930+ </div>
727- </p>
728- if let Some(message) = run.config_error.as_ref() {
729- <pre class="ci-config-error">(message.as_str())</pre>
730- }
731 if let Some(csrf) = writer_csrf {931 if let Some(csrf) = writer_csrf {
732 <div class="ci-actions">932 <div class="ci-actions">
733 if run.can_approve {933 if run.can_approve {
@@ -740,6 +940,36 @@ async fn run_body(
740 </div>940 </div>
741 }941 }
742 </section>942 </section>
943+ if !jobs.is_empty() {
944+ <section class="card">
945+ <h2>(g::t(lang, K::JobGraph))</h2>
946+ <div class="ci-graph" tabindex="0" role="region" aria-label=(g::t(lang, K::JobGraph))>
947+ <div class="ci-graph-canvas">
948+ <svg class="ci-graph-lines" width=(graph.width.as_str()) height=(graph.height.as_str()) aria-hidden="true">
949+ for d in graph.paths.iter() {
950+ <path d=(d.as_str())/>
951+ }
952+ </svg>
953+ for stage in graph.columns.iter() {
954+ <div class="ci-graph-col">
955+ for card in stage.iter() {
956+ <a class=(card.class.as_str()) href=(card.href.as_str())>
957+ <span class="ci-graph-name">(card.name.as_str())</span>
958+ <span class="ci-graph-meta">
959+ <span class="ci-graph-icon" aria-hidden="true"></span>
960+ (card.state.as_str())
961+ if !card.duration.is_empty() {
962+ " \u{b7} " (card.duration.as_str())
963+ }
964+ </span>
965+ </a>
966+ }
967+ </div>
968+ }
969+ </div>
970+ </div>
971+ </section>
972+ }
743 <section class="card">973 <section class="card">
744 <h2>(g::t(lang, K::Jobs))</h2>974 <h2>(g::t(lang, K::Jobs))</h2>
745 if jobs.is_empty() {975 if jobs.is_empty() {
@@ -759,7 +989,7 @@ async fn run_body(
759 <tbody>989 <tbody>
760 for job in jobs.iter() {990 for job in jobs.iter() {
761 <tr>991 <tr>
762- <td><a href=(job.href.as_str())>(job.name.as_str())</a></td>992+ <td><a class="ci-job-link" href=(job.href.as_str())>(job.name.as_str())</a></td>
763 <td><span class=(job.state_class.as_str())>(job.state.as_str())</span></td>993 <td><span class=(job.state_class.as_str())>(job.state.as_str())</span></td>
764 <td>(job.duration.as_str())</td>994 <td>(job.duration.as_str())</td>
765 <td>(job.runner.as_str())</td>995 <td>(job.runner.as_str())</td>
@@ -804,6 +1034,7 @@ async fn run_page(cx: &Cx) -> Result<impl View> {
804 .collect();1034 .collect();
805 let title = title_of(&ctx);1035 let title = title_of(&ctx);
806 let rows = job_rows(&title, &jobs, &runners, lang);1036 let rows = job_rows(&title, &jobs, &runners, lang);
1037+ let graph = job_graph(&title, &jobs, lang);
807 let live =1038 let live =
808 (!run_finished(&run.state)).then(|| format!("{}/events", run_href(&title, run.number)));1039 (!run_finished(&run.state)).then(|| format!("{}/events", run_href(&title, run.number)));
809 let notice = notice_from_query(cx, lang);1040 let notice = notice_from_query(cx, lang);
@@ -813,7 +1044,7 @@ async fn run_page(cx: &Cx) -> Result<impl View> {
813 Ok(view! {1044 Ok(view! {
814 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),1045 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),
815 run_body(head: head, lang: lang, notice: notice, run: header, jobs: rows,1046 run_body(head: head, lang: lang, notice: notice, run: header, jobs: rows,
816- writer_csrf: writer_csrf, live: live))1047+ graph: graph, writer_csrf: writer_csrf, live: live))
817 })1048 })
818 }1049 }
819 1050
crates/forge-web/src/pages/ci_tests.rsmodified+291 -1
@@ -301,7 +301,10 @@ async fn run_list_pages_25_at_a_time() {
301 .await;301 .await;
302 assert_eq!(bogus.status, 200);302 assert_eq!(bogus.status, 200);
303 assert_eq!(303 assert_eq!(
304- bogus.text().matches("href=\"/tahinli/proj/ci/runs/").count(),304+ bogus
305+ .text()
306+ .matches("href=\"/tahinli/proj/ci/runs/")
307+ .count(),
305 25308 25
306 );309 );
307 }310 }
@@ -463,6 +466,65 @@ async fn live_events_open_with_the_status_and_follow_changes() {
463 assert!(next_event(&mut job_frames).await.is_none(), "stream ends");466 assert!(next_event(&mut job_frames).await.is_none(), "stream ends");
464 }467 }
465 468
469+/// The run list is live on page 1 only: a new run can appear there at any time. Page 2 is a fixed
470+/// slice, so it carries no live marker.
471+#[tokio::test]
472+async fn run_list_is_live_on_page_one_only() {
473+ let dir = tempfile::tempdir().expect("tempdir");
474+ let fx = fixture(dir.path()).await;
475+ for _ in 0..30 {
476+ run_with(&fx, &[], false).await;
477+ }
478+ let marker = format!("data-live=\"{RUN_BASE}/events\"");
479+ let first = get(&fx.app, RUN_BASE, Some(&cookie_for("tahinli-token"))).await;
480+ assert!(first.text().contains(&marker), "page 1 is live");
481+ let second = get(
482+ &fx.app,
483+ &format!("{RUN_BASE}?page=2"),
484+ Some(&cookie_for("tahinli-token")),
485+ )
486+ .await;
487+ assert!(!second.text().contains("data-live="), "page 2 is not live");
488+}
489+
490+#[tokio::test]
491+async fn run_list_events_need_the_same_access_as_the_page() {
492+ let dir = tempfile::tempdir().expect("tempdir");
493+ let fx = fixture(dir.path()).await;
494+ let url = format!("{RUN_BASE}/events");
495+ let anon = open(&fx.app, &url, None).await;
496+ assert_eq!(anon.status().as_u16(), 404, "anonymous");
497+ let outsider = open(&fx.app, &url, Some(&cookie_for("carol-token"))).await;
498+ assert_eq!(outsider.status().as_u16(), 404, "outsider");
499+ let reader = open(&fx.app, &url, Some(&cookie_for("dave-token"))).await;
500+ assert_eq!(reader.status().as_u16(), 200, "reader");
501+}
502+
503+/// The list stream sends nothing on connect, then one `changed` event per change of the repo.
504+#[tokio::test]
505+async fn run_list_events_follow_repo_changes() {
506+ use futures_util::StreamExt;
507+
508+ let dir = tempfile::tempdir().expect("tempdir");
509+ let fx = fixture(dir.path()).await;
510+ let mut frames = open(
511+ &fx.app,
512+ &format!("{RUN_BASE}/events"),
513+ Some(&cookie_for("tahinli-token")),
514+ )
515+ .await
516+ .into_body()
517+ .into_data_stream();
518+
519+ let quiet = tokio::time::timeout(Duration::from_millis(200), frames.next()).await;
520+ assert!(quiet.is_err(), "nothing is sent on connect");
521+
522+ run_with(&fx, &["build"], false).await;
523+ fx.live.bump_repo(&fx.repo.id);
524+ let first = next_event(&mut frames).await.expect("a repo change");
525+ assert_eq!(first, b"event: changed\ndata: list\n\n".to_vec());
526+}
527+
466 /// The job's log events: each append is sent as a `log` event with its bytes, the id is the offset528 /// The job's log events: each append is sent as a `log` event with its bytes, the id is the offset
467 /// past them, and the bytes before `?from=` are not sent again.529 /// past them, and the bytes before `?from=` are not sent again.
468 #[tokio::test]530 #[tokio::test]
@@ -995,3 +1057,231 @@ async fn badge_follows_read_access_and_reports_the_latest_run() {
995 let unknown_repo = get(&fx.app, "/tahinli/nothere/badge.svg", None).await;1057 let unknown_repo = get(&fx.app, "/tahinli/nothere/badge.svg", None).await;
996 assert_eq!(unknown_repo.status, 404);1058 assert_eq!(unknown_repo.status, 404);
997 }1059 }
1060+
1061+/// Writes `.forge/ci.toml` with `text` into a new commit of the bare repo and returns its id.
1062+fn commit_ci_toml(bare: &Path, text: &str) -> String {
1063+ fn git(bare: &Path, args: &[&str], stdin: &str) -> String {
1064+ let mut child = std::process::Command::new("git")
1065+ .arg("--git-dir")
1066+ .arg(bare)
1067+ .args(args)
1068+ .env("GIT_AUTHOR_NAME", "tahinli")
1069+ .env("GIT_AUTHOR_EMAIL", "tahinli@example.com")
1070+ .env("GIT_COMMITTER_NAME", "tahinli")
1071+ .env("GIT_COMMITTER_EMAIL", "tahinli@example.com")
1072+ .stdin(std::process::Stdio::piped())
1073+ .stdout(std::process::Stdio::piped())
1074+ .stderr(std::process::Stdio::piped())
1075+ .spawn()
1076+ .expect("spawn git");
1077+ child
1078+ .stdin
1079+ .take()
1080+ .expect("stdin")
1081+ .write_all(stdin.as_bytes())
1082+ .expect("write stdin");
1083+ let out = child.wait_with_output().expect("git output");
1084+ assert!(
1085+ out.status.success(),
1086+ "git {args:?}: {}",
1087+ String::from_utf8_lossy(&out.stderr)
1088+ );
1089+ String::from_utf8(out.stdout)
1090+ .expect("utf8")
1091+ .trim()
1092+ .to_owned()
1093+ }
1094+ let blob = git(bare, &["hash-object", "-w", "--stdin"], text);
1095+ let forge = git(bare, &["mktree"], &format!("100644 blob {blob}\tci.toml\n"));
1096+ let root = git(bare, &["mktree"], &format!("040000 tree {forge}\t.forge\n"));
1097+ git(bare, &["commit-tree", root.as_str(), "-m", "ci config"], "")
1098+}
1099+
1100+/// Creates a queued run of one job `build` at `commit` on `main`.
1101+async fn run_at(fx: &Fixture, commit: &str) {
1102+ let needs: &[String] = &[];
1103+ let specs = [NewJob {
1104+ name: "build",
1105+ spec_json: SPEC,
1106+ needs,
1107+ }];
1108+ fx.store
1109+ .create_run(
1110+ &fx.repo.id,
1111+ "push",
1112+ "refs/heads/main",
1113+ commit,
1114+ None,
1115+ &fx.tahinli,
1116+ false,
1117+ &specs,
1118+ None,
1119+ )
1120+ .await
1121+ .expect("run");
1122+}
1123+
1124+#[tokio::test]
1125+async fn badge_label_comes_from_the_query_job_or_workflow_name() {
1126+ let dir = tempfile::tempdir().expect("tempdir");
1127+ let fx = fixture(dir.path()).await;
1128+ let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path");
1129+ let commit = commit_ci_toml(
1130+ &bare,
1131+ "name = \" release-check \"\n[jobs.build]\nimage = \"i\"\nrun = \"r\"\n",
1132+ );
1133+ run_at(&fx, &commit).await;
1134+ finish_job(&fx).await;
1135+ let path = "/tahinli/proj/badge.svg";
1136+ let reader = Some(cookie_for("dave-token"));
1137+ let named = get(&fx.app, path, reader.as_deref()).await.text();
1138+ assert!(named.contains(">release-check</text>"), "name: {named}");
1139+ assert!(named.contains(">passing</text>"));
1140+
1141+ let job = get(&fx.app, &format!("{path}?job=build"), reader.as_deref())
1142+ .await
1143+ .text();
1144+ assert!(job.contains(">build</text>"), "job beats name: {job}");
1145+
1146+ let label = get(&fx.app, &format!("{path}?label=Ship"), reader.as_deref())
1147+ .await
1148+ .text();
1149+ assert!(label.contains(">Ship</text>"), "label beats name: {label}");
1150+
1151+ let both = get(
1152+ &fx.app,
1153+ &format!("{path}?job=build&label=Ship"),
1154+ reader.as_deref(),
1155+ )
1156+ .await
1157+ .text();
1158+ assert!(both.contains(">Ship</text>"), "label beats job: {both}");
1159+ assert!(both.contains(">passing</text>"), "status is the job's");
1160+}
1161+
1162+#[tokio::test]
1163+async fn badge_label_is_trimmed_and_empty_means_absent() {
1164+ let dir = tempfile::tempdir().expect("tempdir");
1165+ let fx = fixture(dir.path()).await;
1166+ run_with(&fx, &["build"], false).await;
1167+ finish_job(&fx).await;
1168+ let path = "/tahinli/proj/badge.svg";
1169+ let reader = Some(cookie_for("dave-token"));
1170+ let padded = get(
1171+ &fx.app,
1172+ &format!("{path}?label=%20deploy%20"),
1173+ reader.as_deref(),
1174+ )
1175+ .await
1176+ .text();
1177+ assert!(padded.contains(">deploy</text>"), "{padded}");
1178+ let empty = get(&fx.app, &format!("{path}?label="), reader.as_deref())
1179+ .await
1180+ .text();
1181+ assert!(
1182+ empty.contains(">ci</text>"),
1183+ "empty label is absent: {empty}"
1184+ );
1185+ let blank = get(&fx.app, &format!("{path}?label=%20%20"), reader.as_deref())
1186+ .await
1187+ .text();
1188+ assert!(
1189+ blank.contains(">ci</text>"),
1190+ "blank label is absent: {blank}"
1191+ );
1192+}
1193+
1194+#[tokio::test]
1195+async fn badge_label_is_escaped() {
1196+ let dir = tempfile::tempdir().expect("tempdir");
1197+ let fx = fixture(dir.path()).await;
1198+ run_with(&fx, &["build"], false).await;
1199+ finish_job(&fx).await;
1200+ let reader = Some(cookie_for("dave-token"));
1201+ let svg = get(
1202+ &fx.app,
1203+ "/tahinli/proj/badge.svg?label=%3Cb%3E%20a%20%26%20b%20%3E",
1204+ reader.as_deref(),
1205+ )
1206+ .await
1207+ .text();
1208+ assert!(svg.contains("&lt;b&gt; a &amp; b &gt;"), "{svg}");
1209+ assert!(!svg.contains("<b>"), "raw markup must not reach the SVG");
1210+}
1211+
1212+#[tokio::test]
1213+async fn badge_label_defaults_to_ci_without_a_usable_workflow_name() {
1214+ let dir = tempfile::tempdir().expect("tempdir");
1215+ let fx = fixture(dir.path()).await;
1216+ let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path");
1217+ // A run whose config has an empty name: the name is ignored.
1218+ let commit = commit_ci_toml(
1219+ &bare,
1220+ "name = \" \"\n[jobs.build]\nimage = \"i\"\nrun = \"r\"\n",
1221+ );
1222+ run_at(&fx, &commit).await;
1223+ finish_job(&fx).await;
1224+ let reader = Some(cookie_for("dave-token"));
1225+ let svg = get(&fx.app, "/tahinli/proj/badge.svg", reader.as_deref())
1226+ .await
1227+ .text();
1228+ assert!(svg.contains(">ci</text>"), "{svg}");
1229+}
1230+
1231+#[tokio::test]
1232+async fn badge_without_any_run_uses_the_label_or_ci() {
1233+ let dir = tempfile::tempdir().expect("tempdir");
1234+ let fx = fixture(dir.path()).await;
1235+ let reader = Some(cookie_for("dave-token"));
1236+ let plain = get(&fx.app, "/tahinli/proj/badge.svg", reader.as_deref())
1237+ .await
1238+ .text();
1239+ assert!(plain.contains(">ci</text>"), "{plain}");
1240+ assert!(plain.contains(">no status</text>"));
1241+ let labelled = get(
1242+ &fx.app,
1243+ "/tahinli/proj/badge.svg?label=Nightly",
1244+ reader.as_deref(),
1245+ )
1246+ .await
1247+ .text();
1248+ assert!(labelled.contains(">Nightly</text>"), "{labelled}");
1249+ assert!(labelled.contains(">no status</text>"));
1250+}
1251+
1252+/// Stage depths of a run's jobs, from `(name, needs)` pairs in job order.
1253+fn depths_of(jobs: &[(&str, &[&str])]) -> Vec<usize> {
1254+ let owned: Vec<(&str, Vec<String>)> = jobs
1255+ .iter()
1256+ .map(|(name, needs)| (*name, needs.iter().map(|n| n.to_string()).collect()))
1257+ .collect();
1258+ let named: Vec<(&str, &[String])> = owned
1259+ .iter()
1260+ .map(|(name, needs)| (*name, needs.as_slice()))
1261+ .collect();
1262+ crate::pages::ci_runs::stage_depths(&named)
1263+}
1264+
1265+#[test]
1266+fn stage_depths_follow_the_longest_chain_of_needs() {
1267+ // A chain, a job with two needs one stage past the deeper one, and jobs with no needs.
1268+ let depths = depths_of(&[
1269+ ("lint", &[]),
1270+ ("build", &[]),
1271+ ("test", &["build"]),
1272+ ("docs", &["lint"]),
1273+ ("deploy", &["test", "lint"]),
1274+ ]);
1275+ assert_eq!(depths, vec![0, 0, 1, 1, 2]);
1276+ // A job that needs a job which needs a job sits two stages down.
1277+ let chain = depths_of(&[("c", &["b"]), ("b", &["a"]), ("a", &[])]);
1278+ assert_eq!(chain, vec![2, 1, 0]);
1279+}
1280+
1281+#[test]
1282+fn stage_depths_ignore_unknown_needs_and_survive_cycles() {
1283+ assert_eq!(depths_of(&[("a", &["ghost"])]), vec![0]);
1284+ // Config parsing refuses cycles. The walk must still end.
1285+ let cycle = depths_of(&[("a", &["b"]), ("b", &["a"])]);
1286+ assert_eq!(cycle.len(), 2);
1287+}
crates/forge-web/src/pages/settings_profile.rsmodified+157 -179
@@ -1,5 +1,6 @@
1-//! Page: profile (`/settings/profile`). Username capitalization, avatar upload and removal,1+//! Page: public profile (`/settings/profile`). One form saves the username capitalization, the
2-//! the "about" text and the timezone. Every POST checks the CSRF token first.2+//! "about" text and the timezone. The avatar menu beside it posts to its own upload and removal
3+//! routes. Every POST checks the CSRF token first.
3 4
4 use forge_core::AuditAction;5 use forge_core::AuditAction;
5 use forge_core::names::capitalization_change;6 use forge_core::names::capitalization_change;
@@ -36,18 +37,13 @@ struct ProfileQuery {
36 saved: Option<String>,37 saved: Option<String>,
37 }38 }
38 39
40+/// The one profile form: username, about and timezone.
39 #[derive(Deserialize)]41 #[derive(Deserialize)]
40 struct ProfileForm {42 struct ProfileForm {
41 #[serde(default)]43 #[serde(default)]
42 csrf: String,44 csrf: String,
43 #[serde(default)]45 #[serde(default)]
44 username: String,46 username: String,
45-}
46-
47-#[derive(Deserialize)]
48-struct DetailsForm {
49- #[serde(default)]
50- csrf: String,
51 #[serde(default)]47 #[serde(default)]
52 about: String,48 about: String,
53 #[serde(default)]49 #[serde(default)]
@@ -77,12 +73,21 @@ impl Draft {
77 }73 }
78 }74 }
79 75
80-/// Per-section error messages.76+/// Per-field error messages, shown under the field they belong to.
81 #[derive(Default)]77 #[derive(Default)]
82 struct Errors {78 struct Errors {
83 username: Option<String>,79 username: Option<String>,
80+ about: Option<String>,
81+ timezone: Option<String>,
84 avatar: Option<String>,82 avatar: Option<String>,
85- details: Option<String>,83+}
84+
85+impl Errors {
86+ /// True when no profile field has an error. The avatar error does not count: it belongs to
87+ /// its own upload.
88+ fn profile_is_clear(&self) -> bool {
89+ self.username.is_none() && self.about.is_none() && self.timezone.is_none()
90+ }
86 }91 }
87 92
88 struct Zone {93 struct Zone {
@@ -93,7 +98,6 @@ struct Zone {
93 struct ProfilePage {98 struct ProfilePage {
94 lang: Lang,99 lang: Lang,
95 csrf: String,100 csrf: String,
96- current: String,
97 draft: Draft,101 draft: Draft,
98 errors: Errors,102 errors: Errors,
99 notice: Option<&'static str>,103 notice: Option<&'static str>,
@@ -107,7 +111,6 @@ async fn profile_body(page: ProfilePage) -> Result<impl View> {
107 let ProfilePage {111 let ProfilePage {
108 lang,112 lang,
109 csrf,113 csrf,
110- current,
111 draft,114 draft,
112 errors,115 errors,
113 notice,116 notice,
@@ -125,71 +128,67 @@ async fn profile_body(page: ProfilePage) -> Result<impl View> {
125 <p>(message)</p>128 <p>(message)</p>
126 </section>129 </section>
127 }130 }
128- <section class="card">131+ <div class="profile-settings">
129- <h2>(t(lang, Key::Username))</h2>132+ <form method="post" action="/settings/profile" class="profile-form">
130- <p>(t(lang, Key::CurrentUsername)) <strong>(current.as_str())</strong></p>
131- if let Some(message) = errors.username {
132- alert(message: message.as_str())
133- }
134- <form method="post" action="/settings/profile" class="stack">
135 <input type="hidden" name="csrf" value=(csrf.as_str())>133 <input type="hidden" name="csrf" value=(csrf.as_str())>
136- <label>134+ <div class="profile-field">
137- <span>(t(lang, Key::Username))</span>135+ <label for="profile-username">(t(lang, Key::Username))</label>
138- <input type="text" name="username" maxlength="64" required=(true) autocomplete="username" value=(draft.username.as_str())>136+ <input id="profile-username" type="text" name="username" maxlength="64" required=(true) autocomplete="username" value=(draft.username.as_str()) aria-describedby="profile-username-hint">
139- <small class="muted">(t(lang, Key::UsernameHint))</small>137+ <small class="muted" id="profile-username-hint">(t(lang, Key::UsernameHint))</small>
140- </label>138+ if let Some(message) = errors.username {
141- <button type="submit" class="primary">(t(lang, Key::Save))</button>
142- </form>
143- </section>
144- <section class="card">
145- <h2>(t(lang, Key::Avatar))</h2>
146- <div class="avatar-row">
147- <img class="avatar avatar-lg" src=(avatar_src.as_str()) alt=(t(lang, Key::AvatarAlt)) width="96" height="96">
148- <div class="stack">
149- if let Some(message) = errors.avatar {
150 alert(message: message.as_str())139 alert(message: message.as_str())
151 }140 }
152- <form method="post" action="/settings/profile/avatar" enctype="multipart/form-data" class="stack">141+ </div>
153- <input type="hidden" name="csrf" value=(csrf.as_str())>142+ <div class="profile-field">
154- <label>143+ <label for="profile-about">(t(lang, Key::About))</label>
155- <span>(t(lang, Key::Image))</span>144+ <textarea id="profile-about" name="about" rows="6" maxlength="2000" aria-describedby="profile-about-hint">(draft.about.as_str())</textarea>
156- <input type="file" name="avatar" accept="image/png,image/jpeg,image/webp,image/gif" required=(true)>145+ <small class="muted" id="profile-about-hint">(t(lang, Key::AboutHint))</small>
157- <small class="muted">(t(lang, Key::AvatarHint))</small>146+ if let Some(message) = errors.about {
158- </label>147+ alert(message: message.as_str())
159- <button type="submit" class="primary">(t(lang, Key::Upload))</button>
160- </form>
161- if has_avatar {
162- <form method="post" action="/settings/profile/avatar/delete">
163- <input type="hidden" name="csrf" value=(csrf.as_str())>
164- <button type="submit" class="link-button">(t(lang, Key::RemoveAvatar))</button>
165- </form>
166 }148 }
167 </div>149 </div>
168- </div>150+ <div class="profile-field">
169- </section>151+ <label for="profile-timezone">(t(lang, Key::Timezone))</label>
170- <section class="card">152+ <select id="profile-timezone" name="timezone">
171- <h2>(t(lang, Key::AboutAndTimezone))</h2>
172- if let Some(message) = errors.details {
173- alert(message: message.as_str())
174- }
175- <form method="post" action="/settings/profile/details" class="stack">
176- <input type="hidden" name="csrf" value=(csrf.as_str())>
177- <label>
178- <span>(t(lang, Key::About))</span>
179- <textarea name="about" rows="8" maxlength="2000">(draft.about.as_str())</textarea>
180- <small class="muted">(t(lang, Key::AboutHint))</small>
181- </label>
182- <label>
183- <span>(t(lang, Key::Timezone))</span>
184- <select name="timezone">
185 for zone in zones.into_iter() {153 for zone in zones.into_iter() {
186 <option value=(zone.name.clone()) selected=(zone.selected)>(zone.name)</option>154 <option value=(zone.name.clone()) selected=(zone.selected)>(zone.name)</option>
187 }155 }
188 </select>156 </select>
189- </label>157+ if let Some(message) = errors.timezone {
190- <button type="submit" class="primary">(t(lang, Key::Save))</button>158+ alert(message: message.as_str())
159+ }
160+ </div>
161+ <div class="profile-actions">
162+ <button type="submit" class="primary">(t(lang, Key::Save))</button>
163+ </div>
191 </form>164 </form>
192- </section>165+ <aside class="profile-settings-avatar" aria-label=(t(lang, Key::Avatar))>
166+ <div class="profile-settings-avatar-frame">
167+ <img class="avatar profile-settings-avatar-img" src=(avatar_src.as_str()) alt=(t(lang, Key::AvatarAlt)) width="180" height="180">
168+ <details class="menu profile-settings-avatar-menu">
169+ <summary>(t(lang, Key::Edit))</summary>
170+ <div class="menu-list profile-settings-avatar-list">
171+ <form method="post" action="/settings/profile/avatar" enctype="multipart/form-data" class="profile-settings-avatar-upload">
172+ <input type="hidden" name="csrf" value=(csrf.as_str())>
173+ <input class="profile-settings-avatar-file" type="file" id="profile-settings-avatar-file" name="avatar" aria-label=(t(lang, Key::Image)) accept="image/png,image/jpeg,image/webp,image/gif" required=(true)>
174+ <label class="profile-settings-avatar-item" for="profile-settings-avatar-file">(t(lang, Key::UploadPhoto))</label>
175+ <button type="submit" class="primary">(t(lang, Key::Upload))</button>
176+ </form>
177+ if has_avatar {
178+ <form method="post" action="/settings/profile/avatar/delete" class="profile-settings-avatar-remove">
179+ <input type="hidden" name="csrf" value=(csrf.as_str())>
180+ <button type="submit" class="link-button">(t(lang, Key::RemovePhoto))</button>
181+ </form>
182+ }
183+ </div>
184+ </details>
185+ </div>
186+ if let Some(message) = errors.avatar {
187+ alert(message: message.as_str())
188+ }
189+ <small class="muted">(t(lang, Key::AvatarHint))</small>
190+ </aside>
191+ </div>
193 </div>192 </div>
194 })193 })
195 }194 }
@@ -213,7 +212,6 @@ async fn page_data(
213 Ok(ProfilePage {212 Ok(ProfilePage {
214 lang,213 lang,
215 csrf: viewer.1.csrf_token.clone(),214 csrf: viewer.1.csrf_token.clone(),
216- current: viewer.0.username.clone(),
217 draft,215 draft,
218 errors,216 errors,
219 notice,217 notice,
@@ -225,23 +223,31 @@ async fn page_data(
225 223
226 fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> {224 fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> {
227 match saved {225 match saved {
228- Some("1") => Some(t(lang, Key::OkUsernameUpdated)),226+ Some("1") => Some(t(lang, Key::OkProfileSaved)),
229 Some("avatar") => Some(t(lang, Key::OkAvatarUpdated)),227 Some("avatar") => Some(t(lang, Key::OkAvatarUpdated)),
230 Some("avatar-removed") => Some(t(lang, Key::OkAvatarRemoved)),228 Some("avatar-removed") => Some(t(lang, Key::OkAvatarRemoved)),
231- Some("details") => Some(t(lang, Key::OkProfileSaved)),
232 _ => None,229 _ => None,
233 }230 }
234 }231 }
235 232
236-/// Checks the "about" length and the timezone name. Returns the message-carrying error.233+/// Checks the "about" length. The timezone is checked with `validate_timezone`.
237-fn check_details(lang: Lang, about: &str, timezone: &str) -> forge_core::Result<()> {234+fn check_about(lang: Lang, about: &str) -> forge_core::Result<()> {
238 if about.chars().count() > MAX_ABOUT_CHARS {235 if about.chars().count() > MAX_ABOUT_CHARS {
239 return Err(forge_core::Error::Invalid(about_too_long(236 return Err(forge_core::Error::Invalid(about_too_long(
240 lang,237 lang,
241 MAX_ABOUT_CHARS,238 MAX_ABOUT_CHARS,
242 )));239 )));
243 }240 }
244- validate_timezone(timezone)241+ Ok(())
242+}
243+
244+/// The message to show under a field whose check failed. An internal failure is not a form
245+/// error, so it propagates as a server error.
246+fn field_message(err: forge_core::Error) -> Result<String> {
247+ match user_facing_message(&err) {
248+ Some(message) => Ok(message),
249+ None => Err(err.into()),
250+ }
245 }251 }
246 252
247 /// Stores a processed avatar, or removes it if no image was sent.253 /// Stores a processed avatar, or removes it if no image was sent.
@@ -283,89 +289,66 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
283 })289 })
284 }290 }
285 291
292+/// Saves the username, the "about" text and the timezone together. Nothing is written unless
293+/// every field passes, so one bad field keeps the old values for all of them. The username is
294+/// written only when its capitalization differs from the stored one.
286 #[page(POST "/settings/profile")]295 #[page(POST "/settings/profile")]
287 async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl View> {296 async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl View> {
288 let viewer = require_csrf(cx, &form.csrf).await?;297 let viewer = require_csrf(cx, &form.csrf).await?;
289 let lang = i18n::lang(cx, Some(&viewer.0));298 let lang = i18n::lang(cx, Some(&viewer.0));
290 let store = &app_context::<AppState>(cx).store;299 let store = &app_context::<AppState>(cx).store;
300+ let about = form.about.replace("\r\n", "\n");
291 301
292- let result = match capitalization_change(&viewer.0.username, &form.username) {302+ let mut errors = Errors::default();
293- Ok(display) => store.set_username_display(&viewer.0.id, &display).await,303+ let display = match capitalization_change(&viewer.0.username, &form.username) {
294- Err(e) => Err(e),304+ Ok(display) => Some(display),
295- };305+ Err(e) => {
296- let message = match result {306+ errors.username = Some(field_message(e)?);
297- Ok(()) => {307+ None
298- audit::record(
299- store,
300- Some(cx),
301- Actor::User(&viewer.0),
302- AuditAction::UsernameChanged,
303- Target {
304- kind: "user",
305- id: &viewer.0.id,
306- name: form.username.trim(),
307- },
308- serde_json::json!({ "from": viewer.0.username }),
309- )
310- .await;
311- return Err(see_other("/settings/profile?saved=1").into());
312 }308 }
313- Err(e) => match user_facing_message(&e) {
314- Some(message) => message,
315- None => return Err(e.into()),
316- },
317 };309 };
310+ if let Err(e) = check_about(lang, &about) {
311+ errors.about = Some(field_message(e)?);
312+ }
313+ if let Err(e) = validate_timezone(&form.timezone) {
314+ errors.timezone = Some(field_message(e)?);
315+ }
318 316
319- let draft = Draft {317+ let display = match display {
320- username: form.username,318+ Some(display) if errors.profile_is_clear() => display,
321- ..Draft::from_user(&viewer.0)319+ _ => {
322- };320+ let draft = Draft {
323- let errors = Errors {321+ username: form.username,
324- username: Some(message),322+ about,
325- ..Errors::default()323+ timezone: form.timezone,
326- };324+ };
327- let page = page_data(&viewer, lang, draft, errors, None).await?;325+ let page = page_data(&viewer, lang, draft, errors, None).await?;
328- Ok(view! {326+ return Ok(view! {
329- shell(title: "Profile", viewer: Some(&viewer), profile_body(page: page))327+ shell(title: "Profile", viewer: Some(&viewer), profile_body(page: page))
330- })328+ });
331-}
332-
333-#[page(POST "/settings/profile/details")]
334-async fn details_save(cx: &Cx, Form(form): Form<DetailsForm>) -> Result<impl View> {
335- let viewer = require_csrf(cx, &form.csrf).await?;
336- let store = &app_context::<AppState>(cx).store;
337- let lang = i18n::lang(cx, Some(&viewer.0));
338- let about = form.about.replace("\r\n", "\n");
339-
340- let result = match check_details(lang, &about, &form.timezone) {
341- Ok(()) => {
342- store
343- .set_profile(&viewer.0.id, &about, &form.timezone)
344- .await
345 }329 }
346- Err(e) => Err(e),
347- };
348- let message = match result {
349- Ok(()) => return Err(see_other("/settings/profile?saved=details").into()),
350- Err(e) => match user_facing_message(&e) {
351- Some(message) => message,
352- None => return Err(e.into()),
353- },
354 };330 };
355 331
356- let draft = Draft {332+ store
357- username: viewer.0.username.clone(),333+ .set_profile(&viewer.0.id, &about, &form.timezone)
358- about,334+ .await?;
359- timezone: form.timezone,335+ if display != viewer.0.username {
360- };336+ store.set_username_display(&viewer.0.id, &display).await?;
361- let errors = Errors {337+ audit::record(
362- details: Some(message),338+ store,
363- ..Errors::default()339+ Some(cx),
364- };340+ Actor::User(&viewer.0),
365- let page = page_data(&viewer, lang, draft, errors, None).await?;341+ AuditAction::UsernameChanged,
366- Ok(view! {342+ Target {
367- shell(title: "Profile", viewer: Some(&viewer), profile_body(page: page))343+ kind: "user",
368- })344+ id: &viewer.0.id,
345+ name: &display,
346+ },
347+ serde_json::json!({ "from": viewer.0.username }),
348+ )
349+ .await;
350+ }
351+ Err(see_other("/settings/profile?saved=1").into())
369 }352 }
370 353
371 /// Reads the multipart body. The CSRF field is checked before the image is decoded.354 /// Reads the multipart body. The CSRF field is checked before the image is decoded.
@@ -584,9 +567,10 @@ pub(crate) mod tests {
584 }567 }
585 568
586 #[tokio::test]569 #[tokio::test]
587- async fn tahinli_to_capitalized_succeeds_and_dashboard_shows_it() {570+ async fn one_save_changes_capitalization_about_and_timezone() {
588 let fx = fixture().await;571 let fx = fixture().await;
589- let form = format!("csrf={CSRF}&username=Tahinli");572+ let form =
573+ format!("csrf={CSRF}&username=Tahinli&about=Hello+*world*&timezone=Europe%2FIstanbul");
590 let (status, location, _) =574 let (status, location, _) =
591 send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await;575 send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await;
592 assert_eq!(status, 303);576 assert_eq!(status, 303);
@@ -594,6 +578,8 @@ pub(crate) mod tests {
594 578
595 let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap();579 let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap();
596 assert_eq!(stored.username, "Tahinli");580 assert_eq!(stored.username, "Tahinli");
581+ assert_eq!(stored.about, "Hello *world*");
582+ assert_eq!(stored.timezone, "Europe/Istanbul");
597 583
598 let (status, _, body) = send(&fx.router, "GET", "/", true, None).await;584 let (status, _, body) = send(&fx.router, "GET", "/", true, None).await;
599 assert_eq!(status, 200);585 assert_eq!(status, 200);
@@ -602,13 +588,13 @@ pub(crate) mod tests {
602 let (status, _, body) =588 let (status, _, body) =
603 send(&fx.router, "GET", "/settings/profile?saved=1", true, None).await;589 send(&fx.router, "GET", "/settings/profile?saved=1", true, None).await;
604 assert_eq!(status, 200);590 assert_eq!(status, 200);
605- assert!(body.contains("Username updated."), "{body}");591+ assert!(body.contains("Profile saved."), "{body}");
606 }592 }
607 593
608 #[tokio::test]594 #[tokio::test]
609 async fn a_different_name_is_rejected_and_nothing_is_saved() {595 async fn a_different_name_is_rejected_and_nothing_is_saved() {
610 let fx = fixture().await;596 let fx = fixture().await;
611- let form = format!("csrf={CSRF}&username=other");597+ let form = format!("csrf={CSRF}&username=other&about=kept&timezone=UTC");
612 let (status, _, body) =598 let (status, _, body) =
613 send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await;599 send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await;
614 assert_eq!(status, 200);600 assert_eq!(status, 200);
@@ -618,16 +604,17 @@ pub(crate) mod tests {
618 );604 );
619 let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap();605 let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap();
620 assert_eq!(stored.username, "tahinli");606 assert_eq!(stored.username, "tahinli");
607+ assert_eq!(stored.about, "");
621 }608 }
622 609
623 #[tokio::test]610 #[tokio::test]
624 async fn post_without_a_valid_csrf_token_is_rejected() {611 async fn post_without_a_valid_csrf_token_is_rejected() {
625 let fx = fixture().await;612 let fx = fixture().await;
626- let forged = "csrf=wrong&username=Tahinli";613+ let forged = "csrf=wrong&username=Tahinli&about=&timezone=UTC";
627 let (status, _, _) =614 let (status, _, _) =
628 send(&fx.router, "POST", "/settings/profile", true, Some(forged)).await;615 send(&fx.router, "POST", "/settings/profile", true, Some(forged)).await;
629 assert_eq!(status, 403);616 assert_eq!(status, 403);
630- let missing = "username=Tahinli";617+ let missing = "username=Tahinli&about=&timezone=UTC";
631 let (status, _, _) =618 let (status, _, _) =
632 send(&fx.router, "POST", "/settings/profile", true, Some(missing)).await;619 send(&fx.router, "POST", "/settings/profile", true, Some(missing)).await;
633 assert_eq!(status, 403);620 assert_eq!(status, 403);
@@ -654,19 +641,15 @@ pub(crate) mod tests {
654 #[tokio::test]641 #[tokio::test]
655 async fn about_and_timezone_round_trip() {642 async fn about_and_timezone_round_trip() {
656 let fx = fixture().await;643 let fx = fixture().await;
657- let form = format!("csrf={CSRF}&about=Hello+*world*&timezone=Europe%2FIstanbul");644+ let form =
658- let (status, location, _) = send(645+ format!("csrf={CSRF}&username=tahinli&about=Hello+*world*&timezone=Europe%2FIstanbul");
659- &fx.router,646+ let (status, location, _) =
660- "POST",647+ send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await;
661- "/settings/profile/details",
662- true,
663- Some(&form),
664- )
665- .await;
666 assert_eq!(status, 303);648 assert_eq!(status, 303);
667- assert_eq!(location.as_deref(), Some("/settings/profile?saved=details"));649+ assert_eq!(location.as_deref(), Some("/settings/profile?saved=1"));
668 650
669 let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap();651 let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap();
652+ assert_eq!(stored.username, "tahinli");
670 assert_eq!(stored.about, "Hello *world*");653 assert_eq!(stored.about, "Hello *world*");
671 assert_eq!(stored.timezone, "Europe/Istanbul");654 assert_eq!(stored.timezone, "Europe/Istanbul");
672 655
@@ -682,36 +665,27 @@ pub(crate) mod tests {
682 #[tokio::test]665 #[tokio::test]
683 async fn a_bad_timezone_is_rejected_and_nothing_is_saved() {666 async fn a_bad_timezone_is_rejected_and_nothing_is_saved() {
684 let fx = fixture().await;667 let fx = fixture().await;
685- let form = format!("csrf={CSRF}&about=kept&timezone=Mars%2FOlympus");668+ let form = format!("csrf={CSRF}&username=Tahinli&about=kept&timezone=Mars%2FOlympus");
686- let (status, location, body) = send(669+ let (status, location, body) =
687- &fx.router,670+ send(&fx.router, "POST", "/settings/profile", true, Some(&form)).await;
688- "POST",
689- "/settings/profile/details",
690- true,
691- Some(&form),
692- )
693- .await;
694 assert_eq!(status, 200);671 assert_eq!(status, 200);
695 assert!(location.is_none());672 assert!(location.is_none());
696 assert!(body.contains(r#"role="alert""#), "{body}");673 assert!(body.contains(r#"role="alert""#), "{body}");
674+ // The valid username and about text wait for the timezone to be fixed too.
697 let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap();675 let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap();
676+ assert_eq!(stored.username, "tahinli");
698 assert_eq!(stored.timezone, "UTC");677 assert_eq!(stored.timezone, "UTC");
699 assert_eq!(stored.about, "");678 assert_eq!(stored.about, "");
700 }679 }
701 680
702 #[tokio::test]681 #[tokio::test]
703- async fn details_post_without_csrf_is_rejected() {682+ async fn profile_post_without_csrf_is_rejected() {
704 let fx = fixture().await;683 let fx = fixture().await;
705- let form = "about=x&timezone=UTC";684+ let form = "username=tahinli&about=x&timezone=UTC";
706- let (status, _, _) = send(685+ let (status, _, _) = send(&fx.router, "POST", "/settings/profile", true, Some(form)).await;
707- &fx.router,
708- "POST",
709- "/settings/profile/details",
710- true,
711- Some(form),
712- )
713- .await;
714 assert_eq!(status, 403);686 assert_eq!(status, 403);
687+ let stored = fx.store.user_by_id(&fx.user.id).await.unwrap().unwrap();
688+ assert_eq!(stored.about, "");
715 }689 }
716 690
717 #[tokio::test]691 #[tokio::test]
@@ -771,6 +745,7 @@ pub(crate) mod tests {
771 // The page shows the new avatar with the hash as its version.745 // The page shows the new avatar with the hash as its version.
772 let (_, _, body) = send(&fx.router, "GET", "/settings/profile", true, None).await;746 let (_, _, body) = send(&fx.router, "GET", "/settings/profile", true, None).await;
773 assert!(body.contains(&format!("?v={stored_hash}")), "{body}");747 assert!(body.contains(&format!("?v={stored_hash}")), "{body}");
748+ assert!(body.contains("Remove photo"), "{body}");
774 749
775 // The top-nav avatar uses the real hash too, not the default URL.750 // The top-nav avatar uses the real hash too, not the default URL.
776 let (_, _, body) = send(&fx.router, "GET", "/", true, None).await;751 let (_, _, body) = send(&fx.router, "GET", "/", true, None).await;
@@ -829,6 +804,9 @@ pub(crate) mod tests {
829 body.contains(r#"src="/avatars/tahinli?v=default""#),804 body.contains(r#"src="/avatars/tahinli?v=default""#),
830 "{body}"805 "{body}"
831 );806 );
807+ // With no photo there is nothing to remove, so the menu leaves that item out.
808+ let (_, _, body) = send(&fx.router, "GET", "/settings/profile", true, None).await;
809+ assert!(!body.contains("Remove photo"), "{body}");
832 810
833 let default = send_full(811 let default = send_full(
834 &fx.router,812 &fx.router,
docs/ci.mdmodified+23 -0
@@ -18,6 +18,12 @@ The file is limited to 64 KiB. Unknown keys are an error at every level (`deny_u
18 A file with a parse error still creates a run, in state `error`, with the message shown on the run18 A file with a parse error still creates a run, in state `error`, with the message shown on the run
19 page and a `ci/config` status set to `error`.19 page and a `ci/config` status set to `error`.
20 20
21+### Top level
22+
23+| Key | Type | Default | Meaning |
24+|--------|--------|---------|---------|
25+| `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. |
26+
21 ### `[on]`27 ### `[on]`
22 28
23 | Key | Type | Default | Meaning |29 | Key | Type | Default | Meaning |
@@ -111,6 +117,23 @@ config failed to parse reports `ci/config`.
111 Pull request runs from forks, or from authors without write access, wait for approval. Their117 Pull request runs from forks, or from authors without write access, wait for approval. Their
112 statuses are pending with the description `Waiting for approval`.118 statuses are pending with the description `Waiting for approval`.
113 119
120+### Status badge
121+
122+`/{owner}/{repo}/badge.svg` shows the newest run on a branch: `?branch=` picks the branch, and the
123+default is the default branch. Add `&job=<name>` to show one job's state instead. A private repo's
124+badge needs read access, like the rest of the repo.
125+
126+The left half of the badge, its label, is picked in this order:
127+
128+1. `?label=<text>`, for example `?label=Nightly`. Spaces around it are dropped. An empty value is
129+ ignored. Labels are cut at 64 characters.
130+2. The job name, when `&job=` is given.
131+3. The `name` from `.forge/ci.toml` at the run's commit.
132+4. `ci`.
133+
134+With no run on the branch the badge says `no status`, and the label is `?label=`, or the job name,
135+or `ci`.
136+
114 ## Security model137 ## Security model
115 138
116 ### Fork pull requests need approval and get no secrets139 ### Fork pull requests need approval and get no secrets
style/main.scssmodified+396 -18
@@ -1881,18 +1881,6 @@ code {
1881 margin-right: 0.4em;1881 margin-right: 0.4em;
1882 }1882 }
1883 1883
1884-.avatar-lg {
1885- width: 96px;
1886- height: 96px;
1887-}
1888-
1889-.avatar-row {
1890- display: flex;
1891- flex-wrap: wrap;
1892- gap: 1.25rem;
1893- align-items: flex-start;
1894-}
1895-
1896 // Settings pages: the card stack and the form field widths.1884 // Settings pages: the card stack and the form field widths.
1897 .settings-layout {1885 .settings-layout {
1898 display: grid;1886 display: grid;
@@ -1909,12 +1897,6 @@ code {
1909 max-width: 24rem;1897 max-width: 24rem;
1910 }1898 }
1911 1899
1912-@media (max-width: 600px) {
1913- .avatar-row {
1914- flex-direction: column;
1915- }
1916-}
1917-
1918 // branch protection1900 // branch protection
1919 // Settings page: rules table with a Remove form per row, then the add/update form.1901 // Settings page: rules table with a Remove form per row, then the add/update form.
1920 .branch-rules {1902 .branch-rules {
@@ -3592,6 +3574,214 @@ span.reaction {
3592 padding-left: 20px;3574 padding-left: 20px;
3593 }3575 }
3594 3576
3577+// CI runs list: whole-row links.
3578+// The run number link stretches over its row (no JS). Other controls in the row sit above it.
3579+.ci-runs tbody tr {
3580+ position: relative;
3581+ cursor: pointer;
3582+
3583+ &:hover {
3584+ background: var(--surface-2);
3585+ }
3586+}
3587+
3588+.ci-runs .ci-run-link::after {
3589+ content: "";
3590+ position: absolute;
3591+ inset: 0;
3592+}
3593+
3594+.ci-runs tbody a:not(.ci-run-link),
3595+.ci-runs tbody button,
3596+.ci-runs tbody input,
3597+.ci-runs tbody select,
3598+.ci-runs tbody textarea {
3599+ position: relative;
3600+ z-index: 1;
3601+}
3602+
3603+// CI run page: header and job graph.
3604+// Sizes below match the GRAPH_* constants in crates/forge-web/src/pages/ci_runs.rs: the card is
3605+// 200x56, columns are 48px apart, cards in a column 16px apart, and the box is padded 16px.
3606+.ci-run-head {
3607+ display: flex;
3608+ align-items: flex-start;
3609+ justify-content: space-between;
3610+ flex-wrap: wrap;
3611+ gap: 16px;
3612+
3613+ .ci-actions {
3614+ margin-top: 0;
3615+ }
3616+}
3617+
3618+.ci-run-head-main {
3619+ flex: 1 1 320px;
3620+ min-width: 0;
3621+}
3622+
3623+.ci-run-title {
3624+ display: flex;
3625+ align-items: center;
3626+ flex-wrap: wrap;
3627+ gap: 8px;
3628+ margin: 0 0 6px;
3629+ overflow-wrap: anywhere;
3630+
3631+ .ci-state {
3632+ font-size: 0.8rem;
3633+ }
3634+}
3635+
3636+.ci-run-meta {
3637+ margin: 0;
3638+ overflow-wrap: anywhere;
3639+}
3640+
3641+.ci-graph {
3642+ max-width: 100%;
3643+ overflow-x: auto;
3644+ border: 1px solid var(--border);
3645+ border-radius: 8px;
3646+ background: var(--bg);
3647+
3648+ &:focus-visible {
3649+ outline: 2px solid var(--focus);
3650+ outline-offset: 2px;
3651+ }
3652+}
3653+
3654+.ci-graph-canvas {
3655+ position: relative;
3656+ display: flex;
3657+ gap: 48px;
3658+ width: max-content;
3659+ padding: 16px;
3660+}
3661+
3662+.ci-graph-col {
3663+ display: flex;
3664+ flex-direction: column;
3665+ flex-shrink: 0;
3666+ gap: 16px;
3667+ width: 200px;
3668+}
3669+
3670+// Connectors sit under the cards: the SVG comes first and the cards are positioned.
3671+.ci-graph-lines {
3672+ position: absolute;
3673+ top: 0;
3674+ left: 0;
3675+ overflow: visible;
3676+ pointer-events: none;
3677+
3678+ path {
3679+ fill: none;
3680+ stroke: var(--border-strong);
3681+ stroke-width: 2;
3682+ }
3683+}
3684+
3685+.ci-graph-card {
3686+ --ci-icon: var(--muted);
3687+
3688+ position: relative;
3689+ display: flex;
3690+ flex-direction: column;
3691+ justify-content: center;
3692+ flex-shrink: 0;
3693+ gap: 2px;
3694+ box-sizing: border-box;
3695+ width: 200px;
3696+ height: 56px;
3697+ padding: 6px 12px;
3698+ border: 1px solid var(--border);
3699+ border-radius: 8px;
3700+ background: var(--surface);
3701+ color: var(--text);
3702+ text-decoration: none;
3703+
3704+ &:hover {
3705+ border-color: var(--border-strong);
3706+ background: var(--surface-2);
3707+ }
3708+
3709+ &:focus-visible {
3710+ outline: 2px solid var(--focus);
3711+ outline-offset: 2px;
3712+ }
3713+
3714+ &.ci-success {
3715+ --ci-icon: var(--public-text);
3716+ }
3717+
3718+ &.ci-queued,
3719+ &.ci-running,
3720+ &.ci-blocked,
3721+ &.ci-waiting_approval {
3722+ --ci-icon: var(--warning);
3723+ }
3724+
3725+ &.ci-failure,
3726+ &.ci-error {
3727+ --ci-icon: var(--danger);
3728+ }
3729+}
3730+
3731+.ci-graph-name {
3732+ overflow: hidden;
3733+ font-size: 0.9375rem;
3734+ font-weight: 600;
3735+ line-height: 1.5;
3736+ text-overflow: ellipsis;
3737+ white-space: nowrap;
3738+}
3739+
3740+.ci-graph-meta {
3741+ display: flex;
3742+ align-items: center;
3743+ gap: 6px;
3744+ overflow: hidden;
3745+ color: var(--muted);
3746+ font-size: 0.75rem;
3747+ line-height: 1.4;
3748+ white-space: nowrap;
3749+}
3750+
3751+.ci-graph-icon {
3752+ flex-shrink: 0;
3753+ width: 8px;
3754+ height: 8px;
3755+ border-radius: 50%;
3756+ background: var(--ci-icon);
3757+}
3758+
3759+// CI run page: job rows link through the whole row (no JS). The name link stretches over its row
3760+// and the other controls in the row sit above it.
3761+.ci-jobs tbody tr {
3762+ position: relative;
3763+ cursor: pointer;
3764+
3765+ &:hover {
3766+ background: var(--surface-2);
3767+ }
3768+}
3769+
3770+.ci-jobs .ci-job-link::after {
3771+ content: "";
3772+ position: absolute;
3773+ inset: 0;
3774+}
3775+
3776+.ci-jobs tbody a:not(.ci-job-link),
3777+.ci-jobs tbody button,
3778+.ci-jobs tbody input,
3779+.ci-jobs tbody select,
3780+.ci-jobs tbody textarea {
3781+ position: relative;
3782+ z-index: 1;
3783+}
3784+
3595 /* Theme and language preferences (T1). The palettes live at the top of this file: the dark3785 /* Theme and language preferences (T1). The palettes live at the top of this file: the dark
3596 variables apply under :root:not([data-theme="light"]) and under :root[data-theme="dark"]. */3786 variables apply under :root:not([data-theme="light"]) and under :root[data-theme="dark"]. */
3597 .theme-picker {3787 .theme-picker {
@@ -4171,3 +4361,191 @@ span.reaction {
4171 }4361 }
4172 }4362 }
4173 }4363 }
4364+
4365+// ---------------------------------------------------------------------------
4366+// Settings: public profile (/settings/profile). One form on the left, the avatar with its
4367+// Edit menu on the right. Below 48rem the avatar sits above the form.
4368+// ---------------------------------------------------------------------------
4369+
4370+.profile-settings {
4371+ display: grid;
4372+ grid-template-columns: minmax(0, 1fr) 220px;
4373+ gap: 40px;
4374+ align-items: start;
4375+ max-width: 920px;
4376+}
4377+
4378+.profile-form {
4379+ display: flex;
4380+ flex-direction: column;
4381+ gap: 22px;
4382+ min-width: 0;
4383+ max-width: 600px;
4384+}
4385+
4386+.profile-field {
4387+ display: flex;
4388+ flex-direction: column;
4389+ gap: 6px;
4390+ min-width: 0;
4391+
4392+ > label {
4393+ font-size: 0.875rem;
4394+ font-weight: 600;
4395+ color: var(--text);
4396+ }
4397+
4398+ input[type="text"],
4399+ textarea,
4400+ select {
4401+ box-sizing: border-box;
4402+ max-width: 100%;
4403+ }
4404+
4405+ input[type="text"],
4406+ select {
4407+ width: 100%;
4408+ max-width: 320px;
4409+ }
4410+
4411+ textarea {
4412+ width: 100%;
4413+ resize: vertical;
4414+ }
4415+
4416+ small {
4417+ font-size: 0.8125rem;
4418+ line-height: 1.45;
4419+ }
4420+
4421+ .alert {
4422+ margin: 0;
4423+ }
4424+}
4425+
4426+.profile-actions {
4427+ margin-top: 4px;
4428+}
4429+
4430+.profile-settings-avatar {
4431+ display: flex;
4432+ flex-direction: column;
4433+ gap: 10px;
4434+ min-width: 0;
4435+
4436+ small {
4437+ font-size: 0.8125rem;
4438+ line-height: 1.45;
4439+ }
4440+}
4441+
4442+.profile-settings-avatar-frame {
4443+ position: relative;
4444+ width: 180px;
4445+ height: 180px;
4446+}
4447+
4448+.profile-settings-avatar-img {
4449+ display: block;
4450+ width: 180px;
4451+ height: 180px;
4452+ box-sizing: border-box;
4453+ border: 1px solid var(--border);
4454+}
4455+
4456+// The Edit pill sits over the bottom-left edge of the circle.
4457+.profile-settings-avatar-menu {
4458+ position: absolute;
4459+ left: 6px;
4460+ bottom: 10px;
4461+
4462+ > summary {
4463+ display: inline-flex;
4464+ align-items: center;
4465+ height: 32px;
4466+ padding: 0 14px;
4467+ border: 1px solid var(--border-strong);
4468+ border-radius: 999px;
4469+ background: var(--surface);
4470+ box-shadow: var(--shadow);
4471+ color: var(--text);
4472+ font-size: 0.8125rem;
4473+ font-weight: 500;
4474+ cursor: pointer;
4475+
4476+ &:hover {
4477+ background: var(--surface-2);
4478+ }
4479+ }
4480+
4481+ &[open] > summary {
4482+ border-color: var(--accent);
4483+ }
4484+}
4485+
4486+.profile-settings-avatar-list {
4487+ left: 0;
4488+ right: auto;
4489+ top: calc(100% + 8px);
4490+ min-width: 220px;
4491+}
4492+
4493+.profile-settings-avatar-upload {
4494+ display: flex;
4495+ flex-direction: column;
4496+ align-items: stretch;
4497+ margin: 0;
4498+
4499+ > button {
4500+ margin: 4px 14px 10px;
4501+ }
4502+}
4503+
4504+// The file input stays in the tab order but is visually hidden. Its label is the visible item.
4505+.profile-settings-avatar-upload .profile-settings-avatar-file {
4506+ position: absolute;
4507+ width: 1px;
4508+ height: 1px;
4509+ margin: 0;
4510+ padding: 0;
4511+ border: 0;
4512+ overflow: hidden;
4513+ clip: rect(0 0 0 0);
4514+ white-space: nowrap;
4515+ opacity: 0;
4516+}
4517+
4518+.profile-settings-avatar-item {
4519+ display: block;
4520+ padding: 8px 14px;
4521+ color: var(--text);
4522+ font-size: 0.875rem;
4523+ white-space: nowrap;
4524+ cursor: pointer;
4525+
4526+ &:hover {
4527+ background: var(--surface-2);
4528+ }
4529+}
4530+
4531+.profile-settings-avatar-upload .profile-settings-avatar-file:focus-visible + .profile-settings-avatar-item {
4532+ outline: 2px solid var(--accent);
4533+ outline-offset: -2px;
4534+}
4535+
4536+.profile-settings-avatar-remove {
4537+ margin: 0;
4538+ padding-top: 6px;
4539+ border-top: 1px solid var(--border);
4540+}
4541+
4542+@media (max-width: 48rem) {
4543+ .profile-settings {
4544+ grid-template-columns: minmax(0, 1fr);
4545+ gap: 24px;
4546+ }
4547+
4548+ .profile-settings-avatar {
4549+ order: -1;
4550+ }
4551+}