Skip to main content

agentmux_srv_core/backend/
history_changed.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The History pane's agent list changes when an agent's transcript grows, a
5//! conversation is archived, or a fork takes a copy of its parent's. Those
6//! writes are many (every output line) and the list wants one signal, so a
7//! write only [`mark`]s, which costs one atomic store, and one task publishes
8//! `history:sessions:changed` at most once per [`TICK`] while something was
9//! marked. A window that shows the list reloads it on the event
10//! (`frontend/app/view/audit/conversations/history-agents.tsx`).
11//!
12//! A write by another AgentMux sharing the transcript store (another channel)
13//! never reaches [`mark`]; the list's own safety poll covers it.
14
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::sync::Arc;
17use std::time::Duration;
18
19use crate::backend::mps::Broker;
20
21/// The longest a change waits before the event announces it.
22const TICK: Duration = Duration::from_secs(2);
23
24/// Whether anything changed since the last announcement.
25#[derive(Default)]
26pub(crate) struct Changes(AtomicBool);
27
28impl Changes {
29    pub(crate) fn mark(&self) {
30        self.0.store(true, Ordering::Relaxed);
31    }
32
33    /// Whether there is something to announce; clears it.
34    pub(crate) fn take(&self) -> bool {
35        self.0.swap(false, Ordering::Relaxed)
36    }
37}
38
39static CHANGES: Changes = Changes(AtomicBool::new(false));
40
41/// The history list may have changed. Cheap enough for the output path.
42pub fn mark() {
43    CHANGES.mark();
44}
45
46/// Publish the event once per [`TICK`] while something was marked.
47pub fn spawn_publisher(broker: Arc<Broker>) {
48    tokio::spawn(async move {
49        let mut tick = tokio::time::interval(TICK);
50        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
51        loop {
52            tick.tick().await;
53            if CHANGES.take() {
54                broker.publish_event::<crate::backend::mps_events::HistorySessionsChanged>(&(), vec![], 0);
55            }
56        }
57    });
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn many_marks_are_one_announcement() {
66        let changes = Changes::default();
67        assert!(!changes.take(), "nothing changed: nothing to announce");
68        for _ in 0..1000 {
69            changes.mark();
70        }
71        assert!(changes.take());
72        assert!(!changes.take(), "announced once, not once per mark");
73        changes.mark();
74        assert!(changes.take(), "a later change is announced again");
75    }
76}