Skip to main content

agentmux_srv_core/backend/cli_native/
sent.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The user turns srv writes to a CLI's stdin, by uuid.
5//!
6//! Launched with `--replay-user-messages`, the CLI echoes each user turn it is
7//! given back on stdout as an `isReplay` frame carrying the uuid the turn came
8//! with. The pane already records what it sent, so that echo is dropped; but the
9//! CLI also marks frames of its own `isReplay` without the flag (a local
10//! command's output such as `/compact`'s card), and those must stay. A uuid srv
11//! put on a turn it wrote is the only thing that tells the two apart.
12
13use std::collections::VecDeque;
14use std::sync::{Arc, Mutex};
15
16use serde_json::Value;
17
18/// Turns remembered; far more than the CLI can be behind by.
19const REMEMBERED: usize = 1024;
20
21#[derive(Clone, Default)]
22pub struct SentPrompts(Arc<Mutex<VecDeque<String>>>);
23
24impl SentPrompts {
25    fn remember(&self, uuid: String) {
26        let mut g = self.0.lock().unwrap_or_else(|e| e.into_inner());
27        if g.len() >= REMEMBERED {
28            g.pop_front();
29        }
30        g.push_back(uuid);
31    }
32
33    /// True, and forgotten, if `uuid` is a turn srv wrote.
34    pub fn take(&self, uuid: &str) -> bool {
35        let mut g = self.0.lock().unwrap_or_else(|e| e.into_inner());
36        match g.iter().position(|u| u == uuid) {
37            Some(i) => {
38                g.remove(i);
39                true
40            }
41            None => false,
42        }
43    }
44
45    /// `line` as it is written to the CLI: a user turn gets a uuid (its own if it has
46    /// one), remembered here. Anything else (a control response, text that is not
47    /// JSON) is written as it is.
48    pub fn tag(&self, line: &str) -> String {
49        let Ok(Value::Object(mut turn)) = serde_json::from_str::<Value>(line) else { return line.to_string() };
50        if turn.get("type").and_then(Value::as_str) != Some("user") {
51            return line.to_string();
52        }
53        let uuid = match turn.get("uuid").and_then(Value::as_str).filter(|u| !u.is_empty()) {
54            Some(own) => own.to_string(),
55            None => {
56                let fresh = uuid::Uuid::new_v4().to_string();
57                turn.insert("uuid".to_string(), Value::String(fresh.clone()));
58                fresh
59            }
60        };
61        self.remember(uuid);
62        serde_json::to_string(&Value::Object(turn)).unwrap_or_else(|_| line.to_string())
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    fn uuid_of(line: &str) -> String {
71        serde_json::from_str::<Value>(line).unwrap()["uuid"].as_str().unwrap().to_string()
72    }
73
74    #[test]
75    fn a_user_turn_gets_a_uuid_that_is_remembered_once() {
76        let sent = SentPrompts::default();
77        let tagged = sent.tag(r#"{"type":"user","message":{"role":"user","content":"hi"}}"#);
78        let id = uuid_of(&tagged);
79        assert!(sent.take(&id));
80        assert!(!sent.take(&id), "an echo is dropped once");
81        assert!(serde_json::from_str::<Value>(&tagged).unwrap()["message"]["content"] == "hi");
82    }
83
84    #[test]
85    fn a_turn_that_has_a_uuid_keeps_it() {
86        let sent = SentPrompts::default();
87        let tagged = sent.tag(r#"{"type":"user","uuid":"own-1","message":{"role":"user","content":"hi"}}"#);
88        assert_eq!(uuid_of(&tagged), "own-1");
89        assert!(sent.take("own-1"));
90    }
91
92    #[test]
93    fn control_responses_and_non_json_are_written_as_they_are() {
94        let sent = SentPrompts::default();
95        for line in [r#"{"type":"control_response","response":{"request_id":"r"}}"#, "not json", r#"[1,2]"#] {
96            assert_eq!(sent.tag(line), line);
97        }
98        assert!(!sent.take(""));
99    }
100
101    #[test]
102    fn a_uuid_srv_never_wrote_is_not_taken() {
103        let sent = SentPrompts::default();
104        sent.tag(r#"{"type":"user","message":{"role":"user","content":"hi"}}"#);
105        assert!(!sent.take("the-clis-own-frame"));
106    }
107
108    #[test]
109    fn the_oldest_are_forgotten_past_the_bound() {
110        let sent = SentPrompts::default();
111        for i in 0..REMEMBERED + 5 {
112            sent.tag(&format!(r#"{{"type":"user","uuid":"u{i}","message":{{"role":"user","content":"x"}}}}"#));
113        }
114        assert!(!sent.take("u0"));
115        assert!(sent.take(&format!("u{}", REMEMBERED + 4)));
116    }
117}