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
Mark replies cut short by a restart and stop turns that stall
Lin (kwant bot)90468c64600a
diff --git a/src/db/continuity.rs b/src/db/continuity.rsindex 0abb8df5..e8aa88f8 100644--- a/src/db/continuity.rs+++ b/src/db/continuity.rs@@ -29,6 +29,18 @@ pub struct Memory {pub updated_at: DateTime<Utc>,}+/// A chat turn in progress: where its reply would go.+#[derive(Debug, Clone, FromRow, PartialEq)]+pub struct RunningTurn {+ pub turn_id: String,+ pub kwant_id: String,+ pub kwant_name: String,+ pub channel_id: Option<String>,+ pub direct_kwant_id: Option<String>,+ pub thread_id: Option<String>,+ pub started_at: DateTime<Utc>,+}+#[derive(Debug, PartialEq)]pub enum MemoryError {Empty,@@ -193,6 +205,15 @@ impl Database {.await;}+ // Chat turns in progress, so a restart can say which replies it cut off+ sqlx::query(+ "CREATE TABLE IF NOT EXISTS running_turns (\+ turn_id TEXT PRIMARY KEY, kwant_id TEXT NOT NULL, kwant_name TEXT NOT NULL, \+ channel_id TEXT, direct_kwant_id TEXT, thread_id TEXT, started_at DATETIME NOT NULL)",+ )+ .execute(&self.pool)+ .await?;+let had_index: Option<(String,)> = sqlx::query_as("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'messages_fts'",)@@ -701,6 +722,39 @@ impl Database {Ok(())}+ pub async fn add_running_turn(&self, turn: &RunningTurn) -> Result<(), DbError> {+ sqlx::query(+ "INSERT OR REPLACE INTO running_turns (turn_id, kwant_id, kwant_name, channel_id, direct_kwant_id, thread_id, started_at) \+ VALUES (?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(&turn.turn_id)+ .bind(&turn.kwant_id)+ .bind(&turn.kwant_name)+ .bind(&turn.channel_id)+ .bind(&turn.direct_kwant_id)+ .bind(&turn.thread_id)+ .bind(turn.started_at)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ pub async fn remove_running_turn(&self, turn_id: &str) -> Result<(), DbError> {+ sqlx::query("DELETE FROM running_turns WHERE turn_id = ?").bind(turn_id).execute(&self.pool).await?;+ Ok(())+ }++ /// Takes every turn a previous run of kwnt left running (it stopped mid-reply).+ pub async fn take_running_turns(&self) -> Result<Vec<RunningTurn>, DbError> {+ let mut tx = self.pool.begin().await?;+ let turns = sqlx::query_as::<_, RunningTurn>("SELECT * FROM running_turns ORDER BY started_at")+ .fetch_all(&mut *tx)+ .await?;+ sqlx::query("DELETE FROM running_turns").execute(&mut *tx).await?;+ tx.commit().await?;+ Ok(turns)+ }+/// Runs left 'running' by a kwnt that stopped mid-run.pub async fn fail_interrupted_runs(&self) -> Result<u64, DbError> {let res = sqlx::query("UPDATE routine_runs SET status = 'error', error = 'kwnt stopped during the run', ended_at = ? WHERE status = 'running'")diff --git a/src/drivers/api.rs b/src/drivers/api.rsindex 3ecbcea3..824dbde3 100644--- a/src/drivers/api.rs+++ b/src/drivers/api.rs@@ -563,6 +563,10 @@ impl ApiDriver {#[async_trait]impl Driver for ApiDriver {+ fn streams_progress(&self) -> bool {+ true+ }+async fn stream_turn(&self,input: TurnInput,diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex bbee5dea..970449d8 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -411,6 +411,13 @@ pub trait Driver: Send + Sync {input: TurnInput,event_tx: mpsc::Sender<RuntimeEvent>,) -> Result<TurnOutput, DriverError>;++ /// Whether this driver streams its reply as it goes and brackets tool runs with+ /// `ToolCallPending`/`ToolCallCompleted`, so a long silence means it is stuck. Drivers that+ /// only report at the end (one-shot CLIs) say false and are never stopped for silence.+ fn streams_progress(&self) -> bool {+ false+ }}/// The driver for a turn on `target_model` without a profile, and the engine it runs on: thediff --git a/src/main.rs b/src/main.rsindex cfb9483a..91bd5728 100644--- a/src/main.rs+++ b/src/main.rs@@ -152,6 +152,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {// Saved passwords left in a bot's folder by older versions move into the vaultkwnt::server::passwords::migrate_all(&state).await;kwnt::server::passwords::warn_if_exposed(&state).await;+ // Before anything can start a turn: say which replies the last run cut off+ kwnt::server::routes::interrupt_running_turns(&state).await;kwnt::server::scheduler::spawn_background(state.clone(), shutdown.clone());kwnt::server::engine_routes::spawn_startup_check(state.clone());kwnt::server::parallel_routes::spawn_startup_sweep(state.clone());diff --git a/src/server/routes.rs b/src/server/routes.rsindex be83c900..900452ab 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -1144,6 +1144,7 @@ pub(super) async fn try_kwant_turn(turns: turns.clone(),tag: tag.clone(),outcome: "cancelled",+ running_row: None,};let Some(_slot) = turns.acquire(&tag, &scope.cancel_token, &scope.state.event_sender).await else {return Err("stopped by the user".into());@@ -1156,6 +1157,20 @@ pub(super) async fn try_kwant_turn(state: "running".into(),since: chrono::Utc::now(),});+ // Kept until the turn ends, so a restart mid-reply is said in the chat (see interrupt_running_turns)+ let running = crate::db::continuity::RunningTurn {+ turn_id: tag.turn_id.clone(),+ kwant_id: target_kwant.id.clone(),+ kwant_name: target_kwant.name.clone(),+ channel_id: scope.channel_id.clone(),+ // Where scope.save puts the reply+ direct_kwant_id: scope.kwant_id.clone(),+ thread_id: scope.thread_id.clone(),+ started_at: chrono::Utc::now(),+ };+ if scope.state.db.add_running_turn(&running).await.is_ok() {+ ended.running_row = Some(scope.state.db.clone());+ }let _ = scope.state.event_sender.send(RuntimeEvent::TurnStarted {kwant_id: target_kwant.id.clone(),context_id: Some(tag.context_id.clone()),@@ -1181,6 +1196,43 @@ pub(super) async fn try_kwant_turn(reply.map_err(|why| truncate_chars(&scrub_urls(why.trim()), MAX_FAILURE_CHARS).to_string())}+/// Says in each chat which reply a previous run of kwnt cut off by stopping mid-turn. Runs once at+/// startup, before any new turn can start. The note's meta is+/// `{"kind":"turn_interrupted","interrupted":true,"kwant_id","kwant_name","turn_id","started_at"}`.+pub async fn interrupt_running_turns(state: &AppState) -> usize {+ let Ok(turns) = state.db.take_running_turns().await else {+ return 0;+ };+ for t in &turns {+ let msg = NewMessage {+ channel_id: t.channel_id.clone(),+ direct_kwant_id: t.direct_kwant_id.clone(),+ sender_role: "system".into(),+ sender_id: "kwnt".into(),+ text: format!("This reply from {} was interrupted by a restart. Send your message again to retry.", t.kwant_name),+ reasoning_content: None,+ tool_calls: None,+ tokens_used: 0,+ };+ let meta = json!({+ "kind": "turn_interrupted",+ "interrupted": true,+ "kwant_id": t.kwant_id,+ "kwant_name": t.kwant_name,+ "turn_id": t.turn_id,+ "started_at": t.started_at,+ });+ let _ = state.db.insert_message_with(&msg, &MessageExtra { thread_id: t.thread_id.clone(), meta: Some(meta) }).await;+ if let Some(tid) = &t.thread_id {+ let _ = state.db.touch_thread(tid).await;+ }+ }+ if !turns.is_empty() {+ tracing::info!(count = turns.len(), "marked chat replies cut short by a restart as interrupted");+ }+ turns.len()+}+/// `text` with every URL cut to scheme and host, so a failure reason that names a custom/// endpoint can be stored without the credentials some endpoints carry in the userinfo,/// path or query.@@ -1209,11 +1261,19 @@ struct TurnEndedGuard {turns: super::turns::TurnRegistry,tag: crate::drivers::events::TurnTag,outcome: &'static str,+ /// Set once the turn is recorded as running; the record is removed when the turn ends.+ running_row: Option<crate::db::Database>,}impl Drop for TurnEndedGuard {fn drop(&mut self) {self.turns.end_turn(&self.tag.turn_id);+ if let (Some(db), Ok(rt)) = (self.running_row.take(), tokio::runtime::Handle::try_current()) {+ let turn_id = self.tag.turn_id.clone();+ rt.spawn(async move {+ let _ = db.remove_running_turn(&turn_id).await;+ });+ }let tag = std::mem::take(&mut self.tag);let _ = self.sender.send(RuntimeEvent::TurnEnded {kwant_id: tag.kwant_id,@@ -1271,6 +1331,22 @@ impl RanOn {}}+/// Setting: seconds a streaming model may stay silent (outside tool runs) before its turn is stopped.+pub const STALL_SETTING: &str = "turn_stall_secs";+pub const DEFAULT_STALL_SECS: u64 = 120;++/// The stall limit from settings: missing or unreadable means the default, 0 turns it off.+async fn stall_limit(db: &crate::db::Database) -> Option<std::time::Duration> {+ let secs = db+ .get_setting(STALL_SETTING)+ .await+ .ok()+ .flatten()+ .and_then(|v| v.trim().parse::<u64>().ok())+ .unwrap_or(DEFAULT_STALL_SECS);+ (secs > 0).then(|| std::time::Duration::from_secs(secs))+}+async fn run_kwant_turn_inner(scope: &TurnScope,target_kwant: &Kwant,@@ -1530,6 +1606,7 @@ async fn run_kwant_turn_inner(};let had_state = state.db.list_profile_states().await.unwrap_or_default();+ let stall_after = stall_limit(&state.db).await;let turn_start = std::time::Instant::now();// Notices about profile switches, kept with the saved replylet mut notices: Vec<String> = Vec::new();@@ -1623,22 +1700,44 @@ async fn run_kwant_turn_inner(account: super::profile_turn::account_name(profile.as_ref(), e),choice: if unlisted_api { None } else { choice.clone() },});+ let stall_limit = if driver.streams_progress() { stall_after } else { None };let (driver_tx, mut driver_rx) = mpsc::channel(32);let driver_task =tokio::spawn(async move { driver.stream_turn(input, driver_tx).await });+ // Stall watchdog: silence while no tool runs, for longer than the limit, stops the turn+ let mut last_output = tokio::time::Instant::now();+ let mut tools_running = 0usize;+ let mut stalled = false;// The driver's TurnComplete is held back: it's re-sent with the kwant and profile,// or dropped when the turn moves to another profile.let mut held_complete = None;let mut side_effects = false;loop {+ let stall_at = stall_limit.filter(|_| tools_running == 0).map(|d| last_output + d);tokio::select! {_ = cancel_token.cancelled() => {cancelled = true;driver_task.abort();break;}+ _ = async {+ match stall_at {+ Some(at) => tokio::time::sleep_until(at).await,+ None => std::future::pending().await,+ }+ } => {+ stalled = true;+ driver_task.abort();+ break;+ }event_opt = driver_rx.recv() => {+ last_output = tokio::time::Instant::now();+ match &event_opt {+ Some(RuntimeEvent::ToolCallPending { .. }) => tools_running += 1,+ Some(RuntimeEvent::ToolCallCompleted { .. }) => tools_running = tools_running.saturating_sub(1),+ _ => {}+ }match event_opt {Some(RuntimeEvent::TurnComplete { tokens, duration_ms, .. }) => {held_complete = Some((tokens, duration_ms));@@ -1660,6 +1759,23 @@ async fn run_kwant_turn_inner(if cancelled {break;}+ if stalled {+ let secs = stall_limit.map_or(0, |d| d.as_secs());+ let text = format!(+ "⚠️ [{}] The model sent nothing for {secs} s, so this reply was stopped. Send your message again to retry.",+ target_kwant.name+ );+ tracing::warn!(kwant = %target_kwant.id, secs, "turn stopped by the stall watchdog");+ event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));+ event_broadcast.send(RuntimeEvent::TurnComplete {+ tokens: 0,+ duration_ms: turn_start.elapsed().as_millis() as u64,+ kwant_id: Some(target_kwant.id.clone()),+ profile_id: profile.as_ref().map(|p| p.id.clone()),+ });+ gave_up = Some(text);+ break;+ }let result = driver_task.await;let refused = match &result {Ok(Ok(out)) => out.failure.clone(),diff --git a/tests/turn_recovery_test.rs b/tests/turn_recovery_test.rsnew file mode 100644index 00000000..be6e4dad--- /dev/null+++ b/tests/turn_recovery_test.rs@@ -0,0 +1,253 @@+//! Replies that can't finish: a model that goes silent is stopped by the stall watchdog with a+//! visible reason, and replies cut short by a restart are marked interrupted on the next start.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ routing::{get, post},+ Json, Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{continuity::RunningTurn, Database},+ drivers::RuntimeEvent,+ router::LayaRouter,+ server::{create_router, routes, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::time::Duration;+use tower::ServiceExt;++async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let resp = app+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json")+ .body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty))+ .unwrap(),+ )+ .await+ .unwrap();+ let s = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (s, serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())))+}++/// An OpenAI-compatible server that lists one model and then never answers a chat request.+async fn hanging_server() -> String {+ let app = Router::new()+ .route("/v1/models", get(|| async { Json(json!({"object": "list", "data": [{"id": "gpt-4.1"}]})) }))+ .route(+ "/v1/chat/completions",+ post(|| async {+ tokio::time::sleep(Duration::from_secs(3600)).await;+ Json(json!({}))+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let root = format!("http://{}", listener.local_addr().unwrap());+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ root+}++struct Env {+ app: Router,+ state: AppState,+ _tmp: tempfile::TempDir,+}++async fn setup() -> Env {+ let tmp = tempfile::tempdir().unwrap();+ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let config = Config {+ data_dir: data.clone(),+ laya_url: "http://127.0.0.1:9".into(),+ browser_cdp_url: Some("http://127.0.0.1:9".into()),+ ..Config::default()+ };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(data.join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ Env { app: create_router(state.clone()), state, _tmp: tmp }+}++impl Env {+ /// A bot on a custom API account that points at `root`, in its own space.+ async fn api_bot(&self, root: &str) -> String {+ let (s, v) = call(+ &self.app,+ "POST",+ "/api/spaces",+ Some(json!({"name": "Stalls", "icon": "🧪", "this_machine_enabled": false})),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ let space = v["id"].as_str().unwrap().to_string();+ let (s, v) = call(+ &self.app,+ "POST",+ &format!("/api/profiles?space={space}"),+ Some(json!({+ "engine": "custom", "kind": "custom_api", "name": "Silent server",+ "protocol": "openai-chat", "base_url": format!("{root}/v1"),+ "api_key": "sk-test-0123456789", "model": "gpt-4.1",+ })),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{v}");+ let (s, v) = call(+ &self.app,+ "POST",+ &format!("/api/kwants?space={space}"),+ Some(json!({+ "name": "Quill", "title": "Tester", "persona_prompt": "Test persona",+ "avatar_sprite": "s", "driver_type": "api", "preferred_model": "custom",+ })),+ )+ .await;+ assert!(s.is_success(), "{s} {v}");+ v["id"].as_str().unwrap().to_string()+ }++ async fn turn(&self, kwant_id: &str, within: Duration) -> Vec<RuntimeEvent> {+ let mut rx = self.state.event_sender.subscribe();+ let (s, v) = call(+ &self.app,+ "POST",+ "/api/chat/send",+ Some(json!({"kwant_id": kwant_id, "prompt": "hi", "sender_id": "user"})),+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let mut events = Vec::new();+ tokio::time::timeout(within, async {+ while let Ok(e) = rx.recv().await {+ let end = matches!(&e, RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == kwant_id);+ events.push(e.unscoped().clone());+ if end {+ break;+ }+ }+ })+ .await+ .expect("the turn did not end");+ events+ }+}++#[tokio::test]+async fn a_silent_model_is_stopped_with_a_visible_reason() {+ let env = setup().await;+ env.state.db.set_setting(routes::STALL_SETTING, "2").await.unwrap();+ let root = hanging_server().await;+ let kid = env.api_bot(&root).await;++ let started = std::time::Instant::now();+ let events = env.turn(&kid, Duration::from_secs(30)).await;+ let waited = started.elapsed();+ assert!(waited >= Duration::from_secs(2), "stopped before the limit: {waited:?}");+ assert!(waited < Duration::from_secs(15), "the watchdog should stop it soon after 2 s: {waited:?}");+ let shown: String = events+ .iter()+ .filter_map(|e| match e {+ RuntimeEvent::TextDelta(t) => Some(t.as_str()),+ _ => None,+ })+ .collect();+ assert!(shown.contains("sent nothing for 2 s"), "{shown}");++ // The reason is kept in the chat, and the bot isn't left marked as replying+ let saved = env.state.db.list_messages(&kid, 10).await.unwrap();+ assert!(saved.iter().any(|m| m.text.contains("sent nothing for 2 s")), "{saved:?}");+ tokio::time::sleep(Duration::from_millis(200)).await;+ assert!(env.state.db.take_running_turns().await.unwrap().is_empty(), "the running row is cleared");+}++#[tokio::test]+async fn the_stall_limit_comes_from_settings_and_zero_turns_it_off() {+ let env = setup().await;+ env.state.db.set_setting(routes::STALL_SETTING, "0").await.unwrap();+ let root = hanging_server().await;+ let kid = env.api_bot(&root).await;+ let mut rx = env.state.event_sender.subscribe();+ let (s, _) = call(+ &env.app,+ "POST",+ "/api/chat/send",+ Some(json!({"kwant_id": kid, "prompt": "hi", "sender_id": "user"})),+ )+ .await;+ assert_eq!(s, StatusCode::OK);+ let ended = tokio::time::timeout(Duration::from_secs(4), async {+ while let Ok(e) = rx.recv().await {+ if matches!(&e, RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == &kid) {+ return;+ }+ }+ })+ .await;+ assert!(ended.is_err(), "with the watchdog off a silent turn keeps waiting");+ // While it waits, the turn is recorded as running so a restart can mark it+ let running = env.state.db.take_running_turns().await.unwrap();+ assert_eq!(running.len(), 1, "{running:?}");+ assert_eq!(running[0].kwant_id, kid);+ let _ = call(&env.app, "POST", "/api/chat/cancel", Some(json!({"kwant_id": kid}))).await;+}++#[tokio::test]+async fn replies_cut_short_by_a_restart_are_marked_interrupted() {+ let env = setup().await;+ let (s, v) = call(+ &env.app,+ "POST",+ "/api/kwants",+ Some(json!({"name": "Ivy", "title": "Tester", "persona_prompt": "p", "avatar_sprite": "s", "driver_type": "api", "preferred_model": "gpt-4.1"})),+ )+ .await;+ assert!(s.is_success(), "{s} {v}");+ let kid = v["id"].as_str().unwrap().to_string();+ // What the previous run left behind when it stopped mid-reply+ env.state+ .db+ .add_running_turn(&RunningTurn {+ turn_id: "turn-1".into(),+ kwant_id: kid.clone(),+ kwant_name: "Ivy".into(),+ channel_id: None,+ direct_kwant_id: Some(kid.clone()),+ thread_id: None,+ started_at: chrono::Utc::now(),+ })+ .await+ .unwrap();++ assert_eq!(routes::interrupt_running_turns(&env.state).await, 1);+ // Only once: a second start finds nothing left to mark+ assert_eq!(routes::interrupt_running_turns(&env.state).await, 0);++ let (s, msgs) = call(&env.app, "GET", &format!("/api/channels/{kid}/messages"), None).await;+ assert_eq!(s, StatusCode::OK, "{msgs}");+ let marked: Vec<&Value> = msgs+ .as_array()+ .unwrap()+ .iter()+ .filter(|m| m["sender_role"] == "system")+ .collect();+ assert_eq!(marked.len(), 1, "{msgs}");+ assert_eq!(marked[0]["text"], "This reply from Ivy was interrupted by a restart. Send your message again to retry.");+ let meta: Value = serde_json::from_str(marked[0]["meta"].as_str().unwrap()).unwrap();+ assert_eq!(meta["kind"], "turn_interrupted");+ assert_eq!(meta["interrupted"], true);+ assert_eq!(meta["kwant_id"], kid.as_str());+ assert_eq!(meta["turn_id"], "turn-1");+}