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.

18.0 KB
Raw Blame
{
 "repo": "alexsergivan/kwant",
 "kind": "landed",
 "pr": 303,
 "title": "Tell a 👍/👎 to the bot's next turn once, even in the same second as its reply",
 "body": "## What broke\nCI rust on #299 (run 41925843282) failed in `tests/reactions_replies_test.rs::other_reactions_are_feedback_the_bots_next_turn_hears_about`, which #299 doesn't touch. The `fb2` turn was told the 👍/👎 again after the `fb1` turn had already been told them.\n\n## Root cause (confirmed)\n`reactions_since_last_reply` (`src/db/reactions.rs`) picked reactions with `julianday(r.created_at) >= last.at`, where `last.at` is the bot's newest message in the chat. Both `created_at` values come from `CURRENT_TIMESTAMP`, which has 1-second precision. When a reaction landed in the same second as the bot's reply, it still counted as new after that reply, so the next turn heard the same 👎 again. With the fake CLI's fast replies this happens when the test runs inside one second. In real use a bot could be told the same 👎 twice.\n\n## Fix\n- `message_reactions.told INTEGER NOT NULL DEFAULT 0`, added by an idempotent `ALTER` guarded by `pragma_table_info`, the same as `reply_to_message_id`. A new database and one from #296 end up with the same schema. The `CREATE TABLE` is unchanged.\n- `feedback_note` marks the reactions it puts into a turn's prompt as told (`Database::mark_told`, matched on message and reaction).\n- `reactions_since_last_reply` also requires `told = 0`. The \"since the last reply\" time rule stays, so reactions in existing databases that were made before the bot's last reply are still never told, and no backfill is needed.\n- A changed reaction resets `told` (as it already reset `answered`). Clearing and re-setting a reaction makes a new row, which is news again.\n- The note's wording and the history marks (\"(The person reacted 👎 to this message.)\") are unchanged. Docs updated (`docs/reactions-and-replies.md`).\n\n## Tests\n- `feedback_made_in_the_same_second_as_the_bots_reply_is_told_once` (integration, deterministic): pins the 👎 and the bot's reply to the same second via `exec_raw_for_test`, then checks that the next turn isn't told again and that the history mark stays. **It fails on main 1b581a9** (\"told twice\") and passes with the fix.\n- `a_reaction_told_once_is_not_new_even_in_the_same_second_as_the_reply` (lib): told once; the same reaction again isn't news; a changed or re-set one is; telling a stale reaction leaves the changed one untold.\n- `a_database_from_before_told_gets_the_column_and_keeps_its_reactions` (lib): rebuilds the #296 table without `told`, reopens the database, and checks that the column is added and an untold reaction is still news.\n- Locally: `reactions_replies_test` passed 7/7 tests on 5 runs in a row on the final head, plus 2 more runs under 2 CPU burners. `--lib` passed 967/967. `clippy --lib --test reactions_replies_test -D warnings` is clean.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n",
 "head_sha": "0cc0cfc9f54ea29f4048e8782d001c3886de7e79",
 "pr_head_sha": "a7245343d3d31b7af3a3974049d7eb3ce13fd39f",
 "base_branch": "main",
 "merged_at": "2026-11-05T00:00:19Z",
 "merged_by": "Oleks",
 "author": {
  "login": null,
  "name": "pixel-bot",
  "email": "[email protected]",
  "bot": {
   "id": "kw_demo_pixel",
   "name": "Pixel",
   "engine": "claude",
   "model": "claude-opus-5-5"
  }
 },
 "files": [
  {
   "path": "docs/reactions-and-replies.md",
   "status": "modified",
   "additions": 3,
   "deletions": 2,
   "patch": "@@ -18,10 +18,11 @@ Contract: `/home/maus/shared/ship-software-safely/react-reply/contract.md`, sect\n \n These migrations are additive and idempotent, and run in `Database::open`:\n \n-- **`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`.\n+- **`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`.\n   - There's one reaction per message, because kwant has a single person.\n   - A reaction goes away with its message.\n   - `answered` is 1 when the reaction started a turn. A changed reaction resets it to 0.\n+  - `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.\n - **`messages.reply_to_message_id TEXT NULL`:** the column is added only if it's missing.\n \n ## `PUT /api/messages/:id/reaction`\n@@ -99,7 +100,7 @@ For a 👎, reconsider that message briefly: say what you'd change, or ask what\n A 👍 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.\n ```\n \n-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.\n+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.\n \n 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.\n ",
   "previous_path": null
  },
  {
   "path": "src/db/reactions.rs",
   "status": "modified",
   "additions": 92,
   "deletions": 4,
   "patch": "@@ -60,12 +60,21 @@ impl Database {\n         if !has_reply {\n             sqlx::query(\"ALTER TABLE messages ADD COLUMN reply_to_message_id TEXT\").execute(&self.pool).await?;\n         }\n+        // `told`: 1 once a turn's prompt carried the reaction as feedback, so it's told once.\n+        // Added here for every database, new or from before it\n+        let has_told: bool =\n+            sqlx::query_scalar(\"SELECT COUNT(*) > 0 FROM pragma_table_info('message_reactions') WHERE name = 'told'\")\n+                .fetch_one(&self.pool)\n+                .await?;\n+        if !has_told {\n+            sqlx::query(\"ALTER TABLE message_reactions ADD COLUMN told INTEGER NOT NULL DEFAULT 0\").execute(&self.pool).await?;\n+        }\n         Ok(())\n     }\n \n     /// Sets (`Some(\"up\" | \"down\")`) or clears (`None`) the reaction on `message_id`. A new or\n     /// changed reaction gets a fresh `created_at` (so the bot hears about it on its next turn) and\n-    /// counts as feedback until [`Self::mark_answered`].\n+    /// counts as feedback until [`Self::mark_answered`] or [`Self::mark_told`].\n     pub async fn set_reaction(&self, message_id: &str, reaction: Option<&str>) -> Result<ReactionChange, DbError> {\n         let Some(r) = reaction else {\n             let gone = sqlx::query(\"DELETE FROM message_reactions WHERE message_id = ?\").bind(message_id).execute(&self.pool).await?;\n@@ -81,7 +90,7 @@ impl Database {\n             return Ok(ReactionChange::Fresh);\n         }\n         let changed = sqlx::query(\n-            \"UPDATE message_reactions SET reaction = ?1, created_at = CURRENT_TIMESTAMP, answered = 0 \\\n+            \"UPDATE message_reactions SET reaction = ?1, created_at = CURRENT_TIMESTAMP, answered = 0, told = 0 \\\n              WHERE message_id = ?2 AND reaction <> ?1\",\n         )\n         .bind(r)\n@@ -97,6 +106,19 @@ impl Database {\n         Ok(())\n     }\n \n+    /// `reactions` went into a turn's prompt as feedback: later turns aren't told them again. A\n+    /// reaction changed meanwhile (to the other one) is news and stays untold.\n+    pub async fn mark_told(&self, reactions: &[NewReaction]) -> Result<(), DbError> {\n+        for r in reactions {\n+            sqlx::query(\"UPDATE message_reactions SET told = 1 WHERE message_id = ? AND reaction = ?\")\n+                .bind(&r.message_id)\n+                .bind(&r.reaction)\n+                .execute(&self.pool)\n+                .await?;\n+        }\n+        Ok(())\n+    }\n+\n     /// Whether nobody (the person or a bot) wrote in `message`'s chat after it; kwant's own\n     /// notes (`system`) don't count.\n     pub async fn is_newest_said(&self, message: &Message) -> Result<bool, DbError> {\n@@ -204,7 +226,9 @@ impl Database {\n     }\n \n     /// The reactions in chat `context_id` on `bot_name`'s messages made since its newest message\n-    /// there, oldest first: what the person said about its replies since its last turn.\n+    /// there, oldest first: what the person said about its replies since its last turn. One\n+    /// already told to a turn ([`Self::mark_told`]) isn't new, even when it was made in the same\n+    /// second as the bot's reply (timestamps here have 1-second precision).\n     pub async fn reactions_since_last_reply(&self, context_id: &str, bot_name: &str) -> Result<Vec<NewReaction>, DbError> {\n         let rows: Vec<(String, String, String)> = sqlx::query_as(\n             r#\"\n@@ -216,7 +240,7 @@ impl Database {\n             last AS (SELECT MAX(julianday(created_at)) AS at FROM chat)\n             SELECT c.id, r.reaction, c.text\n             FROM message_reactions r JOIN chat c ON c.id = r.message_id, last\n-            WHERE julianday(r.created_at) >= last.at AND r.answered = 0\n+            WHERE julianday(r.created_at) >= last.at AND r.answered = 0 AND r.told = 0\n             ORDER BY julianday(r.created_at), r.rowid\n             \"#,\n         )\n@@ -488,6 +512,70 @@ mod tests {\n         assert_eq!(db.reactions_since_last_reply(\"k3\", \"Ada\").await.unwrap().len(), 1);\n     }\n \n+    #[tokio::test]\n+    async fn a_reaction_told_once_is_not_new_even_in_the_same_second_as_the_reply() {\n+        let (_tmp, db) = db().await;\n+        let m = say(&db, \"k1\", \"kwant\", \"Ada\", \"Ship on Friday.\").await;\n+        db.set_reaction(&m.id, Some(\"down\")).await.unwrap();\n+        let new = db.reactions_since_last_reply(\"k1\", \"Ada\").await.unwrap();\n+        assert_eq!(new.len(), 1);\n+        db.mark_told(&new).await.unwrap();\n+        // The bot's reply and the reaction in the same second\n+        let reply = say(&db, \"k1\", \"kwant\", \"Ada\", \"Noted.\").await;\n+        let same = \"2030-01-01 12:00:00\";\n+        sqlx::query(\"UPDATE message_reactions SET created_at = ?\").bind(same).execute(&db.pool).await.unwrap();\n+        sqlx::query(\"UPDATE messages SET created_at = ? WHERE id = ?\").bind(same).bind(&reply.id).execute(&db.pool).await.unwrap();\n+        assert!(db.reactions_since_last_reply(\"k1\", \"Ada\").await.unwrap().is_empty(), \"told once\");\n+        // The same one again isn't news; the other one is\n+        db.set_reaction(&m.id, Some(\"down\")).await.unwrap();\n+        assert!(db.reactions_since_last_reply(\"k1\", \"Ada\").await.unwrap().is_empty());\n+        db.set_reaction(&m.id, Some(\"up\")).await.unwrap();\n+        sqlx::query(\"UPDATE message_reactions SET created_at = ?\").bind(same).execute(&db.pool).await.unwrap();\n+        let changed = db.reactions_since_last_reply(\"k1\", \"Ada\").await.unwrap();\n+        assert_eq!(changed.iter().map(|r| r.reaction.as_str()).collect::<Vec<_>>(), [\"up\"]);\n+        // Telling a reaction that changed meanwhile leaves the new one untold\n+        db.mark_told(&new).await.unwrap();\n+        assert_eq!(db.reactions_since_last_reply(\"k1\", \"Ada\").await.unwrap().len(), 1);\n+        // Cleared and set again: news\n+        db.mark_told(&changed).await.unwrap();\n+        db.set_reaction(&m.id, None).await.unwrap();\n+        db.set_reaction(&m.id, Some(\"up\")).await.unwrap();\n+        sqlx::query(\"UPDATE message_reactions SET created_at = ?\").bind(same).execute(&db.pool).await.unwrap();\n+        assert_eq!(db.reactions_since_last_reply(\"k1\", \"Ada\").await.unwrap().len(), 1);\n+    }\n+\n+    #[tokio::test]\n+    async fn a_database_from_before_told_gets_the_column_and_keeps_its_reactions() {\n+        let tmp = tempfile::tempdir().unwrap();\n+        let db = Database::init(tmp.path()).await.unwrap();\n+        let m = say(&db, \"k1\", \"kwant\", \"Ada\", \"hello\").await;\n+        db.set_reaction(&m.id, Some(\"down\")).await.unwrap();\n+        // The table as #296 made it, without `told`\n+        for sql in [\n+            \"ALTER TABLE message_reactions RENAME TO r_old\",\n+            \"CREATE TABLE message_reactions (message_id TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE, \\\n+             reaction TEXT NOT NULL CHECK (reaction IN ('up','down')), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \\\n+             answered INTEGER NOT NULL DEFAULT 0)\",\n+            \"INSERT INTO message_reactions SELECT message_id, reaction, created_at, answered FROM r_old\",\n+            \"DROP TABLE r_old\",\n+        ] {\n+            sqlx::query(sql).execute(&db.pool).await.unwrap();\n+        }\n+        let has_told: bool = sqlx::query_scalar(\"SELECT COUNT(*) > 0 FROM pragma_table_info('message_reactions') WHERE name = 'told'\")\n+            .fetch_one(&db.pool)\n+            .await\n+            .unwrap();\n+        assert!(!has_told);\n+        drop(db);\n+        let db = Database::init(tmp.path()).await.unwrap();\n+        db.migrate_reactions().await.unwrap();\n+        assert_eq!(db.get_reaction(&m.id).await.unwrap().as_deref(), Some(\"down\"));\n+        let new = db.reactions_since_last_reply(\"k1\", \"Ada\").await.unwrap();\n+        assert_eq!(new.len(), 1, \"an untold reaction stays news\");\n+        db.mark_told(&new).await.unwrap();\n+        assert!(db.reactions_since_last_reply(\"k1\", \"Ada\").await.unwrap().is_empty());\n+    }\n+\n     #[tokio::test]\n     async fn newest_ignores_kwants_own_notes_but_not_the_person_or_a_bot() {\n         let (_tmp, db) = db().await;",
   "previous_path": null
  },
  {
   "path": "src/server/reactions.rs",
   "status": "modified",
   "additions": 5,
   "deletions": 1,
   "patch": "@@ -202,12 +202,16 @@ pub async fn reply_block(db: &Database, current: Option<&Message>, bot_name: &st\n }\n \n /// The note for `bot_name`'s turn in chat `context_id` about the 👍/👎 the person gave its\n-/// messages there since its last reply (reactions that answered a question excluded).\n+/// messages there since its last reply (reactions that answered a question excluded). Each\n+/// reaction goes into one turn's note: the ones in it are marked told.\n pub async fn feedback_note(db: &Database, context_id: &str, bot_name: &str) -> Option<String> {\n     let new = db.reactions_since_last_reply(context_id, bot_name).await.ok()?;\n     if new.is_empty() {\n         return None;\n     }\n+    if let Err(e) = db.mark_told(&new).await {\n+        tracing::warn!(\"reactions: couldn't mark the feedback told: {e}\");\n+    }\n     let mut out = String::from(\"\\n\\n[The person's reactions to your messages here since your last reply]\");\n     for r in &new {\n         let excerpt = crate::drivers::neutralise_frame_markers(&plain_excerpt(&r.text, NOTE_EXCERPT_CHARS));",
   "previous_path": null
  },
  {
   "path": "tests/reactions_replies_test.rs",
   "status": "modified",
   "additions": 26,
   "deletions": 0,
   "patch": "@@ -167,6 +167,32 @@ async fn other_reactions_are_feedback_the_bots_next_turn_hears_about() {\n     idle(&env, &a.id).await;\n }\n \n+#[tokio::test]\n+async fn feedback_made_in_the_same_second_as_the_bots_reply_is_told_once() {\n+    let env = setup().await;\n+    let a = bot(&env, &env.a).await;\n+    let plain = say(&env, Some(&a.id), None, \"kwant\", &a.name, \"Ship on Friday. MARKsame0\").await;\n+    assert_eq!(react(&env, &plain.id, json!(\"down\")).await.1[\"answered\"], false);\n+    send_direct(&env, &a.id, \"what now? REPLYTAG:same1\", json!({})).await;\n+    let reply = wait_reply(&env, &a.id, \"answer same1\").await;\n+    idle(&env, &a.id).await;\n+    let p = invocations_with(\"REPLYTAG:same1\").pop().unwrap();\n+    assert!(p.contains(\"The person reacted 👎 to your message \\\"Ship on Friday. MARKsame0\\\"\"), \"{p}\");\n+    // The 👎 and the bot's reply in the same second (timestamps have 1-second precision)\n+    let db = &env.state.db;\n+    let same = \"2030-01-01 12:00:00\";\n+    db.exec_raw_for_test(&format!(\"UPDATE message_reactions SET created_at = '{same}' WHERE message_id = '{}'\", plain.id)).await.unwrap();\n+    db.exec_raw_for_test(&format!(\"UPDATE messages SET created_at = '{same}' WHERE id = '{}'\", reply.id)).await.unwrap();\n+\n+    send_direct(&env, &a.id, \"and then? REPLYTAG:same2\", json!({})).await;\n+    wait_reply(&env, &a.id, \"answer same2\").await;\n+    let p = invocations_with(\"REPLYTAG:same2\").pop().unwrap();\n+    assert!(!p.contains(\"since your last reply]\"), \"told twice: {p}\");\n+    // The history mark stays\n+    assert!(p.contains(\"(The person reacted 👎 to this message.)\"), \"{p}\");\n+    idle(&env, &a.id).await;\n+}\n+\n #[tokio::test]\n async fn a_running_turn_clearing_or_changing_a_reaction_starts_no_second_turn() {\n     let env = setup().await;",
   "previous_path": null
  }
 ],
 "cut": null,
 "checks": [
  {
   "name": "rust",
   "status": "completed",
   "conclusion": "success",
   "url": "https://github.com/alexsergivan/kwant/actions/runs/41935033589/job/126941762796"
  },
  {
   "name": "site",
   "status": "completed",
   "conclusion": "success",
   "url": "https://github.com/alexsergivan/kwant/actions/runs/41935033589/job/126941219266"
  },
  {
   "name": "frontend",
   "status": "completed",
   "conclusion": "success",
   "url": "https://github.com/alexsergivan/kwant/actions/runs/41935033589/job/126941218934"
  }
 ],
 "ci": "green",
 "task": null,
 "first_edit_files": [],
 "draft": false,
 "head_branch": "vega-reaction-told-once",
 "links": {
  "pr": "https://github.com/alexsergivan/kwant/pull/303",
  "commit": "https://github.com/alexsergivan/kwant/commit/0cc0cfc9f54ea29f4048e8782d001c3886de7e79",
  "ci": "https://github.com/alexsergivan/kwant/actions/runs/41935033589/job/126941762796"
 }
}