Skip to main content

kitchen_ui/
timeline.rs

1//! An episodic memory of the work: what the person and the agent did, over time, as a story one
2//! can read back (after Scott Jenson's "Episodic Memory" prototype). It shows attention, not
3//! content: which kind of work, when, for how long and how busily.
4//!
5//! - **Input**: [`Activity`]: one thing that happened (a command run, time in a workspace, a job),
6//!   its lane (who or what: you, the agent, jobs), its kind (the colour), what it was, where it
7//!   came from (its provenance: the workspace, how it was started) and what it produced (assets).
8//! - **Synthesis**: [`episodes`] turns many activities into a few episodes: neighbours of the same
9//!   kind merge, then the shortest episodes fold into their neighbours until a handful is left
10//!   (50 browser visits become "Research").
11//! - **View**: [`Timeline`]: one row per lane, a bar per episode (its width the time, its height
12//!   how busy it was, its colour its kind), the hours under it, a card on hover, and, for the
13//!   episode clicked, context cards below: each thing done in it, where it came from and what it
14//!   produced. Summary shows the episodes, All every activity.
15
16use 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,
22    SharedString, StatefulInteractiveElement as _, Styled as _, TestSupportExt as _, Window, div, px, relative,
23};
24
25use crate::theme::{self, color};
26use crate::widgets::MenuSelect;
27
28/// One thing that happened.
29#[derive(Clone, Debug, Default, PartialEq)]
30pub struct Activity {
31    /// When it started (seconds since 1970, UTC).
32    pub start: f64,
33    /// When it ended (the same as `start` for an instant: it then lasts until the next one).
34    pub end: f64,
35    /// Who or what did it: its row ("You", "Agent", "Jobs", "Focus").
36    pub lane: SharedString,
37    /// Its kind: the colour and the episode it joins ("Analyze", "Pipeline", "histology").
38    pub kind: SharedString,
39    /// What it was ("Find cells").
40    pub title: SharedString,
41    /// A short line about it (its arguments, its result).
42    pub detail: SharedString,
43    /// Where it came from: its provenance ("Explore · menu", "agent · lumen MCP").
44    pub source: SharedString,
45    /// What it produced or used (files, ids).
46    pub assets: Vec<SharedString>,
47    /// The person it was done for, by name ("" when unknown, `guest` for no one named).
48    pub by: SharedString,
49}
50
51/// Several activities read as one: a stretch of one kind of work.
52#[derive(Clone, Debug, PartialEq)]
53pub struct Episode {
54    /// When it started (seconds since 1970).
55    pub start: f64,
56    /// When it ended.
57    pub end: f64,
58    /// Its row.
59    pub lane: SharedString,
60    /// Its kind (the colour).
61    pub kind: SharedString,
62    /// What it was mostly ("Find cells ×3").
63    pub title: SharedString,
64    /// The activities in it, in time order.
65    pub items: Vec<Activity>,
66}
67
68impl Episode {
69    /// How long it lasted (s).
70    pub fn duration(&self) -> f64 {
71        (self.end - self.start).max(0.0)
72    }
73
74    /// How busy it was: activities per minute.
75    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        // The kind and the title that cover the most time
83        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
93            .into_iter()
94            .max_by(|a, b| (a.1.0, a.1.1).partial_cmp(&(b.1.0, b.1.1)).unwrap_or(std::cmp::Ordering::Equal))
95            .unwrap_or_default();
96        let title = if n > 1 { format!("{title} ×{n}").into() } else { title };
97        Episode { start, end, lane: items.first().map(|a| a.lane.clone()).unwrap_or_default(), kind, title, items }
98    }
99}
100
101/// The activities with their ends filled in: an instant lasts until the next activity in its lane,
102/// at most `idle` seconds (then the person was away), and at least one second.
103pub fn fill_ends(items: &[Activity], idle: f64, now: f64) -> Vec<Activity> {
104    let mut out: Vec<Activity> = items.to_vec();
105    out.sort_by(|a, b| a.start.total_cmp(&b.start));
106    let mut next_in_lane: HashMap<SharedString, f64> = HashMap::new();
107    for a in out.iter_mut().rev() {
108        if a.end <= a.start {
109            let next = next_in_lane.get(&a.lane).copied().unwrap_or(now);
110            a.end = (a.start + idle).min(next).max(a.start + 1.0);
111        }
112        next_in_lane.insert(a.lane.clone(), a.start);
113    }
114    out
115}
116
117/// Every activity as an episode of its own (the "All" view).
118pub fn each(items: &[Activity]) -> Vec<Episode> {
119    let mut out: Vec<Episode> = items.iter().map(|a| Episode::of(vec![a.clone()])).collect();
120    out.sort_by(|a, b| a.start.total_cmp(&b.start));
121    out
122}
123
124/// The story in a few episodes: per lane, neighbours of the same kind less than `gap` seconds
125/// apart merge; then, while there are more than `target` episodes, the shortest one folds into
126/// the neighbour in its lane it is closer to (in time), until `target` are left or nothing can merge.
127pub fn episodes(items: &[Activity], target: usize, gap: f64) -> Vec<Episode> {
128    let mut lanes: Vec<SharedString> = Vec::new();
129    for a in items {
130        if !lanes.contains(&a.lane) {
131            lanes.push(a.lane.clone());
132        }
133    }
134    let mut per_lane: Vec<Vec<Vec<Activity>>> = lanes
135        .iter()
136        .map(|lane| {
137            let mut mine: Vec<Activity> = items.iter().filter(|a| &a.lane == lane).cloned().collect();
138            mine.sort_by(|a, b| a.start.total_cmp(&b.start));
139            let mut groups: Vec<Vec<Activity>> = Vec::new();
140            for a in mine {
141                match groups.last_mut() {
142                    Some(g) if g.last().is_some_and(|l| l.kind == a.kind && a.start - l.end <= gap) => g.push(a),
143                    _ => groups.push(vec![a]),
144                }
145            }
146            groups
147        })
148        .collect();
149    let span = |g: &[Activity]| g.last().map_or(0.0, |l| l.end) - g.first().map_or(0.0, |f| f.start);
150    loop {
151        let count: usize = per_lane.iter().map(Vec::len).sum();
152        if count <= target.max(1) {
153            break;
154        }
155        // The shortest episode that has a neighbour in its lane
156        let mut best: Option<(usize, usize, f64)> = None;
157        for (l, groups) in per_lane.iter().enumerate() {
158            if groups.len() < 2 {
159                continue;
160            }
161            for (i, g) in groups.iter().enumerate() {
162                let s = span(g);
163                if best.is_none_or(|b| s < b.2) {
164                    best = Some((l, i, s));
165                }
166            }
167        }
168        let Some((l, i, _)) = best else { break };
169        let groups = &mut per_lane[l];
170        // Into the neighbour closer in time
171        let gap_before = (i > 0).then(|| groups[i][0].start - groups[i - 1].last().map_or(0.0, |a| a.end));
172        let gap_after =
173            (i + 1 < groups.len()).then(|| groups[i + 1][0].start - groups[i].last().map_or(0.0, |a| a.end));
174        let into = match (gap_before, gap_after) {
175            (Some(b), Some(a)) => {
176                if b <= a {
177                    i - 1
178                } else {
179                    i + 1
180                }
181            }
182            (Some(_), None) => i - 1,
183            _ => i + 1,
184        };
185        let g = groups.remove(i);
186        let into = if into > i { into - 1 } else { into };
187        groups[into].extend(g);
188        groups[into].sort_by(|a, b| a.start.total_cmp(&b.start));
189    }
190    let mut out: Vec<Episode> = per_lane.into_iter().flatten().map(Episode::of).collect();
191    out.sort_by(|a, b| a.start.total_cmp(&b.start));
192    out
193}
194
195/// The colours of the kinds: a set of hues readable on both themes, given out in order of first
196/// appearance so a kind keeps its colour while the view lives.
197const KIND_HUES: [u32; 10] =
198    [0x5b8def, 0xf2b134, 0x2fb67c, 0xd9479b, 0x1fb5c9, 0x8b6cf0, 0xef6f4a, 0x8a96a8, 0x9bc53d, 0xc98bdb];
199
200/// The time of day of `t` (seconds since 1970) in the local time zone: "09:19".
201pub fn clock(t: f64) -> String {
202    jiff::Timestamp::from_millisecond((t * 1000.0) as i64)
203        .map(|ts| ts.to_zoned_datetime(jiff::tz::TimeZone::system()).strftime("%H:%M").to_string())
204        .unwrap_or_default()
205}
206
207/// A duration as people say it: "45 s", "26 min", "1 h 05".
208pub fn duration(s: f64) -> String {
209    let s = s.max(0.0).round() as u64;
210    match s {
211        0..60 => format!("{s} s"),
212        60..3600 => format!("{} min", s / 60),
213        _ => format!("{} h {:02}", s / 3600, (s % 3600) / 60),
214    }
215}
216
217/// A tick step for a span of `span` seconds: about six ticks, on round times.
218fn tick_step(span: f64) -> f64 {
219    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];
220    STEPS.into_iter().find(|s| span / s <= 7.0).unwrap_or(43200.0)
221}
222
223/// What the timeline tells the app.
224#[derive(Clone, Debug, PartialEq)]
225pub enum TimelineEvent {
226    /// An episode was clicked (its index in [`Timeline::shown`]), or the selection cleared.
227    Selected(Option<usize>),
228}
229
230/// The view.
231pub struct Timeline {
232    title: SharedString,
233    activities: Vec<Activity>,
234    shown: Vec<Episode>,
235    summary: bool,
236    target: usize,
237    gap: f64,
238    idle: f64,
239    hovered: Option<usize>,
240    selected: Option<usize>,
241    colors: HashMap<SharedString, Hsla>,
242}
243
244impl EventEmitter<TimelineEvent> for Timeline {}
245
246impl Timeline {
247    /// An empty timeline titled `title`, summarising to about eight episodes.
248    pub fn new(title: impl Into<SharedString>) -> Self {
249        Self {
250            title: title.into(),
251            activities: Vec::new(),
252            shown: Vec::new(),
253            summary: true,
254            target: 8,
255            gap: 120.0,
256            idle: 300.0,
257            hovered: None,
258            selected: None,
259            colors: HashMap::new(),
260        }
261    }
262
263    /// Sets what happened (instants last until the next activity in their lane, at most five
264    /// minutes) and draws it again; the selection is kept when its episode still starts the same.
265    pub fn set_activities(&mut self, items: Vec<Activity>, now: f64, cx: &mut Context<Self>) {
266        let keep = self.selected.and_then(|i| self.shown.get(i)).map(|e| (e.lane.clone(), e.start));
267        self.activities = fill_ends(&items, self.idle, now);
268        self.rebuild();
269        self.selected =
270            keep.and_then(|(lane, start)| self.shown.iter().position(|e| e.lane == lane && e.start == start));
271        cx.notify();
272    }
273
274    /// Shows the episodes (`true`) or every activity.
275    pub fn set_summary(&mut self, summary: bool, cx: &mut Context<Self>) {
276        self.summary = summary;
277        self.selected = None;
278        self.hovered = None;
279        self.rebuild();
280        cx.notify();
281    }
282
283    /// How many episodes the summary aims at.
284    pub fn set_target(&mut self, target: usize, cx: &mut Context<Self>) {
285        self.target = target.max(1);
286        self.rebuild();
287        cx.notify();
288    }
289
290    /// The episodes shown.
291    pub fn shown(&self) -> &[Episode] {
292        &self.shown
293    }
294
295    /// Every activity.
296    pub fn activities(&self) -> &[Activity] {
297        &self.activities
298    }
299
300    /// The episode clicked.
301    pub fn selected(&self) -> Option<&Episode> {
302        self.selected.and_then(|i| self.shown.get(i))
303    }
304
305    /// Selects the episode `index` (`None`: none), as a click does.
306    pub fn select(&mut self, index: Option<usize>, cx: &mut Context<Self>) {
307        self.selected = index.filter(|i| *i < self.shown.len());
308        cx.emit(TimelineEvent::Selected(self.selected));
309        cx.notify();
310    }
311
312    fn rebuild(&mut self) {
313        self.shown =
314            if self.summary { episodes(&self.activities, self.target, self.gap) } else { each(&self.activities) };
315        for a in &self.activities {
316            if !self.colors.contains_key(&a.kind) {
317                let hue = KIND_HUES[self.colors.len() % KIND_HUES.len()];
318                self.colors.insert(a.kind.clone(), theme::rgb_hsla(hue));
319            }
320        }
321    }
322
323    fn color(&self, kind: &SharedString) -> Hsla {
324        self.colors.get(kind).copied().unwrap_or_else(color::text_muted)
325    }
326
327    fn lanes(&self) -> Vec<SharedString> {
328        let mut out: Vec<SharedString> = Vec::new();
329        for a in &self.activities {
330            if !out.contains(&a.lane) {
331                out.push(a.lane.clone());
332            }
333        }
334        out
335    }
336
337    fn range(&self) -> (f64, f64) {
338        let start = self.activities.iter().map(|a| a.start).fold(f64::INFINITY, f64::min);
339        let end = self.activities.iter().map(|a| a.end).fold(f64::NEG_INFINITY, f64::max);
340        if start.is_finite() && end > start { (start, end) } else { (0.0, 1.0) }
341    }
342
343    fn context_cards(&self, e: &Episode) -> impl IntoElement {
344        let dot = self.color(&e.kind);
345        let head = h_flex()
346            .gap(px(theme::SM))
347            .items_center()
348            .child(div().size(px(10.)).rounded_full().bg(dot))
349            .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(e.title.clone()))
350            .child(div().text_xs().text_color(color::text_muted()).child(format!(
351                "{} · {} · {} – {} · {}",
352                e.lane,
353                e.kind,
354                clock(e.start),
355                clock(e.end),
356                duration(e.duration())
357            )));
358        let cards = e.items.iter().enumerate().map(|(i, a)| {
359            v_flex()
360                .id(SharedString::from(format!("timeline-card-{i}")))
361                .w(px(260.))
362                .flex_none()
363                .gap(px(theme::XS))
364                .p(px(theme::SM))
365                .rounded(px(theme::RADIUS))
366                .border_1()
367                .border_color(color::border())
368                .bg(color::raised())
369                .child(
370                    h_flex()
371                        .gap(px(theme::XS))
372                        .items_center()
373                        .child(div().size(px(8.)).rounded_full().bg(self.color(&a.kind)))
374                        .child(
375                            div()
376                                .flex_1()
377                                .min_w_0()
378                                .truncate()
379                                .text_sm()
380                                .font_weight(FontWeight::SEMIBOLD)
381                                .child(a.title.clone()),
382                        )
383                        .child(div().text_xs().text_color(color::text_muted()).child(clock(a.start))),
384                )
385                .when(!a.source.is_empty(), |d| {
386                    d.child(div().text_xs().text_color(color::text_muted()).child(format!("From {}", a.source)))
387                })
388                .when(!a.by.is_empty(), |d| {
389                    d.child(div().text_xs().text_color(color::text_muted()).child(format!("For {}", a.by)))
390                })
391                .when(!a.detail.is_empty(), |d| {
392                    d.child(
393                        div()
394                            .text_xs()
395                            .font_family("monospace")
396                            .text_color(color::text_muted())
397                            .line_clamp(3)
398                            .child(a.detail.clone()),
399                    )
400                })
401                .when(!a.assets.is_empty(), |d| {
402                    d.child(h_flex().flex_wrap().gap(px(theme::XS)).children(a.assets.iter().map(|s| {
403                        div()
404                            .px(px(theme::XS))
405                            .rounded(px(theme::RADIUS_SM))
406                            .bg(color::control())
407                            .text_xs()
408                            .truncate()
409                            .max_w(px(240.))
410                            .child(s.clone())
411                    })))
412                })
413        });
414        v_flex().gap(px(theme::SM)).child(head).child(
415            h_flex().id("timeline-cards").gap(px(theme::SM)).overflow_x_scroll().pb(px(theme::XS)).children(cards),
416        )
417    }
418}
419
420/// Height of a lane (px): the tallest bar and its label.
421const LANE_H: f32 = 64.;
422/// Width of the lane names (px).
423const LANE_LABEL_W: f32 = 72.;
424
425impl Render for Timeline {
426    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
427        let (t0, t1) = self.range();
428        let span = (t1 - t0).max(1.0);
429        let x = move |t: f64| ((t - t0) / span).clamp(0.0, 1.0) as f32;
430        let busiest = self.shown.iter().map(Episode::intensity).fold(0.0f64, f64::max).max(1e-9);
431        let header = h_flex()
432            .gap(px(theme::MD))
433            .items_center()
434            .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(self.title.clone()))
435            .child(div().flex_1().text_xs().text_color(color::text_muted()).child(if self.activities.is_empty() {
436                "Nothing yet: what you and the agent do shows here".to_string()
437            } else {
438                format!(
439                    "{} episodes from {} actions · {} – {}",
440                    self.shown.len(),
441                    self.activities.len(),
442                    clock(t0),
443                    clock(t1)
444                )
445            }))
446            .child(div().w(px(150.)).child({
447                let me = cx.entity().downgrade();
448                MenuSelect::new(
449                    "timeline-detail",
450                    vec!["Summary".into(), "Every action".into()],
451                    Some(if self.summary { 0 } else { 1 }),
452                    move |i, _, cx| {
453                        let _ = me.update(cx, |t, cx| t.set_summary(i == 0, cx));
454                    },
455                )
456            }));
457        let lanes = self.lanes().into_iter().map(|lane| {
458            let bars = self.shown.iter().enumerate().filter(|(_, e)| e.lane == lane).map(|(i, e)| {
459                let (left, width) = (x(e.start), (x(e.end) - x(e.start)).max(0.002));
460                // Height: how busy it was (at least a third, so a quiet stretch still reads)
461                let h = 0.35 + 0.65 * (e.intensity() / busiest).sqrt() as f32;
462                let (hovered, selected) = (self.hovered == Some(i), self.selected == Some(i));
463                let fill = self.color(&e.kind);
464                let label = (width > 0.07).then(|| {
465                    div()
466                        .absolute()
467                        .left(relative(left))
468                        .w(relative(width))
469                        .top_0()
470                        .px(px(2.))
471                        .truncate()
472                        .text_xs()
473                        .text_color(fill)
474                        .child(e.title.clone())
475                });
476                let bar = div()
477                    .id(SharedString::from(format!("timeline-bar-{i}")))
478                    .absolute()
479                    .left(relative(left))
480                    .w(relative(width))
481                    .bottom_0()
482                    .h(px((LANE_H - 18.) * h))
483                    .rounded(px(2.))
484                    .bg(if hovered || selected { fill } else { fill.opacity(0.85) })
485                    .when(selected, |d| d.border_2().border_color(color::text()))
486                    .cursor_pointer()
487                    .on_hover(cx.listener(move |t, on: &bool, _, cx| {
488                        t.hovered = if *on {
489                            Some(i)
490                        } else if t.hovered == Some(i) {
491                            None
492                        } else {
493                            t.hovered
494                        };
495                        cx.notify();
496                    }))
497                    .on_click(cx.listener(move |t, _, _, cx| {
498                        let next = if t.selected == Some(i) { None } else { Some(i) };
499                        t.select(next, cx);
500                    }))
501                    .test_support();
502                [label.map(|l| l.into_any_element()), Some(bar.into_any_element())]
503            });
504            h_flex()
505                .h(px(LANE_H))
506                .items_end()
507                .child(
508                    div()
509                        .w(px(LANE_LABEL_W))
510                        .flex_none()
511                        .pb(px(theme::XS))
512                        .text_xs()
513                        .text_color(color::text_muted())
514                        .child(lane.clone()),
515                )
516                .child(
517                    div()
518                        .relative()
519                        .flex_1()
520                        .h_full()
521                        .border_b_1()
522                        .border_color(color::border())
523                        .children(bars.flatten().flatten()),
524                )
525        });
526        // The hours (or minutes) under the bars
527        let step = tick_step(span);
528        let first = (t0 / step).ceil() * step;
529        let ticks = (0..12).map(|k| first + k as f64 * step).take_while(|t| *t <= t1).map(|t| {
530            div()
531                .absolute()
532                .left(relative(x(t)))
533                .top_0()
534                .pl(px(2.))
535                .border_l_1()
536                .border_color(color::border())
537                .text_xs()
538                .text_color(color::text_muted())
539                .child(clock(t))
540        });
541        let axis = h_flex()
542            .h(px(18.))
543            .child(div().w(px(LANE_LABEL_W)).flex_none())
544            .child(div().relative().flex_1().h_full().children(ticks));
545        // The card of the episode under the pointer
546        let hover = self.hovered.and_then(|i| self.shown.get(i)).map(|e| {
547            let left = x(e.start).min(0.75);
548            h_flex().h(px(0.)).child(div().w(px(LANE_LABEL_W)).flex_none()).child(
549                div().relative().flex_1().child(
550                    v_flex()
551                        .absolute()
552                        .left(relative(left))
553                        .top(px(theme::XS))
554                        .w(px(260.))
555                        .gap(px(2.))
556                        .p(px(theme::SM))
557                        .rounded(px(theme::RADIUS))
558                        .border_1()
559                        .border_color(color::border())
560                        .bg(color::raised())
561                        .shadow_lg()
562                        .child(
563                            h_flex()
564                                .gap(px(theme::XS))
565                                .items_center()
566                                .child(div().size(px(8.)).rounded_full().bg(self.color(&e.kind)))
567                                .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(e.kind.clone()))
568                                .child(div().text_xs().text_color(color::text_muted()).child(format!(
569                                    "{} · {}",
570                                    clock(e.start),
571                                    duration(e.duration())
572                                ))),
573                        )
574                        .child(div().text_sm().truncate().child(e.title.clone()))
575                        .child(div().text_xs().text_color(color::text_muted()).child(format!(
576                            "{} action{} · {}",
577                            e.items.len(),
578                            if e.items.len() == 1 { "" } else { "s" },
579                            e.lane
580                        )))
581                        .children(e.items.first().filter(|a| !a.detail.is_empty()).map(|a| {
582                            div()
583                                .text_xs()
584                                .font_family("monospace")
585                                .text_color(color::text_muted())
586                                .line_clamp(2)
587                                .child(a.detail.clone())
588                        })),
589                ),
590            )
591        });
592        let context = self.selected.and_then(|i| self.shown.get(i)).map(|e| self.context_cards(e));
593        v_flex()
594            .id("timeline")
595            .size_full()
596            .gap(px(theme::SM))
597            .p(px(theme::MD))
598            .overflow_y_scroll()
599            .child(header)
600            .child(v_flex().children(lanes).child(axis).children(hover))
601            .children(context)
602            .when(self.selected.is_none() && !self.shown.is_empty(), |d| {
603                d.child(
604                    div()
605                        .pt(px(theme::LG))
606                        .text_xs()
607                        .text_color(color::text_muted())
608                        .child("Click a bar to see what was done in it, where it came from and what it produced."),
609                )
610            })
611    }
612}
613
614#[cfg(test)]
615mod tests {
616    use super::*;
617
618    fn act(start: f64, lane: &str, kind: &str, title: &str) -> Activity {
619        Activity { start, end: start, lane: lane.into(), kind: kind.into(), title: title.into(), ..Default::default() }
620    }
621
622    /// Instants last until the next activity in their lane, and never past the idle limit.
623    #[test]
624    fn instants_last_until_the_next_one() {
625        let filled = fill_ends(
626            &[act(0.0, "You", "A", "a"), act(60.0, "You", "B", "b"), act(10.0, "Agent", "C", "c")],
627            300.0,
628            1000.0,
629        );
630        let end = |t: &str| filled.iter().find(|a| a.title == t).unwrap().end;
631        assert_eq!(end("a"), 60.0);
632        assert_eq!(end("b"), 360.0, "the idle limit");
633        assert_eq!(end("c"), 310.0, "lanes are apart");
634    }
635
636    /// Fifty actions of a few kinds become the few episodes asked for, each keeping its actions.
637    #[test]
638    fn many_actions_become_a_few_episodes() {
639        let mut items = Vec::new();
640        let kinds = ["Research", "Draft", "Research", "Chat", "Draft"];
641        for k in 0..50 {
642            let kind = kinds[(k / 10) % kinds.len()];
643            // A stray action of another kind now and then
644            let kind = if k % 7 == 3 { "System" } else { kind };
645            items.push(act(k as f64 * 30.0, "You", kind, &format!("step {}", k % 4)));
646        }
647        let items = fill_ends(&items, 300.0, 1500.0);
648        let raw = each(&items);
649        assert_eq!(raw.len(), 50);
650        let eps = episodes(&items, 7, 120.0);
651        assert!(eps.len() <= 7, "{} episodes", eps.len());
652        assert_eq!(eps.iter().map(|e| e.items.len()).sum::<usize>(), 50, "nothing lost");
653        assert!(eps.windows(2).all(|w| w[0].start <= w[1].start));
654        assert!(eps.iter().any(|e| e.kind == "Research") && eps.iter().any(|e| e.kind == "Draft"));
655    }
656
657    #[test]
658    fn durations_and_ticks_read_well() {
659        assert_eq!(duration(45.0), "45 s");
660        assert_eq!(duration(26.0 * 60.0), "26 min");
661        assert_eq!(duration(3900.0), "1 h 05");
662        assert_eq!(tick_step(3.0 * 3600.0), 1800.0);
663        assert_eq!(tick_step(600.0), 120.0);
664    }
665}