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.

Delegations: read "queued" until the specialist's turn starts

Lin (kwant bot)e29249ba1be3
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 14936070..5dc4d507 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -270,11 +270,15 @@ async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead:
Ok(s) => s,
Err(why) => return finish(&state, &d, &specialist, Err(why)).await,
};
- if state.db.mark_delegation_running(&d.id).await.unwrap_or(false) {
- if let Ok(Some(running)) = state.db.get_delegation(&d.id).await {
- emit_delegation(&state, &running);
+ // Queued until the specialist's turn gets its slot: a busy specialist runs one turn at a time
+ let (started_state, started_id) = (state.clone(), d.id.clone());
+ let on_started = Box::pin(async move {
+ if started_state.db.mark_delegation_running(&started_id).await.unwrap_or(false) {
+ if let Ok(Some(running)) = started_state.db.get_delegation(&started_id).await {
+ emit_delegation(&started_state, &running);
+ }
}
- }
+ });
let prompt = format!(
"{lead} delegated this task to you. Work on it here; when you finish, your reply is posted back to {lead} \
and the chat it came from, so make it a complete, self-contained answer.\n\nTask: {title}\n\n{task}",
@@ -282,7 +286,9 @@ async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead:
title = d.title,
task = d.task,
);
- let outcome = try_kwant_turn(&scope, &specialist, prompt, TurnOpts::default()).await;
+ let mut opts = TurnOpts::default();
+ opts.on_started = Some(on_started);
+ 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,
diff --git a/src/server/routes.rs b/src/server/routes.rs
index fcaa5b6d..316a3a49 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -946,6 +946,7 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, use
nav_prompt: Some(if opening { user_prompt.to_string() } else { String::new() }),
discussion: Some(opening.then(|| discussion::question_label(&kwant.name, &team.name))),
routing: None,
+ on_started: None,
};
let Some(raw) = run_kwant_turn(scope, &kwant, prompt, opts).await else {
if scope.cancel_token.is_cancelled() {
@@ -998,6 +999,7 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, use
nav_prompt: Some(String::new()),
discussion: None,
routing: None,
+ on_started: None,
};
run_kwant_turn(scope, &lead, prompt, opts).await;
}
@@ -1017,6 +1019,9 @@ pub(super) struct TurnOpts {
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, ()>>,
}
/// Runs one kwant turn: picks model/effort, syncs the bot browser, streams the reply and saves it.
@@ -1076,6 +1081,10 @@ pub(super) async fn try_kwant_turn(
if scope.cancel_token.is_cancelled() {
return Err("stopped by the user".into());
}
+ let mut opts = opts;
+ if let Some(started) = opts.on_started.take() {
+ started.await;
+ }
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;
diff --git a/tests/delegation_test.rs b/tests/delegation_test.rs
index c29ce19b..f0660a15 100644
--- a/tests/delegation_test.rs
+++ b/tests/delegation_test.rs
@@ -310,6 +310,83 @@ async fn excess_turns_queue_instead_of_failing() {
wait_for("the delegation to complete", || async { delegation_status(&env, &id).await == "completed" }).await;
}
+/// A delegation to a busy specialist reads "queued" until its turn gets the slot, not "running"
+/// while it waits; it turns "running" (with `started_at`) when the turn starts.
+#[tokio::test]
+async fn a_delegation_waiting_for_a_busy_specialist_reads_queued() {
+ let env = setup().await;
+ let (s, v) = call(&env.app, "POST", "/api/settings", Some(json!({"max_turns_per_agent": 1}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let release = env.release_file("busy-release");
+ let (s, v) = call(
+ &env.app,
+ "POST",
+ "/api/chat/send",
+ Some(json!({"kwant_id": env.specialist, "prompt": format!("busy LONGTASK:{} REPLYTAG:busy", release.display()), "sender_id": "user"})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let specialist = env.specialist.clone();
+ wait_for("the specialist's direct turn to run", || {
+ let (app, specialist) = (env.app.clone(), specialist.clone());
+ async move {
+ let (_, turns) = call(&app, "GET", "/api/turns", None).await;
+ turns["turns"].as_array().unwrap().iter().any(|t| t["state"] == "running" && t["kwant_id"] == specialist.as_str())
+ }
+ })
+ .await;
+
+ let mut rx = env.state.event_sender.subscribe();
+ let d = delegate(&env, "Waits its turn REPLYTAG:waited").await;
+ let id = d["id"].as_str().unwrap().to_string();
+ assert_eq!(d["status"], "queued");
+ let thread = d["thread_id"].as_str().unwrap().to_string();
+ tokio::time::timeout(Duration::from_secs(10), async {
+ loop {
+ if let Ok(e) = rx.recv().await {
+ let wire = e.to_wire();
+ if wire["type"] == "turn_queued" && wire["data"]["thread_id"] == thread.as_str() {
+ return;
+ }
+ }
+ }
+ })
+ .await
+ .expect("the delegated turn queues behind the direct one");
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ let (_, waiting) = call(&env.app, "GET", &format!("/api/delegations/{id}"), None).await;
+ assert_eq!(waiting["status"], "queued", "still waiting: {waiting}");
+ assert!(waiting["started_at"].is_null(), "{waiting}");
+ // No delegation_updated said "running" while it waited
+ while let Ok(e) = rx.try_recv() {
+ let wire = e.to_wire();
+ if wire["type"] == "delegation_updated" {
+ assert_ne!(wire["data"]["delegation"]["status"], "running", "{wire}");
+ }
+ }
+
+ std::fs::write(&release, "").unwrap();
+ let saw_running = tokio::time::timeout(Duration::from_secs(20), async {
+ loop {
+ if let Ok(e) = rx.recv().await {
+ let wire = e.to_wire();
+ if wire["type"] == "delegation_updated" && wire["data"]["delegation"]["id"] == id.as_str() {
+ let status = wire["data"]["delegation"]["status"].as_str().unwrap_or("").to_string();
+ if status != "queued" {
+ return status;
+ }
+ }
+ }
+ }
+ })
+ .await
+ .expect("a delegation_updated once the turn starts");
+ assert_eq!(saw_running, "running", "running is reported before the result");
+ wait_for("the delegation to complete", || async { delegation_status(&env, &id).await == "completed" }).await;
+ let (_, done) = call(&env.app, "GET", &format!("/api/delegations/{id}"), None).await;
+ assert!(!done["started_at"].is_null(), "{done}");
+}
+
/// Stopping a thread stops only that thread: the specialist's direct chat keeps running.
#[tokio::test]
async fn per_thread_cancel_leaves_other_chats_running() {