Skip to main content

agentmux_srv_core/backend/
note_outbox.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One note to a leader about every agent of its that needs a look
5//! (docs/specs/SPEC_LEADER_TOLD_WHEN_AN_AGENT_GOES_QUIET_2026_11_21.md ยง7).
6//!
7//! A note about a watched agent (quiet, failed, exited, waiting on a question) is queued under its leader's pane and
8//! the agent. The first note into an empty window opens it; whatever else arrives for that leader within
9//! `WINDOW_MS` joins it (a later note about the same agent replaces its line), and the window leaves as one note.
10//! A note that must be heard now (no wait key: a failure, an exit, a question) goes out at once when the leader's
11//! window is empty, so a lone failure is never delayed. A window of one line is the note it always was.
12//!
13//! The decision (`Outbox`) is pure and takes the time as an argument, so it is tested with no clock and no
14//! runtime; `queue` and `flush_due` hand what is due to `worker_notes::deliver`, and `worker_notes::install`'s tick
15//! calls `flush_due`.
16
17use std::collections::HashMap;
18use std::sync::LazyLock;
19
20use crate::backend::storage::store::Store;
21use crate::backend::wconfig::ConfigState;
22
23/// How long notes to one leader are gathered after the first.
24pub(crate) const WINDOW_MS: u64 = 20_000;
25
26/// One agent's line in a note to a leader.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub(crate) struct Line {
29    /// Who it is about (an agent definition id): a second line about it replaces the first.
30    pub agent: String,
31    /// What the leader reads, already quoted for a system note, with no `[AgentMux]` prefix.
32    pub text: String,
33    /// `Some` when the line asks nothing and may wait for a cold leader's next turn (the key it waits under);
34    /// `None` when the leader must hear at once.
35    pub held_key: Option<String>,
36}
37
38/// A note ready to be delivered.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub(crate) struct Out {
41    pub leader: String,
42    pub text: String,
43    pub wait_key: Option<String>,
44}
45
46#[derive(Debug)]
47struct Window {
48    opened_ms: u64,
49    lines: Vec<Line>,
50}
51
52/// The windows now open, by the leader's pane.
53#[derive(Debug, Default)]
54pub(crate) struct Outbox {
55    windows: HashMap<String, Window>,
56}
57
58impl Outbox {
59    /// `line` for `leader` at `now_ms`: the note to send at once, or `None` when it waits in the window (opened
60    /// here when there was none and the line can wait).
61    pub fn push(&mut self, leader: &str, line: Line, now_ms: u64) -> Option<Out> {
62        match self.windows.get_mut(leader) {
63            Some(w) => {
64                match w.lines.iter_mut().find(|l| l.agent == line.agent) {
65                    Some(have) => *have = line,
66                    None => w.lines.push(line),
67                }
68                None
69            }
70            None if line.held_key.is_none() => Some(compose(leader, now_ms, &[line])),
71            None => {
72                self.windows.insert(leader.to_string(), Window { opened_ms: now_ms, lines: vec![line] });
73                None
74            }
75        }
76    }
77
78    /// The notes whose window has run its time at `now_ms`; their windows close.
79    pub fn take_due(&mut self, now_ms: u64) -> Vec<Out> {
80        let due: Vec<String> = self.windows.iter().filter(|(_, w)| now_ms.saturating_sub(w.opened_ms) >= WINDOW_MS).map(|(k, _)| k.clone()).collect();
81        let mut out: Vec<Out> = due.into_iter().filter_map(|leader| self.windows.remove(&leader).map(|w| compose(&leader, w.opened_ms, &w.lines))).collect();
82        out.sort_by(|a, b| a.leader.cmp(&b.leader));
83        out
84    }
85
86    /// Whether any window is open.
87    pub fn is_empty(&self) -> bool {
88        self.windows.is_empty()
89    }
90}
91
92/// The note for `lines` (at least one) to `leader`, whose window opened at `opened_ms`. One line is today's note
93/// unchanged; several are a heading and a line each. It waits for a cold leader's next turn only when every line
94/// can, under a key of its own, so a later note never replaces the lines of an earlier one.
95pub(crate) fn compose(leader: &str, opened_ms: u64, lines: &[Line]) -> Out {
96    if let [only] = lines {
97        return Out { leader: leader.to_string(), text: format!("[AgentMux] {}", only.text), wait_key: only.held_key.clone() };
98    }
99    let mut text = format!("[AgentMux] {} of your agents need a look:", lines.len());
100    for l in lines {
101        text.push_str("\n- ");
102        text.push_str(&l.text);
103    }
104    let wait_key = lines.iter().all(|l| l.held_key.is_some()).then(|| format!("group:{leader}:{opened_ms}"));
105    Out { leader: leader.to_string(), text, wait_key }
106}
107
108static OUTBOX: LazyLock<parking_lot::Mutex<Outbox>> = LazyLock::new(Default::default);
109
110/// Queue `line` for each pane of `leaders` and deliver what is due at once.
111pub(crate) fn queue(mstore: &Store, config: &ConfigState, leaders: &[String], line: &Line, now_ms: u64) {
112    let now_out: Vec<Out> = {
113        let mut outbox = OUTBOX.lock();
114        leaders.iter().filter_map(|leader| outbox.push(leader, line.clone(), now_ms)).collect()
115    };
116    send(mstore, config, now_out);
117}
118
119/// Deliver the notes whose window is over. Called by a tick.
120pub(crate) fn flush_due(mstore: &Store, config: &ConfigState, now_ms: u64) {
121    let due = {
122        let mut outbox = OUTBOX.lock();
123        if outbox.is_empty() {
124            return;
125        }
126        outbox.take_due(now_ms)
127    };
128    send(mstore, config, due);
129}
130
131fn send(mstore: &Store, config: &ConfigState, notes: Vec<Out>) {
132    for n in notes {
133        super::worker_notes::deliver(mstore, config, &n.leader, &n.text, n.wait_key.as_deref());
134    }
135}
136
137#[cfg(test)]
138#[path = "note_outbox_tests.rs"]
139mod tests;