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
Ask-user: one-tap questions that pause and resume a turn (batch 2 / C)
Lin (kwant bot)bce9af6c59c7
diff --git a/src/db/mod.rs b/src/db/mod.rsindex 0d49ddef..41027aff 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -2,6 +2,7 @@ pub mod models;pub mod profiles;pub mod continuity;pub mod threads;+pub mod questions;pub mod skills;use models::*;@@ -86,6 +87,7 @@ impl Database {db.migrate_continuity().await?;db.migrate_threads().await?;db.migrate_skills().await?;+ db.migrate_questions().await?;db.seed_defaults().await?;Ok(db)diff --git a/src/db/questions.rs b/src/db/questions.rsnew file mode 100644index 00000000..ff479ddb--- /dev/null+++ b/src/db/questions.rs@@ -0,0 +1,269 @@+//! Questions an agent asked the user mid-turn (`ask_user`): a question, 2–5 choices, and always a+//! free-text answer. A question is `open` until answered, dismissed or its turn is stopped.++use super::{Database, DbError};+use chrono::{DateTime, Utc};+use serde::Serialize;+use sqlx::FromRow;+use uuid::Uuid;++pub const MAX_QUESTION_CHARS: usize = 500;+pub const MAX_CHOICE_CHARS: usize = 80;+pub const MIN_CHOICES: usize = 2;+pub const MAX_CHOICES: usize = 5;+pub const MAX_ANSWER_CHARS: usize = 2000;+/// Most open questions per agent; an agent can't flood the user.+pub const MAX_OPEN_PER_KWANT: i64 = 10;++/// "open", "answered" or "cancelled" (dismissed by the user or its turn was stopped).+pub const QUESTION_STATUSES: [&str; 3] = ["open", "answered", "cancelled"];++#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct Question {+ pub id: String,+ pub kwant_id: String,+ pub channel_id: Option<String>,+ pub direct_kwant_id: Option<String>,+ pub thread_id: Option<String>,+ /// The turn that asked; it may have ended since (a late answer starts a new turn).+ pub turn_id: Option<String>,+ pub question: String,+ /// JSON array of strings.+ #[serde(serialize_with = "as_json")]+ pub choices: String,+ pub status: String,+ pub answer: Option<String>,+ /// The chat message that shows the question.+ pub message_id: Option<String>,+ pub created_at: DateTime<Utc>,+ pub answered_at: Option<DateTime<Utc>>,+}++fn as_json<S: serde::Serializer>(raw: &str, s: S) -> Result<S::Ok, S::Error> {+ let v: serde_json::Value = serde_json::from_str(raw).unwrap_or(serde_json::Value::Array(Vec::new()));+ v.serialize(s)+}++impl Question {+ pub fn choice_list(&self) -> Vec<String> {+ serde_json::from_str(&self.choices).unwrap_or_default()+ }++ /// The chat id the question was asked in: channel, thread or the direct chat's kwant.+ pub fn context_id(&self) -> String {+ self.channel_id+ .clone()+ .or_else(|| self.thread_id.clone())+ .or_else(|| self.direct_kwant_id.clone())+ .unwrap_or_else(|| self.kwant_id.clone())+ }+}++#[derive(Debug, thiserror::Error, PartialEq)]+pub enum QuestionError {+ #[error("{0}")]+ Invalid(String),+ #[error("you already have {MAX_OPEN_PER_KWANT} unanswered questions; wait for answers first")]+ TooManyOpen,+ #[error("database error")]+ Db,+}++impl From<DbError> for QuestionError {+ fn from(_: DbError) -> Self {+ QuestionError::Db+ }+}++impl From<sqlx::Error> for QuestionError {+ fn from(_: sqlx::Error) -> Self {+ QuestionError::Db+ }+}++/// A question and its choices, checked and trimmed.+pub fn clean_question(question: &str, choices: &[String]) -> Result<(String, Vec<String>), QuestionError> {+ let q = question.trim();+ if q.is_empty() {+ return Err(QuestionError::Invalid("question is required".into()));+ }+ if q.chars().count() > MAX_QUESTION_CHARS {+ return Err(QuestionError::Invalid(format!("question is longer than {MAX_QUESTION_CHARS} characters")));+ }+ let mut out: Vec<String> = Vec::new();+ for c in choices {+ let c = c.split_whitespace().collect::<Vec<_>>().join(" ");+ if c.is_empty() {+ return Err(QuestionError::Invalid("choices can't be empty".into()));+ }+ if c.chars().count() > MAX_CHOICE_CHARS {+ return Err(QuestionError::Invalid(format!("a choice is longer than {MAX_CHOICE_CHARS} characters")));+ }+ if out.iter().any(|o| o.eq_ignore_ascii_case(&c)) {+ return Err(QuestionError::Invalid("choices must differ".into()));+ }+ out.push(c);+ }+ if !(MIN_CHOICES..=MAX_CHOICES).contains(&out.len()) {+ return Err(QuestionError::Invalid(format!("give {MIN_CHOICES} to {MAX_CHOICES} choices")));+ }+ Ok((q.to_string(), out))+}++/// Where a question is asked.+#[derive(Debug, Clone, Default)]+pub struct QuestionPlace {+ pub kwant_id: String,+ pub channel_id: Option<String>,+ pub direct_kwant_id: Option<String>,+ pub thread_id: Option<String>,+ pub turn_id: Option<String>,+}++impl Database {+ pub(super) async fn migrate_questions(&self) -> Result<(), DbError> {+ for stmt in [+ "CREATE TABLE IF NOT EXISTS questions (+ id TEXT PRIMARY KEY,+ kwant_id TEXT NOT NULL,+ channel_id TEXT,+ direct_kwant_id TEXT,+ thread_id TEXT,+ turn_id TEXT,+ question TEXT NOT NULL,+ choices TEXT NOT NULL,+ status TEXT NOT NULL CHECK (status IN ('open', 'answered', 'cancelled')),+ answer TEXT,+ message_id TEXT,+ created_at TIMESTAMP NOT NULL,+ answered_at TIMESTAMP+ )",+ "CREATE INDEX IF NOT EXISTS questions_by_status ON questions (status, kwant_id)",+ ] {+ sqlx::query(stmt).execute(&self.pool).await?;+ }+ Ok(())+ }++ pub async fn create_question(+ &self,+ place: &QuestionPlace,+ question: &str,+ choices: &[String],+ ) -> Result<Question, QuestionError> {+ let open: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM questions WHERE kwant_id = ? AND status = 'open'")+ .bind(&place.kwant_id)+ .fetch_one(&self.pool)+ .await?;+ if open >= MAX_OPEN_PER_KWANT {+ return Err(QuestionError::TooManyOpen);+ }+ let id = Uuid::new_v4().to_string();+ sqlx::query(+ "INSERT INTO questions (id, kwant_id, channel_id, direct_kwant_id, thread_id, turn_id, question, choices, status, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?)",+ )+ .bind(&id)+ .bind(&place.kwant_id)+ .bind(&place.channel_id)+ .bind(&place.direct_kwant_id)+ .bind(&place.thread_id)+ .bind(&place.turn_id)+ .bind(question)+ .bind(serde_json::to_string(choices).unwrap_or_else(|_| "[]".into()))+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ self.get_question(&id).await?.ok_or(QuestionError::Db)+ }++ pub async fn get_question(&self, id: &str) -> Result<Option<Question>, DbError> {+ Ok(sqlx::query_as::<_, Question>("SELECT * FROM questions WHERE id = ?")+ .bind(id)+ .fetch_optional(&self.pool)+ .await?)+ }++ pub async fn set_question_message(&self, id: &str, message_id: &str) -> Result<(), DbError> {+ sqlx::query("UPDATE questions SET message_id = ? WHERE id = ?").bind(message_id).bind(id).execute(&self.pool).await?;+ Ok(())+ }++ /// Questions, newest first: by status and/or chat (channel, thread or direct-chat kwant id).+ pub async fn list_questions(&self, status: Option<&str>, context_id: Option<&str>) -> Result<Vec<Question>, DbError> {+ Ok(sqlx::query_as::<_, Question>(+ "SELECT * FROM questions+ WHERE (?1 IS NULL OR status = ?1)+ AND (?2 IS NULL OR channel_id = ?2 OR thread_id = ?2 OR direct_kwant_id = ?2)+ ORDER BY created_at DESC LIMIT 100",+ )+ .bind(status)+ .bind(context_id)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Closes an open question; `false` when it wasn't open any more (someone else closed it).+ pub async fn close_question(&self, id: &str, status: &str, answer: Option<&str>) -> Result<bool, DbError> {+ let done = sqlx::query(+ "UPDATE questions SET status = ?, answer = ?, answered_at = ? WHERE id = ? AND status = 'open'",+ )+ .bind(status)+ .bind(answer)+ .bind(Utc::now())+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(done.rows_affected() == 1)+ }++ /// Replaces a message's `meta` JSON (a question card showing its new status).+ pub async fn set_message_meta(&self, message_id: &str, meta: &serde_json::Value) -> Result<(), DbError> {+ sqlx::query("UPDATE messages SET meta = ? WHERE id = ?")+ .bind(meta.to_string())+ .bind(message_id)+ .execute(&self.pool)+ .await?;+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn s(v: &[&str]) -> Vec<String> {+ v.iter().map(|x| x.to_string()).collect()+ }++ #[test]+ fn questions_are_checked() {+ assert!(clean_question("Which?", &s(&["a", "b"])).is_ok());+ assert!(clean_question(" ", &s(&["a", "b"])).is_err());+ assert!(clean_question("Which?", &s(&["a"])).is_err());+ assert!(clean_question("Which?", &s(&["a", "b", "c", "d", "e", "f"])).is_err());+ assert!(clean_question("Which?", &s(&["a", "A"])).is_err());+ assert!(clean_question("Which?", &s(&["a", ""])).is_err());+ assert!(clean_question(&"q".repeat(501), &s(&["a", "b"])).is_err());+ assert!(clean_question("Which?", &s(&["a", &"b".repeat(81)])).is_err());+ let (_, c) = clean_question("Which?", &s(&[" one\n two ", "b"])).unwrap();+ assert_eq!(c[0], "one two");+ }++ #[tokio::test]+ async fn closing_is_once_only() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let place = QuestionPlace { kwant_id: "k".into(), direct_kwant_id: Some("k".into()), ..Default::default() };+ let q = db.create_question(&place, "Which?", &s(&["a", "b"])).await.unwrap();+ assert_eq!(q.choice_list(), s(&["a", "b"]));+ assert_eq!(q.context_id(), "k");+ assert!(db.close_question(&q.id, "answered", Some("a")).await.unwrap());+ assert!(!db.close_question(&q.id, "cancelled", None).await.unwrap());+ assert_eq!(db.get_question(&q.id).await.unwrap().unwrap().answer.as_deref(), Some("a"));+ for _ in 0..MAX_OPEN_PER_KWANT {+ db.create_question(&place, "Which?", &s(&["a", "b"])).await.unwrap();+ }+ assert_eq!(db.create_question(&place, "Which?", &s(&["a", "b"])).await, Err(QuestionError::TooManyOpen));+ }+}diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex 00f31287..869eb42c 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -84,6 +84,9 @@ pub enum RuntimeEvent {/// `{id, kwant_id, deleted: true}`). See `crate::db::skills`.#[serde(rename = "skill_updated", alias = "SkillUpdated")]SkillUpdated { skill: Value },+ /// A question an agent asked the user was asked, answered or cancelled.+ #[serde(rename = "question_updated", alias = "QuestionUpdated")]+ QuestionUpdated { question: Value },/// An event from inside one turn, tagged with the turn and its chat. On the SSE wire it is/// the inner event with `turn_id`, `kwant_id`, `context_id` and `thread_id` added at the top/// level (see [`RuntimeEvent::to_wire`]), so clients that ignore the tags still work.diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 5a1be3a0..817018a3 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -34,13 +34,14 @@ const AGENT_SEARCH_LIMIT: i64 = 20;/// Longest notification body.pub const NOTIFY_BODY_CHARS: usize = 200;const WEBHOOK_TIMEOUT: Duration = Duration::from_secs(5);-pub const NOTIFY_KINDS: [&str; 6] = [+pub const NOTIFY_KINDS: [&str; 7] = ["turn_finished","approval_needed","routine_failed","delegation_finished","delegation_stalled","skill_proposed",+ "question_asked",];const MASK: &str = "••••••••";@@ -152,6 +153,9 @@ pub struct SelfScope {pub kwant_name: String,/// The chat the turn runs in; delegation tools are offered only when it is known.pub origin: Option<TurnOrigin>,+ /// The turn's stop button: a waiting `ask_user` ends when it fires.+ pub cancel: Option<tokio_util::sync::CancellationToken>,+ pub turn_id: Option<String>,}/// Where a turn runs, for the delegation tools: results go back to this chat.@@ -182,7 +186,8 @@ pub fn self_server(base_url: &str, token: &str) -> McpServer {.into_iter().collect(),enabled: true,- timeout_secs: 30,+ // ask_user waits for the user up to the approval timeout+ timeout_secs: (crate::mcp::APPROVAL_TIMEOUT_SECS + 30) as i64,created_at: None,}}@@ -205,6 +210,9 @@ fn tool_list(scope: &SelfScope) -> Value {list.extend(super::skills::tools());if scope.origin.is_some() {list.extend(delegation_tools());+ if scope.cancel.is_some() {+ list.extend(super::questions::tools());+ }}}tools@@ -464,6 +472,7 @@ async fn call_tool(}"skill_propose" => super::skills::tool_propose(state, scope, args).await,"skill_get" => super::skills::tool_get(state, scope, args).await,+ "ask_user" => super::questions::tool_ask(state, scope, args).await,"delegate" => super::delegation::tool_delegate(state, scope, args).await,"delegation_status" => super::delegation::tool_status(state, scope, args).await,"delegation_cancel" => super::delegation::tool_cancel(state, scope, args).await,diff --git a/src/server/mod.rs b/src/server/mod.rsindex 3aaa4acf..63e83064 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -12,6 +12,7 @@ pub mod continuity;pub mod scheduler;pub mod turns;pub mod delegation;+pub mod questions;pub mod skills;use crate::broker::PermissionBroker;@@ -55,6 +56,8 @@ pub struct AppState {pub running_routines: Arc<Mutex<std::collections::HashSet<String>>>,/// Wakes the scheduler early when routines change.pub scheduler_wake: Arc<tokio::sync::Notify>,+ /// `ask_user` calls waiting for the user's answer.+ pub questions: Arc<questions::QuestionHub>,}impl AppState {@@ -89,6 +92,7 @@ impl AppState {self_tools: Default::default(),running_routines: Default::default(),scheduler_wake: Default::default(),+ questions: Default::default(),}}@@ -176,6 +180,10 @@ pub fn create_router(state: AppState) -> Router {.route("/api/delegations", get(delegation::list_delegations).post(delegation::create_delegation)).route("/api/delegations/:id", get(delegation::get_delegation)).route("/api/delegations/:id/cancel", post(delegation::cancel_delegation))+ .route("/api/questions", get(questions::list))+ .route("/api/questions/:id", get(questions::get))+ .route("/api/questions/:id/answer", post(questions::answer))+ .route("/api/questions/:id/cancel", post(questions::cancel)).route("/api/skills", get(skills::list).post(skills::create)).route("/api/skills/:id", get(skills::get).patch(skills::update).delete(skills::remove)).route("/api/skills/:id/diff", get(skills::diff))diff --git a/src/server/questions.rs b/src/server/questions.rsnew file mode 100644index 00000000..cab6b690--- /dev/null+++ b/src/server/questions.rs@@ -0,0 +1,383 @@+//! One-tap questions (batch 2 / C). An agent calls `ask_user` mid-turn: the question is saved as+//! a card in its chat, the UI gets `question_updated` + `message_added` and a `question_asked`+//! notification, and the tool waits for the answer while the turn stays live (and stoppable).+//! Only that turn waits: the agent's other chats and threads run as usual, since each turn has+//! its own job and slot. If nobody answers in time the tool tells the agent to wrap up, and a+//! later answer starts a new turn in the same chat with it.++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::drivers::events::RuntimeEvent;+use axum::{+ extract::{Path, Query, State},+ http::StatusCode,+ response::{IntoResponse, Response},+ Json,+};+use serde::Deserialize;+use serde_json::{json, Value};+use std::collections::HashMap;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Mutex;+use std::time::Duration;+use tokio::sync::oneshot;++/// What a waiting `ask_user` call is woken with.+#[derive(Debug)]+pub enum Reply {+ Answer(String),+ Dismissed,+}++/// The `ask_user` calls waiting for an answer, by question id. Empty (no cost) when unused.+pub struct QuestionHub {+ waiters: Mutex<HashMap<String, oneshot::Sender<Reply>>>,+ wait_ms: AtomicU64,+}++impl Default for QuestionHub {+ fn default() -> Self {+ Self {+ waiters: Mutex::default(),+ // Shorter than the CLIs' tool timeout (approval timeout + 30 s), so the tool answers first+ wait_ms: AtomicU64::new((crate::mcp::APPROVAL_TIMEOUT_SECS - 10) * 1000),+ }+ }+}++impl QuestionHub {+ /// How long `ask_user` waits before telling the agent to wrap up (tests shorten it).+ pub fn set_wait(&self, wait: Duration) {+ self.wait_ms.store(wait.as_millis() as u64, Ordering::Relaxed);+ }++ fn wait(&self) -> Duration {+ Duration::from_millis(self.wait_ms.load(Ordering::Relaxed))+ }++ fn register(&self, id: &str) -> oneshot::Receiver<Reply> {+ let (tx, rx) = oneshot::channel();+ self.waiters.lock().unwrap().insert(id.to_string(), tx);+ rx+ }++ fn take(&self, id: &str) -> Option<oneshot::Sender<Reply>> {+ self.waiters.lock().unwrap().remove(id)+ }++ /// Whether a live turn is waiting on this question.+ pub fn is_waiting(&self, id: &str) -> bool {+ self.waiters.lock().unwrap().contains_key(id)+ }+}++/// Removes the waiter when the tool call ends any way (also when the CLI hangs up).+struct WaiterGuard<'a> {+ hub: &'a QuestionHub,+ id: String,+}++impl Drop for WaiterGuard<'_> {+ fn drop(&mut self) {+ self.hub.take(&self.id);+ }+}++fn card_meta(q: &Question) -> Value {+ json!({+ "kind": "ask_user",+ "question_id": q.id,+ "question": q.question,+ "choices": q.choice_list(),+ "status": q.status,+ "answer": q.answer,+ })+}++fn place_message(q: &Question, role: &str, sender: &str, text: String) -> (NewMessage, MessageExtra) {+ (+ NewMessage {+ channel_id: q.channel_id.clone(),+ direct_kwant_id: q.direct_kwant_id.clone(),+ sender_role: role.into(),+ sender_id: sender.into(),+ text,+ reasoning_content: None,+ tool_calls: None,+ tokens_used: 0,+ },+ MessageExtra { thread_id: q.thread_id.clone(), meta: None },+ )+}++async fn save_message(state: &AppState, q: &Question, role: &str, sender: &str, text: String, meta: Value) -> Option<String> {+ let (msg, extra) = place_message(q, role, sender, text);+ let saved = state.db.insert_message_with(&msg, &MessageExtra { meta: Some(meta), ..extra }).await.ok()?;+ if let Some(t) = &q.thread_id {+ let _ = state.db.touch_thread(t).await;+ }+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or(Value::Null) });+ Some(saved.id)+}++/// Sends `question_updated` and refreshes the question's card in the chat.+async fn changed(state: &AppState, q: &Question) {+ if let Some(mid) = &q.message_id {+ let _ = state.db.set_message_meta(mid, &card_meta(q)).await;+ }+ let _ = state.event_sender.send(RuntimeEvent::QuestionUpdated { question: serde_json::to_value(q).unwrap_or(Value::Null) });+}++/// Closes an open question and announces it; `None` if it wasn't open any more.+async fn close(state: &AppState, id: &str, status: &str, answer: Option<&str>) -> Option<Question> {+ if !state.db.close_question(id, status, answer).await.ok()? {+ return None;+ }+ let q = state.db.get_question(id).await.ok().flatten()?;+ changed(state, &q).await;+ Some(q)+}++// Agent tool++pub fn tools() -> Vec<Value> {+ vec![json!({+ "name": "ask_user",+ "description": "Ask the user one short question when you can't sensibly go on without their decision. \+ Give 2 to 5 short choices; the user can also type their own answer. Your turn waits for the answer \+ (a few minutes at most) and the tool returns it. Don't ask what you can find out or decide yourself.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "question": {"type": "string", "description": "The question (max 500 characters)"},+ "choices": {+ "type": "array",+ "items": {"type": "string"},+ "minItems": 2,+ "maxItems": 5,+ "description": "2 to 5 short answers to pick from (max 80 characters each)",+ },+ },+ "required": ["question", "choices"],+ },+ })]+}++pub async fn tool_ask(state: &AppState, scope: &SelfScope, args: &Value) -> (String, bool) {+ let (Some(origin), Some(cancel)) = (&scope.origin, &scope.cancel) else {+ return ("You can only ask the user from a chat.".into(), true);+ };+ let choices: Vec<String> = match args["choices"].as_array() {+ Some(list) => list.iter().map(|c| c.as_str().unwrap_or("").to_string()).collect(),+ None => Vec::new(),+ };+ let (question, choices) = match clean_question(args["question"].as_str().unwrap_or(""), &choices) {+ Ok(v) => v,+ Err(e) => return (e.to_string(), true),+ };+ let place = QuestionPlace {+ kwant_id: scope.kwant_id.clone(),+ channel_id: origin.channel_id.clone(),+ direct_kwant_id: origin.direct_kwant_id.clone(),+ thread_id: origin.thread_id.clone(),+ turn_id: scope.turn_id.clone(),+ };+ let mut q = match state.db.create_question(&place, &question, &choices).await {+ Ok(q) => q,+ Err(QuestionError::Db) => return ("Could not save the question.".into(), true),+ Err(e) => return (e.to_string(), true),+ };+ // Waiting before the card exists, so a very fast answer can't miss the turn+ let hub = &state.questions;+ let mut rx = hub.register(&q.id);+ let _guard = WaiterGuard { hub, id: q.id.clone() };+ // The text keeps the choices readable in history and for older clients; the card uses meta+ let text = format!("{}\n\nChoices: {}", q.question, choices.join(" · "));+ if let Some(mid) = save_message(state, &q, "kwant", &scope.kwant_id, text, card_meta(&q)).await {+ let _ = state.db.set_question_message(&q.id, &mid).await;+ q.message_id = Some(mid);+ }+ changed(state, &q).await;+ notify(+ state,+ Notification {+ kind: "question_asked",+ kwant_id: scope.kwant_id.clone(),+ kwant_name: scope.kwant_name.clone(),+ channel_id: origin.channel_id.clone(),+ title: format!("{} has a question", scope.kwant_name),+ body: "Open the chat to answer.".into(),+ },+ )+ .await;+ tracing::info!(question_id = %q.id, kwant_id = %scope.kwant_id, "agent asked the user");++ let reply = tokio::select! {+ r = &mut rx => r.ok(),+ _ = cancel.cancelled() => {+ close(state, &q.id, "cancelled", None).await;+ return ("The user stopped this turn. End it now.".into(), true);+ }+ _ = tokio::time::sleep(hub.wait()) => {+ hub.take(&q.id);+ // An answer that arrived just as the wait ran out still counts+ rx.try_recv().ok()+ }+ };+ match reply {+ Some(Reply::Answer(a)) => (format!("The user answered: {a}"), false),+ Some(Reply::Dismissed) => (+ "The user dismissed the question without answering. Carry on with your best judgment, or stop if you can't.".into(),+ false,+ ),+ None => (+ "The user hasn't answered yet. Don't ask again: end your turn now with a short note on what you're waiting for. \+ When they answer, you'll get a new turn with their answer."+ .into(),+ false,+ ),+ }+}++// Routes++#[derive(Deserialize)]+pub struct ListQuery {+ pub status: Option<String>,+ pub context_id: Option<String>,+}++fn error(status: StatusCode, message: impl Into<String>) -> Response {+ (status, Json(json!({ "error": message.into() }))).into_response()+}++/// `GET /api/questions?status=&context_id=`: newest first (to show open cards after a reload).+pub async fn list(State(state): State<AppState>, Query(q): Query<ListQuery>) -> Response {+ let status = q.status.filter(|s| !s.is_empty());+ if let Some(s) = &status {+ if !QUESTION_STATUSES.contains(&s.as_str()) {+ return error(StatusCode::BAD_REQUEST, "unknown status");+ }+ }+ match state.db.list_questions(status.as_deref(), q.context_id.as_deref().filter(|c| !c.is_empty())).await {+ Ok(list) => Json(list).into_response(),+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ }+}++async fn load(state: &AppState, id: &str) -> Result<Question, StatusCode> {+ match state.db.get_question(id).await {+ Ok(Some(q)) => Ok(q),+ Ok(None) => Err(StatusCode::NOT_FOUND),+ Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),+ }+}++pub async fn get(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ match load(&state, &id).await {+ Ok(q) => Json(json!({"question": q, "waiting": state.questions.is_waiting(&q.id)})).into_response(),+ Err(r) => r.into_response(),+ }+}++#[derive(Deserialize, Default)]+pub struct AnswerPayload {+ /// Index into the question's choices.+ pub choice: Option<usize>,+ /// The user's own answer.+ pub text: Option<String>,+}++/// `POST /api/questions/:id/answer {choice} | {text}`: the waiting turn gets it at once; if the+/// turn already ended, a new turn starts in the same chat with the answer.+pub async fn answer(State(state): State<AppState>, Path(id): Path<String>, Json(p): Json<AnswerPayload>) -> Response {+ let q = match load(&state, &id).await {+ Ok(q) => q,+ Err(r) => return r.into_response(),+ };+ let text = match (p.choice, p.text.as_deref().map(str::trim)) {+ (Some(i), None) => match q.choice_list().get(i) {+ Some(c) => c.clone(),+ None => return error(StatusCode::BAD_REQUEST, "no such choice"),+ },+ (None, Some(t)) if !t.is_empty() => {+ if t.chars().count() > MAX_ANSWER_CHARS {+ return error(StatusCode::BAD_REQUEST, format!("the answer is longer than {MAX_ANSWER_CHARS} characters"));+ }+ t.to_string()+ }+ _ => return error(StatusCode::BAD_REQUEST, "give either a choice or a non-empty text"),+ };+ if q.status != "open" {+ return error(StatusCode::CONFLICT, format!("the question is already {}", q.status));+ }+ let Some(q) = close(&state, &id, "answered", Some(&text)).await else {+ return error(StatusCode::CONFLICT, "the question was just closed");+ };+ save_message(&state, &q, "user", "user", text.clone(), json!({"kind": "question_answer", "question_id": q.id})).await;+ let live = match state.questions.take(&q.id) {+ Some(tx) => tx.send(Reply::Answer(text.clone())).is_ok(),+ None => false,+ };+ if !live {+ resume(&state, &q, &text).await;+ }+ Json(json!({"question": q, "resumed": if live { "turn" } else { "new_turn" }})).into_response()+}++/// A late answer: a new turn in the question's chat, queued like any other turn.+async fn resume(state: &AppState, q: &Question, answer: &str) {+ let Ok(Some(kwant)) = state.db.get_kwant(&q.kwant_id).await else {+ return;+ };+ let depth = match &q.thread_id {+ Some(t) => state.db.delegation_for_thread(t).await.ok().flatten().map(|d| d.depth).unwrap_or(0),+ None => 0,+ };+ let job = state.turns.start_job([q.context_id(), q.id.clone()]);+ let Ok(scope) = scope_for(state, &kwant, q.channel_id.clone(), q.thread_id.clone(), &job, depth).await else {+ return;+ };+ let prompt = format!(+ "[The user answered the question you asked earlier]\nQuestion: {}\nAnswer: {answer}\n\nContinue the task with this answer.",+ q.question+ );+ tokio::spawn(async move {+ let _job = job;+ let _ = try_kwant_turn(&scope, &kwant, prompt, TurnOpts::default()).await;+ });+}++/// After a turn was stopped: its questions that are still open are cancelled, so a late answer+/// doesn't restart work the user stopped. One indexed query, only for stopped turns.+pub async fn cancel_for_turn(state: &AppState, turn_id: &str) {+ let open = state.db.list_questions(Some("open"), None).await.unwrap_or_default();+ for q in open.iter().filter(|q| q.turn_id.as_deref() == Some(turn_id)) {+ if let Some(tx) = state.questions.take(&q.id) {+ drop(tx);+ }+ close(state, &q.id, "cancelled", None).await;+ }+}++/// `POST /api/questions/:id/cancel`: the user dismisses the question; a waiting turn carries on+/// without an answer.+pub async fn cancel(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ let q = match load(&state, &id).await {+ Ok(q) => q,+ Err(r) => return r.into_response(),+ };+ if q.status != "open" {+ return error(StatusCode::CONFLICT, format!("the question is already {}", q.status));+ }+ let Some(q) = close(&state, &id, "cancelled", None).await else {+ return error(StatusCode::CONFLICT, "the question was just closed");+ };+ if let Some(tx) = state.questions.take(&q.id) {+ let _ = tx.send(Reply::Dismissed);+ }+ Json(q).into_response()+}diff --git a/src/server/routes.rs b/src/server/routes.rsindex 3bb80881..98ba06e2 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -818,6 +818,9 @@ pub(super) async fn try_kwant_turn(return Err("stopped by the user".into());}let reply = run_kwant_turn_inner(scope, target_kwant, prompt, opts, &tag).await;+ if scope.cancel_token.is_cancelled() {+ super::questions::cancel_for_turn(&scope.state, &tag.turn_id).await;+ }ended.outcome = match (&reply, scope.cancel_token.is_cancelled()) {(Ok(_), _) => "completed",(Err(_), true) => "cancelled",@@ -1043,6 +1046,8 @@ async fn run_kwant_turn_inner(member_ids: scope.teammates.iter().map(|k| k.id.clone()).collect(),depth: scope.delegation_depth,}),+ cancel: Some(cancel_token.clone()),+ turn_id: Some(tag.turn_id.clone()),}});let mcp_turn = super::mcp_runtime::prepare_turn_with_self(diff --git a/tests/ask_user_test.rs b/tests/ask_user_test.rsnew file mode 100644index 00000000..f50a32da--- /dev/null+++ b/tests/ask_user_test.rs@@ -0,0 +1,232 @@+//! One-tap questions (batch 2 / C): `ask_user` pauses the turn with a question card, an answer+//! resumes it, Stop still works, a late answer starts a new turn, and the agent's other chats keep+//! running while it waits.++mod common;++use axum::http::StatusCode;+use common::*;+use kwnt::server::continuity::SelfScope;+use kwnt::RuntimeEvent;+use serde_json::{json, Value};+use std::time::Duration;++fn ask_marker(question: &str, choices: &[&str]) -> String {+ call_tool_marker("ask_user", json!({"question": question, "choices": choices}))+}++/// Waits until `ctx` has an open question, and returns it.+async fn open_question(env: &Env, ctx: &str) -> Value {+ for _ in 0..300 {+ let (s, list) = call(&env.app, "GET", &format!("/api/questions?status=open&context_id={ctx}"), None).await;+ assert_eq!(s, StatusCode::OK);+ if let Some(q) = list.as_array().and_then(|l| l.first()) {+ return q.clone();+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ panic!("no open question in {ctx}");+}++async fn question(env: &Env, id: &str) -> Value {+ let (s, v) = call(&env.app, "GET", &format!("/api/questions/{id}"), None).await;+ assert_eq!(s, StatusCode::OK);+ v+}++#[tokio::test]+async fn ask_pauses_the_turn_and_a_choice_resumes_it() {+ let env = setup().await;+ let mut rx = env.state.event_sender.subscribe();+ send_direct(&env, &env.a, &format!("Ship it? {} REPLYTAG:q1", ask_marker("Which branch should I ship?", &["main", "batch2"])), json!({})).await;+ let q = open_question(&env, &env.a).await;+ let id = q["id"].as_str().unwrap().to_string();+ assert_eq!(q["choices"], json!(["main", "batch2"]));+ assert_eq!(q["kwant_id"], env.a.as_str());+ assert!(question(&env, &id).await["waiting"].as_bool().unwrap(), "the turn is waiting");++ // The card is a chat message with the question in meta+ let card = messages(&env, &env.a).await.into_iter().find(|m| m.text.starts_with("Which branch")).unwrap();+ let meta: Value = serde_json::from_str(card.meta.as_deref().unwrap()).unwrap();+ assert_eq!(meta["kind"], "ask_user");+ assert_eq!(meta["question_id"], id.as_str());+ assert_eq!(meta["status"], "open");++ let (s, v) = call(&env.app, "POST", &format!("/api/questions/{id}/answer"), Some(json!({"choice": 1}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["resumed"], "turn");+ let reply = wait_reply(&env, &env.a, "answer q1").await;+ assert!(reply.text.contains("TOOL[The user answered: batch2]"), "{}", reply.text);++ // Stored: answered, the answer is a user message, the card shows it+ let q = &question(&env, &id).await["question"];+ assert_eq!(q["status"], "answered");+ assert_eq!(q["answer"], "batch2");+ let msgs = messages(&env, &env.a).await;+ let ans = msgs.iter().find(|m| m.meta.as_deref().is_some_and(|x| x.contains("question_answer"))).unwrap();+ assert_eq!((ans.sender_role.as_str(), ans.text.as_str()), ("user", "batch2"));+ let card = msgs.iter().find(|m| m.id == card.id).unwrap();+ assert!(card.meta.as_deref().unwrap().contains("\"status\":\"answered\""));++ let (mut asked, mut answered, mut notified) = (false, false, false);+ while let Ok(e) = rx.try_recv() {+ match e.unscoped() {+ RuntimeEvent::QuestionUpdated { question } if question["id"] == id.as_str() => match question["status"].as_str() {+ Some("open") => asked = true,+ Some("answered") => answered = true,+ _ => {}+ },+ RuntimeEvent::Notify { kind, body, .. } if kind == "question_asked" => {+ assert!(!body.contains("branch"), "notifications don't carry the question text");+ notified = true;+ }+ _ => {}+ }+ }+ assert!(asked && answered && notified);++ // Answering twice is refused+ let (s, _) = call(&env.app, "POST", &format!("/api/questions/{id}/answer"), Some(json!({"choice": 0}))).await;+ assert_eq!(s, StatusCode::CONFLICT);+}++#[tokio::test]+async fn the_agent_keeps_working_elsewhere_while_it_waits() {+ let env = setup().await;+ send_direct(&env, &env.a, &format!("{} REPLYTAG:w1", ask_marker("Pick a colour", &["red", "blue"])), json!({})).await;+ let q = open_question(&env, &env.a).await;++ // A thread of the same agent, and the other agent, both answer meanwhile+ let (s, thread) = call(&env.app, "POST", &format!("/api/kwants/{}/threads", env.a), Some(json!({"title": "side"}))).await;+ assert_eq!(s, StatusCode::CREATED);+ let tid = thread["id"].as_str().unwrap();+ let (s, _) = call(&env.app, "POST", "/api/chat/send", Some(json!({"prompt": "quick one REPLYTAG:w2", "sender_id": "user", "thread_id": tid}))).await;+ assert_eq!(s, StatusCode::OK);+ wait_reply(&env, tid, "answer w2").await;+ send_direct(&env, &env.b, "disk space? REPLYTAG:w3", json!({})).await;+ wait_reply(&env, &env.b, "answer w3").await;+ assert_eq!(question(&env, q["id"].as_str().unwrap()).await["question"]["status"], "open", "still waiting");++ // Free text answer+ let (s, _) = call(&env.app, "POST", &format!("/api/questions/{}/answer", q["id"].as_str().unwrap()), Some(json!({"text": " green, actually "}))).await;+ assert_eq!(s, StatusCode::OK);+ let reply = wait_reply(&env, &env.a, "answer w1").await;+ assert!(reply.text.contains("The user answered: green, actually]"), "{}", reply.text);+}++#[tokio::test]+async fn stop_cancels_the_waiting_question() {+ let env = setup().await;+ send_direct(&env, &env.a, &format!("{} REPLYTAG:c1", ask_marker("Delete the old logs?", &["yes", "no"])), json!({})).await;+ let q = open_question(&env, &env.a).await;+ let id = q["id"].as_str().unwrap();+ let (s, v) = call(&env.app, "POST", "/api/chat/cancel", Some(json!({"kwant_id": env.a}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ wait_for("question cancelled", || async { question(&env, id).await["question"]["status"] == "cancelled" }).await;+ let (s, _) = call(&env.app, "POST", &format!("/api/questions/{id}/answer"), Some(json!({"choice": 0}))).await;+ assert_eq!(s, StatusCode::CONFLICT, "a stopped turn's question can't be answered");+ wait_for("turn gone", || async {+ let (_, t) = call(&env.app, "GET", "/api/turns", None).await;+ t["turns"].as_array().unwrap().is_empty()+ })+ .await;+}++#[tokio::test]+async fn dismissing_lets_the_turn_carry_on() {+ let env = setup().await;+ send_direct(&env, &env.a, &format!("{} REPLYTAG:d1", ask_marker("Tabs or spaces?", &["tabs", "spaces"])), json!({})).await;+ let q = open_question(&env, &env.a).await;+ let (s, v) = call(&env.app, "POST", &format!("/api/questions/{}/cancel", q["id"].as_str().unwrap()), None).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(v["status"], "cancelled");+ let reply = wait_reply(&env, &env.a, "answer d1").await;+ assert!(reply.text.contains("dismissed the question"), "{}", reply.text);+ assert!(!reply.text.contains("TOOLERROR"));+}++#[tokio::test]+async fn a_late_answer_starts_a_new_turn() {+ let env = setup().await;+ env.state.questions.set_wait(Duration::from_millis(300));+ send_direct(&env, &env.a, &format!("{} REPLYTAG:l1", ask_marker("Which region?", &["eu", "us"])), json!({})).await;+ let reply = wait_reply(&env, &env.a, "answer l1").await;+ assert!(reply.text.contains("hasn't answered yet"), "{}", reply.text);+ let q = open_question(&env, &env.a).await;+ let id = q["id"].as_str().unwrap();+ assert_eq!(question(&env, id).await["waiting"], false);++ let (s, v) = call(&env.app, "POST", &format!("/api/questions/{id}/answer"), Some(json!({"text": "LATE_ANSWER_EU"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["resumed"], "new_turn");+ wait_for("the resumed turn", || async { !invocations_with("Answer: LATE_ANSWER_EU").is_empty() }).await;+ let args = invocations_with("Answer: LATE_ANSWER_EU").pop().unwrap();+ assert!(args.contains("Question: Which region?"));+ assert_eq!(invocations_with("Answer: LATE_ANSWER_EU").len(), 1, "one new turn, the tool isn't called again");+}++#[tokio::test]+async fn answers_and_tool_input_are_validated() {+ let env = setup().await;+ let (s, _) = call(&env.app, "POST", "/api/questions/nope/answer", Some(json!({"choice": 0}))).await;+ assert_eq!(s, StatusCode::NOT_FOUND);+ let (s, _) = call(&env.app, "POST", "/api/questions/nope/cancel", None).await;+ assert_eq!(s, StatusCode::NOT_FOUND);+ let (s, _) = call(&env.app, "GET", "/api/questions/nope", None).await;+ assert_eq!(s, StatusCode::NOT_FOUND);+ let (s, _) = call(&env.app, "GET", "/api/questions?status=bogus", None).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);++ send_direct(&env, &env.a, &format!("{} REPLYTAG:v1", ask_marker("Ok?", &["yes", "no"])), json!({})).await;+ let q = open_question(&env, &env.a).await;+ let url = format!("/api/questions/{}/answer", q["id"].as_str().unwrap());+ for bad in [json!({"choice": 2}), json!({"text": " "}), json!({}), json!({"choice": 0, "text": "x"}), json!({"text": "x".repeat(2001)})] {+ let (s, _) = call(&env.app, "POST", &url, Some(bad.clone())).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{bad}");+ }+ let (s, _) = call(&env.app, "POST", &url, Some(json!({"choice": 0}))).await;+ assert_eq!(s, StatusCode::OK);+ wait_reply(&env, &env.a, "answer v1").await;++ // Bad tool input never creates a question+ for (tag, args) in [+ ("v2", json!({"question": "Only one?", "choices": ["a"]})),+ ("v3", json!({"question": "Six?", "choices": ["a", "b", "c", "d", "e", "f"]})),+ ("v4", json!({"question": "", "choices": ["a", "b"]})),+ ] {+ send_direct(&env, &env.b, &format!("{} REPLYTAG:{tag}", call_tool_marker("ask_user", args)), json!({})).await;+ let r = wait_reply(&env, &env.b, &format!("answer {tag}")).await;+ assert!(r.text.contains("TOOLERROR"), "{}", r.text);+ }+ let (_, open) = call(&env.app, "GET", &format!("/api/questions?context_id={}", env.b), None).await;+ assert!(open.as_array().unwrap().is_empty());++ // Outside a live chat turn the tool isn't offered+ env.state+ .self_tools+ .lock()+ .await+ .insert("tok".into(), SelfScope { kwant_id: env.a.clone(), kwant_name: "A".into(), ..Default::default() });+ let (_, list) = call_with(+ &env.app,+ "POST",+ "/api/mcp/self",+ Some(json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}})),+ &[("authorization", "Bearer tok")],+ )+ .await;+ assert!(!list.to_string().contains("ask_user"));+}++#[tokio::test]+async fn every_question_route_needs_auth() {+ let env = setup().await;+ for (m, u) in [+ ("GET", "/api/questions"),+ ("GET", "/api/questions/x"),+ ("POST", "/api/questions/x/answer"),+ ("POST", "/api/questions/x/cancel"),+ ] {+ assert_eq!(call_remote(&env.app, m, u).await, StatusCode::UNAUTHORIZED, "{m} {u}");+ }+}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex c4a32607..0fa4b1bf 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -3,7 +3,7 @@//! own tools (`kwnt_tools`) over HTTP the way the real CLI does, so a test drives a whole turn://!//! - `CALLTOOL:<tool>:<base64 json args>` in the prompt: call that tool and reply with its text-//! (the last marker counts; earlier ones are chat history).+//! (the last marker counts, and each marker runs once: later turns see it again in history).//! - `REPLYTAG:<tag>`: reply "answer <tag>" (after any tool call).//!//! Each test file that uses it is its own binary, because it changes PATH.@@ -35,7 +35,14 @@ with open(os.path.join(out_dir, "%d-%d" % (os.getpid(), time.time_ns())), "w") af.write("\n".join(args))reply = []m = ([None] + list(re.finditer(r"CALLTOOL:([a-z_]+):([A-Za-z0-9+/=]+)", prompt)))[-1]+done = None+if m:+ import hashlib+ done = os.path.join(os.path.dirname(out_dir), "called-" + hashlib.sha1(m.group(0).encode()).hexdigest())+ if os.path.exists(done):+ m = Noneif m and "--mcp-config" in args:+ open(done, "w").close()cfg = json.load(open(args[args.index("--mcp-config") + 1]))srv = cfg["mcpServers"]["kwnt_tools"]body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call",diff --git a/tests/continuity_test.rs b/tests/continuity_test.rsindex 6adba7f6..d12cdc85 100644--- a/tests/continuity_test.rs+++ b/tests/continuity_test.rs@@ -666,6 +666,7 @@ async fn self_tools_are_scoped_to_the_turn_and_kwant() {kwant_id: k1.id.clone(),kwant_name: k1.name.clone(),origin: None,+ ..Default::default()}),).await@@ -1134,7 +1135,7 @@ async fn webhook_setting_is_https_only_and_masked() {assert_eq!(s["notify_webhook_url"], "");assert_eq!(s["notify_on"],- json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed"])+ json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked"]));let (status, _) = req(diff --git a/tests/delegation_test.rs b/tests/delegation_test.rsindex b541b04c..853f4a1a 100644--- a/tests/delegation_test.rs+++ b/tests/delegation_test.rs@@ -452,6 +452,7 @@ async fn delegation_tools_enforce_their_rules() {kwant_id: env.lead.clone(),kwant_name: names[0].clone(),origin: Some(continuity::TurnOrigin { direct_kwant_id: Some(env.lead.clone()), ..Default::default() }),+ ..Default::default()},);tools.insert(@@ -460,11 +461,12 @@ async fn delegation_tools_enforce_their_rules() {kwant_id: env.lead.clone(),kwant_name: names[0].clone(),origin: Some(continuity::TurnOrigin { direct_kwant_id: Some(env.lead.clone()), depth: 2, ..Default::default() }),+ ..Default::default()},);tools.insert("other-token".into(),- continuity::SelfScope { kwant_id: env.specialist.clone(), kwant_name: names[1].clone(), origin: None },+ continuity::SelfScope { kwant_id: env.specialist.clone(), kwant_name: names[1].clone(), origin: None, ..Default::default() },);}// Offered only to turns that know their chat