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.

Keep driver errors in the chat; give recurring routines their last output

Lin (kwant bot)357d29e97541
diff --git a/src/db/mod.rs b/src/db/mod.rs
index b25223ed..34e96715 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -414,6 +414,10 @@ impl Database {
insert_message_on(&mut conn, input, extra).await
}
+ pub async fn get_message(&self, id: &str) -> Result<Option<Message>, DbError> {
+ Ok(sqlx::query_as::<_, Message>("SELECT * FROM messages WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)
+ }
+
pub async fn list_messages(&self, channel_or_kwant_id: &str, limit: i64) -> Result<Vec<Message>, DbError> {
let rows = sqlx::query_as::<_, Message>(
r#"
diff --git a/src/server/routes.rs b/src/server/routes.rs
index e4a85553..0669ffe1 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1819,6 +1819,7 @@ async fn run_kwant_turn_inner(
let mut notices: Vec<String> = Vec::new();
let mut cancelled = false;
let mut driver_result = None;
+ let mut driver_error: Option<RuntimeEvent> = None;
let mut gave_up: Option<String> = None;
// Saved with the gave-up reply, so a client can offer Retry without reading its wording
let mut gave_up_meta: Option<serde_json::Value> = None;
@@ -2061,23 +2062,20 @@ async fn run_kwant_turn_inner(
let _ = state.db.clear_profile_state(&p.id).await;
}
}
- match &result {
- Ok(Err(e)) => {
- event_broadcast.send(RuntimeEvent::Error {
- code: "driver_error".into(),
- message: e.to_string(),
- kwant_id: Some(target_kwant.id.clone()),
- });
- }
- Err(_) => {
- event_broadcast.send(RuntimeEvent::Error {
- code: "driver_crashed".into(),
- message: "the model driver stopped unexpectedly".into(),
- kwant_id: Some(target_kwant.id.clone()),
- });
- }
- Ok(Ok(_)) => {}
- }
+ // Sent once the failure is saved, so the chat it refreshes already shows it
+ driver_error = match &result {
+ Ok(Err(e)) => Some(RuntimeEvent::Error {
+ code: "driver_error".into(),
+ message: e.to_string(),
+ kwant_id: Some(target_kwant.id.clone()),
+ }),
+ Err(_) => Some(RuntimeEvent::Error {
+ code: "driver_crashed".into(),
+ message: "the model driver stopped unexpectedly".into(),
+ kwant_id: Some(target_kwant.id.clone()),
+ }),
+ Ok(Ok(_)) => None,
+ };
if let Some((tokens, duration_ms)) = held_complete {
event_broadcast.send(RuntimeEvent::TurnComplete {
tokens,
@@ -2106,6 +2104,9 @@ async fn run_kwant_turn_inner(
})
};
if cancelled {
+ if let Some(e) = driver_error.take() {
+ event_broadcast.send(e);
+ }
event_broadcast.send(RuntimeEvent::ThinkingDelta("⏹️ Cancelled by user".into()));
return Err("stopped by the user".into());
} else if let Some(text) = gave_up {
@@ -2182,11 +2183,21 @@ async fn run_kwant_turn_inner(
}
return Ok(output.text);
}
- Err(match driver_result {
+ let why = match driver_result {
Some(Ok(Err(e))) => format!("the {target_model} driver failed: {e}"),
Some(Err(_)) => format!("the {target_model} driver stopped unexpectedly"),
_ => format!("the {target_model} turn ended without a reply"),
- })
+ };
+ // Saved like a reply, so the failure is still there after a reload (the live error event isn't)
+ let msg = NewMessage {
+ reasoning_content: with_notices(opts.label.clone()),
+ ..scope.message("kwant", &target_kwant.name, format!("⚠️ [{}] Couldn't finish this reply: {why}", target_kwant.name))
+ };
+ scope.save(&msg, super::activity::with_activity(Some(json!({"kind": "turn_failed"})), activity)).await;
+ if let Some(e) = driver_error {
+ event_broadcast.send(e);
+ }
+ Err(why)
}
}
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index aa912e83..f9fc6ecc 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -492,7 +492,9 @@ async fn execute(state: &AppState, routine: &RoutineRow) -> Result<Option<String
if let Some(t) = &routine.thread_id {
let _ = state.db.touch_thread(t).await;
}
- let prompt = routine.instructions.clone() + &follow_up_context(state, routine, &kwant, &saved.id).await;
+ let prompt = routine.instructions.clone()
+ + &follow_up_context(state, routine, &kwant, &saved.id).await
+ + &last_run_context(state, routine, &kwant).await;
super::routes::run_routine_turn(state, &kwant, routine.channel_id.clone(), routine.thread_id.clone(), prompt).await
}
@@ -507,6 +509,33 @@ const FOLLOW_UP_CHARS_EACH: usize = 600;
/// What a turn already sees of its chat (see `run_kwant_turn`'s history).
const TURN_HISTORY_MESSAGES: i64 = 20;
+/// Most of a routine's last output its next run quotes.
+const LAST_RUN_CHARS: usize = 1500;
+
+/// For a routine that ran before, its last successful output, so a run builds on it instead of
+/// repeating it. When that reply is still in the history the turn sees, only points at it.
+pub async fn last_run_context(state: &AppState, routine: &RoutineRow, kwant: &crate::db::models::Kwant) -> String {
+ let runs = state.db.list_routine_runs(&routine.id, 10).await.unwrap_or_default();
+ let Some((run, id)) = runs.iter().find_map(|r| Some((r, r.message_id.as_deref().filter(|_| r.status == "ok")?))) else {
+ return String::new();
+ };
+ let Ok(Some(reply)) = state.db.get_message(id).await else {
+ return String::new();
+ };
+ let when = run.started_at.format("%Y-%m-%d %H:%M UTC");
+ let chat = delivery_chat(routine.thread_id.as_deref(), routine.channel_id.as_deref(), &kwant.id);
+ let recent = state.db.list_messages(chat, TURN_HISTORY_MESSAGES).await.unwrap_or_default();
+ if recent.iter().any(|m| m.id == reply.id) {
+ return format!(
+ "\n\n[This routine last ran {when}; its reply is above in this chat. Build on it and don't repeat it word for word.]"
+ );
+ }
+ format!(
+ "\n\n[This routine last ran {when}. Its reply then, for continuity (build on it, don't repeat it word for word):\n{}]",
+ super::routes::truncate_chars(reply.text.trim(), LAST_RUN_CHARS)
+ )
+}
+
/// For a follow-up routine, the exchange it follows up on (from the same chat only), when it has
/// scrolled out of the history the turn sees anyway. Empty otherwise.
pub async fn follow_up_context(state: &AppState, routine: &RoutineRow, kwant: &crate::db::models::Kwant, run_message_id: &str) -> String {
diff --git a/tests/routine_failure_test.rs b/tests/routine_failure_test.rs
index 7385cd76..ad7aff69 100644
--- a/tests/routine_failure_test.rs
+++ b/tests/routine_failure_test.rs
@@ -135,6 +135,14 @@ async fn failed_routine_run_records_the_engine_error() {
std::fs::write(&crash, "").unwrap();
let error = run_once(&app, &id).await;
assert!(error.contains("exited with status 3 and no output"), "{error}");
+
+ // The failure is saved in the chat, so it still shows after a reload (the live error event doesn't)
+ let saved = state.db.list_messages(&kid, 50).await.unwrap();
+ let failed = saved.iter().find(|m| m.text.contains("Couldn't finish this reply")).expect("a saved failure");
+ assert_eq!(failed.sender_role, "kwant");
+ assert!(failed.text.contains("exited with status 3 and no output"), "{}", failed.text);
+ let meta: Value = serde_json::from_str(failed.meta.as_deref().unwrap()).unwrap();
+ assert_eq!(meta["kind"], "turn_failed");
}
/// Runs the routine now and returns the run's error, which it must have.
diff --git a/tests/unattended_test.rs b/tests/unattended_test.rs
index a21e80f7..98e01b6b 100644
--- a/tests/unattended_test.rs
+++ b/tests/unattended_test.rs
@@ -83,3 +83,61 @@ fn ask_user_says_state_the_assumption_for_reversible_choices() {
assert!(d.contains("can't be undone or reaches outside"), "outward steps still ask: {d}");
assert_eq!(kwnt::server::questions::tools()[0]["description"], d);
}
+
+/// Runs routine `id` now and waits until that run has finished ok.
+async fn run_now_and_wait(env: &Env, id: &str) {
+ let (_, before) = call(&env.app, "GET", &format!("/api/routines/{id}/runs"), None).await;
+ let seen = before.as_array().map_or(0, Vec::len);
+ let (s, v) = call(&env.app, "POST", &format!("/api/routines/{id}/run"), None).await;
+ assert!(s.is_success(), "{v}");
+ wait_for("the routine run", || async {
+ let (_, runs) = call(&env.app, "GET", &format!("/api/routines/{id}/runs"), None).await;
+ let runs = runs.as_array().cloned().unwrap_or_default();
+ runs.len() > seen && runs[0]["status"] == "ok"
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn a_recurring_routine_sees_its_last_output() {
+ let env = setup().await;
+ let (s, r) = call(
+ &env.app,
+ "POST",
+ "/api/routines",
+ Some(json!({"kwant_id": env.a, "name": "Daily tip", "instructions": "Send a tip of the day TIPRUN REPLYTAG:tip1",
+ "schedule": {"type": "daily", "time": "08:00", "tz": "UTC"}})),
+ )
+ .await;
+ assert_eq!(s.as_u16(), 201, "{r}");
+ let id = r["id"].as_str().unwrap().to_string();
+
+ // The first run has nothing before it
+ run_now_and_wait(&env, &id).await;
+ assert_eq!(invocations_with("TIPRUN").len(), 1);
+ assert!(!invocations_with("TIPRUN")[0].contains("This routine last ran"));
+
+ // The next one, with the last reply still in view, is pointed at it
+ run_now_and_wait(&env, &id).await;
+ let second = invocations_with("its reply is above in this chat");
+ assert_eq!(second.len(), 1, "{second:?}");
+
+ // Once that reply has scrolled out of the history, it is quoted
+ for i in 0..25 {
+ let filler = kwnt::db::models::NewMessage {
+ channel_id: None,
+ direct_kwant_id: Some(env.a.clone()),
+ sender_role: "user".into(),
+ sender_id: "user".into(),
+ text: format!("unrelated chat {i}"),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 1,
+ };
+ env.state.db.insert_message(&filler).await.unwrap();
+ }
+ run_now_and_wait(&env, &id).await;
+ let third = invocations_with("Its reply then, for continuity");
+ assert_eq!(third.len(), 1, "{third:?}");
+ assert!(third[0].contains("answer tip1"), "{}", third[0]);
+}