agentmux_srv/server/
browser_attached.rs1use serde_json::json;
12
13use super::ui_handlers::{get_host_ipc, proxy_to_host_timeout};
14use super::AppState;
15
16const SHOWN: usize = 10;
18const READ_WITHIN: std::time::Duration = std::time::Duration::from_secs(8);
20const BASELINE_WITHIN: std::time::Duration = std::time::Duration::from_secs(2);
23
24async fn names_in(state: &AppState, pane: &str, within: std::time::Duration) -> Result<(Vec<String>, usize), String> {
26 let host = get_host_ipc(state).await?;
27 let v = proxy_to_host_timeout(state, &host, "file_inputs", json!({ "block_id": pane }), Some(within)).await?;
28 if v.get("ok").and_then(|o| o.as_bool()) == Some(false) {
29 return Err(v.get("error").and_then(|e| e.as_str()).unwrap_or("couldn't read the page's file inputs").to_string());
30 }
31 let names = v
32 .pointer("/data/names")
33 .and_then(|n| n.as_array())
34 .map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_string)).collect())
35 .unwrap_or_default();
36 let unreadable = v.pointer("/data/unreadable").and_then(|n| n.as_u64()).unwrap_or(0) as usize;
37 Ok((names, unreadable))
38}
39
40pub(crate) struct Watch {
42 before: Option<(Vec<String>, usize)>,
44}
45
46impl Watch {
47 pub(crate) async fn begin(state: &AppState, pane: &str) -> Self {
48 Self { before: names_in(state, pane, BASELINE_WITHIN).await.ok() }
49 }
50
51 pub(crate) async fn sentence(&self, state: &AppState, pane: &str) -> String {
53 sentence(self.before.as_ref().map(|(names, unreadable)| (names.as_slice(), *unreadable)), names_in(state, pane, READ_WITHIN).await)
54 }
55}
56
57fn added(before: &[String], now: &[String]) -> Vec<String> {
59 let mut left: Vec<&String> = before.iter().collect();
60 let mut out = Vec::new();
61 for n in now {
62 match left.iter().position(|b| *b == n) {
63 Some(i) => {
64 left.swap_remove(i);
65 }
66 None => out.push(n.clone()),
67 }
68 }
69 out
70}
71
72fn shown(name: &str) -> String {
74 let clean: String = name.chars().filter(|c| !c.is_control()).collect();
75 format!("\"{}\"", agentmux_common::pii_mask::mask_short_text(&clean))
76}
77
78fn sentence(before: Option<(&[String], usize)>, now: Result<(Vec<String>, usize), String>) -> String {
80 let (Some((before, unreadable_before)), Ok((now, unreadable))) = (before, now) else {
81 return "AgentMux could not check whether a file was attached: look at the page in a snapshot.".to_string();
82 };
83 if unreadable_before > unreadable {
85 return "AgentMux could not check whether a file was attached (a frame of the page could not be read when the hand-off began): look at the page in a snapshot.".to_string();
86 }
87 let new = added(before, &now);
88 let unseen = if unreadable > 0 { format!(" ({unreadable} frame(s) could not be read.)") } else { String::new() };
89 if new.is_empty() {
90 return format!("No file was attached to a file input.{unseen}");
91 }
92 let names: Vec<String> = new.iter().take(SHOWN).map(|n| shown(n)).collect();
93 let more = if new.len() > SHOWN { format!(" and {} more", new.len() - SHOWN) } else { String::new() };
94 format!("The person attached: {}{more}. You did not receive the file itself.{unseen}", names.join(", "))
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 fn v(names: &[&str]) -> Vec<String> {
102 names.iter().map(|s| s.to_string()).collect()
103 }
104
105 #[test]
106 fn only_files_that_were_not_there_before_count_and_repeats_count_twice() {
107 assert_eq!(added(&v(&["old.pdf"]), &v(&["old.pdf", "a.pdf"])), v(&["a.pdf"]));
108 assert_eq!(added(&v(&["a.pdf"]), &v(&["a.pdf", "a.pdf"])), v(&["a.pdf"]), "a second file with the same name");
109 assert!(added(&v(&["a.pdf"]), &v(&["a.pdf"])).is_empty());
110 assert!(added(&v(&["a.pdf"]), &[]).is_empty(), "a removed file is not an attachment");
111 }
112
113 #[test]
114 fn the_agent_is_told_the_names_and_that_it_has_not_the_file() {
115 let s = sentence(Some((&v(&[]), 0)), Ok((v(&["a.pdf", "b.png"]), 0)));
116 assert_eq!(s, "The person attached: \"a.pdf\", \"b.png\". You did not receive the file itself.");
117 }
118
119 #[test]
120 fn no_new_file_says_so_and_counts_the_frames_it_could_not_read() {
121 assert_eq!(sentence(Some((&v(&["a.pdf"]), 0)), Ok((v(&["a.pdf"]), 0))), "No file was attached to a file input.");
122 assert!(sentence(Some((&v(&[]), 2)), Ok((v(&[]), 2))).contains("2 frame(s) could not be read"));
123 }
124
125 #[test]
126 fn a_frame_unreadable_at_the_start_and_readable_now_is_not_taken_for_new_files() {
127 let s = sentence(Some((&v(&[]), 1)), Ok((v(&["old.pdf"]), 0)));
129 assert!(s.contains("could not check") && !s.contains("old.pdf"), "{s}");
130 let s = sentence(Some((&v(&["a.pdf"]), 1)), Ok((v(&["a.pdf", "b.pdf"]), 1)));
132 assert!(s.contains("\"b.pdf\"") && s.contains("1 frame(s) could not be read"), "{s}");
133 }
134
135 #[test]
136 fn a_read_that_failed_is_not_taken_for_no_file() {
137 assert!(sentence(None, Ok((v(&["a.pdf"]), 0))).contains("could not check"), "no baseline");
138 assert!(sentence(Some((&v(&[]), 0)), Err("no host".into())).contains("could not check"), "no answer now");
139 }
140
141 #[test]
142 fn many_names_are_counted_and_odd_characters_are_dropped() {
143 let many: Vec<String> = (0..13).map(|i| format!("f{i}.txt")).collect();
144 let s = sentence(Some((&[], 0)), Ok((many, 0)));
145 assert!(s.contains("and 3 more") && s.contains("\"f9.txt\"") && !s.contains("f10.txt"), "{s}");
146 assert_eq!(shown("a\u{0}\nb.pdf"), "\"ab.pdf\"");
147 }
148}