diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index f832d3a..5ea564f 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -128,7 +128,7 @@ }); } - function adopt(doc, keepFields, dd) { + function adopt(doc, keepFields, dd, jobs) { document.title = doc.title; ['lang', 'data-theme', 'data-accent-light', 'data-accent-dark', 'data-base-light', 'data-base-dark', 'data-sidebar', 'data-ui'].forEach(function (name) { if (doc.documentElement.hasAttribute(name)) { root.setAttribute(name, doc.documentElement.getAttribute(name)); } @@ -151,6 +151,7 @@ if (kept) { restoreFields(kept); } if (dd) { focusDropdown(dd); } followTail(); + restoreJobs(jobs); syncUnread(); syncLive(); syncTick(); @@ -162,6 +163,79 @@ if (pre) { pre.scrollTop = pre.scrollHeight; } } + // The run page's job rows each have a last-line preview and a tail that opens under the row + // (li[data-job-row], data-open). A row the reader toggled is marked data-touched. A live swap brings + // the server's defaults, so the touched rows and the scroll of every tail are put back after it. + function jobTails() { return document.querySelectorAll('[data-job-row]'); } + + function setJobRow(li, open, touch) { + var tail = li.querySelector('[data-job-tail]'); + if (!tail) { return; } + li.setAttribute('data-open', open ? 'true' : 'false'); + if (touch) { li.setAttribute('data-touched', 'true'); } + tail.hidden = !open; + var btn = li.querySelector('[data-job-toggle]'); + if (btn) { btn.setAttribute('aria-expanded', open ? 'true' : 'false'); } + if (open) { + var pre = tail.querySelector('pre'); + if (pre) { pre.scrollTop = pre.scrollHeight; } + } + } + + function syncJobAll() { + var all = document.querySelector('[data-job-all]'); + if (!all) { return; } + var closed = false; + jobTails().forEach(function (li) { + if (li.querySelector('[data-job-tail]') && li.getAttribute('data-open') !== 'true') { closed = true; } + }); + all.textContent = all.getAttribute(closed ? 'data-expand' : 'data-collapse'); + } + + // Taken before a live swap: the rows the reader touched and where each open tail was scrolled. + function captureJobs() { + var out = {}; + jobTails().forEach(function (li) { + var pre = li.querySelector('[data-job-tail] pre'); + var open = li.getAttribute('data-open') === 'true'; + out[li.getAttribute('data-job-row')] = { + touched: li.hasAttribute('data-touched'), + open: open, + top: pre && open ? pre.scrollTop : 0, + end: pre && open ? pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 24 : true + }; + }); + return out; + } + + // Every open tail starts at its end; a captured one goes back to where the reader had it. + function restoreJobs(kept) { + jobTails().forEach(function (li) { + var c = kept ? kept[li.getAttribute('data-job-row')] : null; + if (c && c.touched) { setJobRow(li, c.open, true); } + var pre = li.querySelector('[data-job-tail] pre'); + if (!pre || li.getAttribute('data-open') !== 'true') { return; } + pre.scrollTop = c && !c.end ? c.top : pre.scrollHeight; + }); + syncJobAll(); + } + + document.addEventListener('click', function (e) { + var el = e.target && e.target.closest ? e.target : null; + if (!el) { return; } + var all = el.closest('[data-job-all]'); + if (all) { + var open = all.textContent === all.getAttribute('data-expand'); + jobTails().forEach(function (li) { setJobRow(li, open, true); }); + syncJobAll(); + return; + } + var btn = el.closest('[data-job-toggle]'); + if (!btn) { return; } + var li = btn.closest('[data-job-row]'); + if (li) { setJobRow(li, li.getAttribute('data-open') !== 'true', true); syncJobAll(); } + }, false); + function focusMain() { var main = document.querySelector('main'); if (main && main.focus) { main.focus({ preventScroll: true }); } @@ -192,7 +266,7 @@ // A live change must not shut a menu the reader has open (a run's branch picker, say). var dd = how === 'live' ? captureDropdowns() : null; if (how !== 'live') { closeDropdowns(null); } - adopt(doc, keepFields, dd); + adopt(doc, keepFields, dd, how === 'live' ? captureJobs() : null); if (tailAt) { var nextTail = document.querySelector('[data-live-log]'); if (nextTail) { nextTail.scrollTop = tailAt.end ? nextTail.scrollHeight : tailAt.top; } diff --git a/crates/forge-web/src/i18n/releases_ci.rs b/crates/forge-web/src/i18n/releases_ci.rs index 6d8fb80..8b7c21d 100644 --- a/crates/forge-web/src/i18n/releases_ci.rs +++ b/crates/forge-web/src/i18n/releases_ci.rs @@ -45,7 +45,8 @@ pub enum K { Artifacts, Timeline, Waiting, - LastLogLines, + ExpandAll, + CollapseAll, // CI status badge, on the run list. BadgeHeading, @@ -207,8 +208,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { (Timeline, Tr) => "Zaman çizelgesi", (Waiting, En) => "waiting", (Waiting, Tr) => "bekliyor", - (LastLogLines, En) => "last log lines", - (LastLogLines, Tr) => "son günlük satırları", + (ExpandAll, En) => "Expand all", + (ExpandAll, Tr) => "Tümünü aç", + (CollapseAll, En) => "Collapse all", + (CollapseAll, Tr) => "Tümünü kapat", (BadgeHeading, En) => "Status badge", (BadgeHeading, Tr) => "Durum rozeti", (BadgeHelp, En) => { @@ -507,7 +510,8 @@ mod tests { K::Artifacts, K::Timeline, K::Waiting, - K::LastLogLines, + K::ExpandAll, + K::CollapseAll, K::BadgeHeading, K::BadgeHelp, K::BadgeSnippet, diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index af4a985..e0eb3a3 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -345,12 +345,14 @@ struct JobLine { duration: String, /// Unix seconds a running job's duration counts from. since: Option, -} - -/// The last lines of the log of the job the run page points at. -struct LogBlock { - caption: String, - text: String, + /// The job id: what the page script keys the row on. + id: String, + /// The last non-empty log line, or the queued reason of a job with no output yet. + preview: String, + /// The last lines of the log, at most `LOG_LINES`. Empty when the job has no output. + tail: String, + /// Whether the row starts with its tail open. + expanded: bool, } /// The right column: the selected run, its timeline, its jobs and the log tail. @@ -375,7 +377,6 @@ struct RunDetail { writer_csrf: Option, gantt: Option, jobs: Vec, - log: Option, } /// A box in an SVG, with its class and its position and size in the SVG's units. @@ -585,9 +586,9 @@ const AXIS_STEPS: [i64; 14] = [ 60, 120, 300, 600, 900, 1200, 1800, 3600, 7200, 14400, 21600, 43200, 86400, 172800, ]; /// How far back from the end of a log the run page reads for its last lines. -const LOG_TAIL_BYTES: u64 = 8 * 1024; -/// Lines of a log the run page shows. -const LOG_LINES: usize = 3; +const LOG_TAIL_BYTES: u64 = 16 * 1024; +/// Lines of a log an expanded job row shows. +const LOG_LINES: usize = 20; /// Where an offset of `offset` seconds falls on a span of `span` seconds drawn `width` units wide. /// The offset is clamped to the span, so nothing is drawn past its end. @@ -1076,7 +1077,48 @@ fn row_meta(run: &CiRun, jobs: &[Timing], actor: &str, lang: Lang) -> String { meta } -/// The last lines of a log, read from its tail only. A log that cannot be read has none. +/// Drops the ANSI escape sequences and the other control characters (a tab stays) of a log line. +fn strip_ansi(line: &str) -> String { + let mut out = String::with_capacity(line.len()); + let mut chars = line.chars().peekable(); + while let Some(c) = chars.next() { + if c == '\u{1b}' { + match chars.next() { + // A CSI sequence ends at a byte from `@` to `~`. + Some('[') => { + for n in chars.by_ref() { + if ('@'..='~').contains(&n) { + break; + } + } + } + // An OSC sequence ends at BEL or ESC. + Some(']') => { + for n in chars.by_ref() { + if n == '\u{7}' || n == '\u{1b}' { + break; + } + } + } + _ => {} + } + } else if c == '\t' || !c.is_control() { + out.push(c); + } + } + out +} + +/// The last non-empty line of a tail: what a job row previews. +fn last_line(tail: &[String]) -> Option<&str> { + tail.iter() + .rev() + .map(|line| line.trim()) + .find(|line| !line.is_empty()) +} + +/// The last lines of a log, read from its tail only, without ANSI codes and trailing blank lines. +/// A log that cannot be read has none. async fn log_last_lines(path: &Path) -> Vec { let Ok(mut file) = tokio::fs::File::open(path).await else { return Vec::new(); @@ -1096,11 +1138,12 @@ async fn log_last_lines(path: &Path) -> Vec { if start > 0 && !lines.is_empty() { lines.remove(0); } + let mut lines: Vec = lines.iter().map(|line| strip_ansi(line)).collect(); + while lines.last().is_some_and(|line| line.trim().is_empty()) { + lines.pop(); + } let skip = lines.len().saturating_sub(LOG_LINES); - lines[skip..] - .iter() - .map(|line| (*line).to_owned()) - .collect() + lines.split_off(skip) } /// Maps each user id in `ids` to a display name. A user that no longer exists shows as "deleted user". @@ -1338,8 +1381,12 @@ struct RunHeader { writer_csrf: Option, } -/// The selected run: its header values, its timeline, its jobs and the last lines of the job to look at. -/// That is the failed job, else the running one, else the last job. +/// Whether a job row starts with its tail open: a failed job does, and so does the only job of a run. +fn starts_expanded(state: JobState, jobs: usize) -> bool { + matches!(state, JobState::Failure | JobState::Error) || jobs == 1 +} + +/// The selected run: its header values, its timeline and its jobs, each with the last lines of its log. async fn run_detail( state: &AppState, title: &str, @@ -1362,7 +1409,18 @@ async fn run_detail( let size = human_size(lang, u64::try_from(artifact.size).unwrap_or(0)); parts.push(format!("{} {size}", artifact.name)); } + let tail = log_last_lines(&log_path(&state.config.data_dir, &job.id)).await; + let preview = match last_line(&tail) { + Some(line) => line.to_owned(), + None if job.state == JobState::Queued && !job.message.is_empty() => job.message.clone(), + None if job.state == JobState::Queued => state_text(lang, job.state.as_str()), + None => String::new(), + }; lines.push(JobLine { + id: job.id.clone(), + expanded: !tail.is_empty() && starts_expanded(job.state, jobs.len()), + preview, + tail: tail.join("\n"), href: job_href(title, &job.id), name: job.name.clone(), dot: format!("ci-dot ci-{}", job.state.as_str()), @@ -1374,21 +1432,6 @@ async fn run_detail( .flatten(), }); } - let focus = jobs - .iter() - .find(|job| matches!(job.state, JobState::Failure | JobState::Error)) - .or_else(|| jobs.iter().find(|job| job.state == JobState::Running)) - .or(jobs.last()); - let log = match focus { - Some(job) => { - let tail = log_last_lines(&log_path(&state.config.data_dir, &job.id)).await; - (!tail.is_empty()).then(|| LogBlock { - caption: format!("{} \u{b7} {}", job.name, g::t(lang, K::LastLogLines)), - text: tail.join("\n"), - }) - } - None => None, - }; Ok(RunDetail { number: run.number, title: header.title, @@ -1415,7 +1458,6 @@ async fn run_detail( writer_csrf: header.writer_csrf, gantt, jobs: lines, - log, }) } @@ -1600,9 +1642,14 @@ async fn runs_body( if run.jobs.is_empty() {

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

} else { + if run.jobs.len() > 1 { +
+ +
+ } } - if let Some(log) = run.log.as_ref() { -

(log.caption.as_str())

-
(log.text.as_str())
- } } else {

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

@@ -2191,12 +2248,29 @@ mod tests { assert_eq!(bar_text(40, &labels), None); } + #[test] + fn failed_and_lone_jobs_start_expanded() { + assert!(starts_expanded(JobState::Failure, 3)); + assert!(starts_expanded(JobState::Running, 1)); + assert!(!starts_expanded(JobState::Running, 2)); + assert!(!starts_expanded(JobState::Success, 2)); + } + + #[test] + fn previews_skip_blank_lines_and_ansi_codes() { + assert_eq!(strip_ansi("\u{1b}[31mred\u{1b}[0m ok"), "red ok"); + assert_eq!(strip_ansi("\u{1b}]0;title\u{7}x"), "x"); + let tail = vec!["a".to_owned(), " b ".to_owned(), String::new()]; + assert_eq!(last_line(&tail), Some("b")); + assert_eq!(last_line(&[]), None); + } + #[tokio::test] async fn log_tails_keep_their_last_lines() { let dir = tempfile::tempdir().expect("tempdir"); let path = dir.path().join("log.txt"); - std::fs::write(&path, "one\ntwo\nthree\nfour\n").expect("write"); - assert_eq!(log_last_lines(&path).await, vec!["two", "three", "four"]); + std::fs::write(&path, "one\ntwo\n\u{1b}[1mthree\u{1b}[0m\n\n").expect("write"); + assert_eq!(log_last_lines(&path).await, vec!["one", "two", "three"]); assert!(log_last_lines(&dir.path().join("none")).await.is_empty()); } } diff --git a/crates/forge-web/src/pages/ci_tests.rs b/crates/forge-web/src/pages/ci_tests.rs index 5c031a8..608d9c0 100644 --- a/crates/forge-web/src/pages/ci_tests.rs +++ b/crates/forge-web/src/pages/ci_tests.rs @@ -1393,3 +1393,63 @@ async fn running_runs_carry_ticker_attributes_and_finished_ones_do_not() { "nothing grows once the run is done" ); } + +/// The run page previews the last log line of every running job in its row, and a failed job's row +/// starts expanded. +#[tokio::test] +async fn run_page_previews_each_job_and_expands_failed_ones() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + let run = run_with(&fx, &["build", "test", "lint"], false).await; + let token = fx + .store + .create_registration_token(&fx.tahinli, 24) + .await + .expect("token"); + let (runner, _) = fx + .store + .register_runner(&token, "runner-1", &["linux".to_owned()]) + .await + .expect("runner"); + for _ in 0..3 { + fx.store + .claim_job(&runner) + .await + .expect("claim") + .expect("a queued job"); + } + let jobs = fx.store.jobs_for_run(&run.id).await.expect("jobs"); + for job in &jobs { + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write( + &path, + format!("early\n\u{1b}[32mlast of {}\u{1b}[0m\n\n", job.name), + ) + .expect("log"); + } + let lint = jobs.iter().find(|job| job.name == "lint").expect("lint"); + fx.store + .finish_job(&lint.id, JobState::Failure, Some(1), None) + .await + .expect("fail"); + let page = get( + &fx.app, + &format!("{RUN_BASE}/runs/{}", run.number), + Some(&cookie_for("tahinli-token")), + ) + .await; + assert_eq!(page.status, 200); + let html = page.text(); + for name in ["build", "test", "lint"] { + assert!( + html.contains(&format!("title=\"last of {name}\"")), + "{name}: {html}" + ); + } + assert!(!html.contains('\u{1b}')); + assert_eq!(html.matches("data-job-row=").count(), 3); + assert_eq!(html.matches("data-open=\"true\"").count(), 1); + assert!(html.contains(&format!("data-job-row=\"{}\" data-open=\"true\"", lint.id))); + assert!(html.contains("data-job-all")); +} diff --git a/style/main.scss b/style/main.scss index 6781097..b8ca900 100644 --- a/style/main.scss +++ b/style/main.scss @@ -4600,6 +4600,93 @@ span.reaction { color: var(--muted); } +.ci-job-head { + display: flex; + justify-content: flex-end; + margin: 12px 0 -8px; +} + +.ci-job-all { + padding: 2px 8px; + font: inherit; + font-size: 0.8125rem; + color: var(--muted); + background: transparent; + border: 0; + border-radius: var(--radius-md); + cursor: pointer; + + &:hover { + color: var(--text); + background: var(--surface-2); + } +} + +// The last line of a job's log under its row, and the tail that opens below it. +.ci-job-last { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + margin: 0; + padding: 0 6px 8px 26px; + font-family: var(--mono); + font-size: 0.75rem; + color: var(--muted); + text-align: left; + background: transparent; + border: 0; +} + +button.ci-job-last { + cursor: pointer; + + &:hover { + color: var(--text-2); + } +} + +.ci-job-last-text { + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.ci-job-caret { + flex: none; + width: 5px; + height: 5px; + border-right: 1.5px solid currentColor; + border-bottom: 1.5px solid currentColor; + transform: rotate(-45deg); + transition: transform 0.12s; + + [aria-expanded="true"] > & { + transform: rotate(45deg); + } +} + +.ci-job-tail { + padding: 0 6px 10px 26px; + + .ci-logpre { + max-height: 14rem; + margin: 0; + overflow: auto; + } + + &[hidden] { + display: none; + } +} + +.ci-job-full { + display: inline-block; + margin-top: 6px; + font-size: 0.8125rem; +} + .ci-logpre { max-width: 100%; margin: 8px 0 0;