1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum Actor {
25 Person,
27 Agent,
29}
30
31impl Actor {
32 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 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
59pub 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
64pub fn generation() -> u64 {
66 GENERATION.load(Ordering::Relaxed)
67}
68
69fn for_now(mut a: Activity) -> Activity {
71 if a.by.is_empty() {
72 a.by = crate::people::who().into();
73 }
74 a
75}
76
77pub fn record(a: Activity) {
79 let a = for_now(a);
80 with(|l| l.items.push(a));
81}
82
83pub 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
100pub 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
110fn 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
116pub 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
148pub 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
155pub 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
160pub fn job_ended(id: u64) {
162 close(&format!("job-{id}"));
163}
164
165pub 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
175pub 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
187pub 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
196pub fn made(a: &Activity) -> bool {
198 a.lane == "Jobs" || !a.assets.is_empty()
199}
200
201pub fn view(title: &str, cx: &mut App) -> Entity<Timeline> {
203 view_of(title, |_| true, cx)
204}
205
206pub 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 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 #[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}