use crate::Role;
use crate::prompt::{load_prompt, substitute};
use crate::user_activity::{self, Location, State};
pub(crate) async fn prepend(
msg: &str,
agent_id: &str,
role: &Role,
is_admin: bool,
) -> (String, Option<Location>) {
if !is_admin || !matches!(role, Role::Assistant) {
return (msg.to_string(), None);
}
let Some(current) = user_activity::read() else {
return (msg.to_string(), None);
};
let shown = crate::session::store().user_activity(agent_id).await;
line(shown.as_deref(), current, msg)
}
fn line(shown: Option<&str>, current: State, msg: &str) -> (String, Option<Location>) {
if shown == Some(current.location.as_str()) {
return (msg.to_string(), None);
}
let content = match shown {
Some(_) => format!("{}\n\n{msg}", render(current)),
None => msg.to_string(),
};
(content, Some(current.location))
}
fn render(state: State) -> String {
substitute(
&load_prompt("context/user_activity.md"),
&[("{{state}}", state.label())],
)
}
#[cfg(test)]
mod tests {
use super::*;
fn at_computer() -> State {
State {
location: Location::AtComputer,
by_voice: false,
}
}
fn away() -> State {
State {
location: Location::Away,
by_voice: false,
}
}
fn spoken() -> State {
State {
location: Location::AtComputer,
by_voice: true,
}
}
#[test]
fn the_line_rides_a_change_and_the_reference_always_moves() {
type Case = (
Option<&'static str>,
State,
Option<&'static str>,
Option<Location>,
);
let cases: [Case; 5] = [
(None, at_computer(), None, Some(Location::AtComputer)),
(
Some("absent"),
at_computer(),
Some("<user-activity>active</user-activity>\n\n"),
Some(Location::AtComputer),
),
(
Some("active"),
away(),
Some("<user-activity>absent</user-activity>\n\n"),
Some(Location::Away),
),
(
Some("absent"),
spoken(),
Some("<user-activity>active, by voice</user-activity>\n\n"),
Some(Location::AtComputer),
),
(Some("active"), spoken(), None, None),
];
for (shown, current, head, recorded) in cases {
let (content, state) = line(shown, current, "hi");
match head {
Some(head) => assert!(
content.starts_with(head) && content.ends_with("hi"),
"a change opens the message: {content:?}"
),
None => assert_eq!(content, "hi", "no line for this state"),
}
assert_eq!(state, recorded);
}
}
}