use std::{collections::HashMap, rc::Rc, time::Duration}; use common::call::{CreateTag, GetForge}; use gpui_kit::{ Anchor, AnyElement, App, Context, Div, Entity, Focusable, InteractiveElement, IntoElement, ListHorizontalSizingBehavior, ParentElement, ScrollStrategy, Styled, Window, component::popover::{Popover, PopoverState}, div, px, uniform_list, }; use super::releases::caption_text; use super::ui::{card, list_row}; use crate::ci::{self, Event, Job, Run, State}; use crate::gui::builder::BuilderTab; use crate::gui::chat::View; use crate::gui::{ Palette, Trigger, Yumush, entity_action, hoverable, notify_error, parts::{self, Fill, Press}, profile::yumush_action, style::{radius, size, space, text}, text, }; use crate::lang::w; const LOG_LINE: f32 = 18.; const LOG_MAX: usize = 50_000; const TICK: Duration = Duration::from_secs(1); #[derive(Default)] pub(crate) struct Live { repo: Option, watch: Option, run: Option, logs: HashMap>, log_open: Option, seen_live: bool, dismissed: bool, tagging: bool, } impl Live { fn state(&self) -> Option { self.run.as_ref().map(|run| State::of(&run.state)) } fn live(&self) -> bool { self.state().is_some_and(|state| !state.finished()) } fn shown(&self) -> bool { self.run.is_some() && self.seen_live && !self.dismissed } fn done(&self) -> usize { self.run.as_ref().map_or(0, |run| { run.jobs .iter() .filter(|job| State::of(&job.state).finished()) .count() }) } fn share(&self) -> f32 { let total = self.run.as_ref().map_or(0, |run| run.jobs.len()); self.done() as f32 / total.max(1) as f32 } fn failed(&self) -> bool { self.state() == Some(State::Failed) } pub(super) fn tagging(&self) -> bool { self.tagging } } fn span(from: Option<&str>, to: Option<&str>, seconds: bool) -> Option { let from: jiff::Timestamp = from?.parse().ok()?; let to = to .and_then(|to| to.parse().ok()) .unwrap_or_else(jiff::Timestamp::now); let total = to.duration_since(from).as_secs().max(0); let (hours, minutes, rest) = (total / 3600, total / 60 % 60, total % 60); Some(match (seconds, hours) { (true, 0) => format!("{minutes}:{rest:02}"), (true, _) => format!("{hours}:{minutes:02}:{rest:02}"), (false, 0) => format!("{minutes}m"), (false, _) => format!("{hours}h {minutes:02}m"), }) } fn run_label(state: State) -> &'static str { let w = &w().builder_release; match state { State::Waiting => w.queued, State::Running => w.building, State::Success | State::Skipped => w.built, State::Failed => w.build_failed, } } fn job_status(state: State, palette: Palette) -> Div { let w = &w().builder_release; match state { State::Waiting => caption_text(w.waiting, palette.muted), State::Running => caption_text(w.running, palette.text), State::Success => caption_text(w.done, palette.ok), State::Skipped => caption_text(w.skipped, palette.muted), State::Failed => caption_text(w.failed, palette.danger), } } fn job_row( job: &Job, log: Option<&Vec>, seconds: bool, entity: &Entity, palette: Palette, ) -> Div { let state = State::of(&job.state); let step = job.steps.last().map(|step| step.name.as_str()); let line = log.and_then(|log| log.last()).map(String::as_str); let detail = match (state.finished(), step, line) { (false, Some(step), Some(line)) => Some(format!("{step} · {line}")), (_, Some(step), _) => Some(step.to_string()), (_, None, line) => line.map(str::to_string), }; let info = div() .id(format!("ci_job_{}", job.id)) .w_full() .flex() .flex_col() .cursor_pointer() .child( div() .text_size(text(text::LABEL)) .text_color(palette.text) .child(job.label().to_string()), ) .children(detail.map(|detail| caption_text(detail, palette.muted).truncate())); let id = job.id.clone(); let entity = entity.clone(); list_row() .child( div().flex_1().min_w_0().child( Popover::new(format!("ci_log_{}", job.id)) .anchor(Anchor::TopLeft) .appearance(false) .trigger(Trigger::new(info)) .content(move |_, window, cx| log_sheet(&id, &entity, window, cx)), ), ) .child(job_status(state, palette)) .children( span( job.started_at.as_deref(), job.finished_at.as_deref(), seconds, ) .map(|time| caption_text(time, palette.muted)), ) } fn log_sheet(job: &str, entity: &Entity, window: &mut Window, cx: &mut App) -> Div { let palette = crate::gui::palette(cx); let input = entity.read(cx).log_search.clone(); if !input.read(cx).focus_handle(cx).contains_focused(window, cx) { input.update(cx, |state, cx| state.focus(window, cx)); } let query = crate::gui::widget::search_text(&input, cx); let yumush = entity.read(cx); let live = &yumush.desk.live; let lines: Rc> = Rc::new( live.logs .get(job) .map(|log| { log.iter() .enumerate() .filter(|(_, line)| query.is_empty() || line.to_lowercase().contains(&query)) .map(|(index, _)| index) .collect() }) .unwrap_or_default(), ); let scroll = yumush.log_scroll.clone(); let count = lines.len(); if live.log_open.as_deref() != Some(job) { scroll.scroll_to_item(count.saturating_sub(1), ScrollStrategy::Bottom); let job = job.to_string(); entity.update(cx, |yumush, cx| yumush.open_ci_log(job, cx)); } let job = job.to_string(); let entity = entity.clone(); crate::gui::widget::panel(palette) .w(px(size::PAGE - space::XL)) .p(px(space::XS)) .flex() .flex_col() .gap(px(space::XS)) .child(crate::gui::sidebar::input_box(&input, palette)) .child( uniform_list(format!("ci_log_lines_{job}"), count, move |range, _, cx| { let palette = crate::gui::palette(cx); let Some(log) = entity.read(cx).desk.live.logs.get(&job) else { return Vec::new(); }; lines[range] .iter() .filter_map(|&index| log.get(index)) .map(|line| { div() .h(px(LOG_LINE)) .px(px(space::XS)) .whitespace_nowrap() .text_size(text(text::CAPTION)) .text_color(palette.muted) .child(line.clone()) }) .collect() }) .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained) .track_scroll(&scroll) .h(px((count as f32 * LOG_LINE).clamp(LOG_LINE, size::SHEET))), ) } impl Yumush { pub(in crate::gui) fn watch_ci(&mut self, window: &mut Window, cx: &mut Context) { if !self.is_builder() || self.desk.live.watch.is_some() { return; } let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { let Ok(Some(repo)) = network.call(GetForge).await else { return; }; let (watch, mut events) = ci::watch(repo.clone()); let started = this.update(cx, |yumush, _| { yumush.desk.live.repo = Some(repo); yumush.desk.live.watch = Some(watch); }); if started.is_err() { return; } cx.spawn(async move |cx| { while let Some(event) = events.recv().await { if this .update(cx, |yumush, cx| yumush.ci_event(event, cx)) .is_err() { break; } } }) .detach(); }) .detach(); cx.spawn_in(window, async move |this, cx| { loop { cx.background_executor().timer(TICK).await; let Ok(watching) = this.update_in(cx, |yumush, window, cx| { if yumush.desk.live.live() { window.refresh(); cx.notify(); } yumush.desk.live.watch.is_some() }) else { break; }; if !watching { break; } } }) .detach(); } fn ci_event(&mut self, event: Event, cx: &mut Context) { let live = &mut self.desk.live; match event { Event::Run(run) => { if live.run.as_ref().map(|old| old.number) != Some(run.number) { live.logs.clear(); live.dismissed = false; live.seen_live = false; } if !State::of(&run.state).finished() { live.seen_live = true; } live.run = Some(run); } Event::Line { job, line } => { let log = live.logs.entry(job).or_default(); if log.len() >= LOG_MAX { log.drain(..LOG_MAX / 10); } log.push(line); } } cx.notify(); } fn open_ci_log(&mut self, job: String, cx: &mut Context) { let live = &mut self.desk.live; live.log_open = Some(job.clone()); let finished = live.run.as_ref().is_some_and(|run| { run.jobs .iter() .any(|item| item.id == job && State::of(&item.state).finished()) }); let Some(repo) = live.repo.clone().filter(|_| finished) else { return; }; if live.logs.get(&job).is_some_and(|log| !log.is_empty()) { return; } cx.spawn(async move |this, cx| { let fetched = cx .background_executor() .spawn({ let job = job.clone(); async move { ci::whole_log(&repo, &job) } }) .await; let Some(text) = fetched else { return; }; let _ = this.update(cx, |yumush, cx| { let log: Vec = text .lines() .filter(|line| !ci::marker(line)) .map(str::to_string) .collect(); let start = log.len().saturating_sub(LOG_MAX); yumush.desk.live.logs.insert(job, log[start..].to_vec()); cx.notify(); }); }) .detach(); } pub(super) fn create_tag(&mut self, window: &mut Window, cx: &mut Context) { let tag = self.release_tag_text(cx); if tag.is_empty() || self.desk.live.tagging { return; } self.desk.live.tagging = true; cx.notify(); let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { let result = network.call(CreateTag { tag }).await; let _ = this.update(cx, |yumush, cx| { yumush.desk.live.tagging = false; cx.notify(); }); if let Err(error) = result { notify_error(&this, cx, error); } }) .detach(); } fn run_head(&self, palette: Palette) -> Option
{ let live = &self.desk.live; let run = live.run.as_ref()?; let state = State::of(&run.state); let time = span( run.started_at.as_deref(), run.finished_at.as_deref(), self.settings.clock_seconds, ) .unwrap_or_default(); let name = run.tag().unwrap_or(&run.reference); let aside = if state.finished() { time } else { format!("{} / {} · {time}", live.done(), run.jobs.len()) }; Some( div() .flex() .justify_between() .pb(px(space::XS)) .text_size(text(text::LABEL)) .child( div() .text_color(if live.failed() { palette.danger } else { palette.text }) .child(format!("#{} · {name} · {}", run.number, run_label(state))), ) .child(div().text_color(palette.muted).child(aside)), ) } fn ci_rows( &self, entity: &Entity, fit: impl Fn(Div) -> Div, palette: Palette, ) -> Vec
{ let live = &self.desk.live; let seconds = self.settings.clock_seconds; live.run.as_ref().map_or_else(Vec::new, |run| { run.jobs .iter() .map(|job| { fit(job_row( job, live.logs.get(&job.id), seconds, entity, palette, )) }) .collect() }) } fn import_run_button(&self, entity: &Entity, palette: Palette) -> Option { let run = self.desk.live.run.as_ref()?; let tag = run.tag()?.to_string(); (State::of(&run.state) == State::Success).then(|| { parts::button( "ci_import", w().builder_release.import, Press::Primary, palette.tokens, entity_action(entity, move |yumush, window, cx| { yumush.import_tag(tag.clone(), window, cx) }), ) .into_any_element() }) } pub(super) fn ci_card(&self, entity: &Entity, palette: Palette) -> Option
{ let head = self.run_head(palette)?; Some( card(palette) .child(head) .child(parts::track( Fill::Part(self.desk.live.share()), self.desk.live.failed(), palette.tokens, )) .children(self.ci_rows(entity, |row| row, palette)) .children( self.import_run_button(entity, palette) .map(|button| list_row().justify_end().child(button)), ), ) } pub(in crate::gui) fn build_control( &self, entity: &Entity, palette: Palette, ) -> Option { let live = &self.desk.live; if !live.shown() { return None; } let run = live.run.as_ref()?; let state = State::of(&run.state); let aside = if state.finished() { span( run.started_at.as_deref(), run.finished_at.as_deref(), self.settings.clock_seconds, ) .unwrap_or_default() } else { format!("{} / {}", live.done(), run.jobs.len()) }; let failed = live.failed(); let trigger = hoverable( "build_trigger", div() .flex() .flex_col() .gap(px(space::XS)) .py(px(space::XS)) .px(px(space::SM)) .rounded(px(radius::MD)) .child( div() .flex() .justify_between() .text_size(text(text::LABEL)) .child( div() .text_color(if failed { palette.danger } else { palette.text }) .child(run_label(state)), ) .child(div().text_color(palette.muted).child(aside)), ) .child(parts::track( Fill::Part(live.share()), failed, palette.tokens, )), palette, ); let entity = entity.clone(); Some( Popover::new("build_status") .anchor(Anchor::BottomLeft) .appearance(false) .trigger(Trigger::new(trigger)) .content(move |_, _, cx| { let popover = cx.entity(); let palette = crate::gui::palette(cx); entity.read(cx).build_sheet(&entity, &popover, palette) }) .into_any_element(), ) } fn build_sheet( &self, entity: &Entity, popover: &Entity, palette: Palette, ) -> Div { let w = &w().builder_release; let open = parts::button( "build_open_releases", w.open_releases, Press::Plain, palette.tokens, yumush_action(entity, popover, |yumush, window, cx| { yumush.show_view(View::Builder, window, cx); yumush.select_builder_tab(BuilderTab::Releases, window, cx); }), ); let dismiss = (!self.desk.live.live()).then(|| { parts::button( "build_sheet_dismiss", w.dismiss, Press::Plain, palette.tokens, yumush_action(entity, popover, |yumush, _, cx| { yumush.desk.live.dismissed = true; cx.notify(); }), ) }); parts::popover(palette.tokens) .w(px(size::SHEET)) .p(px(space::MD)) .children(self.run_head(palette)) .children(self.ci_rows( entity, |row| row.min_h(px(size::CONTROL)).py(px(space::XXS)), palette, )) .child( div() .pt(px(space::SM)) .flex() .justify_between() .child(open) .children(self.import_run_button(entity, palette)) .children(dismiss), ) } }