Skip to main content

merry_runtime/subagent/
activity.rs

1use merry_core::{
2    InteractiveRunState, RuntimeEvent, SubagentActivityPhase, SubagentActivitySnapshot, SubagentId,
3    SubagentTaskId,
4};
5use std::{collections::BTreeMap, sync::Arc};
6use tokio::sync::watch;
7
8const NON_TERMINAL_COALESCE_MS: u64 = 250;
9const MAX_SUMMARY_BYTES: usize = 120;
10
11/// Receiver for the latest sorted activity snapshot set.
12pub type SubagentActivityReceiver = watch::Receiver<Vec<SubagentActivitySnapshot>>;
13
14/// Runtime-owned latest-value activity projection for UI consumers.
15#[derive(Clone)]
16pub struct SubagentActivityHub {
17    sender: watch::Sender<Vec<SubagentActivitySnapshot>>,
18    state: Arc<std::sync::Mutex<ActivityHubState>>,
19    publication_lock: Arc<std::sync::Mutex<()>>,
20}
21
22struct ActivityHubState {
23    snapshots: BTreeMap<SubagentId, SubagentActivitySnapshot>,
24    last_published_ms: BTreeMap<SubagentId, u64>,
25    #[cfg(test)]
26    published_phases: Vec<SubagentActivityPhase>,
27}
28
29impl SubagentActivityHub {
30    /// Creates an empty latest-value activity hub.
31    #[must_use]
32    pub fn new() -> Self {
33        let (sender, _receiver) = watch::channel(Vec::new());
34        Self {
35            sender,
36            state: Arc::new(std::sync::Mutex::new(ActivityHubState {
37                snapshots: BTreeMap::new(),
38                last_published_ms: BTreeMap::new(),
39                #[cfg(test)]
40                published_phases: Vec::new(),
41            })),
42            publication_lock: Arc::new(std::sync::Mutex::new(())),
43        }
44    }
45
46    /// Subscribes to the current and future latest snapshot sets.
47    #[must_use]
48    pub fn subscribe(&self) -> SubagentActivityReceiver {
49        self.sender.subscribe()
50    }
51
52    pub(crate) fn publish(&self, snapshot: SubagentActivitySnapshot) {
53        // Serialize the state snapshot and watch publication without holding the
54        // state mutex across Tokio's internal watch write lock.
55        let _publication_guard = self
56            .publication_lock
57            .lock()
58            .unwrap_or_else(std::sync::PoisonError::into_inner);
59        let is_terminal = is_terminal_phase(snapshot.phase);
60        let subagent_id = snapshot.subagent_id.clone();
61        let updated_at_ms = snapshot.updated_at_ms;
62        let (values, should_publish) = {
63            let mut state = self
64                .state
65                .lock()
66                .unwrap_or_else(std::sync::PoisonError::into_inner);
67
68            if state
69                .snapshots
70                .get(&snapshot.subagent_id)
71                .is_some_and(|previous| is_terminal_phase(previous.phase) && !is_terminal)
72            {
73                return;
74            }
75
76            let should_publish = is_terminal
77                || state
78                    .last_published_ms
79                    .get(&subagent_id)
80                    .is_none_or(|last_published_ms| {
81                        updated_at_ms >= last_published_ms.saturating_add(NON_TERMINAL_COALESCE_MS)
82                    });
83            #[cfg(test)]
84            state.published_phases.push(snapshot.phase);
85            state.snapshots.insert(subagent_id.clone(), snapshot);
86            if should_publish {
87                state.last_published_ms.insert(subagent_id, updated_at_ms);
88            }
89            let values = state.snapshots.values().cloned().collect::<Vec<_>>();
90            (values, should_publish)
91        };
92
93        let _ = self.sender.send_if_modified(|current| {
94            *current = values;
95            should_publish
96        });
97    }
98
99    #[allow(dead_code)]
100    pub(crate) fn current(&self) -> Vec<SubagentActivitySnapshot> {
101        self.state
102            .lock()
103            .unwrap_or_else(std::sync::PoisonError::into_inner)
104            .snapshots
105            .values()
106            .cloned()
107            .collect()
108    }
109
110    #[cfg(test)]
111    #[allow(dead_code)]
112    pub(crate) fn published_phases(&self) -> Vec<SubagentActivityPhase> {
113        self.state
114            .lock()
115            .unwrap_or_else(std::sync::PoisonError::into_inner)
116            .published_phases
117            .clone()
118    }
119}
120
121impl Default for SubagentActivityHub {
122    fn default() -> Self {
123        Self::new()
124    }
125}
126
127fn is_terminal_phase(phase: SubagentActivityPhase) -> bool {
128    matches!(
129        phase,
130        SubagentActivityPhase::Completed
131            | SubagentActivityPhase::Failed
132            | SubagentActivityPhase::Blocked
133            | SubagentActivityPhase::Cancelled
134    )
135}
136
137#[derive(Debug, Clone)]
138pub(crate) struct SubagentActivityReducer {
139    subagent_id: SubagentId,
140    task_id: SubagentTaskId,
141    last_valid: Option<SubagentActivitySnapshot>,
142}
143
144impl SubagentActivityReducer {
145    pub(crate) fn new(subagent_id: SubagentId, task_id: SubagentTaskId) -> Self {
146        Self {
147            subagent_id,
148            task_id,
149            last_valid: None,
150        }
151    }
152
153    pub(crate) fn reduce(
154        &mut self,
155        event: &RuntimeEvent,
156        updated_at_ms: u64,
157    ) -> Option<SubagentActivitySnapshot> {
158        match self.try_reduce(event, updated_at_ms) {
159            Ok(Some(snapshot)) => {
160                self.last_valid = Some(snapshot.clone());
161                Some(snapshot)
162            }
163            Ok(None) => None,
164            Err(error) => {
165                tracing::warn!(
166                    subagent_id = %self.subagent_id,
167                    task_id = %self.task_id,
168                    error,
169                    "subagent activity event projection skipped"
170                );
171                None
172            }
173        }
174    }
175
176    pub(crate) fn starting(&mut self, updated_at_ms: u64) -> SubagentActivitySnapshot {
177        let snapshot = self.snapshot(SubagentActivityPhase::Starting, "starting", updated_at_ms);
178        self.last_valid = Some(snapshot.clone());
179        snapshot
180    }
181
182    pub(crate) fn terminal(
183        &mut self,
184        phase: SubagentActivityPhase,
185        summary: &str,
186        updated_at_ms: u64,
187    ) -> SubagentActivitySnapshot {
188        let snapshot = self.snapshot(phase, summary, updated_at_ms);
189        self.last_valid = Some(snapshot.clone());
190        snapshot
191    }
192
193    #[cfg(test)]
194    fn last_valid(&self) -> Option<&SubagentActivitySnapshot> {
195        self.last_valid.as_ref()
196    }
197
198    fn try_reduce(
199        &self,
200        event: &RuntimeEvent,
201        updated_at_ms: u64,
202    ) -> Result<Option<SubagentActivitySnapshot>, &'static str> {
203        let (phase, summary) = match event {
204            RuntimeEvent::StepStarted { .. } => {
205                (SubagentActivityPhase::Running, "working".to_owned())
206            }
207            RuntimeEvent::ToolCallStarted { call, .. } => {
208                let tool_name = call.name().as_str();
209                if tool_name.is_empty() {
210                    return Err("tool call name was empty");
211                }
212                (SubagentActivityPhase::Running, format!("tool: {tool_name}"))
213            }
214            RuntimeEvent::PlanSaved { .. } => {
215                (SubagentActivityPhase::Running, "plan saved".to_owned())
216            }
217            RuntimeEvent::InteractiveRunStateChanged { state } => match state {
218                InteractiveRunState::WaitingForInput => (
219                    SubagentActivityPhase::Waiting,
220                    "waiting for input".to_owned(),
221                ),
222                InteractiveRunState::RunningModel | InteractiveRunState::RunningTool => {
223                    (SubagentActivityPhase::Running, "working".to_owned())
224                }
225                InteractiveRunState::Interrupting | InteractiveRunState::Closed => return Ok(None),
226            },
227            _ => return Ok(None),
228        };
229
230        Ok(Some(self.snapshot(phase, &summary, updated_at_ms)))
231    }
232
233    fn snapshot(
234        &self,
235        phase: SubagentActivityPhase,
236        summary: &str,
237        updated_at_ms: u64,
238    ) -> SubagentActivitySnapshot {
239        SubagentActivitySnapshot {
240            subagent_id: self.subagent_id.clone(),
241            task_id: self.task_id.clone(),
242            phase,
243            summary: bounded_summary(summary),
244            updated_at_ms,
245        }
246    }
247}
248
249fn bounded_summary(summary: &str) -> String {
250    let sanitized = summary
251        .chars()
252        .map(|character| {
253            if character.is_control() {
254                ' '
255            } else {
256                character
257            }
258        })
259        .collect::<String>();
260    let mut end = sanitized.len().min(MAX_SUMMARY_BYTES);
261    while !sanitized.is_char_boundary(end) {
262        end -= 1;
263    }
264    sanitized[..end].to_owned()
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270    use merry_core::{
271        PendingToolCall, RuntimeEventSource, ToolCallArguments, ToolCallId, ToolName,
272    };
273    use serde_json::Map;
274    use std::sync::{Arc, Barrier};
275
276    fn agent_id(value: &str) -> SubagentId {
277        SubagentId::new(value).expect("valid subagent id")
278    }
279
280    fn task_id(value: &str) -> SubagentTaskId {
281        SubagentTaskId::new(value).expect("valid task id")
282    }
283
284    fn source() -> RuntimeEventSource {
285        RuntimeEventSource::new(
286            merry_core::SessionId::new("child-session").expect("valid session id"),
287            1,
288        )
289    }
290
291    fn snapshot(
292        id: &str,
293        phase: SubagentActivityPhase,
294        updated_at_ms: u64,
295    ) -> SubagentActivitySnapshot {
296        SubagentActivitySnapshot {
297            subagent_id: agent_id(id),
298            task_id: task_id("task-1"),
299            phase,
300            summary: "working".to_owned(),
301            updated_at_ms,
302        }
303    }
304
305    fn tool_call(name: &str) -> PendingToolCall {
306        PendingToolCall::new(
307            ToolCallId::new("call-1").expect("valid call id"),
308            ToolName::new(name).expect("valid tool name"),
309            ToolCallArguments::new(Map::new()),
310        )
311    }
312
313    #[test]
314    fn reducer_maps_structured_events_and_ignores_assistant_text() {
315        let mut reducer = SubagentActivityReducer::new(agent_id("agent-1"), task_id("task-1"));
316
317        let started = reducer
318            .reduce(&RuntimeEvent::StepStarted { source: source() }, 10)
319            .expect("step start projects activity");
320        assert_eq!(started.phase, SubagentActivityPhase::Running);
321        assert_eq!(started.summary, "working");
322
323        let tool = reducer
324            .reduce(
325                &RuntimeEvent::ToolCallStarted {
326                    call: tool_call("apply_patch"),
327                    source: source(),
328                },
329                20,
330            )
331            .expect("tool start projects activity");
332        assert_eq!(tool.phase, SubagentActivityPhase::Running);
333        assert_eq!(tool.summary, "tool: apply_patch");
334        assert_eq!(reducer.last_valid(), Some(&tool));
335
336        assert!(
337            reducer
338                .reduce(
339                    &RuntimeEvent::AssistantMessageDelta {
340                        delta: "unstructured assistant prose".to_owned(),
341                        source: source(),
342                    },
343                    30,
344                )
345                .is_none()
346        );
347        assert_eq!(reducer.last_valid(), Some(&tool));
348
349        let plan_saved = reducer
350            .reduce(
351                &RuntimeEvent::PlanSaved {
352                    plan: merry_core::PlanDocument {
353                        summary: merry_core::PlanDocumentSummary {
354                            id: merry_core::PlanId::new("plan-1").expect("valid plan id"),
355                            title: "Refactor auth".to_owned(),
356                            file_name: "001-refactor-auth.md".to_owned(),
357                            status: merry_core::PlanDocumentStatus::Draft,
358                            revision: 1,
359                            created_at_ms: 10,
360                            updated_at_ms: 35,
361                        },
362                        content: "# Refactor auth\n".to_owned(),
363                    },
364                    source: source(),
365                },
366                35,
367            )
368            .expect("plan save projects activity");
369        assert_eq!(plan_saved.phase, SubagentActivityPhase::Running);
370        assert_eq!(plan_saved.summary, "plan saved");
371
372        let waiting = reducer
373            .reduce(
374                &RuntimeEvent::InteractiveRunStateChanged {
375                    state: InteractiveRunState::WaitingForInput,
376                },
377                40,
378            )
379            .expect("waiting state projects activity");
380        assert_eq!(waiting.phase, SubagentActivityPhase::Waiting);
381    }
382
383    #[test]
384    fn summaries_sanitize_controls_and_cap_without_splitting_utf8() {
385        let sanitized = bounded_summary("before\n\tafter");
386        assert_eq!(sanitized, "before  after");
387
388        let capped = bounded_summary(&"界".repeat(50));
389        assert_eq!(capped.len(), 120);
390        assert_eq!(capped.chars().count(), 40);
391    }
392
393    #[test]
394    fn hub_publishes_sorted_latest_values_and_coalesces_nonterminal_updates() {
395        let hub = SubagentActivityHub::new();
396        let mut receiver = hub.subscribe();
397
398        hub.publish(snapshot("agent-b", SubagentActivityPhase::Starting, 100));
399        assert!(receiver.has_changed().expect("receiver remains open"));
400        let _ = receiver.borrow_and_update();
401
402        hub.publish(snapshot("agent-b", SubagentActivityPhase::Running, 200));
403        assert!(!receiver.has_changed().expect("receiver remains open"));
404        assert_eq!(receiver.borrow()[0].updated_at_ms, 200);
405
406        hub.publish(snapshot("agent-a", SubagentActivityPhase::Starting, 350));
407        assert!(receiver.has_changed().expect("receiver remains open"));
408        let values = receiver.borrow_and_update().clone();
409        assert_eq!(values[0].subagent_id, agent_id("agent-a"));
410        assert_eq!(values[1].subagent_id, agent_id("agent-b"));
411        assert_eq!(values[1].updated_at_ms, 200);
412
413        hub.publish(snapshot("agent-b", SubagentActivityPhase::Completed, 201));
414        assert!(
415            receiver
416                .has_changed()
417                .expect("terminal update is immediate")
418        );
419        assert_eq!(hub.current()[1].phase, SubagentActivityPhase::Completed);
420    }
421
422    #[test]
423    fn dropping_a_receiver_does_not_cancel_activity_production() {
424        let hub = SubagentActivityHub::new();
425        let receiver = hub.subscribe();
426        drop(receiver);
427
428        hub.publish(snapshot("agent-1", SubagentActivityPhase::Running, 1));
429        assert_eq!(hub.current().len(), 1);
430    }
431
432    #[test]
433    fn concurrent_publish_keeps_watch_value_equal_to_final_sorted_state() {
434        let hub = Arc::new(SubagentActivityHub::new());
435        let receiver = hub.subscribe();
436        let barrier = Arc::new(Barrier::new(3));
437
438        let first_hub = Arc::clone(&hub);
439        let first_barrier = Arc::clone(&barrier);
440        let first = std::thread::spawn(move || {
441            first_barrier.wait();
442            first_hub.publish(snapshot("agent-a", SubagentActivityPhase::Running, 1));
443        });
444        let second_hub = Arc::clone(&hub);
445        let second_barrier = Arc::clone(&barrier);
446        let second = std::thread::spawn(move || {
447            second_barrier.wait();
448            second_hub.publish(snapshot("agent-b", SubagentActivityPhase::Running, 1));
449        });
450
451        barrier.wait();
452        first.join().expect("first publisher should finish");
453        second.join().expect("second publisher should finish");
454
455        let current = hub.current();
456        assert_eq!(&*receiver.borrow(), &current);
457        assert_eq!(
458            current
459                .iter()
460                .map(|snapshot| snapshot.subagent_id.as_str())
461                .collect::<Vec<_>>(),
462            vec!["agent-a", "agent-b"]
463        );
464    }
465
466    #[test]
467    fn publish_tolerates_poisoned_state_and_closed_receiver() {
468        let hub = SubagentActivityHub::new();
469        let state = Arc::clone(&hub.state);
470        let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
471            let _guard = state
472                .lock()
473                .expect("state lock should initially be healthy");
474            panic!("poison activity state for the test");
475        }));
476        assert!(panic_result.is_err());
477
478        let publication_lock = Arc::clone(&hub.publication_lock);
479        let publication_panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
480            let _guard = publication_lock
481                .lock()
482                .expect("publication lock should initially be healthy");
483            panic!("poison activity publication lock for the test");
484        }));
485        assert!(publication_panic.is_err());
486
487        hub.publish(snapshot("agent-1", SubagentActivityPhase::Failed, 1));
488        let receiver = hub.subscribe();
489        drop(receiver);
490        hub.publish(snapshot("agent-1", SubagentActivityPhase::Completed, 2));
491
492        assert_eq!(hub.current()[0].phase, SubagentActivityPhase::Completed);
493    }
494}