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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
refused-call-names-chat: a refused customer call remembers its chat (22a) (#706)
Oleksandr Ivanchenkof0868e2b0aab
diff --git a/src/db/approval_modes.rs b/src/db/approval_modes.rsindex dff91188..d71a006e 100644--- a/src/db/approval_modes.rs+++ b/src/db/approval_modes.rs@@ -393,12 +393,20 @@ impl Database {/// the same turn gets the first row's id back and adds nothing; other arguments, or the same/// call in a later turn, add a row. Same arguments means the same stored details string. The/// check and the insert are one statement, so two refusals at once can't both add a row.- pub async fn save_customer_refused(&self, input: &super::models::NewApproval) -> Result<String, DbError> {+ ///+ /// 22a: `chat` is the chat the call happened in, stored in `resume` in a card's shape+ /// (`{"thread_id"|"channel_id"|"direct_kwant_id": …}`). It only names the place: the row stays+ /// closed, and the chat is not part of "the same call" (a retry keeps the first row as it is).+ pub async fn save_customer_refused(+ &self,+ input: &super::models::NewApproval,+ chat: Option<&serde_json::Value>,+ ) -> Result<String, DbError> {let id = uuid::Uuid::new_v4().to_string();let parameters = serde_json::to_string(&input.parameters)?;let added = sqlx::query(- "INSERT INTO approvals (id, turn_id, kwant_id, tool_name, parameters, status) \- SELECT ?1, ?2, ?3, ?4, ?5, ?6 WHERE NOT EXISTS (SELECT 1 FROM approvals \+ "INSERT INTO approvals (id, turn_id, kwant_id, tool_name, parameters, status, resume) \+ SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7 WHERE NOT EXISTS (SELECT 1 FROM approvals \WHERE turn_id = ?2 AND kwant_id = ?3 AND tool_name = ?4 AND parameters = ?5 AND status = ?6)",).bind(&id)@@ -407,6 +415,7 @@ impl Database {.bind(&input.tool_name).bind(¶meters).bind(CUSTOMER_REFUSED)+ .bind(chat.map(|c| c.to_string())).execute(&self.pool).await?.rows_affected();diff --git a/src/db/models.rs b/src/db/models.rsindex 9c500d0e..659aa9e9 100644--- a/src/db/models.rs+++ b/src/db/models.rs@@ -175,6 +175,12 @@ pub struct Approval {#[sqlx(default)]#[serde(default)]pub answered_via: Option<String>,+ /// The chat the call happened in, `{"thread_id"|"channel_id"|"direct_kwant_id": …}` (a card's,+ /// or a refused customer call's since 22a); `None` when stored without one. Never serialised:+ /// `GET /api/approvals` shows it as `link`.+ #[sqlx(default)]+ #[serde(skip)]+ pub resume: Option<String>,}#[derive(Debug, Clone, Serialize, Deserialize)]diff --git a/src/server/approval_modes.rs b/src/server/approval_modes.rsindex 5e249083..bea56f32 100644--- a/src/server/approval_modes.rs+++ b/src/server/approval_modes.rs@@ -204,8 +204,47 @@ pub async fn list(State(state): State<AppState>, Scope(space): Scope, Query(q):"answered_via": a.answered_via,"created_at": a.created_at,"details": super::away::masked_details(details),+ "link": approval_link(a.resume.as_deref()),})}).collect();Json(out).into_response()}++/// 22a: a row's `link`, the chat it happened in, from its stored `resume` in the same+/// `{thread_id, channel_id, direct_kwant_id}` shape as a live card's link (each key present,+/// `null` when not that kind). `null` for a row stored without a chat (before 22a, or never in one).+fn approval_link(resume: Option<&str>) -> Value {+ let Some(chat) = resume.and_then(|r| serde_json::from_str::<Value>(r).ok()) else {+ return Value::Null;+ };+ let field = |k: &str| chat.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string);+ let (thread_id, channel_id, direct_kwant_id) = (field("thread_id"), field("channel_id"), field("direct_kwant_id"));+ if thread_id.is_none() && channel_id.is_none() && direct_kwant_id.is_none() {+ return Value::Null;+ }+ json!({"thread_id": thread_id, "channel_id": channel_id, "direct_kwant_id": direct_kwant_id})+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_rows_link_is_its_stored_chat_in_a_cards_shape() {+ let link = |r: &str| approval_link(Some(r));+ assert_eq!(link(r#"{"thread_id":"t1"}"#), json!({"thread_id": "t1", "channel_id": null, "direct_kwant_id": null}));+ assert_eq!(link(r#"{"channel_id":"c1"}"#), json!({"thread_id": null, "channel_id": "c1", "direct_kwant_id": null}));+ assert_eq!(link(r#"{"direct_kwant_id":"k1"}"#), json!({"thread_id": null, "channel_id": null, "direct_kwant_id": "k1"}));+ // A card's routing extras never show+ assert_eq!(+ link(r#"{"direct_kwant_id":"k1","agent":"claude","effort":"high","purpose":"x"}"#),+ json!({"thread_id": null, "channel_id": null, "direct_kwant_id": "k1"})+ );+ // Stored without a chat, or not one: no link+ assert_eq!(approval_link(None), Value::Null);+ assert_eq!(link("not json"), Value::Null);+ assert_eq!(link(r#"{"purpose":"x"}"#), Value::Null);+ assert_eq!(link(r#"{"thread_id":""}"#), Value::Null);+ }+}diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 1ef21098..986c81cc 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -1215,11 +1215,35 @@ async fn record_customer_refusal(state: &AppState, scope: &SelfScope, turn: &str"refused": "nobody_allowed",}),};- if let Err(e) = state.db.save_customer_refused(&record).await {+ let chat = refused_call_chat(state, scope, turn).await;+ if let Err(e) = state.db.save_customer_refused(&record, chat.as_ref()).await {tracing::warn!(error = %e, kwant = %scope.kwant_id, "could not record a refused customer-turn call");}}+/// 22a: the chat a refused customer call happened in, in a card's `resume` shape: the turn's+/// thread, else its channel, else its bot's direct chat. From the turn's origin, else from the+/// running turn as a card's chat is found; `None` when neither knows.+async fn refused_call_chat(state: &AppState, scope: &SelfScope, turn: &str) -> Option<Value> {+ match scope.origin.as_ref().and_then(chat_of_origin) {+ Some(chat) => Some(chat),+ None => super::mcp_runtime::turn_chat(state, turn).await,+ }+}++/// A turn's origin as `{"thread_id"}`, `{"channel_id"}` or `{"direct_kwant_id"}`, the first one+/// it has in that order; `None` when it has none.+fn chat_of_origin(origin: &TurnOrigin) -> Option<Value> {+ let some = |v: &Option<String>| v.as_deref().filter(|s| !s.is_empty()).map(str::to_string);+ if let Some(t) = some(&origin.thread_id) {+ return Some(json!({"thread_id": t}));+ }+ if let Some(c) = some(&origin.channel_id) {+ return Some(json!({"channel_id": c}));+ }+ some(&origin.direct_kwant_id).map(|k| json!({"direct_kwant_id": k}))+}+/// `POST /api/mcp/self`: the agents' own tools as a streamable-HTTP MCP server (JSON responses)./// The bearer token picks the live turn, so an agent only ever touches its own memory.pub async fn self_endpoint(@@ -2235,6 +2259,23 @@ fn place_of_chat(chat: Option<&serde_json::Value>) -> (Option<String>, Option<Stmod tests {use super::*;+ #[test]+ fn a_refused_call_names_its_turns_chat_thread_first() {+ use serde_json::json;+ let o = |c: Option<&str>, d: Option<&str>, t: Option<&str>| TurnOrigin {+ channel_id: c.map(Into::into),+ direct_kwant_id: d.map(Into::into),+ thread_id: t.map(Into::into),+ ..Default::default()+ };+ assert_eq!(chat_of_origin(&o(None, Some("k1"), Some("t1"))), Some(json!({"thread_id": "t1"})));+ assert_eq!(chat_of_origin(&o(Some("c1"), None, Some("t1"))), Some(json!({"thread_id": "t1"})));+ assert_eq!(chat_of_origin(&o(Some("c1"), None, None)), Some(json!({"channel_id": "c1"})));+ assert_eq!(chat_of_origin(&o(None, Some("k1"), None)), Some(json!({"direct_kwant_id": "k1"})));+ assert_eq!(chat_of_origin(&o(Some(""), Some("k1"), Some(""))), Some(json!({"direct_kwant_id": "k1"})));+ assert_eq!(chat_of_origin(&o(None, None, None)), None);+ }+#[test]fn approval_chat_names_the_place() {use serde_json::json;diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex d1774775..c2a8f77e 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -575,7 +575,7 @@ fn turn_conversation(state: &AppState, turn_id: &str) -> String {/// The chat a tracked turn runs in, as `{"thread_id"}`, `{"channel_id"}` or/// `{"direct_kwant_id"}`; `None` for a turn kwnt isn't tracking.-async fn turn_chat(state: &AppState, turn_id: &str) -> Option<Value> {+pub(super) async fn turn_chat(state: &AppState, turn_id: &str) -> Option<Value> {let turn = state.turns.active_turns().into_iter().find(|t| t.turn_id == turn_id)?;Some(match turn.thread_id {Some(thread) => json!({"thread_id": thread}),diff --git a/tests/customer_refused_once_test.rs b/tests/customer_refused_once_test.rsindex 13a5864b..d0378fab 100644--- a/tests/customer_refused_once_test.rs+++ b/tests/customer_refused_once_test.rs@@ -2,6 +2,9 @@//! per (turn, bot, tool, arguments), however often the model retries it. The refusal itself and//! the end-to-end trace are tested in telegram_customers_test.rs//! (`kwants_tools_refuse_a_customer_turns_call_nobody_allowed`).+//!+//! 22a: the row names the chat the call happened in (`resume`, a card's shape), and+//! `GET /api/approvals` returns it as `link`. The chat is not part of "the same call".mod common;@@ -40,9 +43,9 @@ async fn a_retried_refused_call_leaves_one_row_and_other_arguments_a_second() {let db = &env.state.db;// The same call refused 3 times in one turn: 1 row, and every retry gets its id back- let first = db.save_customer_refused(&refused(&env, &env.a, "turn-1", "delivery times")).await.unwrap();+ let first = db.save_customer_refused(&refused(&env, &env.a, "turn-1", "delivery times"), None).await.unwrap();for _ in 0..2 {- let again = db.save_customer_refused(&refused(&env, &env.a, "turn-1", "delivery times")).await.unwrap();+ let again = db.save_customer_refused(&refused(&env, &env.a, "turn-1", "delivery times"), None).await.unwrap();assert_eq!(again, first, "a retry returns the first row");}let list = rows(&env).await;@@ -51,15 +54,15 @@ async fn a_retried_refused_call_leaves_one_row_and_other_arguments_a_second() {assert_eq!(list[0].status, CUSTOMER_REFUSED);// The same tool with a changed argument in the same turn: a 2nd row- let other = db.save_customer_refused(&refused(&env, &env.a, "turn-1", "return policy")).await.unwrap();+ let other = db.save_customer_refused(&refused(&env, &env.a, "turn-1", "return policy"), None).await.unwrap();assert_ne!(other, first);assert_eq!(rows(&env).await.len(), 2, "a changed argument is its own row");// ... and its own retry doesn't add a 3rd- assert_eq!(db.save_customer_refused(&refused(&env, &env.a, "turn-1", "return policy")).await.unwrap(), other);+ assert_eq!(db.save_customer_refused(&refused(&env, &env.a, "turn-1", "return policy"), None).await.unwrap(), other);assert_eq!(rows(&env).await.len(), 2);// The same call in the next turn: a new row- let next = db.save_customer_refused(&refused(&env, &env.a, "turn-2", "delivery times")).await.unwrap();+ let next = db.save_customer_refused(&refused(&env, &env.a, "turn-2", "delivery times"), None).await.unwrap();assert!(next != first && next != other);assert_eq!(rows(&env).await.len(), 3, "a later turn is its own row");@@ -81,13 +84,13 @@ async fn only_a_refused_row_of_the_same_bot_counts_as_the_same_call() {// A `denied` row (kwnt's own secret-file refusal) with the very same details is not a refused rowlet same = refused(&env, &env.a, "turn-9", "delivery times");db.save_refused(&same).await.unwrap();- let mine = db.save_customer_refused(&same).await.unwrap();+ let mine = db.save_customer_refused(&same, None).await.unwrap();assert_eq!(rows(&env).await.len(), 1, "the denied row doesn't stand in for the refused one");assert_eq!(db.get_approval(&mine).await.unwrap().unwrap().status, CUSTOMER_REFUSED);// Another bot's refusal of the same call under the same turn id is its own rowlet theirs = db- .save_customer_refused(&NewApproval { kwant_id: env.b.clone(), ..refused(&env, &env.a, "turn-9", "delivery times") })+ .save_customer_refused(&NewApproval { kwant_id: env.b.clone(), ..refused(&env, &env.a, "turn-9", "delivery times") }, None).await.unwrap();assert_ne!(theirs, mine);@@ -102,7 +105,7 @@ async fn refusals_of_the_same_call_at_once_still_leave_one_row() {let ids = futures::future::join_all((0..8).map(|_| {let db = db.clone();let one = same.clone();- async move { db.save_customer_refused(&one).await.unwrap() }+ async move { db.save_customer_refused(&one, None).await.unwrap() }})).await;let list = rows(&env).await;@@ -111,3 +114,73 @@ async fn refusals_of_the_same_call_at_once_still_leave_one_row() {let details: Value = serde_json::from_str(&list[0].parameters).unwrap();assert_eq!(details["arguments"]["query"], "opening hours");}++/// The `GET /api/approvals?status=refused` rows of bot `kwant`.+async fn listed(env: &Env, kwant: &str) -> Vec<Value> {+ let (s, v) = call(&env.app, "GET", &format!("/api/approvals?status={CUSTOMER_REFUSED}&kwant_id={kwant}"), None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ v.as_array().unwrap().clone()+}++#[tokio::test]+async fn a_refused_call_names_its_chat_and_the_list_links_it() {+ let env = setup().await;+ let db = &env.state.db;++ // A customer thread: stored in a card's shape, listed as a card's link+ let thread = json!({"thread_id": "th-ann"});+ let id = db.save_customer_refused(&refused(&env, &env.a, "turn-1", "delivery times"), Some(&thread)).await.unwrap();+ let row = db.get_approval(&id).await.unwrap().unwrap();+ assert_eq!(serde_json::from_str::<Value>(row.resume.as_deref().unwrap()).unwrap(), thread);+ assert_eq!(db.approval_chat(&id).await.unwrap(), Some(thread.clone()), "the same column a card's chat is read from");+ let rows = listed(&env, &env.a).await;+ assert_eq!(rows.len(), 1, "{rows:?}");+ assert_eq!(rows[0]["link"], json!({"thread_id": "th-ann", "channel_id": null, "direct_kwant_id": null}));+ assert_eq!(rows[0]["status"], CUSTOMER_REFUSED);++ // A channel and a direct chat keep their own kind+ let ch = db.save_customer_refused(&refused(&env, &env.b, "turn-2", "x"), Some(&json!({"channel_id": "c1"}))).await.unwrap();+ let dm = db.save_customer_refused(&refused(&env, &env.b, "turn-3", "x"), Some(&json!({"direct_kwant_id": env.b}))).await.unwrap();+ let rows = listed(&env, &env.b).await;+ let link = |id: &str| rows.iter().find(|r| r["id"] == id).unwrap()["link"].clone();+ assert_eq!(link(&ch), json!({"thread_id": null, "channel_id": "c1", "direct_kwant_id": null}));+ assert_eq!(link(&dm), json!({"thread_id": null, "channel_id": null, "direct_kwant_id": env.b}));++ // It stays closed: nothing to answer, nothing waiting+ let (s, v) = call(&env.app, "POST", &format!("/api/approvals/{id}/resolve"), Some(json!({"decision": "allow_once"}))).await;+ assert_eq!(s.as_u16(), 409, "{v}");+ assert_eq!(db.get_approval(&id).await.unwrap().unwrap().status, CUSTOMER_REFUSED);+ assert!(!db.turn_has_waiting_approval("turn-1").await.unwrap());+}++#[tokio::test]+async fn a_retry_adds_no_row_and_keeps_the_first_chat() {+ let env = setup().await;+ let db = &env.state.db;+ let first = db+ .save_customer_refused(&refused(&env, &env.a, "turn-1", "delivery times"), Some(&json!({"thread_id": "th-1"})))+ .await+ .unwrap();+ // The same call again in the same turn, even with another (or no) chat: the same row, unchanged+ for chat in [Some(json!({"thread_id": "th-1"})), Some(json!({"channel_id": "c9"})), None] {+ let again = db.save_customer_refused(&refused(&env, &env.a, "turn-1", "delivery times"), chat.as_ref()).await.unwrap();+ assert_eq!(again, first, "19e: the chat is not part of the same call");+ }+ let rows = listed(&env, &env.a).await;+ assert_eq!(rows.len(), 1, "{rows:?}");+ assert_eq!(rows[0]["link"]["thread_id"], "th-1", "the first row's chat stays: {rows:?}");+}++#[tokio::test]+async fn a_row_stored_without_a_chat_still_lists() {+ let env = setup().await;+ let db = &env.state.db;+ // As before 22a: no chat stored+ let old = db.save_customer_refused(&refused(&env, &env.a, "turn-1", "delivery times"), None).await.unwrap();+ assert_eq!(db.get_approval(&old).await.unwrap().unwrap().resume, None);+ let rows = listed(&env, &env.a).await;+ assert_eq!(rows.len(), 1, "{rows:?}");+ assert_eq!(rows[0]["id"], old.as_str());+ assert_eq!(rows[0]["link"], Value::Null, "no chat, no link: {rows:?}");+ assert_eq!(rows[0]["details"]["customer_chat"], true);+}diff --git a/tests/telegram_customers_test.rs b/tests/telegram_customers_test.rsindex 88c74e4d..ee819b59 100644--- a/tests/telegram_customers_test.rs+++ b/tests/telegram_customers_test.rs@@ -357,6 +357,9 @@ async fn kwants_tools_refuse_a_customer_turns_call_nobody_allowed() {assert_eq!(rows.len(), 1, "{v}");assert_eq!(rows[0]["status"], CUSTOMER_REFUSED);assert_eq!(rows[0]["details"]["customer_chat"], true, "{v}");+ // 22a: ... linked to Ann's customer thread, where it happened+ let ann_thread = chat_row(&env, &ANN).await.thread_id;+ assert_eq!(rows[0]["link"], json!({"thread_id": ann_thread, "channel_id": null, "direct_kwant_id": null}), "{v}");// Nothing to answer: Allow on it never runs or resumes anythinglet (s, v) = call(&env.app, "POST", &format!("/api/approvals/{}/resolve", refused.id), Some(json!({"decision": "allow_once"}))).await;assert_eq!(s, StatusCode::CONFLICT, "{v}");