diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index 16eef91..1e140d1 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -1486,7 +1486,10 @@ impl Store { let mut runs: Vec = Vec::new(); for job in &lost { tx.execute( - "UPDATE ci_jobs SET state = 'error', message = 'runner lost', finished_at = ?2 \ + "UPDATE ci_jobs SET \ + state = CASE WHEN cancel_requested = 1 THEN 'cancelled' ELSE 'error' END, \ + message = CASE WHEN cancel_requested = 1 THEN 'cancelled' ELSE 'runner lost' END, \ + finished_at = ?2 \ WHERE id = ?1 AND state = 'running'", (job.id.clone(), now.clone()), ) @@ -3288,6 +3291,32 @@ mod tests { ); } + #[tokio::test] + async fn reap_lost_jobs_marks_a_cancelled_running_job_cancelled() { + let fx = fixture().await; + let run = create( + &fx.store, + &fx.repo.id, + &fx.tahinli.id, + &[job("a", &[], &[])], + false, + ) + .await; + let claimed = fx + .store + .claim_job(&bare_runner(&[])) + .await + .unwrap() + .unwrap(); + fx.store.request_cancel(&run.id).await.unwrap(); + let future = stamp_after(Duration::from_secs(3600)); + let reaped = fx.store.reap_lost_jobs(&future).await.unwrap(); + assert_eq!(reaped.len(), 1); + assert_eq!(reaped[0].id, claimed.0.id); + assert_eq!(reaped[0].state, JobState::Cancelled); + assert_eq!(reaped[0].message.as_deref(), Some("cancelled")); + } + #[tokio::test] async fn purge_old_returns_logs_and_artifacts_once() { let fx = fixture().await; diff --git a/crates/forge-core/src/store/shell_activity.rs b/crates/forge-core/src/store/shell_activity.rs index e12c317..ed23062 100644 --- a/crates/forge-core/src/store/shell_activity.rs +++ b/crates/forge-core/src/store/shell_activity.rs @@ -12,8 +12,9 @@ use crate::error::{Error, Result}; use crate::notifications::Reason; use crate::time::stamp_ago; -/// Most runs each of `ActorRuns::running` and `ActorRuns::finished` lists. -const MAX_ACTOR_RUNS: i64 = 5; +/// Most runs each of `ActorRuns::running` and `ActorRuns::finished` lists: enough for the strip's +/// counts and list, bounded when runs pile up in the queue with no runner online. +const MAX_ACTOR_RUNS: i64 = 100; /// How far back a failing run still counts toward `ActorRuns::failing`. const FAILING_WINDOW: Duration = Duration::from_secs(7 * 24 * 60 * 60); @@ -49,9 +50,9 @@ pub struct WaitingItem { /// The user's own CI runs, as the corner shows them. #[derive(Debug, Clone)] pub struct ActorRuns { - /// Queued or running runs, newest first, at most 5. + /// Queued or running runs, newest first, at most 100. pub running: Vec, - /// Runs that finished recently, newest first, at most 5. + /// Runs that finished within the caller's window, newest first, at most 100. pub finished: Vec, /// Refs whose newest run by this user failed within the last 7 days. pub failing: u64, diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index dbb4300..f06f1a5 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -623,7 +623,7 @@ // Dropdown menus: the
that float over the page (avatar menu, branch selector, clone // popover, phone menu, profile corner). Inline disclosures are not listed: a click outside leaves them open. - var DROPDOWN = 'details.menu, details.ref-select, details.clone, details.nav-toggle, details.corner'; + var DROPDOWN = 'details.menu, details.ref-select, details.clone, details.nav-toggle, details.corner, details.strip-runs'; // Closes every open dropdown that does not contain `from` (pass null to close them all). The corner // sits inside the phone menu, so a click in the corner keeps the phone menu open too. @@ -1315,53 +1315,108 @@ return typeof href === 'string' && href.charAt(0) === '/' && href.charAt(1) !== '/' ? href : ''; } - // The live strip: running pills first, then finished ones, two at most and a "+N" for the rest. - // The words "passed" and "failed" come from the strip's own data attributes. - function drawStrip(strip, json) { - var pills = []; + // The live strip, drawn from the same JSON as the server's render. One run is a pill. Two or more are + // a summary pill (the counts, joined with " · ") that opens a list of every run. The list's
+ // is kept across a redraw and only its contents change, so an open list stays open. + var OUTCOMES = { + passed: { state: 'ok', word: 'data-passed' }, + failed: { state: 'bad', word: 'data-failed' }, + cancelled: { state: 'off', word: 'data-cancelled' } + }; + + // The strip's runs, running ones first, each with its state class and its text (the job or the word). + function stripRows(strip, json) { + var rows = []; (json.running || []).forEach(function (run) { - pills.push({ cls: 'pill hot', run: run, text: run.job ? ' ' + run.job : '' }); + rows.push({ state: 'hot', run: run, text: run.job ? ' ' + run.job : '' }); }); (json.finished || []).forEach(function (run) { - var word = run.ok ? strip.getAttribute('data-passed') : strip.getAttribute('data-failed'); - pills.push({ cls: run.ok ? 'pill ok' : 'pill bad', run: run, text: ' ' + (word || '') }); + var o = OUTCOMES[run.outcome]; + if (!o) { return; } + rows.push({ state: o.state, run: run, text: ' ' + (strip.getAttribute(o.word) || '') }); }); - var more = pills.length - 2; - strip.textContent = ''; - pills.slice(0, 2).forEach(function (pill) { - var a = document.createElement('a'); - a.className = pill.cls; - a.setAttribute('href', localHref(pill.run.href)); + return rows; + } + + // A run's link: a dot, the run's label in bold, then its text. Used for the lone pill and each row. + function runLink(cls, row) { + var a = document.createElement('a'); + a.className = cls; + a.setAttribute('href', localHref(row.run.href)); + var dot = document.createElement('span'); + dot.className = 'pill-dot'; + var b = document.createElement('b'); + b.textContent = String(row.run.label || ''); + a.appendChild(dot); + a.appendChild(b); + a.appendChild(document.createTextNode(row.text)); + return a; + } + + // The summary's counts: the non-zero ones, each from its template (`{n}` is the count). + function stripSummary(strip, json) { + var running = (json.running || []).length; + var finished = json.finished || []; + var count = function (outcome) { + return finished.filter(function (run) { return run.outcome === outcome; }).length; + }; + var failed = count('failed'); + var passed = count('passed'); + var cancelled = count('cancelled'); + var parts = [ + [running, 'data-count-running'], + [failed, 'data-count-failed'], + [passed, 'data-count-passed'], + [cancelled, 'data-count-cancelled'] + ].filter(function (p) { return p[0] > 0; }).map(function (p) { + return (strip.getAttribute(p[1]) || '').split('{n}').join(String(p[0])); + }); + var cls = running ? 'hot' : failed ? 'bad' : passed ? 'ok' : 'off'; + return { cls: 'pill ' + cls, text: parts.join(' \u00b7 ') }; + } + + function drawStrip(strip, json) { + var rows = stripRows(strip, json); + if (rows.length === 0) { strip.textContent = ''; return; } + if (rows.length === 1) { + strip.textContent = ''; + strip.appendChild(runLink('pill ' + rows[0].state, rows[0])); + return; + } + var details = strip.querySelector('details.strip-runs'); + if (!details) { + strip.textContent = ''; + details = document.createElement('details'); + details.className = 'strip-runs'; + details.id = 'strip-runs'; + var summary = document.createElement('summary'); + summary.setAttribute('aria-label', strip.getAttribute('data-runs-label') || ''); var dot = document.createElement('span'); dot.className = 'pill-dot'; - var b = document.createElement('b'); - b.textContent = String(pill.run.label || ''); - a.appendChild(dot); - a.appendChild(b); - a.appendChild(document.createTextNode(pill.text)); - strip.appendChild(a); - }); - if (more > 0) { - var rest = document.createElement('span'); - rest.className = 'pill more'; - rest.textContent = '+' + more; - strip.appendChild(rest); + summary.appendChild(dot); + summary.appendChild(document.createTextNode('')); + details.appendChild(summary); + var list = document.createElement('ul'); + list.className = 'strip-list'; + details.appendChild(list); + strip.appendChild(details); } + var head = stripSummary(strip, json); + var sum = details.querySelector('summary'); + sum.className = head.cls; + sum.lastChild.nodeValue = head.text; + var rowsEl = details.querySelector('.strip-list'); + rowsEl.textContent = ''; + rows.forEach(function (row) { + var li = document.createElement('li'); + li.appendChild(runLink('strip-row ' + row.state, row)); + rowsEl.appendChild(li); + }); } - // The heat ring: lit while a run is going, filled to the newest run's share of its jobs (at least 8%). + // The heat ring: a full ember ring while any of the viewer's runs is going, a plain ring otherwise. function drawRing(ring, running) { - if (!running.length) { - ring.classList.remove('hot'); - ring.setAttribute('data-p', '0'); - return; - } - var run = running[0]; - var p = run.total ? Math.round(run.done / run.total * 100) : 0; - p = Math.min(100, Math.max(8, p)); - ring.classList.add('hot'); - // In steps of 5, as the server renders it; the stylesheet maps each step to --p. - ring.setAttribute('data-p', String(Math.round(p / 5) * 5)); + if (running.length) { ring.classList.add('hot'); } else { ring.classList.remove('hot'); } } // The chips: one per non-zero count. The titles come from the chip box's templates, with `{n}` diff --git a/crates/forge-web/src/i18n/misc.rs b/crates/forge-web/src/i18n/misc.rs index da1b128..eac882f 100644 --- a/crates/forge-web/src/i18n/misc.rs +++ b/crates/forge-web/src/i18n/misc.rs @@ -176,6 +176,8 @@ pub enum K { AllNotifications, Passed, Failed, + Cancelled, + YourCiRuns, SearchPublicReposFor, } @@ -330,6 +332,8 @@ const ALL: &[K] = &[ K::AllNotifications, K::Passed, K::Failed, + K::Cancelled, + K::YourCiRuns, K::SearchPublicReposFor, ]; @@ -659,6 +663,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { (Passed, Tr) => "geçti", (Failed, En) => "failed", (Failed, Tr) => "başarısız", + (Cancelled, En) => "cancelled", + (Cancelled, Tr) => "iptal edildi", + (YourCiRuns, En) => "Your CI runs", + (YourCiRuns, Tr) => "CI çalıştırmaların", (SearchPublicReposFor, En) => "Search public repositories for", (SearchPublicReposFor, Tr) => "Herkese açık depolarda ara:", } @@ -713,6 +721,39 @@ pub fn failing_runs_count(lang: Lang, n: u64) -> String { } } +/// `28 running` / `3 çalışıyor`: the live strip's counts. Each takes its number as `{n}` in the +/// strip's templates, so these phrases have no plural. +pub fn running_count(lang: Lang, n: u64) -> String { + match lang { + Lang::En => format!("{n} running"), + Lang::Tr => format!("{n} çalışıyor"), + } +} + +/// `2 failed` / `2 başarısız`. +pub fn failed_count(lang: Lang, n: u64) -> String { + match lang { + Lang::En => format!("{n} failed"), + Lang::Tr => format!("{n} başarısız"), + } +} + +/// `2 passed` / `2 başarılı`. +pub fn passed_count(lang: Lang, n: u64) -> String { + match lang { + Lang::En => format!("{n} passed"), + Lang::Tr => format!("{n} başarılı"), + } +} + +/// `2 cancelled` / `2 iptal edildi`. +pub fn cancelled_count(lang: Lang, n: u64) -> String { + match lang { + Lang::En => format!("{n} cancelled"), + Lang::Tr => format!("{n} iptal edildi"), + } +} + /// `1 contribution` / `3 contributions`, and `3 katkı` in Turkish. pub fn contributions_count(lang: Lang, n: u64) -> String { match lang { diff --git a/crates/forge-web/src/i18n/releases_ci.rs b/crates/forge-web/src/i18n/releases_ci.rs index 053253a..5fbab1e 100644 --- a/crates/forge-web/src/i18n/releases_ci.rs +++ b/crates/forge-web/src/i18n/releases_ci.rs @@ -86,6 +86,9 @@ pub enum K { StateError, StateBlocked, StateSkipped, + /// A running job whose cancel was requested, until its runner stops it. + StateStopping, + StoppingButton, // Release notices, shown after a release action. RelSaved, @@ -152,10 +155,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { (CiNoticeStarted, En) => "Workflow run queued.", (CiNoticeStarted, Tr) => "İş akışı çalıştırması sıraya alındı.", (CiNoticeCancelled, En) => { - "Cancellation requested. Queued jobs were cancelled; running jobs stop at their next heartbeat." + "Cancel requested. Queued jobs are cancelled; running jobs show as stopping until the runner stops them." } (CiNoticeCancelled, Tr) => { - "İptal istendi. Sıradaki işler iptal edildi; çalışan işler bir sonraki kalp atışında duracak." + "İptal istendi. Sıradaki işler iptal edildi; çalışan işler, çalıştırıcı onları durdurana dek durduruluyor olarak görünür." } (CiNoticeApproved, En) => "Run approved. Its jobs are queued.", (CiNoticeApproved, Tr) => "Çalıştırma onaylandı. İşler sıraya alındı.", @@ -317,6 +320,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { (StateBlocked, Tr) => "engellendi", (StateSkipped, En) => "skipped", (StateSkipped, Tr) => "atlandı", + (StateStopping, En) => "stopping", + (StateStopping, Tr) => "durduruluyor", + (StoppingButton, En) => "Stopping…", + (StoppingButton, Tr) => "Durduruluyor…", (RelSaved, En) => "Release saved.", (RelSaved, Tr) => "Sürüm kaydedildi.", @@ -620,6 +627,8 @@ mod tests { K::StateError, K::StateBlocked, K::StateSkipped, + K::StateStopping, + K::StoppingButton, K::RelSaved, K::RelDeleted, K::RelAssetUploaded, diff --git a/crates/forge-web/src/pages/activity.rs b/crates/forge-web/src/pages/activity.rs index 929e81b..a45289c 100644 --- a/crates/forge-web/src/pages/activity.rs +++ b/crates/forge-web/src/pages/activity.rs @@ -37,6 +37,16 @@ fn run_json(run: &ActorRun) -> Value { }) } +/// How a finished run ended, as the activity JSON names it. None for any other state. +pub(crate) fn outcome_word(state: RunState) -> Option<&'static str> { + match state { + RunState::Success => Some("passed"), + RunState::Failure | RunState::Error => Some("failed"), + RunState::Cancelled => Some("cancelled"), + _ => None, + } +} + /// The viewer's activity as JSON. `reviews` and `mentions` count unread inbox rows, `failing` counts /// refs whose newest run failed, `running` and `finished` list the viewer's CI runs and `waiting` /// lists the newest review requests and mentions. Reads only; the caller decides how to send it. @@ -49,10 +59,11 @@ pub(crate) async fn activity_json(state: &AppState, user: &User) -> Result = runs .finished .iter() - .map(|run| { + .filter_map(|run| { + let outcome = outcome_word(run.state)?; let mut item = run_json(run); - item["ok"] = json!(matches!(run.state, RunState::Success)); - item + item["outcome"] = json!(outcome); + Some(item) }) .collect(); let waiting: Vec = waiting diff --git a/crates/forge-web/src/pages/ci_badge.rs b/crates/forge-web/src/pages/ci_badge.rs index 37c2df2..dab7308 100644 --- a/crates/forge-web/src/pages/ci_badge.rs +++ b/crates/forge-web/src/pages/ci_badge.rs @@ -41,6 +41,7 @@ pub enum BadgeStatus { Passing, Failing, Error, + Cancelled, Running, Pending, Skipped, @@ -54,6 +55,7 @@ impl BadgeStatus { BadgeStatus::Passing => "passing", BadgeStatus::Failing => "failing", BadgeStatus::Error => "error", + BadgeStatus::Cancelled => "cancelled", BadgeStatus::Running => "running", BadgeStatus::Pending => "pending", BadgeStatus::Skipped => "skipped", @@ -68,7 +70,7 @@ impl BadgeStatus { BadgeStatus::Failing => "#e05d44", BadgeStatus::Error => "#9a5b5b", BadgeStatus::Running | BadgeStatus::Pending => "#dfb317", - BadgeStatus::Skipped | BadgeStatus::NoStatus => GREY, + BadgeStatus::Cancelled | BadgeStatus::Skipped | BadgeStatus::NoStatus => GREY, } } } @@ -78,7 +80,8 @@ pub fn status_of_run(state: RunState) -> BadgeStatus { match state { RunState::Success => BadgeStatus::Passing, RunState::Failure => BadgeStatus::Failing, - RunState::Error | RunState::Cancelled => BadgeStatus::Error, + RunState::Error => BadgeStatus::Error, + RunState::Cancelled => BadgeStatus::Cancelled, RunState::Queued | RunState::Running => BadgeStatus::Running, RunState::WaitingApproval => BadgeStatus::Pending, } @@ -89,7 +92,8 @@ pub fn status_of_job(state: JobState) -> BadgeStatus { match state { JobState::Success => BadgeStatus::Passing, JobState::Failure => BadgeStatus::Failing, - JobState::Error | JobState::Cancelled => BadgeStatus::Error, + JobState::Error => BadgeStatus::Error, + JobState::Cancelled => BadgeStatus::Cancelled, JobState::Blocked | JobState::Queued | JobState::Running => BadgeStatus::Running, JobState::Skipped => BadgeStatus::Skipped, } @@ -289,6 +293,7 @@ mod tests { (BadgeStatus::Error, "#9a5b5b", "error"), (BadgeStatus::Running, "#dfb317", "running"), (BadgeStatus::Pending, "#dfb317", "pending"), + (BadgeStatus::Cancelled, "#9f9f9f", "cancelled"), (BadgeStatus::Skipped, "#9f9f9f", "skipped"), (BadgeStatus::NoStatus, "#9f9f9f", "no status"), ]; @@ -305,7 +310,7 @@ mod tests { fn run_and_job_states_map_to_badge_statuses() { assert_eq!(status_of_run(RunState::Success), BadgeStatus::Passing); assert_eq!(status_of_run(RunState::Failure), BadgeStatus::Failing); - assert_eq!(status_of_run(RunState::Cancelled), BadgeStatus::Error); + assert_eq!(status_of_run(RunState::Cancelled), BadgeStatus::Cancelled); assert_eq!(status_of_run(RunState::Error), BadgeStatus::Error); assert_eq!(status_of_run(RunState::Queued), BadgeStatus::Running); assert_eq!(status_of_run(RunState::Running), BadgeStatus::Running); @@ -314,6 +319,7 @@ mod tests { BadgeStatus::Pending ); assert_eq!(status_of_job(JobState::Blocked), BadgeStatus::Running); + assert_eq!(status_of_job(JobState::Cancelled), BadgeStatus::Cancelled); assert_eq!(status_of_job(JobState::Skipped), BadgeStatus::Skipped); } diff --git a/crates/forge-web/src/pages/ci_job.rs b/crates/forge-web/src/pages/ci_job.rs index 4b44a24..d042661 100644 --- a/crates/forge-web/src/pages/ci_job.rs +++ b/crates/forge-web/src/pages/ci_job.rs @@ -11,7 +11,7 @@ use std::sync::Arc; use std::time::Duration; use bytes::Bytes; -use forge_core::ci::{CiArtifact, CiJob, CiRun}; +use forge_core::ci::{CiArtifact, CiJob, CiRun, JobState}; use forge_core::{Store, User}; use futures_util::{Stream, TryStreamExt}; use http::header::{CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_TYPE}; @@ -304,6 +304,16 @@ fn job_fingerprint(status: &str, artifact_ids: &[&str], log_kept: bool) -> Strin ) } +/// The status the job page shows and fingerprints: `stopping` for a running job with a cancel +/// request its runner has not acted on yet, else the job's state. +pub fn job_status(job: &CiJob) -> &'static str { + if job.state == JobState::Running && job.cancel_requested { + "stopping" + } else { + job.state.as_str() + } +} + /// The job's fingerprint now. `None` when the job row is gone. async fn job_fingerprint_now(store: &Store, job_id: &str) -> Result> { let Some(job) = store.job_by_id(job_id).await? else { @@ -312,7 +322,7 @@ async fn job_fingerprint_now(store: &Store, job_id: &str) -> Result = artifacts.iter().map(|artifact| artifact.id.as_str()).collect(); Ok(Some(job_fingerprint( - job.state.as_str(), + job_status(&job), &ids, job.log_bytes > 0, ))) @@ -422,7 +432,7 @@ async fn job_page(cx: &Cx) -> Result { } = log_tail(&log_path(&state.config.data_dir, &job.id)).await?; let listed = state.store.list_artifacts(&job.id).await?; let ids: Vec<&str> = listed.iter().map(|artifact| artifact.id.as_str()).collect(); - let fingerprint = job_fingerprint(job.state.as_str(), &ids, job.log_bytes > 0); + let fingerprint = job_fingerprint(job_status(&job), &ids, job.log_bytes > 0); let artifacts = listed .into_iter() .map(|artifact| ArtifactRow { @@ -451,7 +461,7 @@ async fn job_page(cx: &Cx) -> Result { let view = JobView { name: job.name.clone(), fingerprint, - state: state_text(lang, job.state.as_str()), + state: state_text(lang, job_status(&job)), state_class: format!("ci-state ci-{}", job.state.as_str()), runner, exit_code: job diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index 56ebad4..ceb02be 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -202,7 +202,7 @@ pub(crate) fn duration_text(lang: Lang, started: Option<&str>, finished: Option< /// The duration formats of `lang` with `{m}` and `{s}` where the numbers go, for the client ticker: /// the one with minutes and the seconds-only one. -fn duration_templates(lang: Lang) -> (String, String) { +pub(crate) fn duration_templates(lang: Lang) -> (String, String) { ( g::duration_minutes(lang, 111_111, 222_222) .replace("111111", "{m}") @@ -221,6 +221,7 @@ pub fn state_text(lang: Lang, state: &str) -> String { "success" => K::StateSuccess, "failure" => K::StateFailure, "cancelled" => K::StateCancelled, + "stopping" => K::StateStopping, "error" => K::StateError, "blocked" => K::StateBlocked, "skipped" => K::StateSkipped, @@ -282,10 +283,11 @@ pub(crate) async fn after_change(state: &AppState, run_id: &str, before: &[CiJob state.ci_live.bump_run(run_id); state.ci_live.bump_repo(&run.repo_id); for job in state.store.jobs_for_run(run_id).await? { + // A cancel request on a running job changes no state, but its row shows "stopping". let changed = before .iter() .find(|old| old.id == job.id) - .is_none_or(|old| old.state != job.state); + .is_none_or(|old| old.state != job.state || old.cancel_requested != job.cancel_requested); if changed { if job.state.is_terminal() { state.ci_live.close_job(&job.id); @@ -395,6 +397,8 @@ struct JobLine { expanded: bool, /// The POST target that runs this job again. Set for a writer, once the job has finished. rerun: Option, + /// A running job whose cancel was requested: it shows as stopping until its runner stops it. + stopping: bool, } /// One artifact of the run: its download link, the job that made it, its name and size. @@ -426,6 +430,8 @@ struct RunDetail { action_base: String, can_approve: bool, can_cancel: bool, + /// A running job of the run has a cancel request: the run shows Stopping in place of Cancel. + stopping: bool, /// A finished run with a failed, errored or cancelled job, for a writer. can_rerun_failed: bool, /// The config keys this forge ignored when it made the run. @@ -606,9 +612,15 @@ struct Timing { queued: Option, started: Option, finished: Option, + cancel_requested: bool, } impl Timing { + /// Whether the job runs and has a cancel request its runner has not yet acted on. + fn stopping(&self) -> bool { + self.cancel_requested && self.state == JobState::Running + } + /// Where the job ends, in unix seconds: its finish, or `now` while it runs. None before it starts. fn end(&self, now: i64) -> Option { self.started?; @@ -1112,6 +1124,7 @@ fn timing_of(job: &CiJob, runner: String, lang: Lang) -> Timing { queued: job.queued_at.as_deref().and_then(unix_of), started: job.started_at.as_deref().and_then(unix_of), finished: job.finished_at.as_deref().and_then(unix_of), + cancel_requested: job.cancel_requested, } } @@ -1535,6 +1548,7 @@ async fn run_detail( since: (job.finished.is_none() && job.state == JobState::Running) .then(|| job.started.map(|at| at.to_string())) .flatten(), + stopping: job.stopping(), }); } let can_rerun_failed = writer @@ -1572,6 +1586,7 @@ async fn run_detail( action_base: run_href(title, run.number), can_approve: header.writer_csrf.is_some() && run.state == RunState::WaitingApproval, can_cancel: header.writer_csrf.is_some() && !run_finished(&run.state), + stopping: jobs.iter().any(Timing::stopping), can_rerun_failed, warnings, artifacts, @@ -1704,7 +1719,9 @@ async fn runs_body( if run.can_approve { action_button(action: format!("{}/approve", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::ApproveAndRun)) } - if run.can_cancel { + if run.can_cancel && run.stopping { + + } else if run.can_cancel { action_button(action: format!("{}/cancel", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::Cancel)) } if run.can_rerun_failed { @@ -1800,6 +1817,9 @@ async fn runs_body( (job.runner.as_str()) (job.duration.as_str()) + if job.stopping { + (g::t(lang, K::StateStopping)) + } if let (Some(action), Some(csrf)) = (job.rerun.as_ref(), run.writer_csrf.as_ref()) { @@ -2432,6 +2452,7 @@ mod tests { queued, started, finished, + cancel_requested: false, } } diff --git a/crates/forge-web/src/pages/repo_side.rs b/crates/forge-web/src/pages/repo_side.rs index 53dd09f..de4fffd 100644 --- a/crates/forge-web/src/pages/repo_side.rs +++ b/crates/forge-web/src/pages/repo_side.rs @@ -10,22 +10,22 @@ use std::sync::{Mutex, OnceLock}; use forge_core::ci::{JobState, RunState}; use forge_core::{Repo, Visibility}; use forge_git::{browse, history}; +use time::OffsetDateTime; +use time::format_description::well_known::Rfc3339; use topcoat::Result; use topcoat::view::{View, component, view}; use crate::i18n::Lang; use crate::i18n::releases_ci as rc; -use crate::pages::ci_runs::{duration_text, run_href}; +use crate::pages::ci_runs::{duration_templates, duration_text, run_href, state_text}; use crate::pages::passkeys::s; use crate::pages::releases::LatestRelease; use crate::repo_stats::{LangShare, languages, license_file, license_id}; use crate::state::AppState; -use crate::views::{human_size, rel_time, short_oid}; +use crate::views::{human_size, now_unix, rel_time, short_oid}; /// CI runs the column lists. const RUNS_SHOWN: u32 = 3; -/// Jobs shown as pips; a run with more shows a count instead. -const MAX_PIPS: usize = 10; /// Languages listed before the rest fold into "Other". const TOP_LANGUAGES: usize = 4; /// Files the language count reads at most. @@ -106,38 +106,38 @@ pub async fn tree_facts( Ok(facts) } -/// One CI run as the column shows it. +/// One CI run as the column shows it: a link to the run, its dot, and one line of words. A run +/// still going has a bar of the jobs done and a clock that ticks. pub struct RunRow { pub href: String, pub number: i64, pub dot: &'static str, - pub meta: String, - /// Each job's pip class, or empty when the run has more jobs than pips. - pub pips: Vec<&'static str>, - /// "3/12" when the jobs do not fit as pips. - pub count: String, + /// The bar's fill and its job count, for a run still going. + pub bar: Option<(String, String)>, + /// Unix seconds the run started, for the ticking clock of a run still going. + pub since: Option, + /// The text before the clock: the current job's name. + pub pre: Option, + /// The right-hand text, or the elapsed time of a run still going. + pub label: String, pub title: String, } -/// The dot of a run: green passed, red failed, amber in progress, grey otherwise. +/// The dot of a run: glowing while it goes, green passed, red failed, grey otherwise. fn run_dot(run: RunState) -> &'static str { match run { RunState::Success => "health-dot ok", RunState::Failure | RunState::Error => "health-dot bad", - RunState::Running | RunState::Queued => "health-dot warn", + RunState::Running | RunState::Queued => "health-dot ember", RunState::Cancelled | RunState::WaitingApproval => "health-dot", } } -/// The pip of a job: filled when it passed, red when it failed, accent while it runs. -fn job_pip(job: JobState) -> &'static str { - match job { - JobState::Success => "side-pip is-ok", - JobState::Failure | JobState::Error => "side-pip is-bad", - JobState::Running => "side-pip is-on", - JobState::Skipped | JobState::Cancelled => "side-pip is-off", - JobState::Blocked | JobState::Queued => "side-pip", - } +/// Unix seconds of an RFC 3339 stamp. +fn unix(stamp: &str) -> Option { + OffsetDateTime::parse(stamp, &Rfc3339) + .ok() + .map(|at| at.unix_timestamp()) } /// The newest runs of the repo, with their jobs. @@ -147,6 +147,7 @@ pub async fn run_rows(state: &AppState, lang: Lang, repo: &Repo) -> Result Result s(lang, "passed", "geçti").to_owned(), + RunState::Failure | RunState::Error => match failed { + Some(name) => format!("{name} {}", s(lang, "failed", "başarısız")), + None => s(lang, "failed", "başarısız").to_owned(), + }, + RunState::Cancelled => s(lang, "cancelled", "iptal edildi").to_owned(), + RunState::WaitingApproval | RunState::Running | RunState::Queued => { + state_text(lang, run.state.as_str()) + } + }; + // The same words as the running clock and the CI pages: "4m 12s". + let took = duration_text(lang, started, run.finished_at.as_deref()); + let label = if took.is_empty() || run.finished_at.is_none() { + word + } else { + format!("{word} \u{b7} {took}") + }; + (None, None, None, label) + }; rows.push(RunRow { href: run_href(&title, run.number), number: run.number, dot: run_dot(run.state), - meta: meta.join(" \u{b7} "), - pips: if fits { - jobs.iter().map(|job| job_pip(job.state)).collect() - } else { - Vec::new() - }, - count: if fits { - String::new() - } else { - format!("{done}/{}", jobs.len()) - }, - title: s(lang, "Jobs passed", "Geçen işler").to_owned() - + &format!(": {done}/{}", jobs.len()), + bar, + since, + pre, + label, + title: format!( + "{}: {done}/{total} \u{b7} {branch} \u{b7} {}", + s(lang, "Jobs passed", "Geçen işler"), + short_oid(&run.commit_oid) + ), }); } Ok(rows) @@ -227,6 +265,9 @@ pub async fn repo_side( let size = facts.as_ref().map(|f| human_size(lang, f.size)); let license = facts.as_ref().and_then(|f| f.license.clone()); let langs = facts.map(|f| f.languages).unwrap_or_default(); + // The CI rows' clock: the server's time and the duration words the page's ticker rewrites with. + let now = now_unix(); + let (fm, fs) = duration_templates(lang); Ok(view! {

(s(lang, "About", "Hakkında"))

@@ -258,30 +299,28 @@ pub async fn repo_side(
if !runs.is_empty() { -
+
diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index 23ccd54..1a8a8a8 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -12,7 +12,7 @@ use std::sync::OnceLock; use forge_core::ci::RunState; use forge_core::store::RepoSort; use forge_core::store::repo_listing::RepoScope; -use forge_core::store::shell_activity::{ActorRuns, InboxKinds}; +use forge_core::store::shell_activity::{ActorRun, ActorRuns, InboxKinds}; use forge_core::{Error as CoreError, Session, User}; use hex::encode; use http::header::{ @@ -208,44 +208,82 @@ struct PathCrumb { class: &'static str, } -/// One pill of the live strip: a CI run of the viewer. -struct LivePill { - class: &'static str, +/// One run on the live strip: its pill when it is the only run, and its row in the dropdown otherwise. +struct StripRun { + pill_class: String, + row_class: String, label: String, - /// The current job's name (with a leading space) or the outcome word; empty when there is none. + /// The current job's name or the outcome word, with a leading space; empty when there is none. text: String, href: String, } -/// The live strip's pills, at most two, and how many runs are left over. Running runs come first, -/// then the finished ones that passed or failed. -fn live_pills(lang: Lang, runs: &ActorRuns) -> (Vec, usize) { - let mut pills = Vec::new(); +/// The live strip: every run of the viewer, running ones first, and the pill it shows. With one run +/// that run's pill; with two or more a summary pill that opens the list of all of them. +struct LiveStrip { + runs: Vec, + summary_class: &'static str, + summary: String, +} + +/// The live strip for the viewer's runs. A finished run that did not pass, fail or get cancelled is +/// left out. +fn live_strip(lang: Lang, runs: &ActorRuns) -> LiveStrip { + let mut rows = Vec::new(); for run in &runs.running { let job = run.current_job.as_deref().unwrap_or(""); - pills.push(LivePill { - class: "pill hot", - label: format!("{} #{}", run.repo, run.number), - text: if job.is_empty() { String::new() } else { format!(" {job}") }, - href: repo_href(&run.owner, &run.repo, "ci", &format!("runs/{}", run.number)), - }); + rows.push(strip_run("hot", run, if job.is_empty() { String::new() } else { format!(" {job}") })); } for run in &runs.finished { - let (class, word) = match run.state { - RunState::Success => ("pill ok", mi::t(lang, MK::Passed)), - RunState::Failure | RunState::Error => ("pill bad", mi::t(lang, MK::Failed)), + let (state, word) = match run.state { + RunState::Success => ("ok", mi::t(lang, MK::Passed)), + RunState::Failure | RunState::Error => ("bad", mi::t(lang, MK::Failed)), + RunState::Cancelled => ("off", mi::t(lang, MK::Cancelled)), _ => continue, }; - pills.push(LivePill { - class, - label: format!("{} #{}", run.repo, run.number), - text: format!(" {word}"), - href: repo_href(&run.owner, &run.repo, "ci", &format!("runs/{}", run.number)), - }); + rows.push(strip_run(state, run, format!(" {word}"))); + } + let count = |pred: fn(RunState) -> bool| runs.finished.iter().filter(|run| pred(run.state)).count() as u64; + let running = runs.running.len() as u64; + let failed = count(|state| matches!(state, RunState::Failure | RunState::Error)); + let passed = count(|state| matches!(state, RunState::Success)); + let cancelled = count(|state| matches!(state, RunState::Cancelled)); + let summary_class = if running > 0 { + "pill hot" + } else if failed > 0 { + "pill bad" + } else if passed > 0 { + "pill ok" + } else { + "pill off" + }; + let parts = [ + (running, mi::running_count as fn(Lang, u64) -> String), + (failed, mi::failed_count), + (passed, mi::passed_count), + (cancelled, mi::cancelled_count), + ]; + let summary = parts + .iter() + .filter(|(n, _)| *n > 0) + .map(|(n, phrase)| phrase(lang, *n)) + .collect::>() + .join(" · "); + LiveStrip { + runs: rows, + summary_class, + summary, + } +} + +fn strip_run(state: &str, run: &ActorRun, text: String) -> StripRun { + StripRun { + pill_class: format!("pill {state}"), + row_class: format!("strip-row {state}"), + label: format!("{} #{}", run.repo, run.number), + text, + href: repo_href(&run.owner, &run.repo, "ci", &format!("runs/{}", run.number)), } - let more = pills.len().saturating_sub(2); - pills.truncate(2); - (pills, more) } /// A count's phrase with its number replaced by `{n}`, for nav.js to fill in again. @@ -253,11 +291,6 @@ fn count_template(phrase: &str, n: u64) -> String { phrase.replacen(&n.to_string(), "{n}", 1) } -/// The heat ring's fill: the share of a run's jobs that are done, at least 8%. -fn heat_percent(done: u64, total: u64) -> u64 { - (done * 100).checked_div(total).map_or(8, |p| p.clamp(8, 100)) -} - /// The viewer's runs when there is no viewer or no app context: none. fn no_runs() -> ActorRuns { ActorRuns { @@ -278,8 +311,8 @@ struct WaitingRow { dot_class: &'static str, } -/// What the profile corner shows: the viewer, their inbox counts, the newest running run's heat -/// (`None` when nothing runs) and the items waiting on them. +/// What the profile corner shows: the viewer, their inbox counts, whether any of their runs is +/// going (the ring glows) and the items waiting on them. #[derive(Clone)] struct ProfileCorner { username: String, @@ -291,7 +324,7 @@ struct ProfileCorner { reviews: u64, mentions: u64, failing: u64, - heat: Option, + hot: bool, waiting: Vec, } @@ -300,9 +333,7 @@ struct ProfileCorner { /// and the profile, settings, admin and log out links. #[component] async fn profile_corner(lang: Lang, corner: ProfileCorner) -> Result { - let ring_class = if corner.heat.is_some() { "heat-ring hot" } else { "heat-ring" }; - // The fill in steps of 5 (the stylesheet maps each step to --p): the CSP refuses style attributes. - let ring_step = (corner.heat.unwrap_or(0).min(100) + 2) / 5 * 5; + let ring_class = if corner.hot { "heat-ring hot" } else { "heat-ring" }; let review_chip = (corner.reviews > 0).then(|| { (corner.reviews.to_string(), mi::review_requests_count(lang, corner.reviews)) }); @@ -336,7 +367,7 @@ async fn profile_corner(lang: Lang, corner: ProfileCorner) -> Result Ok(view! {
- + (corner.username.as_str()) if let Some((count, title)) = review_chip { @@ -569,12 +600,17 @@ pub async fn shell( href, }) .collect(); - let (pills, more) = live_pills(lang, &runs); - let more_label = format!("+{more}"); + let strip = live_strip(lang, &runs); + // The strip's count phrases, as templates for nav.js: `{n}` stands for the count. + let running_tpl = count_template(&mi::running_count(lang, 2), 2); + let failed_tpl = count_template(&mi::failed_count(lang, 2), 2); + let passed_tpl = count_template(&mi::passed_count(lang, 2), 2); + let cancelled_tpl = count_template(&mi::cancelled_count(lang, 2), 2); + let runs_label = mi::t(lang, MK::YourCiRuns); let search_for_label = mi::t(lang, MK::SearchPublicReposFor); // The profile corner, the signed-in sidebar's account menu. The sidebar and the phone menu // each get their own copy. - let heat = runs.running.first().map(|run| heat_percent(run.jobs_done, run.jobs_total)); + let hot = !runs.running.is_empty(); let waiting_rows: Vec = waiting .iter() .map(|item| WaitingRow { @@ -603,7 +639,7 @@ pub async fn shell( reviews: inbox.reviews, mentions: inbox.mentions, failing: runs.failing, - heat, + hot, waiting: waiting_rows, }); let corner_panel = corner.clone(); @@ -678,12 +714,23 @@ pub async fn shell( } if signed_in { -
- for pill in pills.iter() { - (pill.label.as_str())(pill.text.as_str()) +
+ if strip.runs.len() == 1 { + for run in strip.runs.iter() { + (run.label.as_str())(run.text.as_str()) + } } - if more > 0 { - (more_label.as_str()) + if strip.runs.len() > 1 { +
+ (strip.summary.as_str()) + +
}
} else { @@ -1699,6 +1746,40 @@ mod tests { assert_eq!(enc("a~b.c_d-e"), "a~b.c_d-e"); } + #[test] + fn live_strip_is_one_pill_for_one_run_and_a_summary_for_more() { + let run = |state, number| ActorRun { + owner: "tahinli".into(), + repo: "proj".into(), + number, + git_ref: "main".into(), + state, + created_at: String::new(), + finished_at: None, + jobs_total: 0, + jobs_done: 0, + current_job: None, + }; + let many = ActorRuns { + running: vec![run(RunState::Running, 3)], + finished: vec![run(RunState::Failure, 2), run(RunState::Cancelled, 1)], + failing: 0, + }; + let strip = live_strip(Lang::En, &many); + assert_eq!(strip.runs.len(), 3); + assert_eq!(strip.summary, "1 running · 1 failed · 1 cancelled"); + assert_eq!(strip.summary_class, "pill hot"); + let alone = ActorRuns { + running: Vec::new(), + finished: vec![run(RunState::Cancelled, 1)], + failing: 0, + }; + let one = live_strip(Lang::En, &alone); + assert_eq!(one.runs.len(), 1); + assert_eq!(one.runs[0].pill_class, "pill off"); + assert_eq!(one.runs[0].text, " cancelled"); + } + #[test] fn repo_href_builds_each_form() { assert_eq!(repo_href("tahinli", "demo", "", ""), "/tahinli/demo"); diff --git a/style/_repo_side.scss b/style/_repo_side.scss index 47252af..e2e9857 100644 --- a/style/_repo_side.scss +++ b/style/_repo_side.scss @@ -102,45 +102,88 @@ white-space: nowrap; } -// One pip per job, as on the runners list: filled when it passed, red when it failed, the accent -// while it runs, a hollow pip while it waits. -.side-pips { - display: inline-flex; - gap: 3px; +// One row per CI run, the whole row a link: an ember dot that glows while the run goes, the number, +// a slim heat bar of the jobs done (while it goes), and one muted line on the right: the current +// job and its clock, or the result and the total time. +.side-run + .side-run { + border-top: 1px solid var(--border); } -.side-pip { - box-sizing: border-box; - width: 12px; - height: 6px; - border-radius: 2px; - background: var(--surface-2); - box-shadow: inset 0 0 0 1px var(--border); +.side-run-link { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + padding: 11px 0; + color: inherit; + text-decoration: none; - &.is-ok { - background: var(--ok); - box-shadow: none; + &:hover .side-run-name { + text-decoration: underline; } +} + +.health-dot.ember { + background: var(--heat-3); + box-shadow: 0 0 6px var(--heat-glow); + animation: ember-pulse 1.8s ease-in-out infinite; - &.is-bad { - background: var(--bad); - box-shadow: none; + @media (prefers-reduced-motion: reduce) { + animation: none; } +} - &.is-on { - background: var(--accent); - box-shadow: none; +@keyframes ember-pulse { + 50% { + box-shadow: 0 0 10px var(--heat-glow); } +} + +.side-run-name { + flex: none; + color: var(--text); + font-size: 14px; + font-weight: 600; + font-variant-numeric: tabular-nums; +} - &.is-off { - background: var(--border-strong); - box-shadow: none; +progress.side-run-bar { + -webkit-appearance: none; + appearance: none; + flex: 1 1 auto; + box-sizing: border-box; + min-width: 24px; + height: 4px; + margin: 0; + border: 0; + border-radius: 2px; + overflow: hidden; + background: var(--border); + color: var(--heat-3); + + &::-webkit-progress-bar { + background: var(--border); + } + + &::-webkit-progress-value { + border-radius: 2px; + background: linear-gradient(90deg, var(--heat-2), var(--heat-3), var(--heat-4)); + } + + &::-moz-progress-bar { + border-radius: 2px; + background: linear-gradient(90deg, var(--heat-2), var(--heat-3), var(--heat-4)); } } -.side-count { +.side-run-text { + min-width: 0; + margin-left: auto; + overflow: hidden; font-size: 12px; font-variant-numeric: tabular-nums; + text-overflow: ellipsis; + white-space: nowrap; } // Languages: the name and what it is made of, a thin meter in the accent, the share on the right. diff --git a/style/_shell.scss b/style/_shell.scss index a624f02..74fc8c5 100644 --- a/style/_shell.scss +++ b/style/_shell.scss @@ -333,9 +333,83 @@ } } -.pill.more { - color: var(--muted); - border-style: dashed; +// Two or more runs: the summary pill opens a list of all of them, right-aligned under it. +.strip-runs { + position: relative; + + > summary { + list-style: none; + cursor: pointer; + + &::-webkit-details-marker { + display: none; + } + } +} + +.strip-list { + position: absolute; + top: calc(100% + 6px); + right: 0; + z-index: 60; + display: grid; + gap: 2px; + box-sizing: border-box; + width: max-content; + min-width: 240px; + max-width: min(420px, 92vw); + max-height: min(60vh, 420px); + overflow-y: auto; + margin: 0; + padding: 6px; + list-style: none; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-md); + box-shadow: var(--shadow); + + li { + min-width: 0; + } +} + +.strip-row { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + padding: 6px 8px; + border-radius: var(--radius-md); + color: var(--text-2); + font-size: 12.5px; + white-space: nowrap; + text-decoration: none; + + b { + min-width: 0; + overflow: hidden; + font-weight: 600; + color: var(--text); + text-overflow: ellipsis; + } + + &:hover { + background: var(--surface-2); + text-decoration: none; + } + + &.ok .pill-dot { + background: var(--ok); + } + + &.bad .pill-dot { + background: var(--danger); + } + + &.hot .pill-dot { + background: var(--heat-4); + animation: pill-pulse 1.6s ease-out infinite; + } } @keyframes pill-pulse { @@ -583,7 +657,8 @@ white-space: nowrap; } -// The avatar inside a ring: the ring fills with the running run's progress (--p), and glows while hot. +// The avatar inside a ring: a plain border ring when nothing runs, a full ember ring while a run +// of the viewer's is queued or running (.hot), glowing softly. .heat-ring { display: grid; flex: none; @@ -591,18 +666,10 @@ width: 34px; height: 34px; border-radius: 50%; - background: conic-gradient( - var(--heat-2) 0%, - var(--heat-3) calc(var(--p, 8%) * 0.6), - var(--heat-4) var(--p, 8%), - var(--border) var(--p, 8%) - ); - - &:not(.hot) { - background: var(--border); - } + background: var(--border); &.hot { + background: conic-gradient(var(--heat-2), var(--heat-3), var(--heat-4), var(--heat-2)); filter: drop-shadow(0 0 5px var(--heat-glow)); } @@ -615,13 +682,6 @@ } } -// The fill arrives as data-p in steps of 5: the CSP refuses style attributes. -@for $i from 0 through 20 { - .heat-ring[data-p="#{$i * 5}"] { - --p: #{$i * 5}%; - } -} - .corner-chips { display: flex; align-items: center; @@ -1074,7 +1134,8 @@ html[aria-busy="true"] body::before { opacity: 0.45; } - .pill.hot .pill-dot { + .pill.hot .pill-dot, + .strip-row.hot .pill-dot { animation: none; } } diff --git a/style/main.scss b/style/main.scss index dde0cc0..3495823 100644 --- a/style/main.scss +++ b/style/main.scss @@ -6184,6 +6184,25 @@ html.js form.runner-load[data-dirty-form][data-dirty] .runner-save { white-space: nowrap; } +// A running job being stopped: a small label tinted toward the heat colour, in its own grid track +// (the row then has one more track, so the chevron keeps its place). +.ci-job-line:has(.ci-job-stopping) { + grid-template-columns: 8px minmax(0, 1fr) auto auto auto 12px; +} + +.ci-job-stopping { + font-size: 0.75rem; + color: color-mix(in srgb, var(--heat-3) 60%, var(--muted)); + white-space: nowrap; +} + +// Cancel's stand-in while the run is being stopped: disabled, so it reads as taken. +button.ci-stopping { + cursor: not-allowed; + color: var(--muted); + opacity: 0.65; +} + .ci-chev { justify-self: end; width: 6px;