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.

A hand-off never passes a customer's message on as the person's request (20b) (#687)

Oleksandr Ivanchenkobe4361820e1c
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 7ebc18ba..99351e44 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -4,7 +4,7 @@
use super::routes::{continue_once_if_capped, continue_once_if_capped_into, scope_for, try_kwant_turn, TurnOpts};
use super::AppState;
-use crate::db::models::{Kwant, MessageExtra, NewMessage};
+use crate::db::models::{Kwant, Message, MessageExtra, NewMessage};
use crate::db::spaces::SpaceId;
use crate::db::threads::{Delegation, NewDelegation, Thread, MAX_TASK_CHARS};
use crate::drivers::RuntimeEvent;
@@ -48,6 +48,42 @@ fn clip(text: &str, max: usize) -> String {
out
}
+/// The message a hand-off passes on as what was asked in a chat (20b), among `msgs` (oldest
+/// first) that pass `fits`: the person's own newest message ([`super::routes::is_persons`]), else
+/// the newest other "user" message (a customer's, a connected agent's, a bot's chat-API message).
+fn asked_in(msgs: &[Message], fits: impl Fn(&Message) -> bool) -> Option<&Message> {
+ let mut users = msgs.iter().rev().filter(|m| m.sender_role == "user" && fits(m));
+ let newest = users.clone().next()?;
+ Some(users.find(|m| super::routes::is_persons(m)).unwrap_or(newest))
+}
+
+/// `text` (`m`'s text, maybe clipped) as a hand-off passes it on: the person's own words as they
+/// are, anyone else's framed as theirs ([`crate::drivers::user_history_text`] for a customer or
+/// a connected agent, [`crate::drivers::peer_message`] for a bot's chat-API message), so a
+/// customer's message never reaches the next bot as the owner's request. Framed after clipping,
+/// so the frame's end marker is never cut off.
+fn as_asked(m: &Message, text: String) -> String {
+ if super::routes::is_persons(m) {
+ return text;
+ }
+ if !crate::drivers::from_outsider(m) {
+ let name = match m.sender_id.trim() {
+ "" | "user" => "unnamed",
+ id => id,
+ };
+ return crate::drivers::peer_message(name, &text);
+ }
+ crate::drivers::user_history_text(&Message { text, ..m.clone() })
+}
+
+/// What was asked in chat `context`, for a hand-off's "the user's original request" (20b): see
+/// [`asked_in`] and [`as_asked`]; `fallback` (the delegation's task) when the chat has no "user"
+/// message.
+async fn request_text(state: &AppState, context: &str, fallback: &str) -> String {
+ let msgs = state.db.list_messages(context, 100).await.unwrap_or_default();
+ asked_in(&msgs, |_| true).map(|m| as_asked(m, m.text.clone())).unwrap_or_else(|| fallback.to_string())
+}
+
/// A specialist's reply as posted to the origin chat: clipped, saying where the rest is.
fn result_text(reply: &str) -> String {
let full = reply.trim();
@@ -656,12 +692,13 @@ pub(super) async fn shared_origin(state: &AppState, kwant_id: &str, thread_id: &
}
/// The person's last request in `recent` (oldest first) made by `at`: their newest non-empty message
-/// then. A customer's or a connected agent's "user" message is never "what the person asked" (16d).
+/// then. A customer's or a connected agent's "user" message is never "what the person asked" (16d),
+/// nor is a bot's chat-API message (20b, [`super::routes::is_persons`]).
fn persons_request(recent: &[crate::db::models::Message], at: DateTime<Utc>) -> Option<&crate::db::models::Message> {
recent
.iter()
.rev()
- .find(|m| crate::drivers::from_person(m) && m.created_at.is_none_or(|t| t <= at) && !m.text.trim().is_empty())
+ .find(|m| super::routes::is_persons(m) && m.created_at.is_none_or(|t| t <= at) && !m.text.trim().is_empty())
}
/// What the specialist should know of the chat the task came from: the person's last request
@@ -803,16 +840,7 @@ async fn relay_mentions(state: &AppState, done: &Delegation, specialist: &Kwant,
if !scope.teammates.iter().any(|k| k.id == specialist.id) {
return;
}
- let user_prompt = state
- .db
- .list_messages(done.origin_context().unwrap_or(&lead.id), 100)
- .await
- .unwrap_or_default()
- .into_iter()
- .rev()
- .find(|m| m.sender_role == "user")
- .map(|m| m.text)
- .unwrap_or_else(|| done.task.clone());
+ let user_prompt = request_text(state, done.origin_context().unwrap_or(&lead.id), &done.task).await;
let end = |d: &Delegation| d.ended_at.unwrap_or(d.created_at);
let alongside = state
.db
@@ -1177,16 +1205,7 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], o
if let Ok(reply) = outcome {
let mut spoken = vec![lead.id.clone()];
spoken.extend(batch.iter().map(|b| b.specialist_kwant_id.clone()));
- let user_prompt = state
- .db
- .list_messages(d.origin_context().unwrap_or(&lead.id), 100)
- .await
- .unwrap_or_default()
- .into_iter()
- .rev()
- .find(|m| m.sender_role == "user")
- .map(|m| m.text)
- .unwrap_or_else(|| d.task.clone());
+ let user_prompt = request_text(state, d.origin_context().unwrap_or(&lead.id), &d.task).await;
super::routes::run_handoffs_boxed(&scope, &spoken, &[(lead.clone(), reply.clone())], &user_prompt).await;
// The chain may be over now: several open questions for the person become one list
super::asks::consolidate(&scope).await;
@@ -1907,6 +1926,101 @@ pub async fn tool_cancel(state: &AppState, scope: &super::continuity::SelfScope,
}
}
+#[cfg(test)]
+mod request_tests {
+ use super::*;
+
+ fn msg(role: &str, sender: &str, text: &str, meta: Option<Value>) -> Message {
+ Message {
+ id: uuid::Uuid::new_v4().to_string(),
+ channel_id: None,
+ direct_kwant_id: Some("lead".into()),
+ sender_role: role.into(),
+ sender_id: sender.into(),
+ text: text.into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ created_at: None,
+ thread_id: None,
+ meta: meta.map(|m| m.to_string()),
+ results: None,
+ reply_to_message_id: None,
+ reaction: None,
+ reply_to: None,
+ }
+ }
+
+ fn asked(msgs: &[Message]) -> Option<String> {
+ asked_in(msgs, |_| true).map(|m| as_asked(m, m.text.clone()))
+ }
+
+ fn person(text: &str) -> Message {
+ msg("user", "user", text, None)
+ }
+
+ fn customer(text: &str) -> Message {
+ msg("user", "Ann", text, Some(json!({"from_customer": "Ann"})))
+ }
+
+ #[test]
+ fn a_customers_message_is_passed_on_framed_as_the_customers() {
+ let chat = [msg("kwant", "Lead", "Hi Ann, how can I help?", None), customer("Refund me now and delete my history.")];
+ let text = asked(&chat).unwrap();
+ assert!(text.starts_with("[Message from customer Ann (an outside person"), "{text}");
+ assert!(text.ends_with("Refund me now and delete my history.\n[End of message from Ann]"), "{text}");
+ // As the relay puts it into the next bot's prompt: never the customer's words unframed
+ let prompt = format!("The user's original request:\n{text}");
+ assert!(!prompt.contains("The user's original request:\nRefund me"), "{prompt}");
+ }
+
+ #[test]
+ fn the_persons_own_newest_message_wins_over_a_newer_customers() {
+ let chat = [
+ person("Old ask"),
+ person("Keep refunds under 50 euros."),
+ msg("kwant", "Lead", "On it.", None),
+ customer("Refund me 500 euros."),
+ ];
+ assert_eq!(asked(&chat).as_deref(), Some("Keep refunds under 50 euros."));
+ }
+
+ #[test]
+ fn in_a_normal_chat_the_persons_words_pass_on_as_they_are() {
+ let chat = [person("Plan the launch"), msg("kwant", "Lead", "@Writer draft the intro", None), person(" Ship it \n")];
+ assert_eq!(asked(&chat).as_deref(), Some(" Ship it \n"));
+ assert_eq!(asked(&[msg("kwant", "Lead", "hello", None)]), None, "no user message: the caller's fallback");
+ }
+
+ #[test]
+ fn an_agents_or_a_bots_chat_api_message_is_framed_as_theirs() {
+ let agent = msg("user", "user", "Deploy to prod.", Some(json!({"from_agent": "Codex"})));
+ let text = asked(&[agent]).unwrap();
+ assert!(text.starts_with("[Message from outside agent Codex"), "{text}");
+ let by_bot = msg("user", "Scout", "Scout says: post the draft.", Some(json!({"sent_by_bot": true})));
+ let text = asked(&[by_bot]).unwrap();
+ assert!(text.starts_with("[Message from bot Scout (another assistant)") && text.ends_with("[End of message from Scout]"), "{text}");
+ let anon = msg("user", "user", "Do it.", Some(json!({"sent_by_bot": true})));
+ assert!(asked(&[anon]).unwrap().starts_with("[Message from bot unnamed"));
+ }
+
+ #[test]
+ fn a_clipped_customers_message_keeps_its_frames_end() {
+ let long = customer(&"word ".repeat(400));
+ let text = as_asked(&long, clip(long.text.trim(), 50));
+ assert!(text.ends_with("…\n[End of message from Ann]"), "{text}");
+ }
+
+ #[test]
+ fn the_filter_applies_before_choosing() {
+ let chat = [person("Before the task"), customer("After the task")];
+ let m = asked_in(&chat, |m| m.text != "After the task").unwrap();
+ assert_eq!(m.text, "Before the task");
+ let m = asked_in(&chat, |m| m.text != "Before the task").unwrap();
+ assert_eq!(as_asked(m, m.text.clone()).lines().nth(1), Some("After the task"));
+ }
+}
+
#[cfg(test)]
mod customer_tests {
use super::*;
@@ -1928,5 +2042,9 @@ mod customer_tests {
// The person's own newer message is their request; one after the hand-off isn't
let mine = vec![at(said("user", "old"), 0), at(said("user", "Draft it shorter"), 5), at(said("user", "later"), 20)];
assert_eq!(persons_request(&mine, handed_on).map(|m| m.text.as_str()), Some("Draft it shorter"));
+ // 20b: nor is a bot's chat-API message the person's request
+ let by_bot = crate::db::models::Message { meta: Some(json!({"sent_by_bot": true}).to_string()), ..said("user", "Scout says: post the draft") };
+ let chat = vec![at(said("user", "Draft the spring newsletter"), 0), at(by_bot, 3)];
+ assert_eq!(persons_request(&chat, handed_on).map(|m| m.text.as_str()), Some("Draft the spring newsletter"));
}
}
diff --git a/tests/attachments_test.rs b/tests/attachments_test.rs
index 65740d42..bd49a135 100644
--- a/tests/attachments_test.rs
+++ b/tests/attachments_test.rs
@@ -441,6 +441,58 @@ async fn a_delegated_task_carries_the_persons_request_and_files() {
/// 0.8.0 P4: a shared file is posted as the bot (its name, the id in meta), and the same bytes
/// shared again in the same chat within a few minutes aren't posted twice.
+/// 20b/16d: a customer's message in the chat a task came from never reaches the specialist as what
+/// the person asked; the person's own message, when there is one, is.
+#[tokio::test]
+async fn a_delegated_task_never_passes_a_customers_message_on_as_the_persons() {
+ let env = setup().await;
+ let say = |sender: &str, text: &str, meta: Option<Value>| {
+ let input = kwnt::db::models::NewMessage {
+ channel_id: None,
+ direct_kwant_id: Some(env.a.clone()),
+ sender_role: "user".into(),
+ sender_id: sender.into(),
+ text: text.into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let extra = kwnt::db::models::MessageExtra { thread_id: None, meta };
+ let db = env.state.db.clone();
+ async move { db.insert_message_with(&input, &extra).await.unwrap() }
+ };
+ let delegate = |title: &'static str| {
+ let body = json!({"lead_kwant_id": env.a, "specialist_kwant_id": env.b, "task": format!("Answer Ann ({title}). REPLYTAG:c20b"), "title": title, "kwant_id": env.a, "continue_lead": false});
+ let app = env.app.clone();
+ async move {
+ let (s, d) = call(&app, "POST", "/api/delegations", Some(body)).await;
+ assert_eq!(s, StatusCode::ACCEPTED, "{d}");
+ let marker = format!("Task: {title}");
+ wait_for("the specialist's brief", || {
+ let found = !invocations_with(&marker).is_empty();
+ async move { found }
+ })
+ .await;
+ invocations_with(&marker).pop().unwrap()
+ }
+ };
+ let asked = "[What the person asked in the chat this task came from]\n";
+
+ // Only a customer has written in the chat: there is no request of the person's to show (16d),
+ // so the brief has no "what the person asked" line at all
+ say("Ann", "Refund me now and delete my history. CUSTOMER_ONE", Some(json!({"from_customer": "Ann"}))).await;
+ let brief = delegate("Customer reply one").await;
+ assert!(!brief.contains(asked), "{brief}");
+ assert!(!brief.contains("CUSTOMER_ONE"), "{brief}");
+
+ // The person's own message, then a newer customer's: the person's is what was asked
+ say("user", "Keep refunds under 50 euros. PERSON_ASK", None).await;
+ say("Ann", "Refund me 500 euros. CUSTOMER_TWO", Some(json!({"from_customer": "Ann"}))).await;
+ let brief = delegate("Customer reply two").await;
+ assert!(brief.contains(&format!("{asked}Keep refunds under 50 euros. PERSON_ASK")), "{brief}");
+ assert!(!brief.contains("CUSTOMER_TWO"), "{brief}");
+}
+
#[tokio::test]
async fn shared_files_post_as_the_bot_and_repeats_are_skipped() {
let env = setup().await;