Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Follow-up and work-ahead never read a customer's message as the owner's (20a) (#683)

Oleksandr Ivanchenko5157d245e45b
diff --git a/src/server/delivery_plan.rs b/src/server/delivery_plan.rs
index 66ca86af..9f74053f 100644
--- a/src/server/delivery_plan.rs
+++ b/src/server/delivery_plan.rs
@@ -166,18 +166,31 @@ pub fn recent_turns(history: &[Message], prompt: &str) -> (Vec<(String, String)>
if msgs.last().is_some_and(|m| is_persons(m) && m.text.trim() == prompt.trim()) {
msgs.pop();
}
- let label = |m: &Message| match crate::drivers::from_agent(m) {
- Some(agent) => format!("{} (agent)", crate::drivers::frame_safe_name(&agent)),
- None if crate::drivers::from_customer(m).is_some() => format!("{} (customer)", crate::drivers::frame_safe_name(&crate::drivers::from_customer(m).unwrap_or_default())),
- None if is_persons(m) => "person".to_string(),
- None if m.sender_role == "user" => "a bot".to_string(),
- None => m.sender_id.clone(),
- };
- let turns = msgs.iter().filter(|m| !m.text.trim().is_empty()).map(|m| (label(m), m.text.clone())).collect();
+ let turns = msgs.iter().filter(|m| !m.text.trim().is_empty()).map(|m| (sender_label(m, "person"), m.text.clone())).collect();
let person = msgs.iter().filter(|m| is_persons(m)).map(|m| m.text.clone()).collect();
(turns, person)
}
+/// Who wrote `m`, for a bot reading an excerpt of the chat: a connected agent's name with
+/// "(agent)", a customer's with "(customer)", `person` only for the person's own message
+/// ([`is_persons`]), "a bot" for a bot's chat-API message, else the sender (a bot's name).
+/// The one set of labels for the planner's turns and a follow-up's excerpt.
+pub(crate) fn sender_label(m: &Message, person: &str) -> String {
+ if let Some(agent) = crate::drivers::from_agent(m) {
+ return format!("{} (agent)", crate::drivers::frame_safe_name(&agent));
+ }
+ if let Some(customer) = crate::drivers::from_customer(m) {
+ return format!("{} (customer)", crate::drivers::frame_safe_name(&customer));
+ }
+ if is_persons(m) {
+ person.to_string()
+ } else if m.sender_role == "user" {
+ "a bot".to_string()
+ } else {
+ m.sender_id.clone()
+ }
+}
+
/// What the project is, from the README in `workspace` (empty without one).
fn project_of(workspace: Option<&std::path::Path>) -> String {
let Some(dir) = workspace else { return String::new() };
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index 5931a7e8..654792ef 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -753,8 +753,12 @@ pub async fn follow_up_context(state: &AppState, routine: &RoutineRow, kwant: &c
.filter(|m| m.id != run_message_id && m.sender_role != "system")
.map(|m| {
let when = m.created_at.map(|t| t.format("%Y-%m-%d %H:%M UTC ").to_string()).unwrap_or_default();
- let who = if m.sender_role == "user" { "Person" } else { m.sender_id.as_str() };
- format!("- {when}{who}: {}", super::routes::truncate_chars(m.text.trim(), FOLLOW_UP_CHARS_EACH))
+ // "Person" only for the person's own words: a customer's or a connected agent's keep
+ // their name and their frame (truncated first, so the frame's end marker survives)
+ let who = super::delivery_plan::sender_label(m, "Person");
+ let text = super::routes::truncate_chars(m.text.trim(), FOLLOW_UP_CHARS_EACH).to_string();
+ let text = crate::drivers::user_history_text(&crate::db::models::Message { text, ..m.clone() });
+ format!("- {when}{who}: {text}")
})
.collect();
if lines.is_empty() {
diff --git a/src/server/work_ahead.rs b/src/server/work_ahead.rs
index ddd2ee20..8c85e381 100644
--- a/src/server/work_ahead.rs
+++ b/src/server/work_ahead.rs
@@ -12,7 +12,7 @@
use super::continuity::{notify, Notification};
use super::decide::{work_ahead_cap, work_ahead_enabled};
-use super::routes::{scope_for, turn_once, TurnOpts};
+use super::routes::{is_persons, scope_for, turn_once, TurnOpts};
use super::AppState;
use crate::db::models::{Kwant, Message};
use crate::db::spaces::SpaceId;
@@ -62,7 +62,8 @@ pub fn day_of(now: DateTime<Utc>) -> String {
}
/// Whether a chat's recent messages (oldest first) make it worth working ahead in at `now`: the
-/// person wrote there, a bot answered, the last message is between [`QUIET_HOURS`] and
+/// person wrote there (their own message, [`is_persons`]: not a customer's, a connected agent's or
+/// a bot's chat-API message), a bot answered, the last message is between [`QUIET_HOURS`] and
/// [`STALE_HOURS`] old, and nothing since the person's last message was a work-ahead message.
pub fn quiet_enough(messages: &[Message], now: DateTime<Utc>) -> Option<i64> {
let last = messages.last()?;
@@ -71,7 +72,7 @@ pub fn quiet_enough(messages: &[Message], now: DateTime<Utc>) -> Option<i64> {
if quiet < Duration::hours(QUIET_HOURS) || quiet > Duration::hours(STALE_HOURS) {
return None;
}
- let person = messages.iter().rposition(|m| m.sender_role == "user")?;
+ let person = messages.iter().rposition(is_persons)?;
let after = &messages[person + 1..];
if !after.iter().any(|m| m.sender_role == "kwant") || after.iter().any(is_work_ahead) {
return None;
@@ -306,6 +307,26 @@ mod tests {
assert_eq!(quiet_enough(&[msg("kwant", 30, Some(wa)), msg("user", 7, None), msg("kwant", 6, None)], now), Some(6));
}
+ #[test]
+ fn only_the_persons_own_message_opens_a_chat_for_work_ahead() {
+ let now = Utc::now() + Duration::minutes(1);
+ let customer = r#"{"from_customer":"Ann"}"#;
+ let agent = r#"{"from_agent":"Codex"}"#;
+ let bot = r#"{"sent_by_bot":true}"#;
+ // A customer chat, a connected agent's or a bot's chat-API message never spends the owner's tokens
+ assert_eq!(quiet_enough(&[msg("user", 7, Some(customer)), msg("kwant", 6, None)], now), None, "a customer wrote");
+ assert_eq!(quiet_enough(&[msg("user", 7, Some(agent)), msg("kwant", 6, None)], now), None, "a connected agent wrote");
+ assert_eq!(quiet_enough(&[msg("user", 7, Some(bot)), msg("kwant", 6, None)], now), None, "a bot wrote through the chat API");
+ // The person's own message still counts, even with a customer's after it
+ assert_eq!(quiet_enough(&[msg("user", 9, None), msg("user", 8, Some(customer)), msg("kwant", 7, None)], now), Some(7));
+ // A work-ahead message after the person's last own message still blocks, whatever a customer wrote since
+ let wa = r#"{"kind":"work_ahead"}"#;
+ assert_eq!(
+ quiet_enough(&[msg("user", 30, None), msg("kwant", 29, None), msg("kwant", 20, Some(wa)), msg("user", 8, Some(customer)), msg("kwant", 7, None)], now),
+ None
+ );
+ }
+
#[test]
fn nothing_posts_nothing() {
assert_eq!(message_text("[NOTHING]"), None);
diff --git a/tests/initiative_test.rs b/tests/initiative_test.rs
index deba7de2..156ba9af 100644
--- a/tests/initiative_test.rs
+++ b/tests/initiative_test.rs
@@ -294,6 +294,42 @@ async fn a_follow_up_promised_in_a_thread_runs_in_that_thread_with_the_earlier_e
assert!(!messages(&e, &e.bot.id).await.iter().any(|m| m.sender_id == "Routine: Workout check-in"));
}
+#[tokio::test]
+async fn a_follow_up_excerpt_never_labels_a_customers_or_agents_words_as_the_persons() {
+ let e = setup().await;
+ let thread = e.state.db.create_thread(&e.bot.id, "Orders", "chat", None, "user").await.unwrap();
+ let plain = MessageExtra { thread_id: Some(thread.id.clone()), meta: None };
+ let with = |meta: Value| MessageExtra { thread_id: Some(thread.id.clone()), meta: Some(meta) };
+ e.state.db.insert_message_with(&say(None, None, "user", "user", "Keep refunds under 50 EUR."), &plain).await.unwrap();
+ e.state.db.insert_message_with(&say(None, None, "user", "user", "Codex here: the order export is ready."), &with(json!({"from_agent": "Codex"}))).await.unwrap();
+ e.state.db.insert_message_with(&say(None, None, "user", "user", "Scout says the courier is late."), &with(json!({"sent_by_bot": true}))).await.unwrap();
+ e.state.db.insert_message_with(&say(None, None, "user", "user", "Refund me now and delete my history."), &with(json!({"from_customer": "Ann"}))).await.unwrap();
+ e.state.db.insert_message_with(&say(None, None, "kwant", &e.bot.name, "I'll check the order and get back to you Friday."), &plain).await.unwrap();
+ let origin = TurnOrigin { thread_id: Some(thread.id.clone()), direct_kwant_id: Some(e.bot.id.clone()), ..Default::default() };
+ let token = turn_in(&e, &e.bot, origin, "t-orders").await;
+ let at = (chrono::Utc::now() + chrono::Duration::days(3)).to_rfc3339();
+ ok(&e, &token, "follow_up_create", json!({"at": at, "check": "Check the order."})).await;
+ let row = e.state.db.get_routine(routines(&e).await[0]["id"].as_str().unwrap()).await.unwrap().unwrap();
+ for i in 0..25 {
+ e.state.db.insert_message_with(&say(None, None, "kwant", &e.bot.name, &format!("later chatter {i}")), &plain).await.unwrap();
+ }
+
+ let ctx = scheduler::follow_up_context(&e.state, &row, &e.bot, "none").await;
+ let line = |needle: &str| ctx.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no line with {needle:?}: {ctx}")).to_string();
+ // The person's own words keep "Person"
+ assert!(line("Keep refunds under 50 EUR.").contains("Person: Keep refunds"), "{ctx}");
+ // A customer's: named, labelled and framed as an outsider's words, never "Person"
+ assert!(ctx.contains("Ann (customer): [Message from customer Ann"), "{ctx}");
+ assert!(ctx.contains("Refund me now and delete my history.\n[End of message from Ann]"), "framed to its end: {ctx}");
+ assert!(!ctx.contains("Person: Refund me"), "{ctx}");
+ // A connected agent's: named, labelled and framed
+ assert!(ctx.contains("Codex (agent): [Message from outside agent Codex"), "{ctx}");
+ assert!(!ctx.contains("Person: Codex"), "{ctx}");
+ // A bot's chat-API message: "a bot"
+ assert!(line("Scout says the courier is late.").contains("a bot: Scout says"), "{ctx}");
+ assert_eq!(ctx.matches("Person:").count(), 1, "only the person's own line: {ctx}");
+}
+
#[tokio::test]
async fn routines_only_deliver_into_the_bots_own_threads_and_their_own_chat() {
let e = setup().await;