Skip to main content

agentmux_srv_core/backend/
task_flow.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! "A filed task #N for B at T": the `task-flow` event and the short list of recent ones, the task half of the
5//! Atlas agent map's flow data (the message half is [`message_flow`](super::message_flow)).
6//!
7//! Like it, this carries ids, names, hosts and times only: the task's number and board slug, who did it, who it
8//! is for and what was done. There is no field for the title, the payload, a result or a note.
9//!
10//! The srv that owns the board reports what happens to its tasks. A task filed on another computer's board is
11//! also reported by the filer's srv, once it has the number back, so a map connected to either srv draws the
12//! line; both name the task by the board's host and number, which is how a reader joins them.
13//!
14//! The recent list lives in memory only (`RECENT_MAX` entries, newest last). Each entry remembers the board it is
15//! on, so a reader is given only the boards it may see (`GET /api/v1/task-flow`); the board's id is never sent.
16
17use std::collections::VecDeque;
18use std::sync::{Arc, Mutex, OnceLock};
19
20use serde::Serialize;
21
22use super::message_flow::MessageFlowEnd;
23use super::mps::Broker;
24use super::mps_events::TaskFlow;
25
26/// How many recent task events are kept.
27pub const RECENT_MAX: usize = 200;
28
29/// What was done to the task.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ts_rs::TS)]
31#[ts(export, export_to = "../../../frontend/types/rpc/")]
32#[serde(rename_all = "snake_case")]
33pub enum TaskFlowKind {
34    /// Put on a board, for an agent or for anyone.
35    Filed,
36    /// Moved to another agent, or to anyone, by the operator or an agent, or taken back and given to another.
37    Reassigned,
38    /// Started on an agent by the operator or another agent.
39    Started,
40    /// Given back by the agent that held it.
41    HandedBack,
42}
43
44/// A task: its number on a board, the board's slug and the computer whose board it is.
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
46#[ts(export, export_to = "../../../frontend/types/rpc/")]
47pub struct TaskFlowTask {
48    #[ts(type = "number")]
49    pub number: i64,
50    pub board: String,
51    pub host: String,
52}
53
54/// The `task-flow` event's payload (`mps_events::TaskFlow`).
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
56#[ts(export, export_to = "../../../frontend/types/rpc/")]
57pub struct TaskFlowEvent {
58    pub task: TaskFlowTask,
59    /// When the srv that owns the board handled it, in milliseconds since 1970.
60    #[ts(type = "number")]
61    pub at_ms: u64,
62    /// Who did it: absent when the operator did, or the app itself.
63    #[serde(skip_serializing_if = "Option::is_none")]
64    #[ts(optional)]
65    pub by: Option<MessageFlowEnd>,
66    /// Who it is for or went to: absent when it is for anyone (`handed_back` has none either).
67    #[serde(skip_serializing_if = "Option::is_none")]
68    #[ts(optional)]
69    pub to: Option<MessageFlowEnd>,
70    pub kind: TaskFlowKind,
71}
72
73/// What a call site knows of a task event: ids and names, never its content.
74pub struct Seen {
75    pub number: i64,
76    pub board: String,
77    /// The board's id, kept to say who may read the event; never sent.
78    pub board_id: String,
79    pub host: String,
80    pub by: Option<MessageFlowEnd>,
81    pub to: Option<MessageFlowEnd>,
82    pub kind: TaskFlowKind,
83}
84
85struct Kept {
86    event: TaskFlowEvent,
87    board_id: String,
88}
89
90struct Flow {
91    broker: Arc<Broker>,
92    recent: Mutex<VecDeque<Kept>>,
93}
94
95static FLOW: OnceLock<Flow> = OnceLock::new();
96
97/// Start publishing on `broker` for the rest of the process. The first call wins.
98pub fn install(broker: Arc<Broker>) {
99    let _ = FLOW.set(Flow { broker, recent: Mutex::new(VecDeque::with_capacity(RECENT_MAX)) });
100}
101
102/// The event for `seen`, as handled at `at_ms`.
103fn event_of(seen: &Seen, at_ms: u64) -> TaskFlowEvent {
104    TaskFlowEvent {
105        task: TaskFlowTask { number: seen.number, board: seen.board.clone(), host: seen.host.clone() },
106        at_ms,
107        by: seen.by.clone(),
108        to: seen.to.clone(),
109        kind: seen.kind,
110    }
111}
112
113/// Adds `kept` to `recent`, dropping the oldest once there are `RECENT_MAX`.
114fn remember(recent: &mut VecDeque<Kept>, kept: Kept) {
115    if recent.len() >= RECENT_MAX {
116        recent.pop_front();
117    }
118    recent.push_back(kept);
119}
120
121impl Flow {
122    /// Keeps and publishes the event for `seen`, handled at `at_ms`.
123    fn record(&self, seen: &Seen, at_ms: u64) {
124        let event = event_of(seen, at_ms);
125        remember(&mut self.recent.lock().unwrap_or_else(|e| e.into_inner()), Kept { event: event.clone(), board_id: seen.board_id.clone() });
126        self.broker.publish_event::<TaskFlow>(&event, vec![], 0);
127    }
128}
129
130/// Records that `seen` happened: published as the `task-flow` event, and kept in the recent list. Does nothing
131/// before [`install`].
132pub fn note(seen: &Seen) {
133    if let Some(flow) = FLOW.get() {
134        flow.record(seen, agentmux_common::time::now_ms() as u64);
135    }
136}
137
138/// The recent task events on the boards `sees` says yes to (by board id), oldest first.
139pub fn recent_where(sees: impl Fn(&str) -> bool) -> Vec<TaskFlowEvent> {
140    let Some(flow) = FLOW.get() else { return Vec::new() };
141    flow.recent.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|k| sees(&k.board_id)).map(|k| k.event.clone()).collect()
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    fn seen(number: i64, board_id: &str, kind: TaskFlowKind) -> Seen {
149        Seen {
150            number,
151            board: "work".into(),
152            board_id: board_id.into(),
153            host: "charlie".into(),
154            by: Some(MessageFlowEnd { agent: "agenty".into(), host: Some("narko".into()) }),
155            to: Some(MessageFlowEnd { agent: "maricon-2".into(), host: Some("charlie".into()) }),
156            kind,
157        }
158    }
159
160    fn flow() -> Flow {
161        Flow { broker: Arc::new(Broker::new()), recent: Mutex::new(VecDeque::new()) }
162    }
163
164    #[test]
165    fn an_event_has_the_task_the_two_agents_and_the_kind_and_nothing_else() {
166        let e = event_of(&seen(614, "b1", TaskFlowKind::HandedBack), 7);
167        assert_eq!(
168            serde_json::to_value(&e).unwrap(),
169            serde_json::json!({
170                "task": { "number": 614, "board": "work", "host": "charlie" },
171                "at_ms": 7,
172                "by": { "agent": "agenty", "host": "narko" },
173                "to": { "agent": "maricon-2", "host": "charlie" },
174                "kind": "handed_back",
175            })
176        );
177    }
178
179    #[test]
180    fn a_task_for_anyone_filed_by_the_operator_has_neither_end() {
181        let mut s = seen(1, "b1", TaskFlowKind::Filed);
182        (s.by, s.to) = (None, None);
183        let v = serde_json::to_value(event_of(&s, 1)).unwrap();
184        assert!(v.get("by").is_none() && v.get("to").is_none(), "{v}");
185        assert_eq!(v["kind"], "filed");
186    }
187
188    #[test]
189    fn every_kind_has_its_own_name() {
190        let name = |k| serde_json::to_value(event_of(&seen(1, "b", k), 1)).unwrap()["kind"].as_str().unwrap().to_string();
191        assert_eq!(
192            [TaskFlowKind::Filed, TaskFlowKind::Reassigned, TaskFlowKind::Started, TaskFlowKind::HandedBack].map(name),
193            ["filed", "reassigned", "started", "handed_back"]
194        );
195    }
196
197    #[test]
198    fn an_event_is_published_and_kept_with_its_board_for_a_reader_who_may_see_it() {
199        let flow = flow();
200        let published = Arc::new(Mutex::new(Vec::new()));
201        let sink = Arc::clone(&published);
202        flow.broker.add_observer(Arc::new(move |e: &crate::backend::mps::MuxEvent| sink.lock().unwrap().push((e.event.clone(), e.data.clone()))));
203        flow.record(&seen(1, "open-board", TaskFlowKind::Filed), 5);
204        flow.record(&seen(2, "private-board", TaskFlowKind::Started), 6);
205        let published = published.lock().unwrap();
206        assert_eq!(published.iter().map(|p| p.0.as_str()).collect::<Vec<_>>(), ["task-flow", "task-flow"]);
207        assert!(!published[1].1.as_ref().unwrap().to_string().contains("private-board"), "the board's id is never sent");
208        let recent = flow.recent.lock().unwrap();
209        let visible: Vec<i64> = recent.iter().filter(|k| k.board_id == "open-board").map(|k| k.event.task.number).collect();
210        assert_eq!(visible, vec![1]);
211    }
212
213    #[test]
214    fn the_recent_list_keeps_the_newest_and_is_bounded() {
215        let mut recent = VecDeque::new();
216        for n in 0..RECENT_MAX + 5 {
217            remember(&mut recent, Kept { event: event_of(&seen(n as i64, "b", TaskFlowKind::Filed), n as u64), board_id: "b".into() });
218        }
219        assert_eq!(recent.len(), RECENT_MAX);
220        assert_eq!(recent.front().unwrap().event.task.number, 5);
221        assert_eq!(recent.back().unwrap().event.task.number, RECENT_MAX as i64 + 4);
222    }
223}