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
Tell a 👍/👎 to the bot's next turn once, even in the same second as its reply (#303)
Oleksandr Ivanchenko0cc0cfc9f54e
diff --git a/docs/reactions-and-replies.md b/docs/reactions-and-replies.mdindex a9f1b273..35131399 100644--- a/docs/reactions-and-replies.md+++ b/docs/reactions-and-replies.md@@ -18,10 +18,11 @@ Contract: `/home/maus/shared/ship-software-safely/react-reply/contract.md`, sectThese migrations are additive and idempotent, and run in `Database::open`:-- **`message_reactions`:** columns `message_id TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE`, `reaction TEXT NOT NULL CHECK (reaction IN ('up','down'))`, `created_at` and `answered INTEGER NOT NULL DEFAULT 0`.+- **`message_reactions`:** columns `message_id TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE`, `reaction TEXT NOT NULL CHECK (reaction IN ('up','down'))`, `created_at`, `answered INTEGER NOT NULL DEFAULT 0` and `told INTEGER NOT NULL DEFAULT 0`.- There's one reaction per message, because kwant has a single person.- A reaction goes away with its message.- `answered` is 1 when the reaction started a turn. A changed reaction resets it to 0.+ - `told` is 1 once a turn's prompt carried the reaction as feedback. A changed reaction resets it to 0. On an older database the column is added only if it's missing.- **`messages.reply_to_message_id TEXT NULL`:** the column is added only if it's missing.## `PUT /api/messages/:id/reaction`@@ -99,7 +100,7 @@ For a 👎, reconsider that message briefly: say what you'd change, or ask whatA 👍 or 👎 never approves an approval card, a payment, a human step or a decision card: those keep their own buttons, and only the person's click on them counts.```-Each excerpt is plain text, up to 120 characters. The note appears once, because after the bot's reply the reactions are older than its last message.+Each excerpt is plain text, up to 120 characters. The note appears once: putting a reaction in a turn's note marks it `told`, and later notes leave told reactions out. This holds even when the reaction and the bot's reply were made in the same second, since timestamps have 1-second precision. A reaction made before the bot's last reply isn't listed either.In history, which covers every engine and the API drivers, a reacted bot message ends with `(The person reacted 👍 to this message.)`. Only the prompt changes; the stored text stays as it is.diff --git a/src/db/reactions.rs b/src/db/reactions.rsindex 135f0a27..7465556e 100644--- a/src/db/reactions.rs+++ b/src/db/reactions.rs@@ -60,12 +60,21 @@ impl Database {if !has_reply {sqlx::query("ALTER TABLE messages ADD COLUMN reply_to_message_id TEXT").execute(&self.pool).await?;}+ // `told`: 1 once a turn's prompt carried the reaction as feedback, so it's told once.+ // Added here for every database, new or from before it+ let has_told: bool =+ sqlx::query_scalar("SELECT COUNT(*) > 0 FROM pragma_table_info('message_reactions') WHERE name = 'told'")+ .fetch_one(&self.pool)+ .await?;+ if !has_told {+ sqlx::query("ALTER TABLE message_reactions ADD COLUMN told INTEGER NOT NULL DEFAULT 0").execute(&self.pool).await?;+ }Ok(())}/// Sets (`Some("up" | "down")`) or clears (`None`) the reaction on `message_id`. A new or/// changed reaction gets a fresh `created_at` (so the bot hears about it on its next turn) and- /// counts as feedback until [`Self::mark_answered`].+ /// counts as feedback until [`Self::mark_answered`] or [`Self::mark_told`].pub async fn set_reaction(&self, message_id: &str, reaction: Option<&str>) -> Result<ReactionChange, DbError> {let Some(r) = reaction else {let gone = sqlx::query("DELETE FROM message_reactions WHERE message_id = ?").bind(message_id).execute(&self.pool).await?;@@ -81,7 +90,7 @@ impl Database {return Ok(ReactionChange::Fresh);}let changed = sqlx::query(- "UPDATE message_reactions SET reaction = ?1, created_at = CURRENT_TIMESTAMP, answered = 0 \+ "UPDATE message_reactions SET reaction = ?1, created_at = CURRENT_TIMESTAMP, answered = 0, told = 0 \WHERE message_id = ?2 AND reaction <> ?1",).bind(r)@@ -97,6 +106,19 @@ impl Database {Ok(())}+ /// `reactions` went into a turn's prompt as feedback: later turns aren't told them again. A+ /// reaction changed meanwhile (to the other one) is news and stays untold.+ pub async fn mark_told(&self, reactions: &[NewReaction]) -> Result<(), DbError> {+ for r in reactions {+ sqlx::query("UPDATE message_reactions SET told = 1 WHERE message_id = ? AND reaction = ?")+ .bind(&r.message_id)+ .bind(&r.reaction)+ .execute(&self.pool)+ .await?;+ }+ Ok(())+ }+/// Whether nobody (the person or a bot) wrote in `message`'s chat after it; kwant's own/// notes (`system`) don't count.pub async fn is_newest_said(&self, message: &Message) -> Result<bool, DbError> {@@ -204,7 +226,9 @@ impl Database {}/// The reactions in chat `context_id` on `bot_name`'s messages made since its newest message- /// there, oldest first: what the person said about its replies since its last turn.+ /// there, oldest first: what the person said about its replies since its last turn. One+ /// already told to a turn ([`Self::mark_told`]) isn't new, even when it was made in the same+ /// second as the bot's reply (timestamps here have 1-second precision).pub async fn reactions_since_last_reply(&self, context_id: &str, bot_name: &str) -> Result<Vec<NewReaction>, DbError> {let rows: Vec<(String, String, String)> = sqlx::query_as(r#"@@ -216,7 +240,7 @@ impl Database {last AS (SELECT MAX(julianday(created_at)) AS at FROM chat)SELECT c.id, r.reaction, c.textFROM message_reactions r JOIN chat c ON c.id = r.message_id, last- WHERE julianday(r.created_at) >= last.at AND r.answered = 0+ WHERE julianday(r.created_at) >= last.at AND r.answered = 0 AND r.told = 0ORDER BY julianday(r.created_at), r.rowid"#,)@@ -488,6 +512,70 @@ mod tests {assert_eq!(db.reactions_since_last_reply("k3", "Ada").await.unwrap().len(), 1);}+ #[tokio::test]+ async fn a_reaction_told_once_is_not_new_even_in_the_same_second_as_the_reply() {+ let (_tmp, db) = db().await;+ let m = say(&db, "k1", "kwant", "Ada", "Ship on Friday.").await;+ db.set_reaction(&m.id, Some("down")).await.unwrap();+ let new = db.reactions_since_last_reply("k1", "Ada").await.unwrap();+ assert_eq!(new.len(), 1);+ db.mark_told(&new).await.unwrap();+ // The bot's reply and the reaction in the same second+ let reply = say(&db, "k1", "kwant", "Ada", "Noted.").await;+ let same = "2030-01-01 12:00:00";+ sqlx::query("UPDATE message_reactions SET created_at = ?").bind(same).execute(&db.pool).await.unwrap();+ sqlx::query("UPDATE messages SET created_at = ? WHERE id = ?").bind(same).bind(&reply.id).execute(&db.pool).await.unwrap();+ assert!(db.reactions_since_last_reply("k1", "Ada").await.unwrap().is_empty(), "told once");+ // The same one again isn't news; the other one is+ db.set_reaction(&m.id, Some("down")).await.unwrap();+ assert!(db.reactions_since_last_reply("k1", "Ada").await.unwrap().is_empty());+ db.set_reaction(&m.id, Some("up")).await.unwrap();+ sqlx::query("UPDATE message_reactions SET created_at = ?").bind(same).execute(&db.pool).await.unwrap();+ let changed = db.reactions_since_last_reply("k1", "Ada").await.unwrap();+ assert_eq!(changed.iter().map(|r| r.reaction.as_str()).collect::<Vec<_>>(), ["up"]);+ // Telling a reaction that changed meanwhile leaves the new one untold+ db.mark_told(&new).await.unwrap();+ assert_eq!(db.reactions_since_last_reply("k1", "Ada").await.unwrap().len(), 1);+ // Cleared and set again: news+ db.mark_told(&changed).await.unwrap();+ db.set_reaction(&m.id, None).await.unwrap();+ db.set_reaction(&m.id, Some("up")).await.unwrap();+ sqlx::query("UPDATE message_reactions SET created_at = ?").bind(same).execute(&db.pool).await.unwrap();+ assert_eq!(db.reactions_since_last_reply("k1", "Ada").await.unwrap().len(), 1);+ }++ #[tokio::test]+ async fn a_database_from_before_told_gets_the_column_and_keeps_its_reactions() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let m = say(&db, "k1", "kwant", "Ada", "hello").await;+ db.set_reaction(&m.id, Some("down")).await.unwrap();+ // The table as #296 made it, without `told`+ for sql in [+ "ALTER TABLE message_reactions RENAME TO r_old",+ "CREATE TABLE message_reactions (message_id TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE, \+ reaction TEXT NOT NULL CHECK (reaction IN ('up','down')), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \+ answered INTEGER NOT NULL DEFAULT 0)",+ "INSERT INTO message_reactions SELECT message_id, reaction, created_at, answered FROM r_old",+ "DROP TABLE r_old",+ ] {+ sqlx::query(sql).execute(&db.pool).await.unwrap();+ }+ let has_told: bool = sqlx::query_scalar("SELECT COUNT(*) > 0 FROM pragma_table_info('message_reactions') WHERE name = 'told'")+ .fetch_one(&db.pool)+ .await+ .unwrap();+ assert!(!has_told);+ drop(db);+ let db = Database::init(tmp.path()).await.unwrap();+ db.migrate_reactions().await.unwrap();+ assert_eq!(db.get_reaction(&m.id).await.unwrap().as_deref(), Some("down"));+ let new = db.reactions_since_last_reply("k1", "Ada").await.unwrap();+ assert_eq!(new.len(), 1, "an untold reaction stays news");+ db.mark_told(&new).await.unwrap();+ assert!(db.reactions_since_last_reply("k1", "Ada").await.unwrap().is_empty());+ }+#[tokio::test]async fn newest_ignores_kwants_own_notes_but_not_the_person_or_a_bot() {let (_tmp, db) = db().await;diff --git a/src/server/reactions.rs b/src/server/reactions.rsindex bbc9d49a..853c7351 100644--- a/src/server/reactions.rs+++ b/src/server/reactions.rs@@ -202,12 +202,16 @@ pub async fn reply_block(db: &Database, current: Option<&Message>, bot_name: &st}/// The note for `bot_name`'s turn in chat `context_id` about the 👍/👎 the person gave its-/// messages there since its last reply (reactions that answered a question excluded).+/// messages there since its last reply (reactions that answered a question excluded). Each+/// reaction goes into one turn's note: the ones in it are marked told.pub async fn feedback_note(db: &Database, context_id: &str, bot_name: &str) -> Option<String> {let new = db.reactions_since_last_reply(context_id, bot_name).await.ok()?;if new.is_empty() {return None;}+ if let Err(e) = db.mark_told(&new).await {+ tracing::warn!("reactions: couldn't mark the feedback told: {e}");+ }let mut out = String::from("\n\n[The person's reactions to your messages here since your last reply]");for r in &new {let excerpt = crate::drivers::neutralise_frame_markers(&plain_excerpt(&r.text, NOTE_EXCERPT_CHARS));diff --git a/tests/reactions_replies_test.rs b/tests/reactions_replies_test.rsindex 5e43992f..2c155ed8 100644--- a/tests/reactions_replies_test.rs+++ b/tests/reactions_replies_test.rs@@ -167,6 +167,32 @@ async fn other_reactions_are_feedback_the_bots_next_turn_hears_about() {idle(&env, &a.id).await;}+#[tokio::test]+async fn feedback_made_in_the_same_second_as_the_bots_reply_is_told_once() {+ let env = setup().await;+ let a = bot(&env, &env.a).await;+ let plain = say(&env, Some(&a.id), None, "kwant", &a.name, "Ship on Friday. MARKsame0").await;+ assert_eq!(react(&env, &plain.id, json!("down")).await.1["answered"], false);+ send_direct(&env, &a.id, "what now? REPLYTAG:same1", json!({})).await;+ let reply = wait_reply(&env, &a.id, "answer same1").await;+ idle(&env, &a.id).await;+ let p = invocations_with("REPLYTAG:same1").pop().unwrap();+ assert!(p.contains("The person reacted 👎 to your message \"Ship on Friday. MARKsame0\""), "{p}");+ // The 👎 and the bot's reply in the same second (timestamps have 1-second precision)+ let db = &env.state.db;+ let same = "2030-01-01 12:00:00";+ db.exec_raw_for_test(&format!("UPDATE message_reactions SET created_at = '{same}' WHERE message_id = '{}'", plain.id)).await.unwrap();+ db.exec_raw_for_test(&format!("UPDATE messages SET created_at = '{same}' WHERE id = '{}'", reply.id)).await.unwrap();++ send_direct(&env, &a.id, "and then? REPLYTAG:same2", json!({})).await;+ wait_reply(&env, &a.id, "answer same2").await;+ let p = invocations_with("REPLYTAG:same2").pop().unwrap();+ assert!(!p.contains("since your last reply]"), "told twice: {p}");+ // The history mark stays+ assert!(p.contains("(The person reacted 👎 to this message.)"), "{p}");+ idle(&env, &a.id).await;+}+#[tokio::test]async fn a_running_turn_clearing_or_changing_a_reaction_starts_no_second_turn() {let env = setup().await;