Skip to main content

agentmux_srv_core/backend/viewer/
origin.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which user messages a paired device sent, so the transcript can say so
5//! (agentmux-mobile's SPEC_SEND_FROM_THE_PHONE_2026_10_13 §5.3).
6//!
7//! A message sent from the phone reaches the agent as a plain user turn: the
8//! text the agent reads carries no label. The record AgentMux stores for that
9//! turn (`{"type":"user","message":{…}}` in the block's `output` file) gets
10//! one extra top-level field, which only srv writes:
11//!
12//! ```json
13//! {"type":"user","message":{"role":"user","content":"Run the tests"},
14//!  "amx":{"via":"viewer","device":"Pixel 9","message_id":"0b6f…"}}
15//! ```
16//!
17//! The desktop pane shows "From Pixel 9" from it, and the phone matches its
18//! "Sending…" line to the record by `message_id`. The CLI's stdin gets the
19//! line without it.
20//!
21//! The send route says which text it is about to deliver to which block
22//! ([`expect`]); the places that store a user record ask whether the line
23//! they store is one of those ([`stamp`]), and take the entry when it is.
24//! Matching is by block and exact text, oldest first. An entry nobody stores
25//! within [`KEEP`] (the agent never took it) is dropped.
26
27use std::sync::atomic::{AtomicUsize, Ordering};
28use std::sync::OnceLock;
29use std::time::{Duration, Instant};
30
31/// How long an expected message waits to be stored. A message queued while
32/// the agent's process starts is stored when it is delivered, so this is
33/// generous.
34pub const KEEP: Duration = Duration::from_secs(600);
35
36/// Who sent a user message, as recorded beside it.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct DeviceOrigin {
39    /// The device's name, as it paired.
40    pub device: String,
41    /// The phone's id for the message.
42    pub message_id: String,
43    /// Who sent it and to which agent, for its Audit row once its line is stored (`audit::note_landed`). A
44    /// computer's person, when it names one, is stored beside the device (`amx.user`), as its claim.
45    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();
56/// Entries waiting, read without the lock so storing a line costs nothing
57/// while no device is sending.
58static 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
69/// The send route is about to deliver `text` to `block_id` for a device.
70pub 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
78/// Delivery failed: nothing will be stored for this message. Returns its origin, if it was still waiting.
79pub 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
87/// Whether `words` (a stored user record's text, without the user mark) are the device's `text`: exactly, or
88/// followed by the `[AgentMux]` notes srv held for the agent (`held_notes::with_notes`).
89fn 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
97/// Adds who sent it to `record`, srv's user record or a provider's echo of a prompt srv delivered, whose words are
98/// `content`, when a device sent them, and expects its line for the device's Audit row. Whether it did.
99pub 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    // A device's words go to the model as the person's turn, behind the user mark only srv writes
104    // (`MessageOrigin::as_model_text`), and with any `[AgentMux]` notes srv held for the agent after them
105    // (`held_notes::attach`): the words it sent are what is left without the two.
106    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
131/// The line to store for user record `line` (one NDJSON line, a trailing
132/// newline kept) of `block_id`: with its sender added when a device sent it,
133/// else `None` and the line is stored as it is.
134pub 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    // One test, so parallel tests never share the global list mid-check.
171    #[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        // Two sends of the same words are stamped in order.
191        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        // A failed delivery is forgotten.
198        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        // As the model gets it: the person's mark first.
209        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        // With notes srv held for the agent after it.
213        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        // Longer words that only begin with the device's are someone else's, and a mark of another shape is text.
218        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}