Skip to main content

kitchen_shell/
activity.rs

1//! What happened in the app, as an episodic memory (kitchen-ui's [`Timeline`]): every command run
2//! (from a menu, a key, the search, the title bar or an agent) with who ran it, the time spent in
3//! each workspace, and every job from its start to its end. Attention, not content: a command's
4//! arguments are kept in short, never the data it worked on.
5//!
6//! The registry and the frame record into it by themselves; an app adds what a step produced
7//! ([`produced`]) so the timeline can say where a file came from. [`view`] is a timeline that
8//! follows the log as it grows; [`view_of`] shows only what a filter keeps (what was made).
9//!
10//! The log lives in memory for the app's session and is never written anywhere: it is the
11//! session's story, not a record of the person. Each activity names who it was done for
12//! ([`crate::people::who`]: a person's name, or `guest`).
13
14use std::collections::HashMap;
15use std::sync::Mutex;
16use std::sync::atomic::{AtomicU64, Ordering};
17
18use gpui_kit::{App, AppContext as _, Entity, SharedString};
19use kitchen_ui::timeline::{Activity, Timeline};
20use serde_json::Value;
21
22/// Who did it.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum Actor {
25    /// The person at the app.
26    Person,
27    /// An agent (through MCP or the chat).
28    Agent,
29}
30
31impl Actor {
32    /// Its lane on the timeline.
33    pub fn lane(self) -> &'static str {
34        match self {
35            Actor::Person => "You",
36            Actor::Agent => "Agent",
37        }
38    }
39}
40
41#[derive(Default)]
42struct Log {
43    items: Vec<Activity>,
44    /// Spans still open (a job, the workspace shown): their index; they end at "now".
45    open: HashMap<String, usize>,
46    workspace: String,
47}
48
49static LOG: Mutex<Option<Log>> = Mutex::new(None);
50static GENERATION: AtomicU64 = AtomicU64::new(0);
51
52fn with<T>(f: impl FnOnce(&mut Log) -> T) -> T {
53    let mut g = LOG.lock().unwrap_or_else(|e| e.into_inner());
54    let out = f(g.get_or_insert_with(Log::default));
55    GENERATION.fetch_add(1, Ordering::Relaxed);
56    out
57}
58
59/// Seconds since 1970 (UTC).
60pub fn now() -> f64 {
61    web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64())
62}
63
64/// Bumped on every change (redraw when it moves).
65pub fn generation() -> u64 {
66    GENERATION.load(Ordering::Relaxed)
67}
68
69/// `a`, done for the person working now (unless it says).
70fn for_now(mut a: Activity) -> Activity {
71    if a.by.is_empty() {
72        a.by = crate::people::who().into();
73    }
74    a
75}
76
77/// Adds an activity (for the person working, unless it names one).
78pub fn record(a: Activity) {
79    let a = for_now(a);
80    with(|l| l.items.push(a));
81}
82
83/// Opens a span `key` (a job, a workspace shown) that lasts until [`close`]; one open with the
84/// same key is closed first.
85pub fn open(key: impl Into<String>, mut a: Activity) {
86    let key = key.into();
87    let t = now();
88    a = for_now(a);
89    with(|l| {
90        if let Some(i) = l.open.remove(&key) {
91            l.items[i].end = t;
92        }
93        a.start = t;
94        a.end = t;
95        l.items.push(a);
96        l.open.insert(key, l.items.len() - 1);
97    });
98}
99
100/// Closes the span `key` now.
101pub fn close(key: &str) {
102    let t = now();
103    with(|l| {
104        if let Some(i) = l.open.remove(key) {
105            l.items[i].end = t.max(l.items[i].start + 1.0);
106        }
107    });
108}
109
110/// A short line of JSON: at most `max` characters.
111fn short(v: &Value, max: usize) -> String {
112    let s = v.to_string();
113    if s.chars().count() <= max { s } else { format!("{}…", s.chars().take(max).collect::<String>()) }
114}
115
116/// Records a command run: by whom, how (`via`: menu, key, search, title bar, agent), with what
117/// arguments and what came of it.
118pub fn command(actor: Actor, id: &str, title: &str, group: &str, via: &str, args: &Value, result: &Result<Value, String>) {
119    let mut detail = Vec::new();
120    if !args.is_null() && args != &Value::Object(Default::default()) {
121        detail.push(format!("{id} {}", short(args, 120)));
122    } else {
123        detail.push(id.to_string());
124    }
125    match result {
126        Ok(Value::Null) => {}
127        Ok(v) => detail.push(format!("→ {}", short(v, 120))),
128        Err(e) => detail.push(format!("refused: {e}")),
129    }
130    let t = now();
131    let by: SharedString = crate::people::who().into();
132    with(|l| {
133        let source = if l.workspace.is_empty() { via.to_string() } else { format!("{} · {via}", l.workspace) };
134        l.items.push(Activity {
135            start: t,
136            end: t,
137            lane: actor.lane().into(),
138            kind: if group.is_empty() { "Commands".into() } else { SharedString::from(group.to_string()) },
139            title: title.to_string().into(),
140            detail: detail.join("  ").into(),
141            source: source.into(),
142            assets: Vec::new(),
143            by,
144        })
145    });
146}
147
148/// The workspace shown now: a span on the Focus lane, until the next one.
149pub fn focus(workspace: &str) {
150    let name = workspace.to_string();
151    with(|l| l.workspace = name.clone());
152    open("focus", Activity { lane: "Focus".into(), kind: SharedString::from(name.clone()), title: format!("In {name}").into(), ..Default::default() });
153}
154
155/// A job started (its span on the Jobs lane, until [`job_ended`]).
156pub fn job_started(id: u64, kind: &str, name: &str) {
157    open(format!("job-{id}"), Activity { lane: "Jobs".into(), kind: kind.to_string().into(), title: name.to_string().into(), source: "job".into(), ..Default::default() });
158}
159
160/// A job ended.
161pub fn job_ended(id: u64) {
162    close(&format!("job-{id}"));
163}
164
165/// What a step produced (files, ids): added to the last activity titled `title`, or as one of its
166/// own on the person's lane.
167pub fn produced(title: &str, assets: Vec<String>) {
168    let t = now();
169    with(|l| match l.items.iter_mut().rev().find(|a| a.title == title) {
170        Some(a) => a.assets.extend(assets.into_iter().map(SharedString::from)),
171        None => l.items.push(for_now(Activity { start: t, end: t, lane: Actor::Person.lane().into(), kind: "Output".into(), title: title.to_string().into(), assets: assets.into_iter().map(SharedString::from).collect(), ..Default::default() })),
172    });
173}
174
175/// Everything so far; spans still open end now.
176pub fn all() -> Vec<Activity> {
177    let t = now();
178    let g = LOG.lock().unwrap_or_else(|e| e.into_inner());
179    let Some(l) = g.as_ref() else { return Vec::new() };
180    let mut out = l.items.clone();
181    for &i in l.open.values() {
182        out[i].end = t.max(out[i].start + 1.0);
183    }
184    out
185}
186
187/// Forgets everything (a new project).
188pub fn clear() {
189    with(|l| {
190        let ws = std::mem::take(&mut l.workspace);
191        *l = Log::default();
192        l.workspace = ws;
193    });
194}
195
196/// What was made: a job, or an activity that produced something (a [`view_of`] filter).
197pub fn made(a: &Activity) -> bool {
198    a.lane == "Jobs" || !a.assets.is_empty()
199}
200
201/// A timeline titled `title` that follows the log (read again when it changed, every second).
202pub fn view(title: &str, cx: &mut App) -> Entity<Timeline> {
203    view_of(title, |_| true, cx)
204}
205
206/// A timeline of the activities `keep` keeps (e.g. [`made`]: what the session produced, not
207/// every command), following the log.
208pub fn view_of(title: &str, keep: impl Fn(&Activity) -> bool + 'static, cx: &mut App) -> Entity<Timeline> {
209    let keep = std::rc::Rc::new(keep);
210    let shown = { let keep = keep.clone(); move || all().into_iter().filter(|a| keep(a)).collect::<Vec<_>>() };
211    let timeline = cx.new(|_| Timeline::new(title.to_string()));
212    timeline.update(cx, |t, cx| t.set_activities(shown(), now(), cx));
213    let weak = timeline.downgrade();
214    cx.spawn(async move |cx| {
215        let mut seen = generation();
216        loop {
217            cx.background_executor().timer(std::time::Duration::from_secs(1)).await;
218            let g = generation();
219            // Open spans grow with time: read again now and then even when nothing was added
220            let stale = g != seen;
221            seen = g;
222            let alive = weak.update(cx, |t, cx| {
223                if stale || !t.activities().is_empty() {
224                    t.set_activities(shown(), now(), cx)
225                }
226            });
227            if alive.is_err() {
228                break;
229            }
230        }
231    })
232    .detach();
233    timeline
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    /// Commands land on their actor's lane with their provenance; spans close; jobs end.
241    #[test]
242    fn commands_spans_and_jobs_are_recorded() {
243        clear();
244        focus("Explore");
245        command(Actor::Person, "hist.find_cells", "Find cells", "Analyze", "menu", &Value::Null, &Ok(serde_json::json!({"cells": 12})));
246        command(Actor::Agent, "process.op.blur", "Gaussian blur", "Filter", "agent", &serde_json::json!({"sigma": 2}), &Err("Open an image first".into()));
247        job_started(7, "histology", "Finding cells");
248        produced("Find cells", vec!["cells.parquet".into()]);
249        let a = all();
250        let find = a.iter().find(|x| x.title == "Find cells").unwrap();
251        assert_eq!((find.lane.as_ref(), find.kind.as_ref(), find.source.as_ref()), ("You", "Analyze", "Explore · menu"));
252        assert_eq!(find.by.as_ref(), crate::people::who(), "done for the person working");
253        assert!(made(find), "it produced a file: made");
254        assert!(!made(a.iter().find(|x| x.title == "Gaussian blur").unwrap()), "a command that made nothing is not");
255        assert!(find.detail.contains("cells"));
256        assert_eq!(find.assets, vec![SharedString::from("cells.parquet")]);
257        let blur = a.iter().find(|x| x.title == "Gaussian blur").unwrap();
258        assert_eq!(blur.lane.as_ref(), "Agent");
259        assert!(blur.detail.contains("refused"));
260        assert!(a.iter().any(|x| x.lane == "Jobs" && x.end > x.start), "a running job lasts until now");
261        job_ended(7);
262        focus("Analyze");
263        let a = all();
264        assert_eq!(a.iter().filter(|x| x.lane == "Focus").count(), 2);
265        assert!(a.iter().filter(|x| x.lane == "Focus").all(|x| x.end > x.start));
266    }
267}