use std::collections::{HashMap, VecDeque};
use std::sync::{LazyLock, Mutex};
use crate::prompt::{load_prompt, substitute};
use crate::util::UnwrapPoison;
pub(crate) const NOTICE: &str = "MahBot could not read that message.";
const PENDING_PER_CONVERSATION: usize = 64;
struct Fact {
at: String,
person: String,
kind: &'static str,
}
static PENDING: LazyLock<Mutex<HashMap<String, VecDeque<Fact>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
pub(crate) struct Pending {
pub(crate) lines: Vec<crate::ChatMessage>,
pub(crate) note: String,
}
pub(crate) fn is_notice(message: &crate::ChatMessage) -> bool {
message.role == crate::ChatRole::System && message.content == NOTICE
}
pub(crate) fn record(agent_id: &str, person: &str, kind: &'static str) {
let mut pending = PENDING.lock().unwrap_poison();
let facts = pending.entry(agent_id.to_string()).or_default();
facts.push_back(Fact {
at: crate::session::render_timestamp(),
person: person.to_string(),
kind,
});
if facts.len() > PENDING_PER_CONVERSATION {
facts.pop_front();
}
}
pub(crate) fn forget(agent_id: &str) {
PENDING.lock().unwrap_poison().remove(agent_id);
}
pub(crate) fn pending_lines(agent_id: &str) -> Vec<crate::ChatMessage> {
PENDING
.lock()
.unwrap_poison()
.get(agent_id)
.map(|facts| notice_lines(facts.len()))
.unwrap_or_default()
}
fn notice_lines(count: usize) -> Vec<crate::ChatMessage> {
vec![crate::ChatMessage::system(NOTICE); count]
}
pub(crate) fn drain(agent_id: &str) -> Pending {
let Some(facts) = PENDING.lock().unwrap_poison().remove(agent_id) else {
return Pending {
lines: Vec::new(),
note: String::new(),
};
};
let asset = load_prompt("context/unreadable_message.md");
let note = facts
.iter()
.map(|fact| {
substitute(
&asset,
&[
("{{at}}", fact.at.as_str()),
("{{person}}", fact.person.as_str()),
("{{kind}}", fact.kind),
],
)
})
.collect::<Vec<_>>()
.join("\n\n");
Pending {
lines: notice_lines(facts.len()),
note,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
static TEST_ID: AtomicU64 = AtomicU64::new(0);
fn unique_key() -> String {
format!("unreadable{}", TEST_ID.fetch_add(1, Ordering::Relaxed))
}
#[test]
fn a_recorded_fact_rides_the_next_turn_exactly_once() {
let agent_id = unique_key();
record(&agent_id, "Ada", "a picture");
let pending = drain(&agent_id);
assert!(
pending.note.starts_with("<unreadable-message>"),
"got {:?}",
pending.note
);
assert!(
pending.note.contains("Ada sent a picture"),
"got {:?}",
pending.note
);
assert_eq!(pending.lines.len(), 1, "one transcript row per message");
assert_eq!(pending.lines[0].content, NOTICE);
assert_eq!(pending.lines[0].role, crate::ChatRole::System);
let pending = drain(&agent_id);
assert!(pending.note.is_empty(), "a fact is told once");
assert!(pending.lines.is_empty());
}
#[test]
fn facts_never_cross_conversations() {
let first = unique_key();
let second = unique_key();
record(&first, "Ada", "a picture");
record(&second, "Bo", "a voice message");
let pending = drain(&first);
assert!(
pending.note.contains("Ada sent a picture"),
"{:?}",
pending.note
);
assert!(!pending.note.contains("Bo"), "{:?}", pending.note);
let pending = drain(&second);
assert!(
pending.note.contains("Bo sent a voice message"),
"{:?}",
pending.note
);
assert!(!pending.note.contains("Ada"), "{:?}", pending.note);
}
#[test]
fn nothing_queued_carries_nothing() {
let pending = drain("unreadable_never_queued");
assert!(pending.note.is_empty());
assert!(pending.lines.is_empty());
}
#[test]
fn a_conversation_remembers_a_bounded_number_of_facts() {
let agent_id = unique_key();
for index in 0..=PENDING_PER_CONVERSATION {
record(&agent_id, &format!("person{index}"), "a picture");
}
let pending = drain(&agent_id);
assert_eq!(
pending.note.matches("<unreadable-message>").count(),
PENDING_PER_CONVERSATION,
"the queue must stay bounded"
);
assert_eq!(pending.lines.len(), PENDING_PER_CONVERSATION);
assert!(
!pending.note.contains("person0 "),
"the oldest fact fell off"
);
assert!(pending.note.contains("person1 "), "the rest are kept");
}
#[test]
fn a_forgotten_conversation_carries_nothing_into_its_next_one() {
let agent_id = unique_key();
record(&agent_id, "Ada", "a picture");
forget(&agent_id);
assert!(drain(&agent_id).note.is_empty());
}
#[test]
fn a_pending_line_is_offered_until_the_turn_takes_it() {
let agent_id = unique_key();
record(&agent_id, "Ada", "a picture");
let lines = pending_lines(&agent_id);
assert_eq!(lines.len(), 1);
assert_eq!(lines[0].content, NOTICE);
assert_eq!(lines[0].role, crate::ChatRole::System);
drain(&agent_id);
assert!(pending_lines(&agent_id).is_empty());
}
}