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.

A lead that delegates twice in one turn is resumed once

Lin (kwant bot)3f957b72cbd8
diff --git a/src/db/threads.rs b/src/db/threads.rs
index 3536362e..58b2071d 100644
--- a/src/db/threads.rs
+++ b/src/db/threads.rs
@@ -63,6 +63,11 @@ pub struct Delegation {
/// The lead hears both results in one batch (see `finished_batch`).
#[sqlx(default)]
pub relayed_from_delegation_id: Option<String>,
+ /// The lead's turn that started it with the `delegate` tool, while that turn held its
+ /// hand-offs' reports: the lead hears every hand-off of that turn in one batch (see
+ /// `finished_batch`).
+ #[sqlx(default)]
+ pub lead_turn_id: Option<String>,
}
impl Delegation {
@@ -162,6 +167,9 @@ impl Database {
let _ = sqlx::query("ALTER TABLE delegations ADD COLUMN relayed_from_delegation_id TEXT;")
.execute(&self.pool)
.await;
+ let _ = sqlx::query("ALTER TABLE delegations ADD COLUMN lead_turn_id TEXT;")
+ .execute(&self.pool)
+ .await;
Ok(())
}
@@ -300,6 +308,7 @@ impl Database {
retries: 0,
after_delegation_id: None,
relayed_from_delegation_id: None,
+ lead_turn_id: None,
};
sqlx::query(
"INSERT INTO delegations (id, thread_id, lead_kwant_id, specialist_kwant_id, origin_channel_id, origin_kwant_id, \
@@ -476,6 +485,16 @@ impl Database {
Ok(())
}
+ /// Marks `id` as started by the lead's turn `turn_id` (see [`Delegation::lead_turn_id`]).
+ pub async fn set_delegation_lead_turn(&self, id: &str, turn_id: &str) -> Result<(), DbError> {
+ sqlx::query("UPDATE delegations SET lead_turn_id = ? WHERE id = ?")
+ .bind(turn_id)
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
/// Delegations parked until `after` ends.
pub async fn list_dependent_delegations(&self, after: &str) -> Result<Vec<Delegation>, DbError> {
Ok(sqlx::query_as::<_, Delegation>(
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index f5ebebef..712e1d17 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -154,6 +154,9 @@ pub struct StartRequest {
/// The ended delegation whose result @mentioned this teammate (see
/// [`Delegation::relayed_from_delegation_id`]).
pub relayed_from: Option<String>,
+ /// The lead's turn that holds this hand-off's report until it ends (see
+ /// [`super::turns::TurnRegistry::hold`]).
+ pub lead_turn: Option<String>,
}
/// Checks a request, creates the thread and the delegation, and starts the specialist's turn
@@ -313,6 +316,14 @@ pub(super) async fn create(state: &AppState, req: StartRequest) -> Result<Create
}
None => d,
};
+ // Also before it runs: the lead hears it with the turn's other hand-offs (see `finished_batch`)
+ let d = match &req.lead_turn {
+ Some(turn) => {
+ let _ = state.db.set_delegation_lead_turn(&d.id, turn).await;
+ state.db.get_delegation(&d.id).await.ok().flatten().unwrap_or(d)
+ }
+ None => d,
+ };
// Waits for a sibling of the same lead and chat that is still open; anything else is ignored
let prereq = match &req.after {
@@ -806,6 +817,11 @@ async fn report_to_lead(state: &AppState, d: &Delegation, opening: Option<String
if !d.continue_lead {
return;
}
+ // The lead's turn that started it still runs: it reports when that turn ends (see `release_held`)
+ if d.lead_turn_id.as_deref().is_some_and(|t| state.turns.defer(t, &d.id)) {
+ tracing::info!(delegation = %d.id, turn_id = ?d.lead_turn_id, "hand-off ended while its lead's turn runs: reporting when that turn ends");
+ return;
+ }
if let Some(batch) = finished_batch(state, d).await {
continue_lead(state, d, &batch, opening).await;
}
@@ -817,6 +833,61 @@ fn spawn_report_to_lead(state: &AppState, d: Delegation) {
tokio::spawn(async move { report_to_lead(&state, &d, None).await });
}
+/// Reports the hand-offs a lead's turn held (see [`super::turns::TurnRegistry::hold`]) now that
+/// it ended or ran past the limit: the lead gets one turn with every hand-off of that turn once
+/// all of them ended; one still running reports when it ends. Called from the turn's end, so it
+/// only spawns.
+pub(super) fn release_held(state: &AppState, turn_id: &str, held: Vec<String>) {
+ if held.is_empty() {
+ return;
+ }
+ let Ok(rt) = tokio::runtime::Handle::try_current() else {
+ return tracing::warn!(turn_id, held = held.len(), "a lead's turn ended outside the runtime: its held hand-offs weren't reported");
+ };
+ tracing::info!(turn_id, held = held.len(), "the lead's turn ended: reporting the hand-offs it held");
+ let state = state.clone();
+ rt.spawn(async move {
+ for id in held {
+ if let Ok(Some(d)) = state.db.get_delegation(&id).await {
+ spawn_report_to_lead(&state, d);
+ }
+ }
+ });
+}
+
+/// Past the hold limit the held hand-offs go to the lead even though the turn that started them
+/// still runs: at worst the lead hears that turn's hand-offs in two turns, as before the hold,
+/// never in none (2026-10-24).
+fn spawn_hold_limit(state: &AppState, turn_id: String) {
+ let state = state.clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(state.turns.hold_limit()).await;
+ if let Some(held) = state.turns.expire_hold(&turn_id) {
+ tracing::warn!(turn_id, held = held.len(), "a lead's turn held its hand-offs past the limit: reporting them while it runs");
+ release_held(&state, &turn_id, held);
+ }
+ });
+}
+
+/// After a restart: the hand-offs of turns it cut short waited for those turns to end, which
+/// they never will now. Each such turn's batch goes to its lead (one still open reports when
+/// it ends, as usual).
+pub async fn release_cut_short(state: &AppState, turns: &[crate::db::continuity::RunningTurn]) {
+ for t in turns {
+ let held = state
+ .db
+ .list_delegations(Some(&t.kwant_id), None, 50)
+ .await
+ .unwrap_or_default()
+ .into_iter()
+ .find(|d| d.lead_turn_id.as_deref() == Some(t.turn_id.as_str()) && !d.is_open());
+ if let Some(d) = held {
+ tracing::info!(turn_id = %t.turn_id, delegation = %d.id, "a restart cut short the lead's turn: reporting the hand-offs it held");
+ spawn_report_to_lead(state, d);
+ }
+ }
+}
+
/// A question the specialist asked in the delegation's thread that the person hasn't answered.
async fn open_question(state: &AppState, d: &Delegation) -> Option<crate::db::questions::Question> {
state
@@ -906,13 +977,16 @@ async fn finished_batch(state: &AppState, d: &Delegation) -> Option<Vec<Delegati
return None;
}
let end = |s: &Delegation| s.ended_at.unwrap_or(s.created_at);
- // Grow from `d` to every delegation whose run overlaps the batch's span, and to the results
- // that relayed work to a batch member or were relayed from one (they ran one after the other)
+ // Grow from `d` to every delegation whose run overlaps the batch's span, to the results
+ // that relayed work to a batch member or were relayed from one (they ran one after the other),
+ // and to the hand-offs the same lead turn started (one may have ended before the next began)
let mut batch = vec![siblings.iter().find(|s| s.id == d.id)?.clone()];
let (mut lo, mut hi) = (d.created_at, end(d));
let linked = |s: &Delegation, batch: &[Delegation]| {
batch.iter().any(|b| {
- s.relayed_from_delegation_id.as_deref() == Some(b.id.as_str()) || b.relayed_from_delegation_id.as_deref() == Some(s.id.as_str())
+ s.relayed_from_delegation_id.as_deref() == Some(b.id.as_str())
+ || b.relayed_from_delegation_id.as_deref() == Some(s.id.as_str())
+ || (s.lead_turn_id.is_some() && s.lead_turn_id == b.lead_turn_id)
})
};
loop {
@@ -935,6 +1009,11 @@ async fn finished_batch(state: &AppState, d: &Delegation) -> Option<Vec<Delegati
if batch.iter().all(|b| b.status == "cancelled") {
return None;
}
+ // One of them ended while the lead's turn that started it runs: that turn reports the batch
+ // when it ends (see `release_held`)
+ if batch.iter().any(|b| b.lead_turn_id.as_deref().is_some_and(|t| state.turns.holding(t))) {
+ return None;
+ }
let mut ids: Vec<&str> = batch.iter().map(|b| b.id.as_str()).collect();
ids.sort_unstable();
let mut claimed = RESUMED_BATCHES.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
@@ -1062,9 +1141,13 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], o
}
}
-/// Whether another hand-off of `d`'s batch (same lead and chat, reporting back) is still open:
-/// the lead then hears about `d` with the whole batch, so nothing asks it about `d` alone.
+/// Whether another hand-off of `d`'s batch (same lead and chat, reporting back) is still open, or
+/// the lead's turn that started `d` still holds its report: the lead then hears about `d` with the
+/// whole batch, so nothing asks it about `d` alone.
pub async fn batch_running(state: &AppState, d: &Delegation) -> bool {
+ if d.lead_turn_id.as_deref().is_some_and(|t| state.turns.holding(t)) {
+ return true;
+ }
state
.db
.list_delegations(Some(&d.lead_kwant_id), None, 50)
@@ -1567,6 +1650,7 @@ pub async fn create_delegation(State(state): State<AppState>, Json(p): Json<Dele
allowed: None,
after: None,
relayed_from: None,
+ lead_turn: None,
};
match start(&state, req).await {
Ok(d) => (StatusCode::ACCEPTED, Json(d)).into_response(),
@@ -1631,6 +1715,14 @@ pub async fn tool_delegate(state: &AppState, scope: &super::continuity::SelfScop
let names: Vec<&str> = pool.iter().map(|k| k.name.as_str()).collect();
return (format!("No bot named '{to}'. You can delegate to: {}.", names.join(", ")), true);
};
+ // Held before it starts: one that ends while this turn hands out the next one doesn't
+ // resume the lead on its own (see `TurnRegistry::hold`)
+ let lead_turn = scope.turn_id.as_ref().and_then(|t| {
+ if state.turns.hold(t)? {
+ spawn_hold_limit(state, t.clone());
+ }
+ Some(t.clone())
+ });
let req = StartRequest {
lead,
specialist,
@@ -1646,6 +1738,7 @@ pub async fn tool_delegate(state: &AppState, scope: &super::continuity::SelfScop
allowed: (!origin.member_ids.is_empty()).then(|| origin.member_ids.clone()),
after: None,
relayed_from: None,
+ lead_turn,
};
match start(state, req).await {
Ok(d) => (
diff --git a/src/server/routes.rs b/src/server/routes.rs
index a4ef4dab..407f6a2b 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1531,6 +1531,7 @@ pub(super) async fn delegate_mentions(
allowed: Some(allowed.clone()),
after,
relayed_from: relay.map(|r| r.source.id.clone()),
+ lead_turn: None,
};
match super::delegation::create(&scope.state, req).await {
Ok(c) => {
@@ -1869,6 +1870,7 @@ pub(super) async fn turn_once(
// Sends turn_ended even if this future is dropped, queued or mid-turn
let mut ended = TurnEndedGuard {
sender: scope.state.event_sender.clone(),
+ state: scope.state.clone(),
turns: turns.clone(),
tag: tag.clone(),
outcome: "cancelled",
@@ -1966,6 +1968,8 @@ pub async fn interrupt_running_turns(state: &AppState) -> usize {
if !turns.is_empty() {
tracing::info!(count = turns.len(), "marked chat replies cut short by a restart as interrupted");
}
+ // Their hand-offs waited for them to end, and they won't now
+ super::delegation::release_cut_short(state, &turns).await;
turns.len()
}
@@ -1994,6 +1998,8 @@ fn scrub_urls(text: &str) -> String {
struct TurnEndedGuard {
sender: tokio::sync::broadcast::Sender<RuntimeEvent>,
+ /// Reports the hand-offs the turn held when it ends (see [`super::turns::TurnRegistry::hold`]).
+ state: AppState,
turns: super::turns::TurnRegistry,
tag: crate::drivers::events::TurnTag,
outcome: &'static str,
@@ -2004,6 +2010,8 @@ struct TurnEndedGuard {
impl Drop for TurnEndedGuard {
fn drop(&mut self) {
self.turns.end_turn(&self.tag.turn_id);
+ // However it ended (reply, error, stop, panic), the lead hears the hand-offs this turn started
+ super::delegation::release_held(&self.state, &self.tag.turn_id, self.turns.end_hold(&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 {
diff --git a/src/server/turns.rs b/src/server/turns.rs
index 3534fcef..b919f0d7 100644
--- a/src/server/turns.rs
+++ b/src/server/turns.rs
@@ -12,6 +12,7 @@ use crate::drivers::events::RuntimeEvent;
use serde::Serialize;
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
+use std::time::Duration;
use tokio::sync::{broadcast, oneshot};
use tokio_util::sync::CancellationToken;
@@ -54,6 +55,23 @@ struct Inner {
turns: HashMap<String, ActiveTurn>,
/// Usage the engine reported so far in a running turn, by turn id (see [`TurnRegistry::book_usage`]).
meters: HashMap<String, Meter>,
+ /// Lead turns that hold their hand-offs' reports, by turn id (see [`TurnRegistry::hold`]).
+ holds: HashMap<String, Hold>,
+ /// [`HOLD_LIMIT`] unless a test shortened it.
+ hold_limit: Option<Duration>,
+}
+
+/// How long a lead's turn holds its hand-offs' reports at most (see [`TurnRegistry::hold`]):
+/// past it they go to the lead anyway. kwnt sets no limit on a turn's length; one waiting on the
+/// person's answer ends within 5 minutes.
+pub const HOLD_LIMIT: Duration = Duration::from_secs(600);
+
+/// A lead's turn that started hand-offs with the `delegate` tool.
+enum Hold {
+ /// Running: the hand-offs that ended meanwhile wait for it, by delegation id.
+ Open(Vec<String>),
+ /// Past [`HOLD_LIMIT`]: what waited was reported, and the turn holds nothing more.
+ Expired,
}
/// One turn's fresh tokens: reported by the engine so far, and already booked onto a task.
@@ -174,6 +192,73 @@ impl TurnRegistry {
inner.meters.remove(turn_id);
}
+ /// Holds the reports of the hand-offs that `turn_id`, a running lead turn, starts until it
+ /// ends, so the lead hears them all in one turn: one that ended while the lead was still
+ /// handing out the next resumed it on its own, and the next one resumed it again (10 runs in
+ /// 10 with a 300 ms gap between two `delegate` calls, 2026-11-02). `Some(true)` when this
+ /// opened the hold, `Some(false)` when it was open; `None` when the turn isn't running or
+ /// is past [`HOLD_LIMIT`].
+ pub fn hold(&self, turn_id: &str) -> Option<bool> {
+ let mut inner = self.lock();
+ if !inner.turns.contains_key(turn_id) {
+ return None;
+ }
+ match inner.holds.get(turn_id) {
+ Some(Hold::Open(_)) => Some(false),
+ Some(Hold::Expired) => None,
+ None => {
+ inner.holds.insert(turn_id.to_string(), Hold::Open(Vec::new()));
+ Some(true)
+ }
+ }
+ }
+
+ /// Keeps the report of `delegation_id`, which ended, until `turn_id` ends; `false` when that
+ /// turn holds nothing.
+ pub fn defer(&self, turn_id: &str, delegation_id: &str) -> bool {
+ match self.lock().holds.get_mut(turn_id) {
+ Some(Hold::Open(held)) => {
+ held.push(delegation_id.to_string());
+ true
+ }
+ _ => false,
+ }
+ }
+
+ /// Whether `turn_id` holds its hand-offs' reports.
+ pub fn holding(&self, turn_id: &str) -> bool {
+ matches!(self.lock().holds.get(turn_id), Some(Hold::Open(_)))
+ }
+
+ /// Ends `turn_id`'s hold as the turn ends: the hand-offs whose reports waited for it.
+ pub fn end_hold(&self, turn_id: &str) -> Vec<String> {
+ match self.lock().holds.remove(turn_id) {
+ Some(Hold::Open(held)) => held,
+ _ => Vec::new(),
+ }
+ }
+
+ /// Ends `turn_id`'s hold at its limit while the turn still runs: what waited goes to the
+ /// lead now, and the hand-offs it starts from here on aren't held. `None` once the turn ended.
+ pub fn expire_hold(&self, turn_id: &str) -> Option<Vec<String>> {
+ let mut inner = self.lock();
+ let hold = inner.holds.get_mut(turn_id)?;
+ match std::mem::replace(hold, Hold::Expired) {
+ Hold::Open(held) => Some(held),
+ Hold::Expired => None,
+ }
+ }
+
+ /// The hold limit (see [`HOLD_LIMIT`]).
+ pub fn hold_limit(&self) -> Duration {
+ self.lock().hold_limit.unwrap_or(HOLD_LIMIT)
+ }
+
+ /// Shortens the hold limit (tests).
+ pub fn set_hold_limit(&self, limit: Duration) {
+ self.lock().hold_limit = Some(limit);
+ }
+
/// Notes the fresh tokens a running turn used so far, as its engine reports them.
pub fn saw_usage(&self, turn_id: &str, fresh: u64) {
let mut inner = self.lock();
@@ -448,6 +533,38 @@ mod tests {
assert_eq!(reg.book_usage("u"), 0, "an ended turn keeps no meter");
}
+ #[test]
+ fn a_hold_keeps_what_ended_until_the_turn_ends_or_passes_its_limit() {
+ let reg = TurnRegistry::default();
+ assert_eq!(reg.hold("t"), None, "a turn that isn't running holds nothing");
+ reg.set_turn(ActiveTurn {
+ turn_id: "t".into(),
+ kwant_id: "k".into(),
+ context_id: "c".into(),
+ thread_id: None,
+ state: "running".into(),
+ since: chrono::Utc::now(),
+ purpose: None,
+ });
+ assert!(!reg.defer("t", "d1"), "nothing waits before the turn's first hand-off");
+ assert_eq!(reg.hold("t"), Some(true));
+ assert_eq!(reg.hold("t"), Some(false), "opened once");
+ assert!(reg.defer("t", "d1") && reg.holding("t"));
+ assert_eq!(reg.end_hold("t"), ["d1"]);
+ assert!(!reg.holding("t") && reg.end_hold("t").is_empty(), "reported once");
+ // Past the limit: what waited goes out once, and nothing the turn starts after it waits
+ assert_eq!(reg.hold("t"), Some(true));
+ assert!(reg.defer("t", "d2"));
+ assert_eq!(reg.expire_hold("t"), Some(vec!["d2".to_string()]));
+ assert_eq!(reg.expire_hold("t"), None);
+ assert_eq!(reg.hold("t"), None, "an expired hold doesn't open again");
+ assert!(!reg.defer("t", "d3") && !reg.holding("t"));
+ reg.end_turn("t");
+ assert!(reg.end_hold("t").is_empty());
+ assert_eq!(reg.hold("t"), None, "nor once the turn ended");
+ assert_eq!(reg.expire_hold("t"), None, "a limit that fires after the turn ended finds nothing");
+ }
+
use super::*;
#[test]
diff --git a/tests/delegation_test.rs b/tests/delegation_test.rs
index 4d367e56..256f8506 100644
--- a/tests/delegation_test.rs
+++ b/tests/delegation_test.rs
@@ -30,6 +30,9 @@ use tower::ServiceExt;
/// for a lead's results follow-up with "FOLLOWUP:<name>"; several names go as "<a>+<b>". A
/// follow-up with "CREDIT:<name>" adds "As @<name> found, it's done." (a mention that asks nothing);
/// a "LONGTASK:<file>" prompt waits (up to 60 s) for that file first, and a "FAILTASK" prompt fails.
+/// "HOLDTURN:<file>" waits the same way, but only in the request itself (not the chat history
+/// before it, nor the person's words a delegated task quotes after it), and fails then with
+/// "HOLDFAIL": it keeps the lead's own turn running while its hand-offs and results turns run.
/// "LINES:<name>:<n>" adds n lines "@<name>, please build part <i>." to a reply that isn't a
/// delegated task or a results follow-up. Every prompt is saved under `$KWNT_TEST_PROMPTS`.
const FAKE_CLAUDE: &str = r#"#!/bin/sh
@@ -44,6 +47,14 @@ if [ -n "$release" ]; then
i=0
while [ ! -f "$release" ] && [ $i -lt 600 ]; do sleep 0.1; i=$((i+1)); done
fi
+request=$(printf '%s\n' "$last" | sed -n '/^### Current User Request:/,$p' | sed '/^\[What the person asked in the chat this task came from\]/,$d')
+[ -n "$request" ] || request="$last"
+turn=$(printf '%s\n' "$request" | sed -n 's/.*HOLDTURN:\([^ ]*\).*/\1/p' | head -n 1)
+if [ -n "$turn" ]; then
+ i=0
+ while [ ! -f "$turn" ] && [ $i -lt 600 ]; do sleep 0.1; i=$((i+1)); done
+ case "$request" in *HOLDFAIL*) echo "boom" >&2; exit 1 ;; esac
+fi
tag=$(printf '%s\n' "$last" | sed -n 's/.*REPLYTAG:\([A-Za-z0-9_]*\).*/\1/p' | tail -n 1)
mention=$(printf '%s\n' "$last" | sed -n 's/.*MENTION:\([A-Za-z0-9_+]*\).*/\1/p' | head -n 1)
followup=$(printf '%s\n' "$last" | sed -n 's/.*FOLLOWUP:\([A-Za-z0-9_+]*\).*/\1/p' | head -n 1)
@@ -1593,3 +1604,220 @@ async fn lines_past_the_per_teammate_cap_wait_for_continue_and_are_sent_once() {
assert_eq!(ds.len(), 5, "Continue sends only the line that waited: {:?}", ds.iter().map(|d| &d.title).collect::<Vec<_>>());
assert!(ds[4].title.to_lowercase().contains("build part 5."), "{}", ds[4].title);
}
+
+/// A call to kwnt's own tools as the agent turn that holds `token`, as its CLI makes it.
+async fn self_tool(env: &Env, token: &str, name: &str, args: Value) -> (String, bool) {
+ let resp = env
+ .app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/api/mcp/self")
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {token}"))
+ .body(Body::from(json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}}).to_string()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let v: Value = serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap();
+ (v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string(), v["result"]["isError"] == true)
+}
+
+/// The person asks the lead in its own chat; the lead's turn runs until `release` exists (and then
+/// fails, with `fail`). Returns that turn's id and the token its CLI calls kwnt's tools with.
+async fn lead_turn(env: &Env, release: &std::path::Path, fail: bool) -> (String, String) {
+ let prompt = format!("Plan the launch HOLDTURN:{}{}", release.display(), if fail { " HOLDFAIL" } else { "" });
+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(json!({"kwant_id": env.lead, "prompt": prompt, "sender_id": "user"}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ for _ in 0..300 {
+ let turn = env.state.turns.active_turns().into_iter().find(|t| t.kwant_id == env.lead && t.context_id == env.lead && t.state == "running");
+ if let Some(t) = turn {
+ let token = env.state.self_tools.lock().await.iter().find(|(_, s)| s.turn_id.as_deref() == Some(t.turn_id.as_str())).map(|(k, _)| k.clone());
+ if let Some(token) = token {
+ return (t.turn_id, token);
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("the lead's turn didn't start");
+}
+
+/// The lead's turns that report the results of the tasks titled "<marker> …".
+fn resumes(marker: &str) -> Vec<String> {
+ prompts_with(marker)
+ .into_iter()
+ .filter(|p| ["finished the task you delegated", "tasks you delegated have ended", "ended without a result"].iter().any(|o| p.contains(o)))
+ .collect()
+}
+
+/// In one turn the lead hands part A to its first teammate and, `gap` later, part B to `second`;
+/// returns their delegation ids once both completed.
+async fn delegate_twice(env: &Env, token: &str, second: &str, marker: &str, gap: u64, b_task: &str) -> (String, String) {
+ let (first, second) = (name(env, &env.specialist).await, name(env, second).await);
+ let (text, err) = self_tool(env, token, "delegate", json!({"to": first, "task": "Part one REPLYTAG:mcA", "title": format!("{marker} part A")})).await;
+ assert!(!err, "{text}");
+ // The lead's model takes a moment before its next tool call
+ tokio::time::sleep(Duration::from_millis(gap)).await;
+ let (text, err) = self_tool(env, token, "delegate", json!({"to": second, "task": b_task, "title": format!("{marker} part B")})).await;
+ assert!(!err, "{text}");
+ let ids = env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap();
+ let id = |part: &str| ids.iter().find(|d| d.title == format!("{marker} part {part}")).map(|d| d.id.clone()).expect("delegated");
+ (id("A"), id("B"))
+}
+
+/// Waits for the lead's one turn with both parts' results, then makes sure no second one follows.
+async fn assert_resumed_once(marker: &str) {
+ wait_for("the lead's turn with both results", || async { resumes(marker).iter().any(|p| p.contains("answer mcB")) }).await;
+ tokio::time::sleep(Duration::from_millis(1000)).await;
+ let resumes = resumes(marker);
+ let openings: Vec<&str> = resumes.iter().map(|p| p.lines().next().unwrap_or("")).collect();
+ assert_eq!(resumes.len(), 1, "resumed once with both results: {openings:?}");
+ assert!(resumes[0].contains("answer mcA") && resumes[0].contains("answer mcB"), "{}", resumes[0]);
+}
+
+/// 2026-11-02: a lead that called `delegate` twice in one turn was resumed twice when the first
+/// task ended before the second began (10 runs in 10 with 300 ms or more between the calls), and
+/// answered the person twice. The turn now holds what its hand-offs report until it ends: the
+/// lead is resumed once, after that turn, with both results. `KWNT_MC_GAP_MS` runs one gap only.
+#[tokio::test]
+async fn a_lead_that_delegates_twice_in_one_turn_is_resumed_once() {
+ let gaps: Vec<u64> = match std::env::var("KWNT_MC_GAP_MS").ok().and_then(|v| v.parse().ok()) {
+ Some(gap) => vec![gap],
+ None => vec![0, 100, 300, 700],
+ };
+ for gap in gaps {
+ let env = setup().await;
+ let second = add_bot(&env, "Second").await;
+ let marker = format!("HOLDMC{gap}");
+ let release = env.release_file("lead-turn");
+ let (turn_id, token) = lead_turn(&env, &release, false).await;
+ let (a, b) = delegate_twice(&env, &token, &second, &marker, gap, "Part two REPLYTAG:mcB").await;
+ wait_for("both parts to complete", || async { delegation_status(&env, &a).await == "completed" && delegation_status(&env, &b).await == "completed" }).await;
+ let d = env.state.db.get_delegation(&a).await.unwrap().unwrap();
+ assert_eq!(d.lead_turn_id.as_deref(), Some(turn_id.as_str()));
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ assert!(resumes(&marker).is_empty(), "the lead isn't resumed while its turn runs (gap {gap} ms)");
+ std::fs::write(&release, "").unwrap();
+ assert_resumed_once(&marker).await;
+ }
+}
+
+/// The lead's turn that handed out the work fails, or the person stops it: the lead is still
+/// resumed, once, with every result.
+#[tokio::test]
+async fn a_lead_turn_that_fails_or_is_stopped_still_reports_its_hand_offs_once() {
+ // Fails after the hand-offs ended
+ let env = setup().await;
+ let second = add_bot(&env, "Second").await;
+ let release = env.release_file("lead-turn");
+ let (_, token) = lead_turn(&env, &release, true).await;
+ let (a, b) = delegate_twice(&env, &token, &second, "HOLDERR", 300, "Part two REPLYTAG:mcB").await;
+ wait_for("both parts to complete", || async { delegation_status(&env, &a).await == "completed" && delegation_status(&env, &b).await == "completed" }).await;
+ assert!(resumes("HOLDERR").is_empty());
+ std::fs::write(&release, "").unwrap();
+ assert_resumed_once("HOLDERR").await;
+
+ // Stopped by the person
+ let env = setup().await;
+ let second = add_bot(&env, "Second").await;
+ let release = env.release_file("lead-turn");
+ let (turn_id, token) = lead_turn(&env, &release, false).await;
+ let (a, b) = delegate_twice(&env, &token, &second, "HOLDSTOP", 300, "Part two REPLYTAG:mcB").await;
+ wait_for("both parts to complete", || async { delegation_status(&env, &a).await == "completed" && delegation_status(&env, &b).await == "completed" }).await;
+ assert!(resumes("HOLDSTOP").is_empty());
+ let (s, v) = call(&env.app, "POST", "/api/chat/cancel", Some(json!({"turn_id": turn_id}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_resumed_once("HOLDSTOP").await;
+ std::fs::write(&release, "").unwrap();
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ assert_eq!(resumes("HOLDSTOP").len(), 1);
+}
+
+/// The lead's turn waits on a question to the person: what its hand-offs report waits too, at most
+/// until `ask_user` gives up and the turn ends.
+#[tokio::test]
+async fn a_lead_turn_waiting_on_a_question_reports_its_hand_offs_when_it_ends() {
+ let env = setup().await;
+ env.state.questions.set_wait(Duration::from_millis(1500));
+ let second = add_bot(&env, "Second").await;
+ let release = env.release_file("lead-turn");
+ let (_, token) = lead_turn(&env, &release, false).await;
+ let (a, b) = delegate_twice(&env, &token, &second, "HOLDASK", 300, "Part two REPLYTAG:mcB").await;
+ wait_for("both parts to complete", || async { delegation_status(&env, &a).await == "completed" && delegation_status(&env, &b).await == "completed" }).await;
+ let ask = json!({"question": "Which launch date?", "choices": ["Monday", "Friday"], "why_you": "missing_after_research", "checked": "The brief names no date."});
+ let (text, err) = self_tool(&env, &token, "ask_user", ask).await;
+ assert!(!err && text.contains("hasn't answered"), "{text}");
+ assert!(resumes("HOLDASK").is_empty(), "nothing while the question waits");
+ // The lead ends its turn, as the tool told it to
+ std::fs::write(&release, "").unwrap();
+ assert_resumed_once("HOLDASK").await;
+}
+
+/// A lead's turn that runs past the hold limit: what its hand-offs reported goes to the lead
+/// anyway, once, and the turn's end adds nothing.
+#[tokio::test]
+async fn a_lead_turn_past_the_hold_limit_reports_its_hand_offs_while_it_runs() {
+ let env = setup().await;
+ env.state.turns.set_hold_limit(Duration::from_secs(3));
+ let second = add_bot(&env, "Second").await;
+ let release = env.release_file("lead-turn");
+ let (turn_id, token) = lead_turn(&env, &release, false).await;
+ delegate_twice(&env, &token, &second, "HOLDLIMIT", 300, "Part two REPLYTAG:mcB").await;
+ wait_for("the lead's turn with both results", || async { resumes("HOLDLIMIT").iter().any(|p| p.contains("answer mcB")) }).await;
+ assert!(env.state.turns.active_turns().iter().any(|t| t.turn_id == turn_id), "the turn still runs");
+ std::fs::write(&release, "").unwrap();
+ assert_resumed_once("HOLDLIMIT").await;
+}
+
+/// A hand-off still running when the lead's turn ends reports as before: the lead is resumed once,
+/// when it ends, with the one held for the turn.
+#[tokio::test]
+async fn a_hand_off_still_running_when_the_lead_turn_ends_joins_the_held_one() {
+ let env = setup().await;
+ let second = add_bot(&env, "Second").await;
+ let release = env.release_file("lead-turn");
+ let slow = env.release_file("part-b");
+ let (_, token) = lead_turn(&env, &release, false).await;
+ let (a, b) = delegate_twice(&env, &token, &second, "HOLDLATE", 300, &format!("Part two LONGTASK:{} REPLYTAG:mcB", slow.display())).await;
+ wait_for("part A to complete", || async { delegation_status(&env, &a).await == "completed" }).await;
+ std::fs::write(&release, "").unwrap();
+ wait_for("the lead's turn to end", || async { !env.state.turns.active_turns().iter().any(|t| t.kwant_id == env.lead && t.context_id == env.lead) }).await;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ assert!(resumes("HOLDLATE").is_empty(), "part B still runs");
+ assert_eq!(delegation_status(&env, &b).await, "running");
+ std::fs::write(&slow, "").unwrap();
+ assert_resumed_once("HOLDLATE").await;
+}
+
+/// kwnt restarts while the lead's turn that handed out the work runs: the restarted kwnt resumes
+/// the lead with what its hand-offs reported, once.
+#[tokio::test]
+async fn a_restart_mid_turn_still_reports_the_held_hand_offs() {
+ let env = setup().await;
+ let second = add_bot(&env, "Second").await;
+ let release = env.release_file("lead-turn");
+ let (_, token) = lead_turn(&env, &release, false).await;
+ let (a, b) = delegate_twice(&env, &token, &second, "HOLDRESTART", 300, "Part two REPLYTAG:mcB").await;
+ wait_for("both parts to complete", || async { delegation_status(&env, &a).await == "completed" && delegation_status(&env, &b).await == "completed" }).await;
+ assert!(resumes("HOLDRESTART").is_empty());
+
+ // A new kwnt on the same data, as at startup
+ let data = env.tmp.path().join("data");
+ 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 restarted = AppState::new(
+ config.clone(),
+ Database::init(&data).await.unwrap(),
+ ToolRunner::new(data.join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ assert!(kwnt::server::routes::interrupt_running_turns(&restarted).await >= 1, "the lead's turn was cut short");
+ delegation::interrupt_open(&restarted).await;
+ assert_resumed_once("HOLDRESTART").await;
+ // (In a real restart the old turn is gone; here its end must not report the batch again)
+ std::fs::write(&release, "").unwrap();
+ tokio::time::sleep(Duration::from_millis(1000)).await;
+ assert_eq!(resumes("HOLDRESTART").len(), 1);
+}