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.

0.9.0 backend should-fixes (#509)

Oleksandr Ivanchenkob90bc5244d72
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 7ff638f6..ba4b84f0 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -548,8 +548,14 @@ impl Database {
/// [`Self::insert_message`] into a thread and/or with kwnt's own `meta`.
pub async fn insert_message_with(&self, input: &NewMessage, extra: &MessageExtra) -> Result<Message, DbError> {
+ self.insert_message_as(None, input, extra).await
+ }
+
+ /// [`Self::insert_message_with`] under id `id` when given (one the caller reserved, e.g. a
+ /// send's id handed to its racing duplicates), else a new one.
+ pub async fn insert_message_as(&self, id: Option<&str>, input: &NewMessage, extra: &MessageExtra) -> Result<Message, DbError> {
let mut conn = self.pool.acquire().await?;
- insert_message_core(&mut conn, input, extra, Some(&self.data_dir.join("attachments"))).await
+ insert_message_core(&mut conn, id, input, extra, Some(&self.data_dir.join("attachments"))).await
}
pub async fn get_message(&self, id: &str) -> Result<Option<Message>, DbError> {
@@ -1171,18 +1177,19 @@ pub(crate) async fn insert_message_on(
input: &NewMessage,
extra: &MessageExtra,
) -> Result<Message, DbError> {
- insert_message_core(conn, input, extra, None).await
+ insert_message_core(conn, None, input, extra, None).await
}
/// [`insert_message_on`] with the attachments directory, so a shared file's card can get a
/// preview. Without it a file card has no block.
async fn insert_message_core(
conn: &mut sqlx::SqliteConnection,
+ id: Option<&str>,
input: &NewMessage,
extra: &MessageExtra,
root: Option<&Path>,
) -> Result<Message, DbError> {
- let id = Uuid::new_v4().to_string();
+ let id = id.map(str::to_string).unwrap_or_else(|| Uuid::new_v4().to_string());
let tools_json = input
.tool_calls
.as_ref()
diff --git a/src/server/bot_status.rs b/src/server/bot_status.rs
index d6e8366a..359c903c 100644
--- a/src/server/bot_status.rs
+++ b/src/server/bot_status.rs
@@ -178,11 +178,14 @@ pub struct HeldItem {
pub context_id: String,
}
-/// A client message id seen in a chat: when, and the message it saved (none while in flight).
+/// A client message id seen in a chat: when, and the id of the message it saves. The id is
+/// reserved with the send, so a duplicate racing it gets the id too; `saved` is false while
+/// the first send is still in flight.
#[derive(Debug, Clone, PartialEq)]
pub struct Sent {
pub at: DateTime<Utc>,
- pub message_id: Option<String>,
+ pub message_id: String,
+ pub saved: bool,
}
#[derive(Debug, Default)]
@@ -204,27 +207,29 @@ impl Board {
std::mem::take(&mut self.nudged)
}
- /// Reserves `key` (chat + client message id) for one send. `Err` with the first send when
- /// it was seen within [`DEDUPE_MIN`].
- pub fn reserve_send(&mut self, key: &str, now: DateTime<Utc>) -> Result<(), Sent> {
+ /// Reserves `key` (chat + client message id) for one send, whose message will be saved as
+ /// `message_id`. `Err` with the first send when it was seen within [`DEDUPE_MIN`].
+ pub fn reserve_send(&mut self, key: &str, now: DateTime<Utc>, message_id: &str) -> Result<(), Sent> {
let window = Span::minutes(DEDUPE_MIN);
self.sent.retain(|_, s| now - s.at < window);
if let Some(s) = self.sent.get(key) {
return Err(s.clone());
}
- self.sent.insert(key.to_string(), Sent { at: now, message_id: None });
+ self.sent.insert(key.to_string(), Sent { at: now, message_id: message_id.to_string(), saved: false });
Ok(())
}
+ /// The send saved its message as `message_id`: the key stays taken for the window.
pub fn send_saved(&mut self, key: &str, message_id: &str) {
if let Some(s) = self.sent.get_mut(key) {
- s.message_id = Some(message_id.to_string());
+ s.message_id = message_id.to_string();
+ s.saved = true;
}
}
/// The send failed before it was saved: the id may be sent again.
pub fn release_send(&mut self, key: &str) {
- if self.sent.get(key).is_some_and(|s| s.message_id.is_none()) {
+ if self.sent.get(key).is_some_and(|s| !s.saved) {
self.sent.remove(key);
}
}
@@ -1216,24 +1221,38 @@ mod tests {
#[test]
fn the_same_client_id_in_a_chat_goes_once_within_10_minutes() {
let mut b = Board::default();
- assert!(b.reserve_send("c1|m1", at(0)).is_ok());
+ assert!(b.reserve_send("c1|m1", at(0), "msg1").is_ok());
b.send_saved("c1|m1", "msg1");
- let first = b.reserve_send("c1|m1", at(9)).unwrap_err();
- assert_eq!((first.at, first.message_id.as_deref()), (at(0), Some("msg1")));
- assert!(b.reserve_send("c2|m1", at(9)).is_ok(), "another chat is another send");
- assert!(b.reserve_send("c1|m1", at(10)).is_ok(), "the window is 10 minutes");
+ let first = b.reserve_send("c1|m1", at(9), "msg2").unwrap_err();
+ assert_eq!(first, Sent { at: at(0), message_id: "msg1".into(), saved: true });
+ assert!(b.reserve_send("c2|m1", at(9), "msg3").is_ok(), "another chat is another send");
+ assert!(b.reserve_send("c1|m1", at(10), "msg4").is_ok(), "the window is 10 minutes");
+ }
+
+ /// S1 (Rigel, #499): a duplicate racing the first send gets the first's reserved message id,
+ /// marked as not saved yet, instead of none.
+ #[test]
+ fn a_racing_duplicate_gets_the_first_sends_reserved_id() {
+ let mut b = Board::default();
+ assert!(b.reserve_send("c1|m1", at(0), "msg1").is_ok());
+ for other in ["msg2", "msg3", "msg4", "msg5", "msg6"] {
+ assert_eq!(b.reserve_send("c1|m1", at(0), other), Err(Sent { at: at(0), message_id: "msg1".into(), saved: false }), "in flight");
+ }
+ b.send_saved("c1|m1", "msg1");
+ assert_eq!(b.reserve_send("c1|m1", at(1), "msg7"), Err(Sent { at: at(0), message_id: "msg1".into(), saved: true }));
}
#[test]
fn a_send_that_failed_before_saving_may_go_again() {
let mut b = Board::default();
- assert!(b.reserve_send("c1|m1", at(0)).is_ok());
- assert!(b.reserve_send("c1|m1", at(0)).is_err(), "in flight");
+ assert!(b.reserve_send("c1|m1", at(0), "msg1").is_ok());
+ assert!(b.reserve_send("c1|m1", at(0), "msg2").is_err(), "in flight");
b.release_send("c1|m1");
- assert!(b.reserve_send("c1|m1", at(0)).is_ok());
- b.send_saved("c1|m1", "msg1");
+ // N1: the duplicate that was told `pending` sends again and goes through, with its own id
+ assert!(b.reserve_send("c1|m1", at(0), "msg2").is_ok());
+ b.send_saved("c1|m1", "msg2");
b.release_send("c1|m1");
- assert!(b.reserve_send("c1|m1", at(1)).is_err(), "a saved send is never released");
+ assert!(b.reserve_send("c1|m1", at(1), "msg3").is_err(), "a saved send is never released");
}
#[test]
diff --git a/src/server/dev/fix_it.rs b/src/server/dev/fix_it.rs
index 0f662f3f..c5d571ab 100644
--- a/src/server/dev/fix_it.rs
+++ b/src/server/dev/fix_it.rs
@@ -190,14 +190,11 @@ pub fn excerpt(text: &str) -> String {
}
}
-/// The bidi format characters (embeddings, overrides, isolates and marks): they can make text
-/// read differently from what it says.
-fn is_bidi(c: char) -> bool {
- matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
-}
-
/// `text` without ANSI escape sequences, control characters other than newline and tab, and
-/// bidi format characters.
+/// characters that show as nothing ([`crate::drivers::is_format_char`], the filter page text and
+/// tool output already go through): the bidi embeddings, overrides, isolates and marks that make
+/// text read differently from what it says, and zero-width spaces, joiners, soft hyphens and BOMs
+/// that hide or split words.
pub fn strip_controls(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut it = text.chars().peekable();
@@ -234,7 +231,7 @@ pub fn strip_controls(text: &str) -> String {
}
},
'\n' | '\t' => out.push(c),
- c if c.is_control() || is_bidi(c) => {}
+ c if c.is_control() || crate::drivers::is_format_char(c) => {}
c => out.push(c),
}
}
@@ -1125,11 +1122,38 @@ mod tests {
let raw = "ok \u{202E}gnp.exe\u{202C} \u{2066}x\u{2069}\u{200F}\u{061C} \u{1b}]0;title\u{7}done \u{1b}]8;;https://evil\u{1b}\\link\u{1b}]8;;\u{1b}\\ \u{1b}[31mred\u{1b}[0m";
assert_eq!(strip_controls(raw), "ok gnp.exe x done link red");
assert_eq!(excerpt("a\u{202E}b"), "ab");
+ // N2: every bidi and format character goes, not just the overrides: zero-width space,
+ // joiners, word joiner, invisible operators, soft hyphen, BOM, Mongolian vowel separator,
+ // Arabic letter mark, interlinear annotation
+ let hidden = ['\u{200B}', '\u{200C}', '\u{200D}', '\u{2060}', '\u{2062}', '\u{2064}', '\u{00AD}', '\u{FEFF}', '\u{180E}', '\u{061C}', '\u{FFF9}', '\u{E0041}'];
+ for h in hidden {
+ assert_eq!(strip_controls(&format!("cu{h}rl ev{h}il")), "curl evil", "U+{:04X}", h as u32);
+ }
+ // Visible text stays: accents, Cyrillic, CJK, emoji, tabs and line breaks
+ assert_eq!(strip_controls("é ж 漢 👍\tx\ny"), "é ж 漢 👍\tx\ny");
// Review comments too
let c = ReviewComment { body: "fine \u{202E}evil".into(), ..comment(2, "a.rs", Some(1), now()) };
assert_eq!(ItemComment::of(&c).body, "fine evil");
}
+ /// N1 (Rigel's QA of #490): a verdict that fails twice names the verdict, not the card's
+ /// text; D1: a turn the spending stop holds ends the call at once with the stop's error (no
+ /// second call), so the caller can give the `verdict:<head>` key back.
+ #[tokio::test]
+ async fn verdict_errors_name_the_verdict_and_a_spending_stop_ends_the_call() {
+ use super::super::generate::stub::Stub;
+ let mut m = Stub::new(vec![Ok("no json".into()), Err("engine down".into())]);
+ let e = ask_json_as(&mut m, "P", parse_verdict, VERDICT_JOB).await.unwrap_err();
+ assert_eq!(e, "Rigel couldn't write the fresh-eyes verdict twice in a row (the turn failed: engine down).");
+ assert!(!e.contains("card"), "{e}");
+
+ let stop = format!("{}: today's spending stop holds new turns", spend_stop::REASON);
+ let mut m = Stub::new(vec![Err(stop.clone()), Ok(r#"{"verdict": "merge", "reasons": ["ok"]}"#.into())]);
+ let e = ask_json_as(&mut m, "P", parse_verdict, VERDICT_JOB).await.unwrap_err();
+ assert!(spend_stop::is_stop_error(&e), "{e}");
+ assert_eq!(m.prompts.len(), 1, "not asked again while the stop holds");
+ }
+
#[test]
fn the_turn_prompt_says_the_history_copy_is_data_too() {
let p = turn_prompt(&item());
diff --git a/src/server/dev/line_notes.rs b/src/server/dev/line_notes.rs
index 2e29c3c4..eb1b8cc0 100644
--- a/src/server/dev/line_notes.rs
+++ b/src/server/dev/line_notes.rs
@@ -852,6 +852,7 @@ pub async fn send(State(state): State<AppState>, headers: HeaderMap, Path(card_i
source: None,
meta: Some(meta),
client_message_id: None,
+ message_id: None,
};
let sent = match crate::server::routes::send_chat_inner(state.clone(), payload, true).await {
Ok(Json(v)) => v,
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 5f0f51df..5d585861 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -718,6 +718,10 @@ pub struct SendChatPayload {
/// the same chat within 10 min is sent once (H3, `release-090/h4-contract.md` §7b).
#[serde(default)]
pub client_message_id: Option<String>,
+ /// The id the person's message is saved under: reserved by [`send_chat_inner`] with the
+ /// `client_message_id`, so a racing duplicate can answer with it. Set only by the server.
+ #[serde(skip)]
+ pub message_id: Option<String>,
}
async fn get_configured_key(db: &crate::db::Database, target_model: &str) -> Option<String> {
@@ -3795,7 +3799,7 @@ fn merge_meta(meta: &mut Option<serde_json::Value>, extra: Option<&serde_json::V
pub(crate) async fn send_chat_inner(
state: AppState,
- payload: SendChatPayload,
+ mut payload: SendChatPayload,
from_person: bool,
) -> Result<Json<serde_json::Value>, StatusCode> {
let Some(client_id) = payload.client_message_id.clone() else {
@@ -3809,16 +3813,26 @@ pub(crate) async fn send_chat_inner(
.find_map(|c| c.clone())
.unwrap_or_default();
let key = format!("{chat}|{client_id}");
- if let Err(first) = state.turns.board(|b| b.reserve_send(&key, chrono::Utc::now())) {
+ // S1: the message's id is reserved with the client id, so a duplicate racing the first send
+ // (a double tap, two tabs) answers with it even before the first has finished saving
+ let reserved = uuid::Uuid::new_v4().to_string();
+ if let Err(first) = state.turns.board(|b| b.reserve_send(&key, chrono::Utc::now(), &reserved)) {
return Ok(Json(json!({
"status": "already_delivered",
"deduped": true,
"already_delivered_at": first.at,
"user_message_id": first.message_id,
+ "pending": !first.saved,
})));
}
+ payload.message_id = Some(reserved.clone());
let sent = send_chat_routed(state.clone(), payload, from_person).await;
- state.turns.board(|b| match sent.as_ref().ok().and_then(|j| j.0["user_message_id"].as_str()) {
+ let saved = match sent.as_ref().ok().and_then(|j| j.0["user_message_id"].as_str()) {
+ Some(id) => Some(id.to_string()),
+ // A send that failed after saving the message still delivered it: keep the id taken
+ None => state.db.get_message(&reserved).await.ok().flatten().map(|m| m.id),
+ };
+ state.turns.board(|b| match &saved {
Some(id) => b.send_saved(&key, id),
None => b.release_send(&key),
});
@@ -4053,7 +4067,7 @@ async fn send_chat_routed(
let user_extra = MessageExtra { thread_id: None, meta: user_meta };
let saved_user_msg = state
.db
- .insert_message_with(&user_msg, &user_extra)
+ .insert_message_as(payload.message_id.as_deref(), &user_msg, &user_extra)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if let Some(target) = &payload.reply_to_message_id {
@@ -4495,7 +4509,7 @@ async fn send_to_thread(
meta.get_or_insert_with(|| json!({}))[SENT_BY_BOT] = json!(true);
}
let extra = MessageExtra { thread_id: Some(thread.id.clone()), meta };
- let saved = state.db.insert_message_with(&user_msg, &extra).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ let saved = state.db.insert_message_as(payload.message_id.as_deref(), &user_msg, &extra).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if let Some(target) = &payload.reply_to_message_id {
state.db.set_reply_to(&saved.id, target).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
}
diff --git a/src/server/telegram/bridge.rs b/src/server/telegram/bridge.rs
index 97ee5a05..261035c9 100644
--- a/src/server/telegram/bridge.rs
+++ b/src/server/telegram/bridge.rs
@@ -237,6 +237,7 @@ async fn person_message(state: &AppState, runner: &Runner, link: &TelegramLink,
source: Some("telegram".into()),
meta: None,
client_message_id: None,
+ message_id: None,
};
match crate::server::routes::send_chat_inner(state.clone(), payload, true).await {
Ok(axum::Json(v)) => {
diff --git a/tests/bot_status_test.rs b/tests/bot_status_test.rs
index c5036c57..9432e3d2 100644
--- a/tests/bot_status_test.rs
+++ b/tests/bot_status_test.rs
@@ -126,3 +126,38 @@ async fn quiet_and_retry_routes_answer_for_the_person() {
let (s, _) = call(&env.app, "POST", "/api/kwants/no-such-bot/status/retry", Some(json!({}))).await;
assert_eq!(s, StatusCode::NOT_FOUND);
}
+
+/// S1 (Rigel's QA of #499): six parallel sends with one `client_message_id` in one chat. One is
+/// dispatched; every duplicate answers `already_delivered` with the first message's id (§7b),
+/// `pending` while the first was still saving, and exactly one message is saved under that id.
+#[tokio::test]
+async fn racing_duplicates_carry_the_first_messages_id() {
+ let env = setup().await;
+ let body = json!({"prompt": "race REPLYTAG:r1", "sender_id": "user", "kwant_id": env.b, "client_message_id": "cm-race.1"});
+ let sends = (0..6).map(|_| call(&env.app, "POST", "/api/chat/send", Some(body.clone())));
+ let replies = futures::future::join_all(sends).await;
+ for (s, v) in &replies {
+ assert_eq!(*s, StatusCode::OK, "{v}");
+ }
+ let firsts: Vec<&Value> = replies.iter().map(|(_, v)| v).filter(|v| v["status"] != "already_delivered").collect();
+ assert_eq!(firsts.len(), 1, "exactly one dispatched: {replies:?}");
+ let id = firsts[0]["user_message_id"].as_str().expect("the first send's message id").to_string();
+ let dups: Vec<&Value> = replies.iter().map(|(_, v)| v).filter(|v| v["status"] == "already_delivered").collect();
+ assert_eq!(dups.len(), 5, "{replies:?}");
+ for d in &dups {
+ assert_eq!(d["user_message_id"].as_str(), Some(id.as_str()), "a duplicate carries the first message's id: {d}");
+ assert_eq!(d["deduped"], true, "{d}");
+ assert!(d["pending"].is_boolean(), "{d}");
+ }
+ assert!(dups.iter().any(|d| d["pending"] == true), "at least one raced the first send while it was saving: {dups:?}");
+ let saved = env.state.db.get_message(&id).await.unwrap().expect("saved under the reserved id");
+ assert_eq!((saved.sender_role.as_str(), saved.text.as_str()), ("user", "race REPLYTAG:r1"));
+ wait_reply(&env, &env.b, "r1").await;
+ let mine: Vec<_> = messages(&env, &env.b).await.into_iter().filter(|m| m.sender_role == "user" && m.text == "race REPLYTAG:r1").collect();
+ assert_eq!(mine.len(), 1, "saved once");
+
+ // After the first was saved, a retry says so: not pending, same id
+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(body)).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!((v["status"].as_str(), v["user_message_id"].as_str(), v["pending"].as_bool()), (Some("already_delivered"), Some(id.as_str()), Some(false)), "{v}");
+}