1use std::collections::HashMap;
17
18use gpui_kit::component::{h_flex, v_flex};
19use gpui_kit::prelude::FluentBuilder as _;
20use gpui_kit::{
21 Context, EventEmitter, FontWeight, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _,
22 TestSupportExt as _, Window, div, px, relative,
23};
24
25use crate::theme::{self, color};
26use crate::widgets::MenuSelect;
27
28#[derive(Clone, Debug, Default, PartialEq)]
30pub struct Activity {
31 pub start: f64,
33 pub end: f64,
35 pub lane: SharedString,
37 pub kind: SharedString,
39 pub title: SharedString,
41 pub detail: SharedString,
43 pub source: SharedString,
45 pub assets: Vec<SharedString>,
47 pub by: SharedString,
49}
50
51#[derive(Clone, Debug, PartialEq)]
53pub struct Episode {
54 pub start: f64,
56 pub end: f64,
58 pub lane: SharedString,
60 pub kind: SharedString,
62 pub title: SharedString,
64 pub items: Vec<Activity>,
66}
67
68impl Episode {
69 pub fn duration(&self) -> f64 {
71 (self.end - self.start).max(0.0)
72 }
73
74 pub fn intensity(&self) -> f64 {
76 self.items.len() as f64 / (self.duration() / 60.0).max(1.0)
77 }
78
79 fn of(items: Vec<Activity>) -> Episode {
80 let start = items.iter().map(|a| a.start).fold(f64::INFINITY, f64::min);
81 let end = items.iter().map(|a| a.end).fold(f64::NEG_INFINITY, f64::max);
82 let mut by_kind: HashMap<SharedString, f64> = HashMap::new();
84 let mut by_title: HashMap<SharedString, (usize, f64)> = HashMap::new();
85 for a in &items {
86 *by_kind.entry(a.kind.clone()).or_default() += (a.end - a.start).max(1.0);
87 let t = by_title.entry(a.title.clone()).or_default();
88 t.0 += 1;
89 t.1 += (a.end - a.start).max(1.0);
90 }
91 let kind = by_kind.into_iter().max_by(|a, b| a.1.total_cmp(&b.1)).map(|k| k.0).unwrap_or_default();
92 let (title, (n, _)) = by_title.into_iter().max_by(|a, b| (a.1.0, a.1.1).partial_cmp(&(b.1.0, b.1.1)).unwrap_or(std::cmp::Ordering::Equal)).unwrap_or_default();
93 let title = if n > 1 { format!("{title} ×{n}").into() } else { title };
94 Episode { start, end, lane: items.first().map(|a| a.lane.clone()).unwrap_or_default(), kind, title, items }
95 }
96}
97
98pub fn fill_ends(items: &[Activity], idle: f64, now: f64) -> Vec<Activity> {
101 let mut out: Vec<Activity> = items.to_vec();
102 out.sort_by(|a, b| a.start.total_cmp(&b.start));
103 let mut next_in_lane: HashMap<SharedString, f64> = HashMap::new();
104 for a in out.iter_mut().rev() {
105 if a.end <= a.start {
106 let next = next_in_lane.get(&a.lane).copied().unwrap_or(now);
107 a.end = (a.start + idle).min(next).max(a.start + 1.0);
108 }
109 next_in_lane.insert(a.lane.clone(), a.start);
110 }
111 out
112}
113
114pub fn each(items: &[Activity]) -> Vec<Episode> {
116 let mut out: Vec<Episode> = items.iter().map(|a| Episode::of(vec![a.clone()])).collect();
117 out.sort_by(|a, b| a.start.total_cmp(&b.start));
118 out
119}
120
121pub fn episodes(items: &[Activity], target: usize, gap: f64) -> Vec<Episode> {
125 let mut lanes: Vec<SharedString> = Vec::new();
126 for a in items {
127 if !lanes.contains(&a.lane) {
128 lanes.push(a.lane.clone());
129 }
130 }
131 let mut per_lane: Vec<Vec<Vec<Activity>>> = lanes
132 .iter()
133 .map(|lane| {
134 let mut mine: Vec<Activity> = items.iter().filter(|a| &a.lane == lane).cloned().collect();
135 mine.sort_by(|a, b| a.start.total_cmp(&b.start));
136 let mut groups: Vec<Vec<Activity>> = Vec::new();
137 for a in mine {
138 match groups.last_mut() {
139 Some(g) if g.last().is_some_and(|l| l.kind == a.kind && a.start - l.end <= gap) => g.push(a),
140 _ => groups.push(vec![a]),
141 }
142 }
143 groups
144 })
145 .collect();
146 let span = |g: &[Activity]| g.last().map_or(0.0, |l| l.end) - g.first().map_or(0.0, |f| f.start);
147 loop {
148 let count: usize = per_lane.iter().map(Vec::len).sum();
149 if count <= target.max(1) {
150 break;
151 }
152 let mut best: Option<(usize, usize, f64)> = None;
154 for (l, groups) in per_lane.iter().enumerate() {
155 if groups.len() < 2 {
156 continue;
157 }
158 for (i, g) in groups.iter().enumerate() {
159 let s = span(g);
160 if best.is_none_or(|b| s < b.2) {
161 best = Some((l, i, s));
162 }
163 }
164 }
165 let Some((l, i, _)) = best else { break };
166 let groups = &mut per_lane[l];
167 let gap_before = (i > 0).then(|| groups[i][0].start - groups[i - 1].last().map_or(0.0, |a| a.end));
169 let gap_after = (i + 1 < groups.len()).then(|| groups[i + 1][0].start - groups[i].last().map_or(0.0, |a| a.end));
170 let into = match (gap_before, gap_after) {
171 (Some(b), Some(a)) => if b <= a { i - 1 } else { i + 1 },
172 (Some(_), None) => i - 1,
173 _ => i + 1,
174 };
175 let g = groups.remove(i);
176 let into = if into > i { into - 1 } else { into };
177 groups[into].extend(g);
178 groups[into].sort_by(|a, b| a.start.total_cmp(&b.start));
179 }
180 let mut out: Vec<Episode> = per_lane.into_iter().flatten().map(Episode::of).collect();
181 out.sort_by(|a, b| a.start.total_cmp(&b.start));
182 out
183}
184
185const KIND_HUES: [u32; 10] = [0x5b8def, 0xf2b134, 0x2fb67c, 0xd9479b, 0x1fb5c9, 0x8b6cf0, 0xef6f4a, 0x8a96a8, 0x9bc53d, 0xc98bdb];
188
189pub fn clock(t: f64) -> String {
191 jiff::Timestamp::from_millisecond((t * 1000.0) as i64)
192 .map(|ts| ts.to_zoned_datetime(jiff::tz::TimeZone::system()).strftime("%H:%M").to_string())
193 .unwrap_or_default()
194}
195
196pub fn duration(s: f64) -> String {
198 let s = s.max(0.0).round() as u64;
199 match s {
200 0..60 => format!("{s} s"),
201 60..3600 => format!("{} min", s / 60),
202 _ => format!("{} h {:02}", s / 3600, (s % 3600) / 60),
203 }
204}
205
206fn tick_step(span: f64) -> f64 {
208 const STEPS: [f64; 12] = [10.0, 30.0, 60.0, 120.0, 300.0, 600.0, 900.0, 1800.0, 3600.0, 7200.0, 10800.0, 21600.0];
209 STEPS.into_iter().find(|s| span / s <= 7.0).unwrap_or(43200.0)
210}
211
212#[derive(Clone, Debug, PartialEq)]
214pub enum TimelineEvent {
215 Selected(Option<usize>),
217}
218
219pub struct Timeline {
221 title: SharedString,
222 activities: Vec<Activity>,
223 shown: Vec<Episode>,
224 summary: bool,
225 target: usize,
226 gap: f64,
227 idle: f64,
228 hovered: Option<usize>,
229 selected: Option<usize>,
230 colors: HashMap<SharedString, Hsla>,
231}
232
233impl EventEmitter<TimelineEvent> for Timeline {}
234
235impl Timeline {
236 pub fn new(title: impl Into<SharedString>) -> Self {
238 Self { title: title.into(), activities: Vec::new(), shown: Vec::new(), summary: true, target: 8, gap: 120.0, idle: 300.0, hovered: None, selected: None, colors: HashMap::new() }
239 }
240
241 pub fn set_activities(&mut self, items: Vec<Activity>, now: f64, cx: &mut Context<Self>) {
244 let keep = self.selected.and_then(|i| self.shown.get(i)).map(|e| (e.lane.clone(), e.start));
245 self.activities = fill_ends(&items, self.idle, now);
246 self.rebuild();
247 self.selected = keep.and_then(|(lane, start)| self.shown.iter().position(|e| e.lane == lane && e.start == start));
248 cx.notify();
249 }
250
251 pub fn set_summary(&mut self, summary: bool, cx: &mut Context<Self>) {
253 self.summary = summary;
254 self.selected = None;
255 self.hovered = None;
256 self.rebuild();
257 cx.notify();
258 }
259
260 pub fn set_target(&mut self, target: usize, cx: &mut Context<Self>) {
262 self.target = target.max(1);
263 self.rebuild();
264 cx.notify();
265 }
266
267 pub fn shown(&self) -> &[Episode] {
269 &self.shown
270 }
271
272 pub fn activities(&self) -> &[Activity] {
274 &self.activities
275 }
276
277 pub fn selected(&self) -> Option<&Episode> {
279 self.selected.and_then(|i| self.shown.get(i))
280 }
281
282 pub fn select(&mut self, index: Option<usize>, cx: &mut Context<Self>) {
284 self.selected = index.filter(|i| *i < self.shown.len());
285 cx.emit(TimelineEvent::Selected(self.selected));
286 cx.notify();
287 }
288
289 fn rebuild(&mut self) {
290 self.shown = if self.summary { episodes(&self.activities, self.target, self.gap) } else { each(&self.activities) };
291 for a in &self.activities {
292 if !self.colors.contains_key(&a.kind) {
293 let hue = KIND_HUES[self.colors.len() % KIND_HUES.len()];
294 self.colors.insert(a.kind.clone(), theme::rgb_hsla(hue));
295 }
296 }
297 }
298
299 fn color(&self, kind: &SharedString) -> Hsla {
300 self.colors.get(kind).copied().unwrap_or_else(color::text_muted)
301 }
302
303 fn lanes(&self) -> Vec<SharedString> {
304 let mut out: Vec<SharedString> = Vec::new();
305 for a in &self.activities {
306 if !out.contains(&a.lane) {
307 out.push(a.lane.clone());
308 }
309 }
310 out
311 }
312
313 fn range(&self) -> (f64, f64) {
314 let start = self.activities.iter().map(|a| a.start).fold(f64::INFINITY, f64::min);
315 let end = self.activities.iter().map(|a| a.end).fold(f64::NEG_INFINITY, f64::max);
316 if start.is_finite() && end > start { (start, end) } else { (0.0, 1.0) }
317 }
318
319 fn context_cards(&self, e: &Episode) -> impl IntoElement {
320 let dot = self.color(&e.kind);
321 let head = h_flex()
322 .gap(px(theme::SM))
323 .items_center()
324 .child(div().size(px(10.)).rounded_full().bg(dot))
325 .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(e.title.clone()))
326 .child(div().text_xs().text_color(color::text_muted()).child(format!("{} · {} · {} – {} · {}", e.lane, e.kind, clock(e.start), clock(e.end), duration(e.duration()))));
327 let cards = e.items.iter().enumerate().map(|(i, a)| {
328 v_flex()
329 .id(SharedString::from(format!("timeline-card-{i}")))
330 .w(px(260.))
331 .flex_none()
332 .gap(px(theme::XS))
333 .p(px(theme::SM))
334 .rounded(px(theme::RADIUS))
335 .border_1()
336 .border_color(color::border())
337 .bg(color::raised())
338 .child(h_flex().gap(px(theme::XS)).items_center().child(div().size(px(8.)).rounded_full().bg(self.color(&a.kind))).child(div().flex_1().min_w_0().truncate().text_sm().font_weight(FontWeight::SEMIBOLD).child(a.title.clone())).child(div().text_xs().text_color(color::text_muted()).child(clock(a.start))))
339 .when(!a.source.is_empty(), |d| d.child(div().text_xs().text_color(color::text_muted()).child(format!("From {}", a.source))))
340 .when(!a.by.is_empty(), |d| d.child(div().text_xs().text_color(color::text_muted()).child(format!("For {}", a.by))))
341 .when(!a.detail.is_empty(), |d| d.child(div().text_xs().font_family("monospace").text_color(color::text_muted()).line_clamp(3).child(a.detail.clone())))
342 .when(!a.assets.is_empty(), |d| {
343 d.child(h_flex().flex_wrap().gap(px(theme::XS)).children(a.assets.iter().map(|s| div().px(px(theme::XS)).rounded(px(theme::RADIUS_SM)).bg(color::control()).text_xs().truncate().max_w(px(240.)).child(s.clone()))))
344 })
345 });
346 v_flex().gap(px(theme::SM)).child(head).child(h_flex().id("timeline-cards").gap(px(theme::SM)).overflow_x_scroll().pb(px(theme::XS)).children(cards))
347 }
348}
349
350const LANE_H: f32 = 64.;
352const LANE_LABEL_W: f32 = 72.;
354
355impl Render for Timeline {
356 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
357 let (t0, t1) = self.range();
358 let span = (t1 - t0).max(1.0);
359 let x = move |t: f64| ((t - t0) / span).clamp(0.0, 1.0) as f32;
360 let busiest = self.shown.iter().map(Episode::intensity).fold(0.0f64, f64::max).max(1e-9);
361 let header = h_flex()
362 .gap(px(theme::MD))
363 .items_center()
364 .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(self.title.clone()))
365 .child(div().flex_1().text_xs().text_color(color::text_muted()).child(if self.activities.is_empty() {
366 "Nothing yet: what you and the agent do shows here".to_string()
367 } else {
368 format!("{} episodes from {} actions · {} – {}", self.shown.len(), self.activities.len(), clock(t0), clock(t1))
369 }))
370 .child(div().w(px(150.)).child({
371 let me = cx.entity().downgrade();
372 MenuSelect::new("timeline-detail", vec!["Summary".into(), "Every action".into()], Some(if self.summary { 0 } else { 1 }), move |i, _, cx| {
373 let _ = me.update(cx, |t, cx| t.set_summary(i == 0, cx));
374 })
375 }));
376 let lanes = self.lanes().into_iter().map(|lane| {
377 let bars = self.shown.iter().enumerate().filter(|(_, e)| e.lane == lane).map(|(i, e)| {
378 let (left, width) = (x(e.start), (x(e.end) - x(e.start)).max(0.002));
379 let h = 0.35 + 0.65 * (e.intensity() / busiest).sqrt() as f32;
381 let (hovered, selected) = (self.hovered == Some(i), self.selected == Some(i));
382 let fill = self.color(&e.kind);
383 let label = (width > 0.07).then(|| {
384 div().absolute().left(relative(left)).w(relative(width)).top_0().px(px(2.)).truncate().text_xs().text_color(fill).child(e.title.clone())
385 });
386 let bar = div()
387 .id(SharedString::from(format!("timeline-bar-{i}")))
388 .absolute()
389 .left(relative(left))
390 .w(relative(width))
391 .bottom_0()
392 .h(px((LANE_H - 18.) * h))
393 .rounded(px(2.))
394 .bg(if hovered || selected { fill } else { fill.opacity(0.85) })
395 .when(selected, |d| d.border_2().border_color(color::text()))
396 .cursor_pointer()
397 .on_hover(cx.listener(move |t, on: &bool, _, cx| {
398 t.hovered = if *on { Some(i) } else if t.hovered == Some(i) { None } else { t.hovered };
399 cx.notify();
400 }))
401 .on_click(cx.listener(move |t, _, _, cx| {
402 let next = if t.selected == Some(i) { None } else { Some(i) };
403 t.select(next, cx);
404 }))
405 .test_support();
406 [label.map(|l| l.into_any_element()), Some(bar.into_any_element())]
407 });
408 h_flex()
409 .h(px(LANE_H))
410 .items_end()
411 .child(div().w(px(LANE_LABEL_W)).flex_none().pb(px(theme::XS)).text_xs().text_color(color::text_muted()).child(lane.clone()))
412 .child(div().relative().flex_1().h_full().border_b_1().border_color(color::border()).children(bars.flatten().flatten()))
413 });
414 let step = tick_step(span);
416 let first = (t0 / step).ceil() * step;
417 let ticks = (0..12).map(|k| first + k as f64 * step).take_while(|t| *t <= t1).map(|t| {
418 div().absolute().left(relative(x(t))).top_0().pl(px(2.)).border_l_1().border_color(color::border()).text_xs().text_color(color::text_muted()).child(clock(t))
419 });
420 let axis = h_flex().h(px(18.)).child(div().w(px(LANE_LABEL_W)).flex_none()).child(div().relative().flex_1().h_full().children(ticks));
421 let hover = self.hovered.and_then(|i| self.shown.get(i)).map(|e| {
423 let left = x(e.start).min(0.75);
424 h_flex().h(px(0.)).child(div().w(px(LANE_LABEL_W)).flex_none()).child(
425 div().relative().flex_1().child(
426 v_flex()
427 .absolute()
428 .left(relative(left))
429 .top(px(theme::XS))
430 .w(px(260.))
431 .gap(px(2.))
432 .p(px(theme::SM))
433 .rounded(px(theme::RADIUS))
434 .border_1()
435 .border_color(color::border())
436 .bg(color::raised())
437 .shadow_lg()
438 .child(h_flex().gap(px(theme::XS)).items_center().child(div().size(px(8.)).rounded_full().bg(self.color(&e.kind))).child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(e.kind.clone())).child(div().text_xs().text_color(color::text_muted()).child(format!("{} · {}", clock(e.start), duration(e.duration())))))
439 .child(div().text_sm().truncate().child(e.title.clone()))
440 .child(div().text_xs().text_color(color::text_muted()).child(format!("{} action{} · {}", e.items.len(), if e.items.len() == 1 { "" } else { "s" }, e.lane)))
441 .children(e.items.first().filter(|a| !a.detail.is_empty()).map(|a| div().text_xs().font_family("monospace").text_color(color::text_muted()).line_clamp(2).child(a.detail.clone()))),
442 ),
443 )
444 });
445 let context = self.selected.and_then(|i| self.shown.get(i)).map(|e| self.context_cards(e));
446 v_flex()
447 .id("timeline")
448 .size_full()
449 .gap(px(theme::SM))
450 .p(px(theme::MD))
451 .overflow_y_scroll()
452 .child(header)
453 .child(v_flex().children(lanes).child(axis).children(hover))
454 .children(context)
455 .when(self.selected.is_none() && !self.shown.is_empty(), |d| d.child(div().pt(px(theme::LG)).text_xs().text_color(color::text_muted()).child("Click a bar to see what was done in it, where it came from and what it produced.")))
456 }
457}
458
459#[cfg(test)]
460mod tests {
461 use super::*;
462
463 fn act(start: f64, lane: &str, kind: &str, title: &str) -> Activity {
464 Activity { start, end: start, lane: lane.into(), kind: kind.into(), title: title.into(), ..Default::default() }
465 }
466
467 #[test]
469 fn instants_last_until_the_next_one() {
470 let filled = fill_ends(&[act(0.0, "You", "A", "a"), act(60.0, "You", "B", "b"), act(10.0, "Agent", "C", "c")], 300.0, 1000.0);
471 let end = |t: &str| filled.iter().find(|a| a.title == t).unwrap().end;
472 assert_eq!(end("a"), 60.0);
473 assert_eq!(end("b"), 360.0, "the idle limit");
474 assert_eq!(end("c"), 310.0, "lanes are apart");
475 }
476
477 #[test]
479 fn many_actions_become_a_few_episodes() {
480 let mut items = Vec::new();
481 let kinds = ["Research", "Draft", "Research", "Chat", "Draft"];
482 for k in 0..50 {
483 let kind = kinds[(k / 10) % kinds.len()];
484 let kind = if k % 7 == 3 { "System" } else { kind };
486 items.push(act(k as f64 * 30.0, "You", kind, &format!("step {}", k % 4)));
487 }
488 let items = fill_ends(&items, 300.0, 1500.0);
489 let raw = each(&items);
490 assert_eq!(raw.len(), 50);
491 let eps = episodes(&items, 7, 120.0);
492 assert!(eps.len() <= 7, "{} episodes", eps.len());
493 assert_eq!(eps.iter().map(|e| e.items.len()).sum::<usize>(), 50, "nothing lost");
494 assert!(eps.windows(2).all(|w| w[0].start <= w[1].start));
495 assert!(eps.iter().any(|e| e.kind == "Research") && eps.iter().any(|e| e.kind == "Draft"));
496 }
497
498 #[test]
499 fn durations_and_ticks_read_well() {
500 assert_eq!(duration(45.0), "45 s");
501 assert_eq!(duration(26.0 * 60.0), "26 min");
502 assert_eq!(duration(3900.0), "1 h 05");
503 assert_eq!(tick_step(3.0 * 3600.0), 1800.0);
504 assert_eq!(tick_step(600.0), 120.0);
505 }
506}