Skip to main content

kitchen_services/
activity.rs

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