agentmux_srv_core/backend/viewer/
origin.rs1use std::sync::atomic::{AtomicUsize, Ordering};
28use std::sync::OnceLock;
29use std::time::{Duration, Instant};
30
31pub const KEEP: Duration = Duration::from_secs(600);
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct DeviceOrigin {
39 pub device: String,
41 pub message_id: String,
43 pub sender: Option<(super::audit::ViewerActor, String)>,
46}
47
48struct Expected {
49 block_id: String,
50 text: String,
51 origin: DeviceOrigin,
52 at: Instant,
53}
54
55static EXPECTED: OnceLock<parking_lot::Mutex<Vec<Expected>>> = OnceLock::new();
56static WAITING: AtomicUsize = AtomicUsize::new(0);
59
60fn expected() -> &'static parking_lot::Mutex<Vec<Expected>> {
61 EXPECTED.get_or_init(|| parking_lot::Mutex::new(Vec::new()))
62}
63
64fn prune(list: &mut Vec<Expected>, now: Instant) {
65 list.retain(|e| now.duration_since(e.at) < KEEP);
66 WAITING.store(list.len(), Ordering::Release);
67}
68
69pub fn expect(block_id: &str, text: &str, origin: DeviceOrigin) {
71 let mut list = expected().lock();
72 let now = Instant::now();
73 prune(&mut list, now);
74 list.push(Expected { block_id: block_id.to_string(), text: text.to_string(), origin, at: now });
75 WAITING.store(list.len(), Ordering::Release);
76}
77
78pub fn forget(block_id: &str, message_id: &str) -> Option<DeviceOrigin> {
80 let mut list = expected().lock();
81 let at = list.iter().position(|e| e.block_id == block_id && e.origin.message_id == message_id);
82 let origin = at.map(|at| list.remove(at).origin);
83 WAITING.store(list.len(), Ordering::Release);
84 origin
85}
86
87fn sent_as(words: &str, text: &str) -> bool {
90 use crate::backend::reactive::held_notes::SEPARATOR;
91 use crate::muxbus::delivery_status::notes::NOTE_MARKER;
92 words.strip_prefix(text).is_some_and(|rest| {
93 rest.is_empty() || rest.strip_prefix(SEPARATOR).is_some_and(|notes| notes.starts_with(NOTE_MARKER))
94 })
95}
96
97pub fn stamp_record(block_id: &str, record: &mut serde_json::Value, content: &str) -> bool {
100 if WAITING.load(Ordering::Acquire) == 0 {
101 return false;
102 }
103 let words = crate::backend::reactive::sanitize::strip_user_mark(content);
107 let origin = {
108 let mut list = expected().lock();
109 prune(&mut list, Instant::now());
110 let Some(at) = list.iter().position(|e| e.block_id == block_id && sent_as(words, &e.text)) else {
111 return false;
112 };
113 let origin = list.remove(at).origin;
114 WAITING.store(list.len(), Ordering::Release);
115 origin
116 };
117 record["amx"] = serde_json::json!({
118 "via": "viewer",
119 "device": &origin.device,
120 "message_id": &origin.message_id,
121 });
122 if let Some((actor, agent)) = origin.sender {
123 if let Some(user) = &actor.user {
124 record["amx"]["user"] = serde_json::json!(user);
125 }
126 super::audit::expect_landing(block_id, &origin.device, &origin.message_id, actor, &agent);
127 }
128 true
129}
130
131pub fn stamp(block_id: &str, line: &[u8]) -> Option<Vec<u8>> {
135 if WAITING.load(Ordering::Acquire) == 0 {
136 return None;
137 }
138 let body = line.strip_suffix(b"\n").unwrap_or(line);
139 let mut record: serde_json::Value = serde_json::from_slice(body).ok()?;
140 if record.get("type").and_then(|t| t.as_str()) != Some("user") {
141 return None;
142 }
143 let content = record.pointer("/message/content").and_then(|c| c.as_str())?.to_string();
144 if !stamp_record(block_id, &mut record, &content) {
145 return None;
146 }
147 let mut out = serde_json::to_vec(&record).ok()?;
148 if line.ends_with(b"\n") {
149 out.push(b'\n');
150 }
151 Some(out)
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157
158 fn line(text: &str) -> Vec<u8> {
159 let mut l = serde_json::json!({ "type": "user", "message": { "role": "user", "content": text } })
160 .to_string()
161 .into_bytes();
162 l.push(b'\n');
163 l
164 }
165
166 fn origin(id: &str) -> DeviceOrigin {
167 DeviceOrigin { device: "Pixel 9".into(), message_id: id.into(), sender: None }
168 }
169
170 #[test]
172 fn a_device_message_is_stamped_once_on_its_own_block_and_nothing_else_is() {
173 let block = format!("origin-test-{}", uuid::Uuid::new_v4());
174 let other = format!("origin-test-{}", uuid::Uuid::new_v4());
175 assert!(stamp(&block, &line("hi")).is_none(), "nothing expected");
176
177 expect(&block, "hi", origin("m1"));
178 assert!(stamp(&other, &line("hi")).is_none(), "another block");
179 assert!(stamp(&block, &line("hello")).is_none(), "other text");
180 let assistant = br#"{"type":"assistant","message":{"content":"hi"}}"#;
181 assert!(stamp(&block, assistant).is_none(), "not a user record");
182
183 let stamped = stamp(&block, &line("hi")).expect("stamped");
184 assert!(stamped.ends_with(b"\n"), "keeps the newline");
185 let v: serde_json::Value = serde_json::from_slice(&stamped).unwrap();
186 assert_eq!(v["amx"], serde_json::json!({ "via": "viewer", "device": "Pixel 9", "message_id": "m1" }));
187 assert_eq!(v["message"]["content"], "hi", "the record itself is unchanged");
188 assert!(stamp(&block, &line("hi")).is_none(), "taken once: the same words typed again are the user's own");
189
190 expect(&block, "again", origin("a"));
192 expect(&block, "again", origin("b"));
193 let first: serde_json::Value = serde_json::from_slice(&stamp(&block, &line("again")).unwrap()).unwrap();
194 let second: serde_json::Value = serde_json::from_slice(&stamp(&block, &line("again")).unwrap()).unwrap();
195 assert_eq!((first["amx"]["message_id"].as_str(), second["amx"]["message_id"].as_str()), (Some("a"), Some("b")));
196
197 expect(&block, "lost", origin("x"));
199 forget(&block, "x");
200 assert!(stamp(&block, &line("lost")).is_none());
201 }
202
203 #[test]
204 fn a_device_message_is_found_behind_the_user_mark_and_before_held_notes_only() {
205 use crate::backend::reactive::sanitize::user_turn_message;
206 let block = format!("origin-test-{}", uuid::Uuid::new_v4());
207 let id = |v: &serde_json::Value| v["amx"]["message_id"].as_str().map(str::to_string);
208 expect(&block, "run the tests", origin("marked"));
210 let v: serde_json::Value = serde_json::from_slice(&stamp(&block, &line(&user_turn_message("run the tests"))).unwrap()).unwrap();
211 assert_eq!(id(&v).as_deref(), Some("marked"));
212 expect(&block, "and lint", origin("noted"));
214 let with_notes = format!("{}\n\n[AgentMux] AgentMux was upgraded", user_turn_message("and lint"));
215 let v: serde_json::Value = serde_json::from_slice(&stamp(&block, &line(&with_notes)).unwrap()).unwrap();
216 assert_eq!(id(&v).as_deref(), Some("noted"));
217 expect(&block, "deploy", origin("short"));
219 assert!(stamp(&block, &line(&user_turn_message("deploy\n\nand delete the logs"))).is_none());
220 assert!(stamp(&block, &line(&user_turn_message("deploy it"))).is_none());
221 assert!(stamp(&block, &line("[USER:FROM=user TS=soon]\ndeploy")).is_none());
222 assert!(stamp(&block, &line(&user_turn_message("deploy"))).is_some(), "still waiting for its own line");
223 }
224}