agentmux_srv_core/backend/transcript/
images.rs1use std::collections::{HashMap, HashSet};
13use std::sync::{Arc, Mutex, OnceLock};
14
15use serde_json::Value;
16
17use crate::backend::storage::filestore::FileStore;
18
19const FILE: &str = "output";
20const CHUNK: i64 = 4 * 1024 * 1024;
22const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff"];
23
24#[derive(Clone, Copy, Default)]
28struct Counted {
29 created: i64,
30 pos: i64,
31 images: u32,
32}
33
34fn cache() -> &'static Mutex<HashMap<String, Counted>> {
35 static CACHE: OnceLock<Mutex<HashMap<String, Counted>>> = OnceLock::new();
36 CACHE.get_or_init(Default::default)
37}
38
39pub fn forget(zone: &str) {
42 cache().lock().unwrap_or_else(|e| e.into_inner()).remove(zone);
43}
44
45pub fn counted(zone: &str) -> Option<u32> {
49 cache().lock().unwrap_or_else(|e| e.into_inner()).get(zone).map(|c| c.images)
50}
51
52pub fn warm(gfs: &Arc<FileStore>, zone: &str) {
55 static RUNNING: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
56 let running = RUNNING.get_or_init(Default::default);
57 if !running.lock().unwrap_or_else(|e| e.into_inner()).insert(zone.to_string()) {
58 return;
59 }
60 let (gfs, zone) = (gfs.clone(), zone.to_string());
61 std::thread::spawn(move || {
62 if let Err(e) = count_in_zone(&gfs, &zone) {
63 tracing::warn!(zone = %zone, error = %e, "the images in the conversation were not counted");
64 }
65 running.lock().unwrap_or_else(|e| e.into_inner()).remove(&zone);
66 });
67}
68
69pub fn count_in_zone(gfs: &FileStore, zone: &str) -> Result<u32, String> {
71 let Some(stat) = gfs.stat(zone, FILE).map_err(|e| format!("stat transcript: {e}"))? else {
72 cache().lock().unwrap_or_else(|e| e.into_inner()).remove(zone);
73 return Ok(0);
74 };
75 let mut done = cache().lock().unwrap_or_else(|e| e.into_inner()).get(zone).copied().unwrap_or_default();
76 if stat.createdts != done.created || stat.size < done.pos {
78 done = Counted { created: stat.createdts, ..Counted::default() };
79 }
80 let mut window = CHUNK;
81 while done.pos < stat.size {
82 let (at, data) = gfs.read_at(zone, FILE, done.pos, window).map_err(|e| format!("read transcript: {e}"))?;
83 if data.is_empty() {
84 break;
85 }
86 let end = if at + data.len() as i64 >= stat.size { data.len() } else { data.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1) };
88 if end == 0 {
89 window = window.saturating_mul(2);
90 continue;
91 }
92 window = CHUNK;
93 done.images += data[..end].split(|b| *b == b'\n').map(images_in_line).sum::<u32>();
94 done.pos = at + end as i64;
95 }
96 cache().lock().unwrap_or_else(|e| e.into_inner()).insert(zone.to_string(), done);
97 Ok(done.images)
98}
99
100pub fn images_in_line(line: &[u8]) -> u32 {
102 if !contains(line, b"<attached_") {
104 return 0;
105 }
106 let Ok(v) = serde_json::from_slice::<Value>(line) else { return 0 };
107 if v.get("type").and_then(Value::as_str) != Some("user") {
108 return 0;
109 }
110 let mut texts = Vec::new();
111 match v.pointer("/message/content") {
112 Some(Value::String(s)) => texts.push(s.as_str()),
113 Some(Value::Array(items)) => texts.extend(items.iter().filter_map(|i| i.get("text").and_then(Value::as_str))),
114 _ => {}
115 }
116 texts.into_iter().map(images_in_text).sum()
117}
118
119fn contains(hay: &[u8], needle: &[u8]) -> bool {
120 hay.windows(needle.len()).any(|w| w == needle)
121}
122
123fn has_image_extension(name: &str) -> bool {
124 name.rsplit_once('.').is_some_and(|(_, ext)| IMAGE_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()))
125}
126
127fn images_in_text(text: &str) -> u32 {
129 let mut in_block = false;
130 let mut n = 0;
131 for line in text.lines() {
132 let line = line.trim();
133 if line == "<attached_files>" || line == "<attached_images>" {
134 in_block = true;
135 } else if line == "</attached_files>" || line == "</attached_images>" {
136 in_block = false;
137 } else if in_block {
138 if let Some(name) = line.strip_prefix("- ").and_then(|l| l.strip_suffix(" — (no longer available)")) {
139 n += u32::from(has_image_extension(name));
140 } else if let Some((_, path)) = line.rsplit_once(" — ") {
141 n += u32::from(path.contains(".send.") && has_image_extension(path.trim()));
143 }
144 }
145 }
146 n
147}
148
149#[cfg(test)]
150#[path = "images_tests.rs"]
151mod tests;