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
Usage limits and restarts: retry once instead of giving up
Lin (kwant bot)ccd1e3dadbb5
diff --git a/src/db/mod.rs b/src/db/mod.rsindex 88e00381..ed8e738d 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -17,6 +17,7 @@ pub mod bot_actions;pub mod hires;pub mod imports;pub mod approval_modes;+pub mod parked;/// What a space's #general says about itself.pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";@@ -142,6 +143,7 @@ impl Database {db.migrate_zombie().await?;db.migrate_parallel().await?;db.migrate_documents().await?;+ db.migrate_parked().await?;if spaces {let migration = db.migrate_spaces(data_dir, fresh).await?;db.require_spaces_schema(&migration).await?;diff --git a/src/db/parked.rs b/src/db/parked.rsnew file mode 100644index 00000000..f7e5b9cc--- /dev/null+++ b/src/db/parked.rs@@ -0,0 +1,163 @@+//! Turns a usage limit stopped before the bot did anything: parked until the limit resets+//! (`retry_at`), then run once more. A parked turn never parks again.++use super::{Database, DbError};+use chrono::{DateTime, Utc};+use serde::Serialize;+use sqlx::FromRow;+use uuid::Uuid;++#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct ParkedTurn {+ pub id: String,+ pub kwant_id: String,+ pub channel_id: Option<String>,+ pub direct_kwant_id: Option<String>,+ pub thread_id: Option<String>,+ /// Set when the turn was a delegated task; then the delegation runs again instead.+ pub delegation_id: Option<String>,+ pub depth: i64,+ pub prompt: String,+ pub retry_at: DateTime<Utc>,+ /// "pending", "running", "done" or "dropped" (the chat moved on before the retry).+ pub status: String,+ pub created_at: DateTime<Utc>,+}++pub struct NewParkedTurn {+ pub kwant_id: String,+ pub channel_id: Option<String>,+ pub direct_kwant_id: Option<String>,+ pub thread_id: Option<String>,+ pub delegation_id: Option<String>,+ pub depth: i64,+ pub prompt: String,+ pub retry_at: DateTime<Utc>,+}++/// The chat a turn ran in, matched the way it was parked.+const SAME_CHAT: &str = "kwant_id = ? AND COALESCE(channel_id, '') = ? AND COALESCE(direct_kwant_id, '') = ? \+ AND COALESCE(thread_id, '') = ?";++impl Database {+ pub(super) async fn migrate_parked(&self) -> Result<(), DbError> {+ for stmt in [+ "CREATE TABLE IF NOT EXISTS parked_turns (+ id TEXT PRIMARY KEY,+ kwant_id TEXT NOT NULL,+ channel_id TEXT,+ direct_kwant_id TEXT,+ thread_id TEXT,+ delegation_id TEXT,+ depth INTEGER NOT NULL DEFAULT 0,+ prompt TEXT NOT NULL,+ retry_at TIMESTAMP NOT NULL,+ status TEXT NOT NULL DEFAULT 'pending',+ created_at TIMESTAMP NOT NULL+ )",+ "CREATE INDEX IF NOT EXISTS parked_turns_due ON parked_turns (status, retry_at)",+ // A delegation restarted after a kwnt restart is restarted only once+ "ALTER TABLE delegations ADD COLUMN retries INTEGER NOT NULL DEFAULT 0",+ ] {+ let _ = sqlx::query(stmt).execute(&self.pool).await;+ }+ Ok(())+ }++ /// Parks a turn; `None` when one is already waiting for that bot in that chat (it keeps its+ /// time, so a chat gets at most one retry however many messages hit the limit).+ pub async fn park_turn(&self, t: &NewParkedTurn) -> Result<Option<ParkedTurn>, DbError> {+ let mut tx = self.pool.begin().await?;+ let waiting: Option<(String,)> = sqlx::query_as(&format!("SELECT id FROM parked_turns WHERE status = 'pending' AND {SAME_CHAT}"))+ .bind(&t.kwant_id)+ .bind(t.channel_id.as_deref().unwrap_or(""))+ .bind(t.direct_kwant_id.as_deref().unwrap_or(""))+ .bind(t.thread_id.as_deref().unwrap_or(""))+ .fetch_optional(&mut *tx)+ .await?;+ if waiting.is_some() {+ return Ok(None);+ }+ let row = sqlx::query_as::<_, ParkedTurn>(+ "INSERT INTO parked_turns (id, kwant_id, channel_id, direct_kwant_id, thread_id, delegation_id, depth, prompt, retry_at, status, created_at) \+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?) RETURNING *",+ )+ .bind(Uuid::new_v4().to_string())+ .bind(&t.kwant_id)+ .bind(&t.channel_id)+ .bind(&t.direct_kwant_id)+ .bind(&t.thread_id)+ .bind(&t.delegation_id)+ .bind(t.depth)+ .bind(&t.prompt)+ .bind(t.retry_at)+ .bind(Utc::now())+ .fetch_one(&mut *tx)+ .await?;+ tx.commit().await?;+ Ok(Some(row))+ }++ /// The parked turns due by `now`, each claimed (`running`) so it runs once.+ pub async fn take_due_parked(&self, now: DateTime<Utc>) -> Result<Vec<ParkedTurn>, DbError> {+ let due = sqlx::query_as::<_, ParkedTurn>("SELECT * FROM parked_turns WHERE status = 'pending' AND retry_at <= ? ORDER BY retry_at")+ .bind(now)+ .fetch_all(&self.pool)+ .await?;+ let mut claimed = Vec::new();+ for p in due {+ let res = sqlx::query("UPDATE parked_turns SET status = 'running' WHERE id = ? AND status = 'pending'")+ .bind(&p.id)+ .execute(&self.pool)+ .await?;+ if res.rows_affected() > 0 {+ claimed.push(ParkedTurn { status: "running".into(), ..p });+ }+ }+ Ok(claimed)+ }++ pub async fn next_parked_due(&self) -> Result<Option<DateTime<Utc>>, DbError> {+ let row: Option<(DateTime<Utc>,)> =+ sqlx::query_as("SELECT retry_at FROM parked_turns WHERE status = 'pending' ORDER BY retry_at LIMIT 1")+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.map(|(at,)| at))+ }++ pub async fn set_parked_status(&self, id: &str, status: &str) -> Result<(), DbError> {+ sqlx::query("UPDATE parked_turns SET status = ? WHERE id = ?").bind(status).bind(id).execute(&self.pool).await?;+ Ok(())+ }++ /// A later turn in the same chat got through: the parked one would repeat it, so it's dropped.+ pub async fn drop_parked_for_chat(+ &self,+ kwant_id: &str,+ channel_id: Option<&str>,+ direct_kwant_id: Option<&str>,+ thread_id: Option<&str>,+ ) -> Result<u64, DbError> {+ let res = sqlx::query(&format!(+ "UPDATE parked_turns SET status = 'dropped' WHERE status = 'pending' AND delegation_id IS NULL AND {SAME_CHAT}"+ ))+ .bind(kwant_id)+ .bind(channel_id.unwrap_or(""))+ .bind(direct_kwant_id.unwrap_or(""))+ .bind(thread_id.unwrap_or(""))+ .execute(&self.pool)+ .await?;+ Ok(res.rows_affected())+ }++ pub async fn parked_for_delegation(&self, delegation_id: &str) -> Result<Option<ParkedTurn>, DbError> {+ Ok(sqlx::query_as::<_, ParkedTurn>("SELECT * FROM parked_turns WHERE delegation_id = ? AND status = 'pending' LIMIT 1")+ .bind(delegation_id)+ .fetch_optional(&self.pool)+ .await?)+ }++ pub async fn list_parked(&self) -> Result<Vec<ParkedTurn>, DbError> {+ Ok(sqlx::query_as::<_, ParkedTurn>("SELECT * FROM parked_turns ORDER BY created_at").fetch_all(&self.pool).await?)+ }+}diff --git a/src/db/threads.rs b/src/db/threads.rsindex fcbba3e6..e844fe1c 100644--- a/src/db/threads.rs+++ b/src/db/threads.rs@@ -52,6 +52,9 @@ pub struct Delegation {pub created_at: DateTime<Utc>,pub started_at: Option<DateTime<Utc>>,pub ended_at: Option<DateTime<Utc>>,+ /// Times a kwnt restart sent it back to the queue (at most once).+ #[sqlx(default)]+ pub retries: i64,}impl Delegation {@@ -280,6 +283,7 @@ impl Database {created_at: now,started_at: None,ended_at: None,+ retries: 0,};sqlx::query("INSERT INTO delegations (id, thread_id, lead_kwant_id, specialist_kwant_id, origin_channel_id, origin_kwant_id, \@@ -404,19 +408,36 @@ impl Database {Ok(due)}- /// Delegations left open by a kwnt that stopped; they become `interrupted`.- pub async fn interrupt_open_delegations(&self) -> Result<Vec<Delegation>, DbError> {- let open = sqlx::query_as::<_, Delegation>("SELECT * FROM delegations WHERE status IN ('queued', 'running')")- .fetch_all(&self.pool)- .await?;- sqlx::query(- "UPDATE delegations SET status = 'interrupted', error = 'kwnt stopped before the task finished', ended_at = ? \- WHERE status IN ('queued', 'running')",+ /// Delegations left open by a kwnt that stopped. Each is restarted once: the first time it's+ /// queued again (returned in `.0`); one cut short a second time becomes `interrupted` (`.1`).+ /// One waiting out a usage limit (a parked turn) is left alone: its retry restarts it.+ pub async fn restart_open_delegations(&self) -> Result<(Vec<Delegation>, Vec<Delegation>), DbError> {+ let open = sqlx::query_as::<_, Delegation>(+ "SELECT * FROM delegations WHERE status IN ('queued', 'running') AND id NOT IN \+ (SELECT delegation_id FROM parked_turns WHERE status = 'pending' AND delegation_id IS NOT NULL)",)- .bind(Utc::now())- .execute(&self.pool)+ .fetch_all(&self.pool).await?;- Ok(open)+ let (mut again, mut cut) = (Vec::new(), Vec::new());+ for d in open {+ if d.retries < 1 {+ sqlx::query("UPDATE delegations SET status = 'queued', retries = retries + 1, started_at = NULL WHERE id = ?")+ .bind(&d.id)+ .execute(&self.pool)+ .await?;+ again.push(d);+ } else {+ sqlx::query(+ "UPDATE delegations SET status = 'interrupted', error = 'kwnt stopped before the task finished', ended_at = ? WHERE id = ?",+ )+ .bind(Utc::now())+ .bind(&d.id)+ .execute(&self.pool)+ .await?;+ cut.push(d);+ }+ }+ Ok((again, cut))}}diff --git a/src/server/delegation.rs b/src/server/delegation.rsindex df45d6bb..ee963b77 100644--- a/src/server/delegation.rs+++ b/src/server/delegation.rs@@ -260,12 +260,13 @@ pub async fn start(state: &AppState, req: StartRequest) -> Result<Delegation, (Slet job = state.turns.start_job([d.id.clone(), thread.id.clone()]);let runner_state = state.clone();let (lead, specialist, delegation) = (req.lead, req.specialist, d.clone());- tokio::spawn(async move { run(runner_state, job, delegation, lead, specialist).await });+ tokio::spawn(async move { run(runner_state, job, delegation, lead, specialist, false).await });Ok(d)}/// The background part: the specialist's turn in the thread, then the report in the origin chat.-async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead: Kwant, specialist: Kwant) {+/// `retried`: the run after a usage limit reset, which never waits for one again.+async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead: Kwant, specialist: Kwant, retried: bool) {let scope = match scope_for(&state, &specialist, None, Some(d.thread_id.clone()), &job, d.depth).await {Ok(s) => s,Err(why) => return finish(&state, &d, &specialist, Err(why)).await,@@ -288,12 +289,35 @@ async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead:);let mut opts = TurnOpts::default();opts.on_started = Some(on_started);+ opts.retried = retried;+ opts.delegation_id = Some(d.id.clone());let outcome = try_kwant_turn(&scope, &specialist, prompt, opts).await;let outcome = match outcome {Err(_) if job.token.is_cancelled() => Err("stopped".to_string()),other => other,};drop(job);+ // A usage limit stopped it before anything happened: it stays open and runs again when the+ // limit resets+ if outcome.is_err() {+ if let Ok(Some(p)) = state.db.parked_for_delegation(&d.id).await {+ post_to_origin(+ &state,+ &d,+ "system",+ "kwnt",+ format!(+ "{} hit a usage limit on “{}”. {}",+ specialist.name,+ d.title,+ super::parked::retry_line(p.retry_at, Utc::now())+ ),+ meta("delegation_started", &d, &specialist.name),+ )+ .await;+ return;+ }+ }finish(&state, &d, &specialist, outcome).await;}@@ -522,12 +546,13 @@ pub async fn follow_ups(state: &AppState, now: chrono::DateTime<Utc>) -> usize {due.len()}-/// Delegations a restart cut short become `interrupted`, with a note where they came from.+/// Delegations a restart cut short are restarted once, with a note where they came from; one+/// cut short again becomes `interrupted`.pub async fn interrupt_open(state: &AppState) {- let Ok(open) = state.db.interrupt_open_delegations().await else {+ let Ok((again, cut)) = state.db.restart_open_delegations().await else {return;};- for d in open {+ for d in cut {let specialist = name_of(state, &d.specialist_kwant_id).await;let Ok(Some(done)) = state.db.get_delegation(&d.id).await else {continue;@@ -537,11 +562,62 @@ pub async fn interrupt_open(state: &AppState) {&done,"system","kwnt",- format!("kwnt restarted before {specialist} finished “{}”. Ask again to restart it.", done.title),+ format!("kwnt restarted again before {specialist} finished “{}”, after one retry. Ask again to restart it.", done.title),meta("delegation_result", &done, &specialist),).await;}+ for d in again {+ let Ok(Some(d)) = state.db.get_delegation(&d.id).await else {+ continue;+ };+ let specialist = name_of(state, &d.specialist_kwant_id).await;+ post_to_origin(+ state,+ &d,+ "system",+ "kwnt",+ format!("kwnt restarted before {specialist} finished “{}”: retrying it once now.", d.title),+ meta("delegation_started", &d, &specialist),+ )+ .await;+ restart(state, d, false).await;+ }+}++/// The retry of a delegation a usage limit stopped (see [`super::parked`]).+pub async fn retry_parked(state: &AppState, delegation_id: &str) -> bool {+ let Ok(Some(d)) = state.db.get_delegation(delegation_id).await else {+ return false;+ };+ if !d.is_open() {+ return false;+ }+ let specialist = name_of(state, &d.specialist_kwant_id).await;+ post_to_origin(+ state,+ &d,+ "system",+ "kwnt",+ format!("The usage limit has reset: {specialist} is retrying “{}” once.", d.title),+ meta("delegation_started", &d, &specialist),+ )+ .await;+ restart(state, d, true).await+}++/// Runs an open delegation's task again in its thread.+async fn restart(state: &AppState, d: Delegation, retried: bool) -> bool {+ let (Ok(Some(lead)), Ok(Some(specialist))) =+ (state.db.get_kwant(&d.lead_kwant_id).await, state.db.get_kwant(&d.specialist_kwant_id).await)+ else {+ let _ = state.db.finish_delegation(&d.id, "failed", Some("the bot no longer exists"), None).await;+ return false;+ };+ let job = state.turns.start_job([d.id.clone(), d.thread_id.clone()]);+ tracing::info!(delegation = %d.id, retried, "delegation restarted");+ tokio::spawn(run(state.clone(), job, d, lead, specialist, retried));+ true}// Routesdiff --git a/src/server/mod.rs b/src/server/mod.rsindex bb773acd..33f8474b 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -14,6 +14,7 @@ pub mod continuity;pub mod scheduler;pub mod turns;pub mod delegation;+pub mod parked;pub mod attachments;pub mod questions;pub mod skills;diff --git a/src/server/parked.rs b/src/server/parked.rsnew file mode 100644index 00000000..a195a96d--- /dev/null+++ b/src/server/parked.rs@@ -0,0 +1,105 @@+//! Turns a usage limit stopped before the bot did anything visible are parked until the limit+//! resets, then run once more (the retry never parks again). The scheduler runs due ones; they're+//! kept in the database, so a restart in between doesn't lose them.++use super::routes::{scope_for, try_kwant_turn, TurnOpts, TurnScope};+use super::AppState;+use crate::db::models::Kwant;+use crate::db::parked::{NewParkedTurn, ParkedTurn};+use chrono::{DateTime, Utc};++/// The line added to the give-up notice when the turn was parked.+pub fn retry_line(at: DateTime<Utc>, now: DateTime<Utc>) -> String {+ let mins = (at - now).num_minutes().max(1);+ let wait = if mins >= 90 { format!("about {} h", (mins + 30) / 60) } else { format!("about {mins} min") };+ format!("⏳ kwnt will retry this once at {} UTC (in {wait}), when the limit resets.", at.format("%H:%M"))+}++/// Parks the turn that just hit a usage limit, if it can be retried: not already a retry or a+/// discussion round (`no_park`), and in a chat the retry can find again. Returns the line for+/// the notice.+pub(super) async fn park(+ scope: &TurnScope,+ kwant: &Kwant,+ prompt: &str,+ no_park: bool,+ delegation_id: Option<String>,+ retry_at: Option<DateTime<Utc>>,+) -> Option<String> {+ if no_park {+ return None;+ }+ let at = retry_at?;+ // A direct chat with another bot (a hand-off) isn't a chat this bot's retry can open+ if scope.kwant_id.as_deref().is_some_and(|k| k != kwant.id) {+ return None;+ }+ let row = scope+ .state+ .db+ .park_turn(&NewParkedTurn {+ kwant_id: kwant.id.clone(),+ channel_id: scope.channel_id.clone(),+ direct_kwant_id: scope.kwant_id.clone(),+ thread_id: scope.thread_id.clone(),+ delegation_id,+ depth: scope.delegation_depth,+ prompt: prompt.to_string(),+ retry_at: at,+ })+ .await+ .ok()?;+ let Some(row) = row else {+ return Some("⏳ A retry for this chat is already set for when the limit resets.".into());+ };+ tracing::info!(kwant = %kwant.id, parked = %row.id, retry_at = %at, "turn parked until the usage limit resets");+ scope.state.scheduler_wake.notify_one();+ Some(retry_line(at, Utc::now()))+}++/// The prompt a retried turn gets: the original request, marked as a retry.+pub fn retry_prompt(original: &str) -> String {+ format!(+ "[kwnt is retrying your last turn: a usage limit stopped it before you could reply, and the limit has reset]\n\n{original}"+ )+}++/// Runs the parked turns due by `now`, each once. Returns how many it started.+pub async fn run_due(state: &AppState, now: DateTime<Utc>) -> usize {+ let Ok(due) = state.db.take_due_parked(now).await else {+ return 0;+ };+ let mut started = 0;+ for p in due {+ if retry(state, &p).await {+ started += 1;+ }+ let _ = state.db.set_parked_status(&p.id, "done").await;+ }+ started+}++async fn retry(state: &AppState, p: &ParkedTurn) -> bool {+ if let Some(d) = &p.delegation_id {+ return super::delegation::retry_parked(state, d).await;+ }+ let Ok(Some(kwant)) = state.db.get_kwant(&p.kwant_id).await else {+ return false;+ };+ let context = p.channel_id.clone().or_else(|| p.thread_id.clone()).unwrap_or_else(|| kwant.id.clone());+ let job = state.turns.start_job([context, p.id.clone()]);+ let Ok(scope) = scope_for(state, &kwant, p.channel_id.clone(), p.thread_id.clone(), &job, p.depth).await else {+ return false;+ };+ let note = scope.message("system", "kwnt", format!("The usage limit has reset: retrying {}'s turn once.", kwant.name));+ scope.save(¬e, None).await;+ let prompt = retry_prompt(&p.prompt);+ tracing::info!(kwant = %kwant.id, parked = %p.id, "retrying a parked turn");+ tokio::spawn(async move {+ let _job = job;+ let mut opts = TurnOpts::default();+ opts.retried = true;+ let _ = try_kwant_turn(&scope, &kwant, prompt, opts).await;+ });+ true+}diff --git a/src/server/routes.rs b/src/server/routes.rsindex de035a2c..2582a22e 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -650,7 +650,7 @@ impl TurnScope {.unwrap_or_else(|| speaker.id.clone())}- fn message(&self, sender_role: &str, sender_id: &str, text: String) -> NewMessage {+ pub(super) fn message(&self, sender_role: &str, sender_id: &str, text: String) -> NewMessage {NewMessage {channel_id: self.channel_id.clone(),direct_kwant_id: self.kwant_id.clone(),@@ -1140,6 +1140,7 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, usediscussion: Some(opening.then(|| discussion::question_label(&kwant.name, &team.name))),routing: None,on_started: None,+ ..Default::default()};let Some(raw) = run_kwant_turn(scope, &kwant, prompt, opts).await else {if scope.cancel_token.is_cancelled() {@@ -1193,6 +1194,7 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, usediscussion: None,routing: None,on_started: None,+ ..Default::default()};run_kwant_turn(scope, &lead, prompt, opts).await;}@@ -1204,17 +1206,21 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, use#[derive(Default)]pub(super) struct TurnOpts {/// Saved as the message's `reasoning_content` instead of the driver's reasoning.- label: Option<String>,+ pub(super) label: Option<String>,/// Text checked for a URL to open in the bot browser; defaults to the prompt.nav_prompt: Option<String>,/// Discussion reply handling: `[PASS]` replies aren't saved; `Some(label)` lets an `[ASK_USER]`/// reply be saved as a question for the user under that label.- discussion: Option<Option<String>>,+ pub(super) discussion: Option<Option<String>>,/// How this reply's agent was picked, saved as the reply's `meta.routing`.routing: Option<serde_json::Value>,/// Awaited once the turn has its slot and is running, before the driver starts; a turn/// that is stopped while queued never calls it.pub(super) on_started: Option<futures::future::BoxFuture<'static, ()>>,+ /// The retry of a turn a usage limit stopped (see [`super::parked`]): it never parks again.+ pub(super) retried: bool,+ /// The delegation this turn works on; a parked retry restarts the delegation.+ pub(super) delegation_id: Option<String>,}/// Runs one kwant turn: picks model/effort, syncs the bot browser, streams the reply and saves it.@@ -1389,6 +1395,7 @@ async fn run_kwant_turn_inner() -> Result<String, String> {let state = &scope.state;let event_broadcast = TurnEvents { sender: state.event_sender.clone(), tag: tag.clone() };+ let park_prompt = prompt.clone();let db = state.db.clone();let router = state.router.clone();let channel_id = scope.channel_id.clone();@@ -1809,6 +1816,12 @@ async fn run_kwant_turn_inner(failure.detail),};+ let mut text = text;+ if failure.class == crate::profiles::classify::FailClass::Quota && !side_effects {+ if let Some(line) = super::parked::park(scope, target_kwant, &park_prompt, opts.retried || opts.discussion.is_some(), opts.delegation_id.clone(), failure.retry_at).await {+ text = format!("{text}\n\n{line}");+ }+ }event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));event_broadcast.send(RuntimeEvent::TurnComplete {tokens: 0,@@ -1877,6 +1890,10 @@ async fn run_kwant_turn_inner(scope.save(&msg, None).await;return Err(text);} else if let Some(Ok(Ok(output))) = driver_result {+ // This chat got through: a turn parked behind a usage limit would only repeat it+ let _ = db+ .drop_parked_for_chat(&target_kwant.id, scope.channel_id.as_deref(), scope.kwant_id.as_deref(), scope.thread_id.as_deref())+ .await;// Post-turn sync: If bot response outputs a URL, sync navigation so the user sees it in Sandbox VMif let Some(bot_url) = extract_url_from_text(&output.text) {if let Some(ctrl) = get_or_create_browser_controller(state, &sandbox_target).await {diff --git a/src/server/scheduler.rs b/src/server/scheduler.rsindex ccb4ba12..aa912e83 100644--- a/src/server/scheduler.rs+++ b/src/server/scheduler.rs@@ -619,7 +619,13 @@ pub fn spawn(state: AppState, shutdown: CancellationToken) -> tokio::task::JoinHloop {tick(&state, Utc::now()).await;super::delegation::follow_ups(&state, Utc::now()).await;- let sleep = match state.db.next_routine_due().await.ok().flatten() {+ super::parked::run_due(&state, Utc::now()).await;+ let next_parked = state.db.next_parked_due().await.ok().flatten();+ let next = match (state.db.next_routine_due().await.ok().flatten(), next_parked) {+ (Some(a), Some(b)) => Some(a.min(b)),+ (a, b) => a.or(b),+ };+ let sleep = match next {Some(at) => (at - Utc::now()).to_std().unwrap_or(Duration::ZERO)diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 0fa4b1bf..f9ad621c 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -5,6 +5,7 @@//! - `CALLTOOL:<tool>:<base64 json args>` in the prompt: call that tool and reply with its text//! (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).+//! - `QUOTAONCE:<tag>` / `QUOTAALWAYS`: fail with Claude's usage-limit error, once / every time.//!//! Each test file that uses it is its own binary, because it changes PATH.#![allow(dead_code)]@@ -33,6 +34,16 @@ prompt = args[-1] if args else ""out_dir = os.environ["KWNT_TEST_PROMPTS"]with open(os.path.join(out_dir, "%d-%d" % (os.getpid(), time.time_ns())), "w") as f:f.write("\n".join(args))+# QUOTAONCE:<tag>: the first call answers with Claude's usage-limit error (resets in 2 s);+# QUOTAALWAYS: every call does+q = re.findall(r"QUOTAONCE:([A-Za-z0-9_]+)", prompt)+flag = q and os.path.join(os.path.dirname(out_dir), "quota-" + q[-1])+if "QUOTAALWAYS" in prompt or (flag and not os.path.exists(flag)):+ if flag:+ open(flag, "w").close()+ print(json.dumps({"type": "result", "is_error": True, "num_turns": 1,+ "result": "Claude AI usage limit reached|%d" % (int(time.time()) + 2)}))+ sys.exit(1)reply = []m = ([None] + list(re.finditer(r"CALLTOOL:([a-z_]+):([A-Za-z0-9+/=]+)", prompt)))[-1]done = Nonediff --git a/tests/delegation_test.rs b/tests/delegation_test.rsindex fd33b041..65313ae7 100644--- a/tests/delegation_test.rs+++ b/tests/delegation_test.rs@@ -628,29 +628,36 @@ async fn follow_ups_and_restarts_report_in_the_origin_chat() {}).await;- // A delegation left open by a stopped kwnt becomes interrupted, with a note- let (_, open) = env- .state- .db- .create_delegation(&kwnt::db::threads::NewDelegation {- lead_kwant_id: env.lead.clone(),- specialist_kwant_id: env.specialist.clone(),- origin_channel_id: None,- origin_kwant_id: Some(env.lead.clone()),- origin_thread_id: None,- team_id: None,- task: "t".into(),- title: "Cut short".into(),- continue_lead: true,- depth: 1,- follow_up_at: None,- })- .await- .unwrap();+ // A delegation left open by a stopped kwnt is restarted once, with a note+ let left_open = |title: &str| kwnt::db::threads::NewDelegation {+ lead_kwant_id: env.lead.clone(),+ specialist_kwant_id: env.specialist.clone(),+ origin_channel_id: None,+ origin_kwant_id: Some(env.lead.clone()),+ origin_thread_id: None,+ team_id: None,+ task: "t REPLYTAG:restarted".into(),+ title: title.into(),+ continue_lead: false,+ depth: 1,+ follow_up_at: None,+ };+ let (_, open) = env.state.db.create_delegation(&left_open("Cut short")).await.unwrap();delegation::interrupt_open(&env.state).await;- assert_eq!(delegation_status(&env, &open.id).await, "interrupted");+ wait_for("the restarted delegation to complete", || async { delegation_status(&env, &open.id).await == "completed" }).await;let lead_chat = env.state.db.list_messages(&env.lead, 30).await.unwrap();- assert!(lead_chat.iter().any(|m| m.text.contains("Cut short") && m.text.contains("restarted")));+ assert!(lead_chat.iter().any(|m| m.text.contains("Cut short") && m.text.contains("retrying it once now")));+ assert!(lead_chat.iter().any(|m| m.text.contains("answer restarted")));++ // Only once: one cut short a second time becomes interrupted+ let (_, twice) = env.state.db.create_delegation(&left_open("Cut twice")).await.unwrap();+ let (again, cut) = env.state.db.restart_open_delegations().await.unwrap();+ assert_eq!((again.len(), cut.len()), (1, 0));+ assert_eq!(delegation_status(&env, &twice.id).await, "queued");+ delegation::interrupt_open(&env.state).await;+ assert_eq!(delegation_status(&env, &twice.id).await, "interrupted");+ let lead_chat = env.state.db.list_messages(&env.lead, 40).await.unwrap();+ assert!(lead_chat.iter().any(|m| m.text.contains("Cut twice") && m.text.contains("after one retry")));}/// The new columns and tables are additive: rows written the old way still load, and init twicediff --git a/tests/quota_retry_test.rs b/tests/quota_retry_test.rsnew file mode 100644index 00000000..4fdcd9be--- /dev/null+++ b/tests/quota_retry_test.rs@@ -0,0 +1,136 @@+//! A turn a usage limit stopped before the bot did anything is parked until the limit resets and+//! retried once; a retry never parks again, and a later turn that got through drops it.++mod common;++use common::*;+use kwnt::server::parked;+use serde_json::json;+use std::time::Duration;++fn later() -> chrono::DateTime<chrono::Utc> {+ chrono::Utc::now() + chrono::Duration::seconds(30)+}++/// Waits until the parked turns' reset time has passed (the profile skips turns until then).+async fn past_reset(env: &Env) {+ let at = parked_rows(env).await.iter().map(|p| p.retry_at).max().unwrap();+ let wait = (at - chrono::Utc::now()).to_std().unwrap_or_default() + Duration::from_millis(1200);+ tokio::time::sleep(wait).await;+}++async fn parked_rows(env: &Env) -> Vec<kwnt::db::parked::ParkedTurn> {+ env.state.db.list_parked().await.unwrap()+}++#[tokio::test]+async fn a_limited_turn_is_retried_once_when_the_limit_resets() {+ let env = setup().await;+ send_direct(&env, &env.a, "do it QUOTAONCE:q1 REPLYTAG:q1done", json!({})).await;+ let notice = wait_reply(&env, &env.a, "will retry this once").await;+ assert!(notice.text.contains("UTC"), "{}", notice.text);+ let rows = parked_rows(&env).await;+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].status, "pending");+ assert!(rows[0].retry_at > chrono::Utc::now() - chrono::Duration::seconds(5));+ assert!(rows[0].retry_at <= chrono::Utc::now() + chrono::Duration::seconds(5), "the provider's reset time");++ // Not due yet: nothing runs+ assert_eq!(parked::run_due(&env.state, rows[0].retry_at - chrono::Duration::seconds(1)).await, 0);+ past_reset(&env).await;+ assert_eq!(parked::run_due(&env.state, later()).await, 1);+ let reply = wait_reply(&env, &env.a, "answer q1done").await;+ assert!(!reply.text.contains("usage limit"));+ let all = messages(&env, &env.a).await;+ assert!(all.iter().any(|m| m.sender_role == "system" && m.text.contains("retrying")), "a visible retry line");+ let prompts = invocations_with("REPLYTAG:q1done");+ assert_eq!(prompts.len(), 2, "the first try and one retry");+ assert!(prompts.iter().any(|p| p.contains("[kwnt is retrying your last turn")));++ // Once+ assert_eq!(parked_rows(&env).await[0].status, "done");+ assert_eq!(parked::run_due(&env.state, later()).await, 0);+}++#[tokio::test]+async fn a_retry_that_hits_the_limit_again_is_not_parked_again() {+ let env = setup().await;+ send_direct(&env, &env.a, "do it QUOTAALWAYS REPLYTAG:never", json!({})).await;+ wait_reply(&env, &env.a, "will retry this once").await;+ past_reset(&env).await;+ assert_eq!(parked::run_due(&env.state, later()).await, 1);+ wait_for("the retry to fail", || async {+ messages(&env, &env.a).await.iter().filter(|m| m.sender_role == "kwant" && m.text.contains("out of usage")).count() == 2+ })+ .await;+ tokio::time::sleep(Duration::from_millis(300)).await;+ let rows = parked_rows(&env).await;+ assert_eq!(rows.len(), 1, "no second park");+ let last = messages(&env, &env.a).await.into_iter().rfind(|m| m.sender_role == "kwant").unwrap();+ assert!(!last.text.contains("will retry"), "{}", last.text);+}++#[tokio::test]+async fn a_later_turn_that_got_through_drops_the_parked_one() {+ let env = setup().await;+ send_direct(&env, &env.b, "first QUOTAONCE:q3 REPLYTAG:q3a", json!({})).await;+ wait_reply(&env, &env.b, "will retry this once").await;+ past_reset(&env).await;+ // A second limited message in the same chat doesn't add a second retry+ send_direct(&env, &env.b, "second QUOTAONCE:q3c", json!({})).await;+ wait_reply(&env, &env.b, "already set").await;+ tokio::time::sleep(Duration::from_secs(4)).await;+ assert_eq!(parked_rows(&env).await.len(), 1);++ send_direct(&env, &env.b, "third REPLYTAG:q3b", json!({})).await;+ wait_reply(&env, &env.b, "answer q3b").await;+ assert_eq!(parked_rows(&env).await[0].status, "dropped");+ assert_eq!(parked::run_due(&env.state, later()).await, 0);+}++#[test]+fn the_retry_line_says_when() {+ let now = chrono::Utc::now();+ let line = parked::retry_line(now + chrono::Duration::minutes(200), now);+ assert!(line.contains("about 3 h"), "{line}");+ assert!(parked::retry_line(now + chrono::Duration::minutes(20), now).contains("about 20 min"));+}++#[tokio::test]+async fn a_limited_delegation_stays_open_and_its_retry_finishes_it() {+ let env = setup().await;+ let (s, d) = call(+ &env.app,+ "POST",+ "/api/delegations",+ Some(json!({+ "lead_kwant_id": env.a, "specialist_kwant_id": env.b, "kwant_id": env.a,+ "task": "research QUOTAONCE:qd REPLYTAG:qddone", "title": "Limited task", "continue_lead": false,+ })),+ )+ .await;+ assert_eq!(s.as_u16(), 202, "{d}");+ let id = d["id"].as_str().unwrap().to_string();+ let status = |env: &Env, id: String| {+ let db = env.state.db.clone();+ async move { db.get_delegation(&id).await.unwrap().unwrap().status }+ };+ wait_for("the lead chat to hear about the limit", || async {+ messages(&env, &env.a).await.iter().any(|m| m.text.contains("hit a usage limit") && m.text.contains("will retry"))+ })+ .await;+ assert_eq!(status(&env, id.clone()).await, "running", "not failed: it waits for the reset");+ let rows = parked_rows(&env).await;+ assert_eq!(rows[0].delegation_id.as_deref(), Some(id.as_str()));++ // A kwnt restart meanwhile leaves it to the parked retry+ let (again, cut) = env.state.db.restart_open_delegations().await.unwrap();+ assert!(again.is_empty() && cut.is_empty());++ past_reset(&env).await;+ assert_eq!(parked::run_due(&env.state, later()).await, 1);+ wait_for("the retried delegation to complete", || async { status(&env, id.clone()).await == "completed" }).await;+ let lead = messages(&env, &env.a).await;+ assert!(lead.iter().any(|m| m.text.contains("retrying “Limited task” once")));+ assert!(lead.iter().any(|m| m.text.contains("answer qddone")));+}