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.

ask_user: save why_you and checked with the question, not after it

Lin (kwant bot)26948d973eef
diff --git a/src/db/questions.rs b/src/db/questions.rs
index 25de13e3..4045c9de 100644
--- a/src/db/questions.rs
+++ b/src/db/questions.rs
@@ -118,6 +118,14 @@ pub fn clean_question(question: &str, choices: &[String]) -> Result<(String, Vec
Ok((q.to_string(), out))
}
+/// Why the bot asked (`why_you`) and what it checked first, saved with the question so no
+/// reader ever sees an open question without them.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct QuestionReason<'a> {
+ pub why_you: Option<&'a str>,
+ pub checked: Option<&'a str>,
+}
+
/// Where a question is asked.
#[derive(Debug, Clone, Default)]
pub struct QuestionPlace {
@@ -157,24 +165,13 @@ impl Database {
Ok(())
}
- /// Saves why the bot asked and what it checked first.
- pub async fn set_question_reason(&self, id: &str, why_you: Option<&str>, checked: Option<&str>) -> Result<(), DbError> {
- sqlx::query("UPDATE questions SET why_you = ?, checked = ? WHERE id = ?")
- .bind(why_you)
- .bind(checked)
- .bind(id)
- .execute(&self.pool)
- .await?;
- Ok(())
- }
-
pub async fn create_question(
&self,
place: &QuestionPlace,
question: &str,
choices: &[String],
) -> Result<Question, QuestionError> {
- let (q, _) = self.create_question_with_card(place, question, choices, |_| None).await?;
+ let (q, _) = self.create_question_with_card(place, question, choices, QuestionReason::default(), |_| None).await?;
Ok(q)
}
@@ -185,6 +182,7 @@ impl Database {
place: &QuestionPlace,
question: &str,
choices: &[String],
+ reason: QuestionReason<'_>,
card: impl FnOnce(&Question) -> Option<(NewMessage, MessageExtra)>,
) -> Result<(Question, Option<Message>), QuestionError> {
// The first statement writes, so the transaction takes SQLite's write lock up front
@@ -192,8 +190,8 @@ impl Database {
let mut tx = self.pool.begin().await?;
let id = Uuid::new_v4().to_string();
let inserted = sqlx::query(
- "INSERT INTO questions (id, kwant_id, channel_id, direct_kwant_id, thread_id, turn_id, question, choices, status, created_at)
- SELECT ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?
+ "INSERT INTO questions (id, kwant_id, channel_id, direct_kwant_id, thread_id, turn_id, question, choices, why_you, checked, status, created_at)
+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?
WHERE (SELECT COUNT(*) FROM questions WHERE kwant_id = ? AND status = 'open') < ?",
)
.bind(&id)
@@ -204,6 +202,8 @@ impl Database {
.bind(&place.turn_id)
.bind(question)
.bind(serde_json::to_string(choices).unwrap_or_else(|_| "[]".into()))
+ .bind(reason.why_you)
+ .bind(reason.checked)
.bind(Utc::now())
.bind(&place.kwant_id)
.bind(MAX_OPEN_PER_KWANT)
diff --git a/src/server/questions.rs b/src/server/questions.rs
index 58745a7c..4971177c 100644
--- a/src/server/questions.rs
+++ b/src/server/questions.rs
@@ -9,7 +9,7 @@ use super::continuity::{notify, Notification, SelfScope};
use super::routes::{scope_for, try_kwant_turn, TurnOpts};
use super::AppState;
use crate::db::models::{MessageExtra, NewMessage};
-use crate::db::questions::{clean_question, Question, QuestionError, QuestionPlace, MAX_ANSWER_CHARS, QUESTION_STATUSES};
+use crate::db::questions::{clean_question, Question, QuestionError, QuestionPlace, QuestionReason, MAX_ANSWER_CHARS, QUESTION_STATUSES};
use crate::drivers::events::RuntimeEvent;
use axum::{
extract::{Path, Query, State},
@@ -250,18 +250,18 @@ pub async fn tool_ask(state: &AppState, scope: &SelfScope, args: &Value) -> (Str
// transaction, so neither a list poll nor a very fast answer can see one without the others.
// The text keeps the choices readable in history and for older clients; the card uses meta
let hub = &state.questions;
+ let reason = QuestionReason { why_you: why_you.as_deref(), checked: checked.as_deref() };
let mut waiter = None;
let created = state
.db
- .create_question_with_card(&place, &question, &choices, |q| {
+ .create_question_with_card(&place, &question, &choices, reason, |q| {
waiter = Some((q.id.clone(), hub.register(&q.id)));
let text = format!("{}\n\nChoices: {}", q.question, choices.join(" · "));
let (msg, extra) = place_message(q, "kwant", &scope.kwant_id, text);
- let shown = Question { why_you: why_you.clone(), checked: checked.clone(), ..q.clone() };
- Some((msg, MessageExtra { meta: Some(card_meta(&shown)), ..extra }))
+ Some((msg, MessageExtra { meta: Some(card_meta(q)), ..extra }))
})
.await;
- let (mut q, card) = match created {
+ let (q, card) = match created {
Ok(v) => v,
Err(e) => {
if let Some((id, _)) = waiter {
@@ -277,11 +277,6 @@ pub async fn tool_ask(state: &AppState, scope: &SelfScope, args: &Value) -> (Str
return ("Could not save the question.".into(), true);
};
let _guard = WaiterGuard { hub, id: q.id.clone() };
- if why_you.is_some() || checked.is_some() {
- let _ = state.db.set_question_reason(&q.id, why_you.as_deref(), checked.as_deref()).await;
- q.why_you = why_you;
- q.checked = checked;
- }
if let Some(card) = card {
if let Some(t) = &q.thread_id {
let _ = state.db.touch_thread(t).await;
@@ -590,7 +585,7 @@ pub async fn record_native(state: &AppState, place: &QuestionPlace, kwant_name:
for (question, choices) in native_questions(args) {
let created = state
.db
- .create_question_with_card(place, &question, &choices, |q| {
+ .create_question_with_card(place, &question, &choices, QuestionReason::default(), |q| {
let text = match choices.is_empty() {
true => q.question.clone(),
false => format!("{}\n\nChoices: {}", q.question, choices.join(" · ")),
diff --git a/tests/ask_user_test.rs b/tests/ask_user_test.rs
index 9dfab079..08dcb13a 100644
--- a/tests/ask_user_test.rs
+++ b/tests/ask_user_test.rs
@@ -111,6 +111,8 @@ async fn a_question_is_never_visible_without_its_card_and_waiter() {
};
let id = q["id"].as_str().unwrap().to_string();
let mid = q["message_id"].as_str().unwrap_or_else(|| panic!("open question without its card: {q}")).to_string();
+ // Why the bot asked and what it checked are saved with the question, not after it
+ assert_eq!((q["why_you"].as_str(), q["checked"].as_str()), (Some("irreversible"), Some("Read the release notes.")), "{q}");
assert!(question(&env, &id).await["waiting"].as_bool().unwrap(), "open question without a waiting turn");
assert!(messages(&env, &env.a).await.iter().any(|m| m.id == mid), "card message missing");
let (s, v) = call(&env.app, "POST", &format!("/api/questions/{id}/answer"), Some(json!({"choice": 0}))).await;