agentmux_srv_core/backend/
record_notice.rs1use std::sync::atomic::{AtomicBool, Ordering};
19
20use serde_json::Value;
21
22use super::record_flags::{Flag, Looked};
23
24pub const NOTE_KEY: &str = "record-flags";
26
27#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, ts_rs::TS)]
29#[ts(export, export_to = "../../../frontend/types/rpc/")]
30pub struct RecordFlagLine {
31 pub rule: String,
33 pub key: String,
36 #[ts(type = "number")]
38 pub t: u64,
39 #[ts(type = "number | null")]
41 pub n: Option<u64>,
42 #[ts(type = "number | null")]
44 pub worst_ms: Option<u64>,
45 pub unit: Option<String>,
47 #[ts(type = "number | null")]
49 pub level: Option<u64>,
50 #[ts(type = "number | null")]
52 pub rise: Option<u64>,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, ts_rs::TS)]
58#[ts(export, export_to = "../../../frontend/types/rpc/")]
59pub struct RecordFlagsEvent {
60 #[ts(type = "\"record\"")]
62 pub kind: String,
63 #[ts(type = "\"normal\" | \"warn\"")]
65 pub level: String,
66 #[ts(type = "number | null")]
68 pub since_ms: Option<u64>,
69 pub flags: Vec<RecordFlagLine>,
71}
72
73fn line(e: &Value) -> Option<RecordFlagLine> {
74 let n = |field: &str| e[field].as_u64();
75 Some(RecordFlagLine {
76 rule: e["rule"].as_str()?.to_string(),
77 key: e["key"].as_str()?.to_string(),
78 t: n("t")?,
79 n: n("n"),
80 worst_ms: n("worst_ms"),
81 unit: e["unit"].as_str().map(str::to_string),
82 level: n("level"),
83 rise: n("rise"),
84 })
85}
86
87pub fn event(said: &[Value]) -> RecordFlagsEvent {
89 let flags: Vec<RecordFlagLine> = said.iter().filter_map(line).collect();
90 RecordFlagsEvent {
91 kind: "record".to_string(),
92 level: if flags.is_empty() { "normal" } else { "warn" }.to_string(),
93 since_ms: flags.iter().map(|f| f.t).min(),
94 flags,
95 }
96}
97
98fn about(flag: &Flag) -> String {
100 let stalled = if flag.key == "ui_stall" { "the window host's UI thread" } else { "srv's runtime" };
101 let n = |field: &str| flag.fields[field].as_u64().unwrap_or(0);
102 match flag.rule {
103 "stalls" => format!("{stalled} stalled {} times for 5 s or more in one hour (the longest {} s)", n("n"), n("worst_ms") / 1000),
104 "long_stall" => format!("{stalled} stalled for {} s", n("worst_ms") / 1000),
105 "growth" => format!("{} has grown two days running, by more than a fifth of its size each day", flag.key),
106 other => format!("{other}: {}", flag.key),
107 }
108}
109
110pub fn note_text(new: &[Flag]) -> Option<String> {
112 if new.is_empty() {
113 return None;
114 }
115 let what: Vec<String> = new.iter().map(about).collect();
116 Some(format!(
117 "[AgentMux] The record of this AgentMux flagged {}: {}. \
118 Nothing was stopped and the person was not interrupted; the status bar shows a note. \
119 `App record` (view \"summary\") has the numbers and the days behind them. \
120 If it is real, file it for the seat that owns it, with the export of those days.",
121 if new.len() == 1 { "one thing".to_string() } else { format!("{} things", new.len()) },
122 what.join("; ")
123 ))
124}
125
126fn steward_targets(mstore: &crate::backend::storage::store::Store) -> Vec<String> {
128 let defs = mstore.agent_def_list().unwrap_or_default();
129 let mut out: Vec<String> = Vec::new();
130 for rec in crate::backend::reactive::get_global_handler().list_agents() {
131 let def = defs.iter().find(|d| rec.uid.as_deref() == Some(d.id.as_str()) || d.slug == rec.agent_id || d.id == rec.agent_id);
132 if !def.and_then(|d| crate::backend::agent_seat::effective_seat(mstore, d)).is_some_and(|seat| crate::backend::agent_seat::is_steward(&seat)) {
133 continue;
134 }
135 let target = rec.uid.clone().filter(|u| !u.is_empty()).unwrap_or(rec.agent_id.clone());
136 if !out.contains(&target) {
137 out.push(target);
138 }
139 }
140 out
141}
142
143static SAID: AtomicBool = AtomicBool::new(false);
145
146pub fn tell(broker: &crate::backend::mps::Broker, mstore: &crate::backend::storage::store::Store, looked: &Looked) {
150 let event = event(&looked.said);
151 let says = !event.flags.is_empty();
152 let said_before = SAID.swap(says, Ordering::Relaxed);
153 if says || said_before {
154 broker.publish_event::<crate::backend::mps_events::RecordFlags>(&event, vec![], 1);
155 }
156 let Some(text) = note_text(&looked.new) else { return };
157 let handler = crate::backend::reactive::get_global_handler();
158 let targets = steward_targets(mstore);
159 if targets.is_empty() {
160 tracing::info!("[record] flags were written and no steward is here to be told");
161 }
162 for target in targets {
163 match handler.hold_system_note(&target, NOTE_KEY, &text) {
164 Ok(()) => tracing::info!(agent = %target, "[record] the steward has a note about the flags"),
165 Err(e) => tracing::debug!(agent = %target, error = %e, "[record] the steward was not told"),
166 }
167 }
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173 use serde_json::json;
174
175 const END: u64 = 1_794_830_400_000;
177
178 #[test]
179 fn the_event_carries_each_flag_still_said_with_its_numbers_and_is_normal_with_none() {
180 let said = vec![
181 json!({ "t": END - 3_600_000, "kind": "flag", "rule": "growth", "key": "page:main:heap", "unit": "mb", "level": 306, "rise": 72, "rise_before": 70, "content_pct": 2 }),
182 json!({ "t": END, "kind": "flag", "rule": "stalls", "key": "srv_stall", "n": 4, "worst_ms": 6_200 }),
183 json!({ "t": END, "kind": "flag", "rule": "growth" }),
185 ];
186 let e = event(&said);
187 assert_eq!((e.kind.as_str(), e.level.as_str(), e.since_ms), ("record", "warn", Some(END - 3_600_000)));
188 assert_eq!(e.flags.len(), 2);
189 assert_eq!(
190 e.flags[0],
191 RecordFlagLine { rule: "growth".into(), key: "page:main:heap".into(), t: END - 3_600_000, n: None, worst_ms: None, unit: Some("mb".into()), level: Some(306), rise: Some(72) }
192 );
193 assert_eq!((e.flags[1].rule.as_str(), e.flags[1].n, e.flags[1].worst_ms), ("stalls", Some(4), Some(6_200)));
194
195 let none = event(&[]);
196 assert_eq!((none.level.as_str(), none.since_ms, none.flags.len()), ("normal", None, 0));
197 let wire = serde_json::to_value(&e).unwrap();
199 assert_eq!(wire["kind"], "record");
200 assert_eq!(wire["flags"][1]["worst_ms"], 6_200);
201 }
202
203 #[test]
204 fn the_steward_is_told_once_for_what_a_look_wrote_and_nothing_for_a_look_that_wrote_nothing() {
205 assert_eq!(note_text(&[]), None);
206 let one = note_text(&[Flag { rule: "long_stall", key: "ui_stall".into(), fields: json!({ "n": 1, "worst_ms": 41_000 }) }]).unwrap();
207 assert!(one.starts_with("[AgentMux] The record of this AgentMux flagged one thing: the window host's UI thread stalled for 41 s."), "{one}");
208 let two = note_text(&[
209 Flag { rule: "stalls", key: "srv_stall".into(), fields: json!({ "n": 4, "worst_ms": 6_200 }) },
210 Flag { rule: "growth", key: "core:srv".into(), fields: json!({ "unit": "bytes", "level": 300, "rise": 90 }) },
211 ])
212 .unwrap();
213 assert!(two.contains("flagged 2 things: srv's runtime stalled 4 times for 5 s or more in one hour (the longest 6 s); core:srv has grown two days running"), "{two}");
214 assert!(two.contains("`App record`"));
215 assert!(two.contains("Nothing was stopped"));
216 }
217}