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.

Concurrent turns, threads and background delegation (batch 2 / A)

Lin (kwant bot)34a8c9e3c0b0
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 7e16b805..69a1ab9a 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -1,6 +1,7 @@
pub mod models;
pub mod profiles;
pub mod continuity;
+pub mod threads;
use models::*;
use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite};
@@ -82,6 +83,7 @@ impl Database {
let db = Self { pool };
db.migrate_profiles().await?;
db.migrate_continuity().await?;
+ db.migrate_threads().await?;
db.seed_defaults().await?;
Ok(db)
@@ -277,6 +279,11 @@ impl Database {
// Messages CRUD
pub async fn insert_message(&self, input: &NewMessage) -> Result<Message, DbError> {
+ self.insert_message_with(input, &MessageExtra::default()).await
+ }
+
+ /// [`Self::insert_message`] into a thread and/or with kwnt's own `meta`.
+ pub async fn insert_message_with(&self, input: &NewMessage, extra: &MessageExtra) -> Result<Message, DbError> {
let id = Uuid::new_v4().to_string();
let tools_json = input
.tool_calls
@@ -286,8 +293,8 @@ impl Database {
sqlx::query(
r#"
- INSERT INTO messages (id, channel_id, direct_kwant_id, sender_role, sender_id, text, reasoning_content, tool_calls, tokens_used)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ INSERT INTO messages (id, channel_id, direct_kwant_id, sender_role, sender_id, text, reasoning_content, tool_calls, tokens_used, thread_id, meta)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"#,
)
.bind(&id)
@@ -299,6 +306,8 @@ impl Database {
.bind(&input.reasoning_content)
.bind(&tools_json)
.bind(input.tokens_used)
+ .bind(&extra.thread_id)
+ .bind(extra.meta.as_ref().map(|m| m.to_string()))
.execute(&self.pool)
.await?;
@@ -314,7 +323,7 @@ impl Database {
r#"
SELECT * FROM (
SELECT *, rowid AS _seq FROM messages
- WHERE channel_id = ? OR direct_kwant_id = ?
+ WHERE channel_id = ? OR direct_kwant_id = ? OR thread_id = ?
ORDER BY created_at DESC, rowid DESC
LIMIT ?
)
@@ -323,6 +332,7 @@ impl Database {
)
.bind(channel_or_kwant_id)
.bind(channel_or_kwant_id)
+ .bind(channel_or_kwant_id)
.bind(limit)
.fetch_all(&self.pool)
.await?;
diff --git a/src/db/models.rs b/src/db/models.rs
index 17c8fc51..65cd0952 100644
--- a/src/db/models.rs
+++ b/src/db/models.rs
@@ -82,6 +82,22 @@ pub struct Message {
pub tool_calls: Option<String>, // JSON serialized tool calls & outputs
pub tokens_used: i64,
pub created_at: Option<DateTime<Utc>>,
+ /// Set for messages in a thread (see `crate::db::threads`); `channel_id` and
+ /// `direct_kwant_id` are then both empty.
+ #[serde(default)]
+ #[sqlx(default)]
+ pub thread_id: Option<String>,
+ /// JSON for messages kwnt writes itself, e.g. `{"kind":"delegation_result",…}`.
+ #[serde(default)]
+ #[sqlx(default)]
+ pub meta: Option<String>,
+}
+
+/// Where a message goes besides [`NewMessage`]'s channel or direct chat.
+#[derive(Debug, Clone, Default)]
+pub struct MessageExtra {
+ pub thread_id: Option<String>,
+ pub meta: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/src/db/threads.rs b/src/db/threads.rs
new file mode 100644
index 00000000..fcbba3e6
--- /dev/null
+++ b/src/db/threads.rs
@@ -0,0 +1,435 @@
+//! Threads (an agent's separate conversations, each with its own history) and delegations (a lead
+//! handing a task to a specialist, run in a delegation thread and reported back to the lead's chat).
+
+use super::{Database, DbError};
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use sqlx::FromRow;
+use uuid::Uuid;
+
+/// Longest thread or delegation title.
+pub const MAX_TITLE_CHARS: usize = 120;
+/// Longest delegated task.
+pub const MAX_TASK_CHARS: usize = 8000;
+
+/// Delegation states that are not over yet.
+pub const OPEN_STATUSES: [&str; 2] = ["queued", "running"];
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct Thread {
+ pub id: String,
+ pub kwant_id: String,
+ pub title: String,
+ /// "chat" (the user opened it) or "delegation".
+ pub kind: String,
+ pub team_id: Option<String>,
+ /// "user" or the id of the kwant that delegated into it.
+ pub created_by: String,
+ pub archived: bool,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+}
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct Delegation {
+ pub id: String,
+ pub thread_id: String,
+ pub lead_kwant_id: String,
+ pub specialist_kwant_id: String,
+ pub origin_channel_id: Option<String>,
+ pub origin_kwant_id: Option<String>,
+ pub origin_thread_id: Option<String>,
+ pub task: String,
+ pub title: String,
+ /// "queued", "running", "completed", "failed", "cancelled" or "interrupted".
+ pub status: String,
+ pub continue_lead: bool,
+ pub depth: i64,
+ pub result_message_id: Option<String>,
+ pub error: Option<String>,
+ pub follow_up_at: Option<DateTime<Utc>>,
+ pub followed_up: bool,
+ pub created_at: DateTime<Utc>,
+ pub started_at: Option<DateTime<Utc>>,
+ pub ended_at: Option<DateTime<Utc>>,
+}
+
+impl Delegation {
+ pub fn is_open(&self) -> bool {
+ OPEN_STATUSES.contains(&self.status.as_str())
+ }
+
+ /// The chat the result goes back to: a channel, the lead's direct chat or a thread.
+ pub fn origin_context(&self) -> Option<&str> {
+ self.origin_channel_id
+ .as_deref()
+ .or(self.origin_thread_id.as_deref())
+ .or(self.origin_kwant_id.as_deref())
+ }
+}
+
+/// What a new delegation needs; the thread is created with it.
+#[derive(Debug, Clone)]
+pub struct NewDelegation {
+ pub lead_kwant_id: String,
+ pub specialist_kwant_id: String,
+ pub origin_channel_id: Option<String>,
+ pub origin_kwant_id: Option<String>,
+ pub origin_thread_id: Option<String>,
+ pub team_id: Option<String>,
+ pub task: String,
+ pub title: String,
+ pub continue_lead: bool,
+ pub depth: i64,
+ pub follow_up_at: Option<DateTime<Utc>>,
+}
+
+/// Title from free text: one line, at most [`MAX_TITLE_CHARS`].
+pub fn clean_title(text: &str) -> String {
+ let line = text.split_whitespace().collect::<Vec<_>>().join(" ");
+ if line.chars().count() <= MAX_TITLE_CHARS {
+ return line;
+ }
+ let mut out: String = line.chars().take(MAX_TITLE_CHARS - 1).collect();
+ out.push('…');
+ out
+}
+
+impl Database {
+ /// Additive: thread and meta columns on messages, and the two tables. An old binary never
+ /// shows thread messages (they have no channel or direct chat) and ignores the rest.
+ pub(super) async fn migrate_threads(&self) -> Result<(), DbError> {
+ let _ = sqlx::query("ALTER TABLE messages ADD COLUMN thread_id TEXT;")
+ .execute(&self.pool)
+ .await;
+ let _ = sqlx::query("ALTER TABLE messages ADD COLUMN meta TEXT;")
+ .execute(&self.pool)
+ .await;
+ for stmt in [
+ "CREATE INDEX IF NOT EXISTS messages_by_thread ON messages (thread_id, created_at) WHERE thread_id IS NOT NULL",
+ "CREATE TABLE IF NOT EXISTS threads (
+ id TEXT PRIMARY KEY,
+ kwant_id TEXT NOT NULL,
+ title TEXT NOT NULL,
+ kind TEXT NOT NULL CHECK (kind IN ('chat', 'delegation')),
+ team_id TEXT,
+ created_by TEXT NOT NULL,
+ archived INTEGER NOT NULL DEFAULT 0,
+ created_at TIMESTAMP NOT NULL,
+ updated_at TIMESTAMP NOT NULL
+ )",
+ "CREATE INDEX IF NOT EXISTS threads_by_kwant ON threads (kwant_id, updated_at)",
+ "CREATE TABLE IF NOT EXISTS delegations (
+ id TEXT PRIMARY KEY,
+ thread_id TEXT NOT NULL,
+ lead_kwant_id TEXT NOT NULL,
+ specialist_kwant_id TEXT NOT NULL,
+ origin_channel_id TEXT,
+ origin_kwant_id TEXT,
+ origin_thread_id TEXT,
+ task TEXT NOT NULL,
+ title TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('queued', 'running', 'completed', 'failed', 'cancelled', 'interrupted')),
+ continue_lead INTEGER NOT NULL DEFAULT 1,
+ depth INTEGER NOT NULL DEFAULT 1,
+ result_message_id TEXT,
+ error TEXT,
+ follow_up_at TIMESTAMP,
+ followed_up INTEGER NOT NULL DEFAULT 0,
+ created_at TIMESTAMP NOT NULL,
+ started_at TIMESTAMP,
+ ended_at TIMESTAMP
+ )",
+ "CREATE INDEX IF NOT EXISTS delegations_by_lead ON delegations (lead_kwant_id, created_at)",
+ "CREATE INDEX IF NOT EXISTS delegations_by_thread ON delegations (thread_id)",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ // Threads
+
+ pub async fn create_thread(
+ &self,
+ kwant_id: &str,
+ title: &str,
+ kind: &str,
+ team_id: Option<&str>,
+ created_by: &str,
+ ) -> Result<Thread, DbError> {
+ let now = Utc::now();
+ let thread = Thread {
+ id: Uuid::new_v4().to_string(),
+ kwant_id: kwant_id.into(),
+ title: clean_title(title),
+ kind: kind.into(),
+ team_id: team_id.map(Into::into),
+ created_by: created_by.into(),
+ archived: false,
+ created_at: now,
+ updated_at: now,
+ };
+ sqlx::query(
+ "INSERT INTO threads (id, kwant_id, title, kind, team_id, created_by, archived, created_at, updated_at) \
+ VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?)",
+ )
+ .bind(&thread.id)
+ .bind(&thread.kwant_id)
+ .bind(&thread.title)
+ .bind(&thread.kind)
+ .bind(&thread.team_id)
+ .bind(&thread.created_by)
+ .bind(now)
+ .bind(now)
+ .execute(&self.pool)
+ .await?;
+ Ok(thread)
+ }
+
+ pub async fn get_thread(&self, id: &str) -> Result<Option<Thread>, DbError> {
+ Ok(sqlx::query_as::<_, Thread>("SELECT * FROM threads WHERE id = ?")
+ .bind(id)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ /// Most recently active first.
+ pub async fn list_threads(&self, kwant_id: &str, include_archived: bool, limit: i64) -> Result<Vec<Thread>, DbError> {
+ Ok(sqlx::query_as::<_, Thread>(
+ "SELECT * FROM threads WHERE kwant_id = ? AND (? OR archived = 0) ORDER BY updated_at DESC, rowid DESC LIMIT ?",
+ )
+ .bind(kwant_id)
+ .bind(include_archived)
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ pub async fn update_thread(&self, id: &str, title: Option<&str>, archived: Option<bool>) -> Result<Option<Thread>, DbError> {
+ sqlx::query(
+ "UPDATE threads SET title = COALESCE(?, title), archived = COALESCE(?, archived), updated_at = ? WHERE id = ?",
+ )
+ .bind(title.map(clean_title))
+ .bind(archived)
+ .bind(Utc::now())
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ self.get_thread(id).await
+ }
+
+ /// Moves the thread up the list when something happens in it.
+ pub async fn touch_thread(&self, id: &str) -> Result<(), DbError> {
+ sqlx::query("UPDATE threads SET updated_at = ? WHERE id = ?")
+ .bind(Utc::now())
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ // Delegations
+
+ /// Creates the delegation thread and the delegation (status `queued`) together.
+ pub async fn create_delegation(&self, input: &NewDelegation) -> Result<(Thread, Delegation), DbError> {
+ let mut tx = self.pool.begin().await?;
+ let now = Utc::now();
+ let title = clean_title(&input.title);
+ let thread = Thread {
+ id: Uuid::new_v4().to_string(),
+ kwant_id: input.specialist_kwant_id.clone(),
+ title: title.clone(),
+ kind: "delegation".into(),
+ team_id: input.team_id.clone(),
+ created_by: input.lead_kwant_id.clone(),
+ archived: false,
+ created_at: now,
+ updated_at: now,
+ };
+ sqlx::query(
+ "INSERT INTO threads (id, kwant_id, title, kind, team_id, created_by, archived, created_at, updated_at) \
+ VALUES (?, ?, ?, 'delegation', ?, ?, 0, ?, ?)",
+ )
+ .bind(&thread.id)
+ .bind(&thread.kwant_id)
+ .bind(&thread.title)
+ .bind(&thread.team_id)
+ .bind(&thread.created_by)
+ .bind(now)
+ .bind(now)
+ .execute(&mut *tx)
+ .await?;
+ let delegation = Delegation {
+ id: Uuid::new_v4().to_string(),
+ thread_id: thread.id.clone(),
+ lead_kwant_id: input.lead_kwant_id.clone(),
+ specialist_kwant_id: input.specialist_kwant_id.clone(),
+ origin_channel_id: input.origin_channel_id.clone(),
+ origin_kwant_id: input.origin_kwant_id.clone(),
+ origin_thread_id: input.origin_thread_id.clone(),
+ task: input.task.clone(),
+ title,
+ status: "queued".into(),
+ continue_lead: input.continue_lead,
+ depth: input.depth,
+ result_message_id: None,
+ error: None,
+ follow_up_at: input.follow_up_at,
+ followed_up: false,
+ created_at: now,
+ started_at: None,
+ ended_at: None,
+ };
+ sqlx::query(
+ "INSERT INTO delegations (id, thread_id, lead_kwant_id, specialist_kwant_id, origin_channel_id, origin_kwant_id, \
+ origin_thread_id, task, title, status, continue_lead, depth, follow_up_at, created_at) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, ?)",
+ )
+ .bind(&delegation.id)
+ .bind(&delegation.thread_id)
+ .bind(&delegation.lead_kwant_id)
+ .bind(&delegation.specialist_kwant_id)
+ .bind(&delegation.origin_channel_id)
+ .bind(&delegation.origin_kwant_id)
+ .bind(&delegation.origin_thread_id)
+ .bind(&delegation.task)
+ .bind(&delegation.title)
+ .bind(delegation.continue_lead)
+ .bind(delegation.depth)
+ .bind(delegation.follow_up_at)
+ .bind(now)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok((thread, delegation))
+ }
+
+ pub async fn get_delegation(&self, id: &str) -> Result<Option<Delegation>, DbError> {
+ Ok(sqlx::query_as::<_, Delegation>("SELECT * FROM delegations WHERE id = ?")
+ .bind(id)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ pub async fn delegation_for_thread(&self, thread_id: &str) -> Result<Option<Delegation>, DbError> {
+ Ok(sqlx::query_as::<_, Delegation>(
+ "SELECT * FROM delegations WHERE thread_id = ? ORDER BY created_at DESC LIMIT 1",
+ )
+ .bind(thread_id)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ /// Newest first; `lead` and `status` narrow it down.
+ pub async fn list_delegations(&self, lead: Option<&str>, status: Option<&str>, limit: i64) -> Result<Vec<Delegation>, DbError> {
+ Ok(sqlx::query_as::<_, Delegation>(
+ "SELECT * FROM delegations WHERE (? IS NULL OR lead_kwant_id = ?) AND (? IS NULL OR status = ?) \
+ ORDER BY created_at DESC, rowid DESC LIMIT ?",
+ )
+ .bind(lead)
+ .bind(lead)
+ .bind(status)
+ .bind(status)
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ pub async fn count_open_delegations(&self, lead: &str) -> Result<i64, DbError> {
+ let (n,): (i64,) = sqlx::query_as(
+ "SELECT COUNT(*) FROM delegations WHERE lead_kwant_id = ? AND status IN ('queued', 'running')",
+ )
+ .bind(lead)
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(n)
+ }
+
+ pub async fn mark_delegation_running(&self, id: &str) -> Result<bool, DbError> {
+ let res = sqlx::query("UPDATE delegations SET status = 'running', started_at = ? WHERE id = ? AND status = 'queued'")
+ .bind(Utc::now())
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected() > 0)
+ }
+
+ /// Ends an open delegation; `false` if it was already over (e.g. cancelled meanwhile).
+ pub async fn finish_delegation(
+ &self,
+ id: &str,
+ status: &str,
+ error: Option<&str>,
+ result_message_id: Option<&str>,
+ ) -> Result<bool, DbError> {
+ let res = sqlx::query(
+ "UPDATE delegations SET status = ?, error = ?, result_message_id = COALESCE(?, result_message_id), ended_at = ? \
+ WHERE id = ? AND status IN ('queued', 'running')",
+ )
+ .bind(status)
+ .bind(error)
+ .bind(result_message_id)
+ .bind(Utc::now())
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected() > 0)
+ }
+
+ pub async fn set_delegation_result_message(&self, id: &str, message_id: &str) -> Result<(), DbError> {
+ sqlx::query("UPDATE delegations SET result_message_id = ? WHERE id = ?")
+ .bind(message_id)
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// Open delegations whose follow-up time has passed and that got no follow-up yet; marks them.
+ pub async fn take_due_follow_ups(&self, now: DateTime<Utc>) -> Result<Vec<Delegation>, DbError> {
+ let due = sqlx::query_as::<_, Delegation>(
+ "SELECT * FROM delegations WHERE status IN ('queued', 'running') AND followed_up = 0 \
+ AND follow_up_at IS NOT NULL AND follow_up_at <= ? ORDER BY follow_up_at",
+ )
+ .bind(now)
+ .fetch_all(&self.pool)
+ .await?;
+ for d in &due {
+ sqlx::query("UPDATE delegations SET followed_up = 1 WHERE id = ?")
+ .bind(&d.id)
+ .execute(&self.pool)
+ .await?;
+ }
+ 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')",
+ )
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(open)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn titles_are_one_short_line() {
+ assert_eq!(clean_title(" Fix\nthe build "), "Fix the build");
+ let long = "x".repeat(300);
+ let t = clean_title(&long);
+ assert_eq!(t.chars().count(), MAX_TITLE_CHARS);
+ assert!(t.ends_with('…'));
+ }
+}
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index 32aef6ef..ed4b78c7 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -998,6 +998,8 @@ mod tests {
tool_calls: None,
tokens_used: 10,
created_at: None,
+ thread_id: None,
+ meta: None,
},
Message {
id: "m2".into(),
@@ -1010,6 +1012,8 @@ mod tests {
tool_calls: None,
tokens_used: 20,
created_at: None,
+ thread_id: None,
+ meta: None,
},
],
model_override: None,
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index 8c341b4d..4c9de06d 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -39,6 +39,12 @@ pub enum RuntimeEvent {
TurnStarted {
kwant_id: String,
context_id: Option<String>,
+ /// This turn; matches `turn_id` on the turn's streamed events.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ turn_id: Option<String>,
+ /// Set when the turn runs in a thread (then `context_id` is the thread id too).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ thread_id: Option<String>,
},
/// A kwant's turn is over, however it ended: "completed", "failed" or "cancelled".
#[serde(rename = "turn_ended", alias = "TurnEnded")]
@@ -46,6 +52,41 @@ pub enum RuntimeEvent {
kwant_id: String,
context_id: Option<String>,
outcome: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ turn_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ thread_id: Option<String>,
+ },
+ /// A turn is waiting for a free slot: its agent already runs as many turns as allowed
+ /// (`reason` "agent_busy") or the whole server does ("server_busy"). It starts on its own,
+ /// with `turn_started`; it is never dropped. `position` is 1 for the next to start.
+ #[serde(rename = "turn_queued", alias = "TurnQueued")]
+ TurnQueued {
+ turn_id: String,
+ kwant_id: String,
+ context_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ thread_id: Option<String>,
+ position: usize,
+ reason: String,
+ },
+ /// A thread was created, renamed or archived.
+ #[serde(rename = "thread_updated", alias = "ThreadUpdated")]
+ ThreadUpdated { thread: Value },
+ /// A delegation changed state; `delegation` is the whole record (see `crate::db::threads`).
+ #[serde(rename = "delegation_updated", alias = "DelegationUpdated")]
+ DelegationUpdated { delegation: Value },
+ /// kwnt wrote a message outside a streamed turn (delegation notes and results); `message` is
+ /// the saved message, with `channel_id` / `direct_kwant_id` / `thread_id` saying which chat.
+ #[serde(rename = "message_added", alias = "MessageAdded")]
+ MessageAdded { message: Value },
+ /// An event from inside one turn, tagged with the turn and its chat. On the SSE wire it is
+ /// the inner event with `turn_id`, `kwant_id`, `context_id` and `thread_id` added at the top
+ /// level (see [`RuntimeEvent::to_wire`]), so clients that ignore the tags still work.
+ #[serde(rename = "scoped")]
+ Scoped {
+ tag: TurnTag,
+ event: Box<RuntimeEvent>,
},
/// A turn moved to another profile of the same engine because the first ran out of quota
/// or was signed out. `class` is "quota" or "auth".
@@ -153,6 +194,46 @@ pub enum RuntimeEvent {
},
}
+/// Which turn and chat an event belongs to.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
+pub struct TurnTag {
+ pub turn_id: String,
+ pub kwant_id: String,
+ /// Channel id, kwant id (direct chat) or thread id.
+ pub context_id: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub thread_id: Option<String>,
+}
+
+impl RuntimeEvent {
+ /// The JSON sent to SSE clients.
+ pub fn to_wire(&self) -> Value {
+ match self {
+ RuntimeEvent::Scoped { tag, event } => {
+ let mut v = event.to_wire();
+ if let Value::Object(map) = &mut v {
+ map.insert("turn_id".into(), Value::String(tag.turn_id.clone()));
+ map.entry("kwant_id").or_insert_with(|| Value::String(tag.kwant_id.clone()));
+ map.insert("context_id".into(), Value::String(tag.context_id.clone()));
+ if let Some(t) = &tag.thread_id {
+ map.insert("thread_id".into(), Value::String(t.clone()));
+ }
+ }
+ v
+ }
+ other => serde_json::to_value(other).unwrap_or(Value::Null),
+ }
+ }
+
+ /// The event without its turn tag.
+ pub fn unscoped(&self) -> &RuntimeEvent {
+ match self {
+ RuntimeEvent::Scoped { event, .. } => event.unscoped(),
+ other => other,
+ }
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RoutingCandidate {
pub id: String,
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 1b3bf89e..89f0ab7a 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -34,7 +34,8 @@ const AGENT_SEARCH_LIMIT: i64 = 20;
/// Longest notification body.
pub const NOTIFY_BODY_CHARS: usize = 200;
const WEBHOOK_TIMEOUT: Duration = Duration::from_secs(5);
-pub const NOTIFY_KINDS: [&str; 3] = ["turn_finished", "approval_needed", "routine_failed"];
+pub const NOTIFY_KINDS: [&str; 5] =
+ ["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled"];
const MASK: &str = "••••••••";
fn error(status: StatusCode, message: impl Into<String>) -> Response {
@@ -143,6 +144,21 @@ pub fn memory_block(memories: &[Memory], with_tools: bool) -> String {
pub struct SelfScope {
pub kwant_id: String,
pub kwant_name: String,
+ /// The chat the turn runs in; delegation tools are offered only when it is known.
+ pub origin: Option<TurnOrigin>,
+}
+
+/// Where a turn runs, for the delegation tools: results go back to this chat.
+#[derive(Clone, Debug, Default)]
+pub struct TurnOrigin {
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ pub team_id: Option<String>,
+ /// The chat's members, when it has a member list: the only agents the lead may delegate to.
+ pub member_ids: Vec<String>,
+ /// 0 in user chats, 1 in a delegation thread, …
+ pub depth: i64,
}
/// The synthetic http MCP server a turn reaches its own tools through. The token travels as a
@@ -177,7 +193,45 @@ impl ToolApprover for SelfToolsApprover {
}
}
-fn tool_list() -> Value {
+fn tool_list(scope: &SelfScope) -> Value {
+ let mut tools = memory_tools();
+ if scope.origin.is_some() {
+ if let Some(list) = tools.as_array_mut() {
+ list.extend(delegation_tools());
+ }
+ }
+ tools
+}
+
+fn delegation_tools() -> Vec<Value> {
+ vec![
+ json!({
+ "name": "delegate",
+ "description": "Hand a task to another agent (a specialist). It works on it in its own thread in the background while you and the user carry on; its result is posted to this chat and you get a turn to continue. Use it for longer, self-contained work that fits another agent's role. Write the task so it stands on its own.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "to": {"type": "string", "description": "The agent's name"},
+ "task": {"type": "string", "description": "What to do and what to report back (max 8000 characters)"},
+ "title": {"type": "string", "description": "A short title for the task"},
+ },
+ "required": ["to", "task"],
+ },
+ }),
+ json!({
+ "name": "delegation_status",
+ "description": "See your delegated tasks: one by id, or your latest 10.",
+ "inputSchema": {"type": "object", "properties": {"id": {"type": "string"}}},
+ }),
+ json!({
+ "name": "delegation_cancel",
+ "description": "Stop one of your delegated tasks by its id.",
+ "inputSchema": {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]},
+ }),
+ ]
+}
+
+fn memory_tools() -> Value {
json!([
{
"name": "search_history",
@@ -308,7 +362,7 @@ pub async fn self_endpoint(
}),
),
"ping" => rpc_result(id, json!({})),
- "tools/list" => rpc_result(id, json!({ "tools": tool_list() })),
+ "tools/list" => rpc_result(id, json!({ "tools": tool_list(&scope) })),
"tools/call" => {
let args = &msg["params"]["arguments"];
let name = msg["params"]["name"].as_str().unwrap_or("");
@@ -401,6 +455,9 @@ async fn call_tool(
Err(_) => ("database error".into(), true),
}
}
+ "delegate" => super::delegation::tool_delegate(state, scope, args).await,
+ "delegation_status" => super::delegation::tool_status(state, scope, args).await,
+ "delegation_cancel" => super::delegation::tool_cancel(state, scope, args).await,
_ => (format!("Unknown tool {name}."), true),
}
}
@@ -840,19 +897,30 @@ async fn place(state: &AppState, context_id: Option<&str>) -> (Option<String>, S
match context_id {
Some(id) => match state.db.get_channel(id).await.ok().flatten() {
Some(c) => (Some(c.id), format!("#{}", c.name)),
- None => (None, "your direct chat".into()),
+ None => match state.db.get_thread(id).await.ok().flatten() {
+ Some(t) => (None, format!("the thread “{}”", clip(&t.title, 60))),
+ None => (None, "your direct chat".into()),
+ },
},
None => (None, "a chat".into()),
}
}
async fn notification_for(state: &AppState, event: &RuntimeEvent) -> Option<Notification> {
- match event {
+ match event.unscoped() {
RuntimeEvent::TurnEnded {
kwant_id,
context_id,
outcome,
+ thread_id,
+ ..
} if outcome == "completed" => {
+ // A delegated task reports with delegation_finished instead
+ if let Some(t) = thread_id {
+ if state.db.delegation_for_thread(t).await.ok().flatten().is_some() {
+ return None;
+ }
+ }
let name = kwant_name(state, kwant_id).await;
let (channel_id, where_) = place(state, context_id.as_deref()).await;
Some(Notification {
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
new file mode 100644
index 00000000..911754da
--- /dev/null
+++ b/src/server/delegation.rs
@@ -0,0 +1,702 @@
+//! Threads and delegations: an agent's extra conversations, and a lead handing a task to a
+//! specialist that runs in its own thread in the background and reports back to the chat it came
+//! from. See `design-A.md` (batch 2) for the API and SSE contract.
+
+use super::routes::{scope_for, try_kwant_turn, TurnOpts};
+use super::AppState;
+use crate::db::models::{Kwant, MessageExtra, NewMessage};
+use crate::db::threads::{Delegation, NewDelegation, Thread, MAX_TASK_CHARS};
+use crate::drivers::RuntimeEvent;
+use axum::{
+ extract::{Path, Query, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ Json,
+};
+use chrono::Utc;
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+/// A specialist may delegate once more; deeper chains are refused (no loops, bounded cost).
+pub const MAX_DEPTH: i64 = 2;
+/// Unfinished delegations one lead may have at a time.
+pub const MAX_OPEN_PER_LEAD: i64 = 5;
+/// How much of the specialist's reply is copied into the origin chat; the thread keeps it all.
+pub const RESULT_CHARS: usize = 8000;
+pub const FOLLOW_UP_SETTING: &str = "delegation_follow_up_minutes";
+pub const DEFAULT_FOLLOW_UP_MINUTES: i64 = 15;
+pub const MAX_FOLLOW_UP_MINUTES: i64 = 24 * 60;
+
+fn error(status: StatusCode, message: impl Into<String>) -> Response {
+ (status, Json(json!({ "error": message.into() }))).into_response()
+}
+
+fn internal() -> Response {
+ StatusCode::INTERNAL_SERVER_ERROR.into_response()
+}
+
+fn clip(text: &str, max: usize) -> String {
+ if text.chars().count() <= max {
+ return text.to_string();
+ }
+ let mut out: String = text.chars().take(max.saturating_sub(1)).collect();
+ out.push('…');
+ out
+}
+
+/// Minutes after which an unfinished delegation gets one "still working" note; 0 turns it off.
+pub async fn follow_up_minutes(state: &AppState) -> i64 {
+ state
+ .db
+ .get_setting(FOLLOW_UP_SETTING)
+ .await
+ .ok()
+ .flatten()
+ .and_then(|v| v.parse::<i64>().ok())
+ .map(|m| m.clamp(0, MAX_FOLLOW_UP_MINUTES))
+ .unwrap_or(DEFAULT_FOLLOW_UP_MINUTES)
+}
+
+fn emit_delegation(state: &AppState, d: &Delegation) {
+ let _ = state.event_sender.send(RuntimeEvent::DelegationUpdated {
+ delegation: serde_json::to_value(d).unwrap_or(Value::Null),
+ });
+}
+
+fn emit_thread(state: &AppState, t: &Thread) {
+ let _ = state.event_sender.send(RuntimeEvent::ThreadUpdated { thread: serde_json::to_value(t).unwrap_or(Value::Null) });
+}
+
+/// Posts a message from kwnt or an agent into the chat a delegation came from.
+async fn post_to_origin(
+ state: &AppState,
+ d: &Delegation,
+ role: &str,
+ sender: &str,
+ text: String,
+ meta: Value,
+) -> Option<String> {
+ let msg = NewMessage {
+ channel_id: d.origin_channel_id.clone(),
+ direct_kwant_id: d.origin_kwant_id.clone(),
+ sender_role: role.into(),
+ sender_id: sender.into(),
+ text,
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let extra = MessageExtra { thread_id: d.origin_thread_id.clone(), meta: Some(meta) };
+ let saved = state.db.insert_message_with(&msg, &extra).await.ok()?;
+ if let Some(t) = &d.origin_thread_id {
+ let _ = state.db.touch_thread(t).await;
+ }
+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or(Value::Null) });
+ Some(saved.id)
+}
+
+fn meta(kind: &str, d: &Delegation, specialist: &str) -> Value {
+ json!({
+ "kind": kind,
+ "delegation_id": d.id,
+ "thread_id": d.thread_id,
+ "specialist_id": d.specialist_kwant_id,
+ "specialist_name": specialist,
+ "lead_id": d.lead_kwant_id,
+ "status": d.status,
+ "title": d.title,
+ })
+}
+
+async fn name_of(state: &AppState, id: &str) -> String {
+ state.db.get_kwant(id).await.ok().flatten().map(|k| k.name).unwrap_or_else(|| "An agent".into())
+}
+
+// Starting
+
+/// Where a delegation's result goes: exactly one of a channel, the lead's direct chat or a thread.
+#[derive(Debug, Clone, Default)]
+pub struct Origin {
+ pub channel_id: Option<String>,
+ pub kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+}
+
+pub struct StartRequest {
+ pub lead: Kwant,
+ pub specialist: Kwant,
+ pub task: String,
+ pub title: Option<String>,
+ pub origin: Origin,
+ pub continue_lead: bool,
+ /// Depth of the chat the lead is in (0 for user chats).
+ pub origin_depth: i64,
+ /// Agents the lead may delegate to, when its chat has a member list.
+ pub allowed: Option<Vec<String>>,
+}
+
+/// Checks a request, creates the thread and the delegation, and starts the specialist's turn
+/// in the background. Returns at once; the error is a message fit for the user or the agent.
+pub async fn start(state: &AppState, req: StartRequest) -> Result<Delegation, (StatusCode, String)> {
+ let bad = |m: &str| Err((StatusCode::BAD_REQUEST, m.to_string()));
+ if req.lead.id == req.specialist.id {
+ return bad("An agent can't delegate to itself.");
+ }
+ let task = req.task.trim();
+ if task.is_empty() {
+ return bad("task is required");
+ }
+ if task.chars().count() > MAX_TASK_CHARS {
+ return bad(&format!("task is longer than {MAX_TASK_CHARS} characters"));
+ }
+ if req.origin_depth + 1 > MAX_DEPTH {
+ return bad("This task was already delegated; it can't be delegated further.");
+ }
+ if let Some(allowed) = &req.allowed {
+ if !allowed.iter().any(|id| id == &req.specialist.id) {
+ return Err((StatusCode::FORBIDDEN, format!("{} isn't in this chat.", req.specialist.name)));
+ }
+ }
+ let o = &req.origin;
+ let set = [&o.channel_id, &o.kwant_id, &o.thread_id].iter().filter(|x| x.is_some()).count();
+ if set != 1 {
+ return bad("give exactly one of channel_id, kwant_id or thread_id");
+ }
+ // The origin must exist, and a direct chat or thread origin must be the lead's own
+ let team_id = if let Some(cid) = &o.channel_id {
+ let channel = state.db.get_channel(cid).await.ok().flatten().ok_or((StatusCode::NOT_FOUND, "channel not found".into()))?;
+ match channel.name.strip_prefix("team-") {
+ Some(name) => state.db.list_teams().await.unwrap_or_default().into_iter().find(|t| t.name.eq_ignore_ascii_case(name)).map(|t| t.id),
+ None => None,
+ }
+ } else if let Some(kid) = &o.kwant_id {
+ if kid != &req.lead.id {
+ return bad("kwant_id must be the lead's own direct chat");
+ }
+ None
+ } else {
+ let tid = o.thread_id.as_deref().unwrap_or_default();
+ let thread = state.db.get_thread(tid).await.ok().flatten().ok_or((StatusCode::NOT_FOUND, "thread not found".into()))?;
+ if thread.kwant_id != req.lead.id {
+ return bad("thread_id must be one of the lead's own threads");
+ }
+ thread.team_id
+ };
+ let open = state.db.count_open_delegations(&req.lead.id).await.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "database error".into()))?;
+ if open >= MAX_OPEN_PER_LEAD {
+ return Err((
+ StatusCode::TOO_MANY_REQUESTS,
+ format!("{} already has {open} unfinished delegations; wait for one to finish.", req.lead.name),
+ ));
+ }
+ let minutes = follow_up_minutes(state).await;
+ let title = req.title.as_deref().map(str::trim).filter(|t| !t.is_empty()).unwrap_or(task);
+ let (thread, d) = state
+ .db
+ .create_delegation(&NewDelegation {
+ lead_kwant_id: req.lead.id.clone(),
+ specialist_kwant_id: req.specialist.id.clone(),
+ origin_channel_id: o.channel_id.clone(),
+ origin_kwant_id: o.kwant_id.clone(),
+ origin_thread_id: o.thread_id.clone(),
+ team_id,
+ task: task.to_string(),
+ title: title.to_string(),
+ continue_lead: req.continue_lead,
+ depth: req.origin_depth + 1,
+ follow_up_at: (minutes > 0).then(|| Utc::now() + chrono::Duration::minutes(minutes)),
+ })
+ .await
+ .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "database error".into()))?;
+
+ // The task opens the thread, from the lead, so the specialist's history shows who asked
+ let task_msg = NewMessage {
+ channel_id: None,
+ direct_kwant_id: None,
+ sender_role: "kwant".into(),
+ sender_id: req.lead.name.clone(),
+ text: task.to_string(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let _ = state
+ .db
+ .insert_message_with(&task_msg, &MessageExtra { thread_id: Some(thread.id.clone()), meta: None })
+ .await;
+ post_to_origin(
+ state,
+ &d,
+ "system",
+ "kwnt",
+ format!("{} asked {} to work on “{}”. It runs in its own thread; the result will be posted here.", req.lead.name, req.specialist.name, d.title),
+ meta("delegation_started", &d, &req.specialist.name),
+ )
+ .await;
+ emit_thread(state, &thread);
+ emit_delegation(state, &d);
+ tracing::info!(delegation = %d.id, lead = %req.lead.id, specialist = %req.specialist.id, depth = d.depth, "delegation started");
+
+ let 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 });
+ 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) {
+ 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,
+ };
+ 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);
+ }
+ }
+ 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}",
+ lead = lead.name,
+ title = d.title,
+ task = d.task,
+ );
+ let outcome = try_kwant_turn(&scope, &specialist, prompt, TurnOpts::default()).await;
+ let outcome = match outcome {
+ Err(_) if job.token.is_cancelled() => Err("stopped".to_string()),
+ other => other,
+ };
+ drop(job);
+ finish(&state, &d, &specialist, outcome).await;
+}
+
+async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: Result<String, String>) {
+ let (status, error) = match &outcome {
+ Ok(_) => ("completed", None),
+ Err(e) if e == "stopped" => ("cancelled", Some("stopped by the user".to_string())),
+ Err(e) => ("failed", Some(clip(e, 500))),
+ };
+ // Someone may have cancelled it meanwhile; then the cancel already reported it
+ if !state.db.finish_delegation(&d.id, status, error.as_deref(), None).await.unwrap_or(false) {
+ return;
+ }
+ let Ok(Some(done)) = state.db.get_delegation(&d.id).await else {
+ return;
+ };
+ let text = match &outcome {
+ Ok(reply) => {
+ let full = reply.trim();
+ let mut text = clip(full, RESULT_CHARS);
+ if text.len() < full.len() {
+ text.push_str("\n\n(The full answer is in the delegation thread.)");
+ }
+ text
+ }
+ Err(_) if status == "cancelled" => format!("Stopped work on “{}”.", done.title),
+ Err(e) => format!("Couldn't finish “{}”: {}", done.title, clip(e, 500)),
+ };
+ let result_id = post_to_origin(state, &done, "kwant", &specialist.name, text, meta("delegation_result", &done, &specialist.name)).await;
+ if let Some(id) = &result_id {
+ let _ = state.db.set_delegation_result_message(&done.id, id).await;
+ }
+ let done = state.db.get_delegation(&d.id).await.ok().flatten().unwrap_or(done);
+ emit_delegation(state, &done);
+ tracing::info!(delegation = %done.id, status, "delegation finished");
+ let lead_name = name_of(state, &done.lead_kwant_id).await;
+ super::continuity::notify(
+ state,
+ super::continuity::Notification {
+ kind: "delegation_finished",
+ kwant_id: specialist.id.clone(),
+ kwant_name: specialist.name.clone(),
+ channel_id: done.origin_channel_id.clone(),
+ title: format!("{} finished a task for {lead_name}", specialist.name),
+ body: format!("“{}”: {status}.", clip(&done.title, 80)),
+ },
+ )
+ .await;
+ if let (Ok(reply), true) = (&outcome, done.continue_lead) {
+ continue_lead(state, &done, specialist, reply).await;
+ }
+}
+
+/// Gives the lead a turn in the origin chat with the result, so it can carry on with the request.
+async fn continue_lead(state: &AppState, d: &Delegation, specialist: &Kwant, reply: &str) {
+ let Ok(Some(lead)) = state.db.get_kwant(&d.lead_kwant_id).await else {
+ return;
+ };
+ let context = d.origin_context().unwrap_or(&lead.id).to_string();
+ let job = state.turns.start_job([context, d.id.clone()]);
+ let Ok(scope) = scope_for(state, &lead, d.origin_channel_id.clone(), d.origin_thread_id.clone(), &job, d.depth - 1).await else {
+ return;
+ };
+ let prompt = format!(
+ "{name} finished the task you delegated (“{title}”). Their result is in the chat above, quoted here:\n\n{result}\n\n\
+ Continue with what the user asked: use the result, and reply to the user. Don't repeat the whole result.",
+ name = specialist.name,
+ title = d.title,
+ result = clip(reply, 4000),
+ );
+ let _ = try_kwant_turn(&scope, &lead, prompt, TurnOpts::default()).await;
+}
+
+// Cancelling, follow-ups, restarts
+
+/// Stops a delegation and reports it; `None` if it was already over.
+pub async fn cancel(state: &AppState, id: &str) -> Option<Delegation> {
+ let d = state.db.get_delegation(id).await.ok().flatten()?;
+ state.turns.cancel(Some(&d.id));
+ if !state.db.finish_delegation(&d.id, "cancelled", Some("stopped by the user"), None).await.unwrap_or(false) {
+ return None;
+ }
+ let done = state.db.get_delegation(id).await.ok().flatten()?;
+ let specialist = name_of(state, &done.specialist_kwant_id).await;
+ if let Some(mid) = post_to_origin(
+ state,
+ &done,
+ "system",
+ "kwnt",
+ format!("Stopped {specialist}'s work on “{}”.", done.title),
+ meta("delegation_result", &done, &specialist),
+ )
+ .await
+ {
+ let _ = state.db.set_delegation_result_message(&done.id, &mid).await;
+ }
+ emit_delegation(state, &done);
+ Some(done)
+}
+
+/// A Stop for a thread also ends the delegation running in it.
+pub async fn cancel_thread_delegation(state: &AppState, thread_id: &str) {
+ if let Ok(Some(d)) = state.db.delegation_for_thread(thread_id).await {
+ if d.is_open() {
+ cancel(state, &d.id).await;
+ }
+ }
+}
+
+/// Posts one "still working" note for each delegation past its follow-up time. Called by the
+/// routines scheduler loop; no agent turn is started, so it costs nothing.
+pub async fn follow_ups(state: &AppState, now: chrono::DateTime<Utc>) -> usize {
+ let due = state.db.take_due_follow_ups(now).await.unwrap_or_default();
+ for d in &due {
+ let specialist = name_of(state, &d.specialist_kwant_id).await;
+ let minutes = (now - d.created_at).num_minutes().max(1);
+ let queued = d.status == "queued";
+ let text = if queued {
+ format!("“{}” is still waiting for {specialist}, who is busy with other work ({minutes} min so far).", d.title)
+ } else {
+ format!("{specialist} is still working on “{}” ({minutes} min so far). Open the thread to follow along or stop it.", d.title)
+ };
+ post_to_origin(state, d, "system", "kwnt", text, meta("delegation_stalled", d, &specialist)).await;
+ super::continuity::notify(
+ state,
+ super::continuity::Notification {
+ kind: "delegation_stalled",
+ kwant_id: d.specialist_kwant_id.clone(),
+ kwant_name: specialist.clone(),
+ channel_id: d.origin_channel_id.clone(),
+ title: format!("{specialist} is still on a delegated task"),
+ body: format!("“{}”: {minutes} min so far.", clip(&d.title, 80)),
+ },
+ )
+ .await;
+ }
+ due.len()
+}
+
+/// Delegations a restart cut short become `interrupted`, with a note where they came from.
+pub async fn interrupt_open(state: &AppState) {
+ let Ok(open) = state.db.interrupt_open_delegations().await else {
+ return;
+ };
+ for d in open {
+ let specialist = name_of(state, &d.specialist_kwant_id).await;
+ let Ok(Some(done)) = state.db.get_delegation(&d.id).await else {
+ continue;
+ };
+ post_to_origin(
+ state,
+ &done,
+ "system",
+ "kwnt",
+ format!("kwnt restarted before {specialist} finished “{}”. Ask again to restart it.", done.title),
+ meta("delegation_result", &done, &specialist),
+ )
+ .await;
+ }
+}
+
+// Routes
+
+pub async fn list_turns(State(state): State<AppState>) -> Response {
+ let (per_agent, global) = state.turns.limiter.limits();
+ Json(json!({ "turns": state.turns.active_turns(), "max_turns_per_agent": per_agent, "max_turns_global": global })).into_response()
+}
+
+#[derive(Deserialize)]
+pub struct ThreadsQuery {
+ #[serde(default)]
+ pub include_archived: Option<String>,
+}
+
+async fn thread_view(state: &AppState, t: &Thread) -> Value {
+ let mut v = serde_json::to_value(t).unwrap_or(Value::Null);
+ let delegation = state.db.delegation_for_thread(&t.id).await.ok().flatten();
+ let active: Vec<_> = state.turns.active_turns().into_iter().filter(|a| a.thread_id.as_deref() == Some(&t.id)).collect();
+ v["delegation"] = serde_json::to_value(delegation).unwrap_or(Value::Null);
+ v["active"] = serde_json::to_value(active).unwrap_or(Value::Null);
+ v
+}
+
+pub async fn list_threads(State(state): State<AppState>, Path(kwant_id): Path<String>, Query(q): Query<ThreadsQuery>) -> Response {
+ match state.db.get_kwant(&kwant_id).await {
+ Ok(Some(_)) => {}
+ Ok(None) => return error(StatusCode::NOT_FOUND, "agent not found"),
+ Err(_) => return internal(),
+ }
+ let archived = matches!(q.include_archived.as_deref(), Some("1" | "true"));
+ let Ok(threads) = state.db.list_threads(&kwant_id, archived, 200).await else {
+ return internal();
+ };
+ let mut out = Vec::with_capacity(threads.len());
+ for t in &threads {
+ out.push(thread_view(&state, t).await);
+ }
+ Json(out).into_response()
+}
+
+#[derive(Deserialize, Default)]
+pub struct NewThreadPayload {
+ pub title: Option<String>,
+}
+
+pub async fn create_thread(
+ State(state): State<AppState>,
+ Path(kwant_id): Path<String>,
+ body: Option<Json<NewThreadPayload>>,
+) -> Response {
+ match state.db.get_kwant(&kwant_id).await {
+ Ok(Some(_)) => {}
+ Ok(None) => return error(StatusCode::NOT_FOUND, "agent not found"),
+ Err(_) => return internal(),
+ }
+ let title = body.and_then(|b| b.0.title).filter(|t| !t.trim().is_empty()).unwrap_or_else(|| "New conversation".into());
+ match state.db.create_thread(&kwant_id, &title, "chat", None, "user").await {
+ Ok(t) => {
+ emit_thread(&state, &t);
+ (StatusCode::CREATED, Json(thread_view(&state, &t).await)).into_response()
+ }
+ Err(_) => internal(),
+ }
+}
+
+pub async fn get_thread(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ match state.db.get_thread(&id).await {
+ Ok(Some(t)) => Json(thread_view(&state, &t).await).into_response(),
+ Ok(None) => error(StatusCode::NOT_FOUND, "thread not found"),
+ Err(_) => internal(),
+ }
+}
+
+#[derive(Deserialize)]
+pub struct PatchThreadPayload {
+ pub title: Option<String>,
+ pub archived: Option<bool>,
+}
+
+pub async fn patch_thread(State(state): State<AppState>, Path(id): Path<String>, Json(p): Json<PatchThreadPayload>) -> Response {
+ if p.title.as_deref().is_some_and(|t| t.trim().is_empty()) {
+ return error(StatusCode::BAD_REQUEST, "title can't be empty");
+ }
+ match state.db.update_thread(&id, p.title.as_deref(), p.archived).await {
+ Ok(Some(t)) => {
+ emit_thread(&state, &t);
+ Json(thread_view(&state, &t).await).into_response()
+ }
+ Ok(None) => error(StatusCode::NOT_FOUND, "thread not found"),
+ Err(_) => internal(),
+ }
+}
+
+pub async fn thread_messages(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ match state.db.get_thread(&id).await {
+ Ok(Some(_)) => {}
+ Ok(None) => return error(StatusCode::NOT_FOUND, "thread not found"),
+ Err(_) => return internal(),
+ }
+ match state.db.list_messages(&id, 100).await {
+ Ok(m) => Json(m).into_response(),
+ Err(_) => internal(),
+ }
+}
+
+pub async fn cancel_thread(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ match state.db.get_thread(&id).await {
+ Ok(Some(_)) => {}
+ Ok(None) => return error(StatusCode::NOT_FOUND, "thread not found"),
+ Err(_) => return internal(),
+ }
+ let cancelled = state.turns.cancel(Some(&id));
+ cancel_thread_delegation(&state, &id).await;
+ Json(json!({ "status": "cancelled", "cancelled": cancelled })).into_response()
+}
+
+#[derive(Deserialize)]
+pub struct DelegatePayload {
+ pub lead_kwant_id: String,
+ pub specialist_kwant_id: String,
+ pub task: String,
+ pub title: Option<String>,
+ pub channel_id: Option<String>,
+ pub kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ pub continue_lead: Option<bool>,
+}
+
+pub async fn create_delegation(State(state): State<AppState>, Json(p): Json<DelegatePayload>) -> Response {
+ let (lead, specialist) = match (state.db.get_kwant(&p.lead_kwant_id).await, state.db.get_kwant(&p.specialist_kwant_id).await) {
+ (Ok(Some(l)), Ok(Some(s))) => (l, s),
+ (Ok(_), Ok(_)) => return error(StatusCode::NOT_FOUND, "agent not found"),
+ _ => return internal(),
+ };
+ let origin_depth = match &p.thread_id {
+ Some(t) => state.db.delegation_for_thread(t).await.ok().flatten().map(|d| d.depth).unwrap_or(0),
+ None => 0,
+ };
+ let req = StartRequest {
+ lead,
+ specialist,
+ task: p.task,
+ title: p.title,
+ origin: Origin { channel_id: p.channel_id, kwant_id: p.kwant_id, thread_id: p.thread_id },
+ continue_lead: p.continue_lead.unwrap_or(true),
+ origin_depth,
+ allowed: None,
+ };
+ match start(&state, req).await {
+ Ok(d) => (StatusCode::ACCEPTED, Json(d)).into_response(),
+ Err((status, m)) => error(status, m),
+ }
+}
+
+#[derive(Deserialize)]
+pub struct DelegationsQuery {
+ pub lead_kwant_id: Option<String>,
+ pub status: Option<String>,
+}
+
+pub async fn list_delegations(State(state): State<AppState>, Query(q): Query<DelegationsQuery>) -> Response {
+ match state.db.list_delegations(q.lead_kwant_id.as_deref(), q.status.as_deref(), 50).await {
+ Ok(d) => Json(d).into_response(),
+ Err(_) => internal(),
+ }
+}
+
+pub async fn get_delegation(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ match state.db.get_delegation(&id).await {
+ Ok(Some(d)) => Json(d).into_response(),
+ Ok(None) => error(StatusCode::NOT_FOUND, "delegation not found"),
+ Err(_) => internal(),
+ }
+}
+
+pub async fn cancel_delegation(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ match state.db.get_delegation(&id).await {
+ Ok(Some(_)) => {}
+ Ok(None) => return error(StatusCode::NOT_FOUND, "delegation not found"),
+ Err(_) => return internal(),
+ }
+ cancel(&state, &id).await;
+ match state.db.get_delegation(&id).await {
+ Ok(Some(d)) => Json(d).into_response(),
+ _ => internal(),
+ }
+}
+
+// Agent tools
+
+/// What a lead's `delegate` tool call becomes; the scope says who is calling and from where.
+pub async fn tool_delegate(state: &AppState, scope: &super::continuity::SelfScope, args: &Value) -> (String, bool) {
+ let Some(origin) = &scope.origin else {
+ return ("Delegation isn't available in this turn.".into(), true);
+ };
+ let to = args["to"].as_str().map(str::trim).unwrap_or("").trim_start_matches('@');
+ let task = args["task"].as_str().unwrap_or("").to_string();
+ let kwants = state.db.list_kwants().await.unwrap_or_default();
+ let Some(lead) = kwants.iter().find(|k| k.id == scope.kwant_id).cloned() else {
+ return ("Unknown agent.".into(), true);
+ };
+ let pool: Vec<&Kwant> = if origin.member_ids.is_empty() {
+ kwants.iter().filter(|k| k.id != lead.id).collect()
+ } else {
+ kwants.iter().filter(|k| k.id != lead.id && origin.member_ids.contains(&k.id)).collect()
+ };
+ let Some(specialist) = kwants.iter().find(|k| k.id == to || k.name.eq_ignore_ascii_case(to)).cloned() else {
+ let names: Vec<&str> = pool.iter().map(|k| k.name.as_str()).collect();
+ return (format!("No agent named '{to}'. You can delegate to: {}.", names.join(", ")), true);
+ };
+ let req = StartRequest {
+ lead,
+ specialist,
+ task,
+ title: args["title"].as_str().map(str::to_string),
+ origin: Origin {
+ channel_id: origin.channel_id.clone(),
+ kwant_id: origin.direct_kwant_id.clone(),
+ thread_id: origin.thread_id.clone(),
+ },
+ continue_lead: true,
+ origin_depth: origin.depth,
+ allowed: (!origin.member_ids.is_empty()).then(|| origin.member_ids.clone()),
+ };
+ match start(state, req).await {
+ Ok(d) => (
+ format!(
+ "Delegated as [{}]. It runs in the background; its result will be posted to this chat and you'll get a turn to continue. \
+ Tell the user who is working on it, then carry on.",
+ d.id
+ ),
+ false,
+ ),
+ Err((_, m)) => (m, true),
+ }
+}
+
+pub async fn tool_status(state: &AppState, scope: &super::continuity::SelfScope, args: &Value) -> (String, bool) {
+ let list = match args["id"].as_str().filter(|s| !s.is_empty()) {
+ Some(id) => match state.db.get_delegation(id).await.ok().flatten() {
+ Some(d) if d.lead_kwant_id == scope.kwant_id => vec![d],
+ _ => return ("No delegation of yours has that id.".into(), true),
+ },
+ None => state.db.list_delegations(Some(&scope.kwant_id), None, 10).await.unwrap_or_default(),
+ };
+ if list.is_empty() {
+ return ("You have no delegations.".into(), false);
+ }
+ let mut out = String::new();
+ for d in list {
+ let who = name_of(state, &d.specialist_kwant_id).await;
+ out.push_str(&format!("- [{}] {who}: “{}” — {}", d.id, clip(&d.title, 80), d.status));
+ if let Some(e) = &d.error {
+ out.push_str(&format!(" ({})", clip(e, 120)));
+ }
+ out.push('\n');
+ }
+ (out, false)
+}
+
+pub async fn tool_cancel(state: &AppState, scope: &super::continuity::SelfScope, args: &Value) -> (String, bool) {
+ let Some(id) = args["id"].as_str().filter(|s| !s.is_empty()) else {
+ return ("id is required".into(), true);
+ };
+ match state.db.get_delegation(id).await.ok().flatten() {
+ Some(d) if d.lead_kwant_id == scope.kwant_id => match cancel(state, id).await {
+ Some(_) => (format!("Stopped [{id}]."), false),
+ None => (format!("[{id}] had already finished ({}).", d.status), false),
+ },
+ _ => ("No delegation of yours has that id.".into(), true),
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index d08357b9..53df2f9a 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -10,6 +10,8 @@ pub mod profile_turn;
pub mod auth;
pub mod continuity;
pub mod scheduler;
+pub mod turns;
+pub mod delegation;
use crate::broker::PermissionBroker;
use crate::config::Config;
@@ -25,7 +27,6 @@ use axum::{
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{broadcast, Mutex};
-use tokio_util::sync::CancellationToken;
#[derive(Clone)]
pub struct AppState {
@@ -35,7 +36,8 @@ pub struct AppState {
pub broker: PermissionBroker,
pub router: LayaRouter,
pub event_sender: broadcast::Sender<RuntimeEvent>,
- pub active_cancellations: Arc<Mutex<HashMap<String, CancellationToken>>>,
+ /// Running dispatches (their cancel tokens) and turns, and the caps on concurrent turns.
+ pub turns: turns::TurnRegistry,
pub sandbox_manager: Arc<SandboxManager>,
pub browser_controllers: Arc<Mutex<HashMap<String, BrowserController>>>,
pub browser_service: Arc<crate::sandbox::service::BrowserService>,
@@ -75,7 +77,7 @@ impl AppState {
broker,
router,
event_sender,
- active_cancellations: Arc::new(Mutex::new(HashMap::new())),
+ turns: turns::TurnRegistry::default(),
sandbox_manager,
browser_controllers,
browser_service,
@@ -165,6 +167,14 @@ pub fn create_router(state: AppState) -> Router {
)
.route("/api/routines/:id/run", post(scheduler::run_now))
.route("/api/routines/:id/runs", get(scheduler::runs))
+ .route("/api/turns", get(delegation::list_turns))
+ .route("/api/kwants/:id/threads", get(delegation::list_threads).post(delegation::create_thread))
+ .route("/api/threads/:id", get(delegation::get_thread).patch(delegation::patch_thread))
+ .route("/api/threads/:id/messages", get(delegation::thread_messages))
+ .route("/api/threads/:id/cancel", post(delegation::cancel_thread))
+ .route("/api/delegations", get(delegation::list_delegations).post(delegation::create_delegation))
+ .route("/api/delegations/:id", get(delegation::get_delegation))
+ .route("/api/delegations/:id/cancel", post(delegation::cancel_delegation))
.route("/api/events", get(sse::sse_handler))
.fallback(crate::embedded::static_handler)
.layer(axum::middleware::from_fn_with_state(state.clone(), auth::guard))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index f22cd3bf..7db0ea4f 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -282,36 +282,32 @@ pub async fn delete_team(
#[derive(Debug, Deserialize)]
pub struct CancelPayload {
+ pub turn_id: Option<String>,
pub session_id: Option<String>,
+ pub thread_id: Option<String>,
pub channel_id: Option<String>,
pub team_id: Option<String>,
pub kwant_id: Option<String>,
}
+/// Stops the dispatches for one turn, message, thread, channel, team or direct chat (the first
+/// given), or everything with no body. A direct chat's Stop leaves that agent's threads running.
pub async fn cancel_chat(
State(state): State<AppState>,
body: axum::body::Bytes,
) -> Result<Json<serde_json::Value>, StatusCode> {
- let mut tokens = state.active_cancellations.lock().await;
- let maybe_session_id = if !body.is_empty() {
- serde_json::from_slice::<CancelPayload>(&body)
- .ok()
- .and_then(|p| p.session_id.or(p.channel_id).or(p.team_id).or(p.kwant_id))
+ let key = if !body.is_empty() {
+ serde_json::from_slice::<CancelPayload>(&body).ok().and_then(|p| {
+ p.turn_id.or(p.session_id).or(p.thread_id).or(p.channel_id).or(p.team_id).or(p.kwant_id)
+ })
} else {
None
};
-
- if let Some(session_id) = maybe_session_id {
- if let Some(token) = tokens.remove(&session_id) {
- token.cancel();
- }
- } else {
- for (_, token) in tokens.drain() {
- token.cancel();
- }
+ let cancelled = state.turns.cancel(key.as_deref());
+ if let Some(thread_id) = &key {
+ super::delegation::cancel_thread_delegation(&state, thread_id).await;
}
-
- Ok(Json(json!({ "status": "cancelled" })))
+ Ok(Json(json!({ "status": "cancelled", "cancelled": cancelled })))
}
#[derive(Debug, Deserialize)]
@@ -319,6 +315,9 @@ pub struct SendChatPayload {
pub channel_id: Option<String>,
pub kwant_id: Option<String>,
pub team_id: Option<String>,
+ /// Send into this thread of its agent (then `channel_id`, `kwant_id` and `team_id` are ignored).
+ #[serde(default)]
+ pub thread_id: Option<String>,
pub prompt: String,
pub sender_id: String,
}
@@ -367,16 +366,128 @@ fn routing_candidates(members: &[Kwant]) -> Vec<RoutingCandidate> {
}
/// Everything a kwant turn needs besides the speaker and the prompt, shared by handoff turns.
-struct TurnScope {
- state: AppState,
- channel_id: Option<String>,
- kwant_id: Option<String>,
- team_keys: Option<(String, String)>,
- team_context: Option<crate::drivers::TeamContext>,
- workspace_dir: Option<std::path::PathBuf>,
+pub(super) struct TurnScope {
+ pub(super) state: AppState,
+ pub(super) channel_id: Option<String>,
+ pub(super) kwant_id: Option<String>,
+ /// Set for turns in a thread; then `channel_id` and `kwant_id` are `None`.
+ pub(super) thread_id: Option<String>,
+ pub(super) team_keys: Option<(String, String)>,
+ pub(super) team_context: Option<crate::drivers::TeamContext>,
+ pub(super) workspace_dir: Option<std::path::PathBuf>,
/// Kwants in this chat that a speaker may hand the turn to with an @mention.
- teammates: Vec<Kwant>,
- cancel_token: CancellationToken,
+ pub(super) teammates: Vec<Kwant>,
+ pub(super) cancel_token: CancellationToken,
+ /// The dispatch this turn belongs to (see [`super::turns`]); its turns are added as keys.
+ pub(super) job_id: String,
+ /// How many delegations deep this chat is: 0 for user chats, 1 in a delegation thread, …
+ pub(super) delegation_depth: i64,
+}
+
+impl TurnScope {
+ /// The chat's id: channel, thread, or the direct chat's kwant (falling back to `speaker`).
+ pub(super) fn context_id(&self, speaker: &Kwant) -> String {
+ self.channel_id
+ .clone()
+ .or_else(|| self.thread_id.clone())
+ .or_else(|| self.kwant_id.clone())
+ .unwrap_or_else(|| speaker.id.clone())
+ }
+
+ 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(),
+ sender_role: sender_role.into(),
+ sender_id: sender_id.into(),
+ text,
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ }
+ }
+
+ fn extra(&self) -> MessageExtra {
+ MessageExtra { thread_id: self.thread_id.clone(), meta: None }
+ }
+
+ /// Saves a message in this chat (moving a thread up its list).
+ pub(super) async fn save(&self, msg: &NewMessage, meta: Option<serde_json::Value>) -> Option<Message> {
+ let extra = MessageExtra { meta, ..self.extra() };
+ let saved = self.state.db.insert_message_with(msg, &extra).await.ok();
+ if let Some(t) = &self.thread_id {
+ let _ = self.state.db.touch_thread(t).await;
+ }
+ saved
+ }
+}
+
+/// Builds the scope for a turn in a channel, a thread or `kwant`'s direct chat (when both are
+/// `None`): its team, workspace and members, like a user message there would get.
+pub(super) async fn scope_for(
+ state: &AppState,
+ kwant: &Kwant,
+ channel_id: Option<String>,
+ thread_id: Option<String>,
+ job: &super::turns::JobGuard,
+ delegation_depth: i64,
+) -> Result<TurnScope, String> {
+ let all_kwants = state.db.list_kwants().await.map_err(|_| "could not load agents".to_string())?;
+ let channel = match &channel_id {
+ Some(id) => Some(
+ state.db.get_channel(id).await.ok().flatten().ok_or_else(|| "the chat's channel no longer exists".to_string())?,
+ ),
+ None => None,
+ };
+ let thread = match &thread_id {
+ Some(id) => Some(state.db.get_thread(id).await.ok().flatten().ok_or_else(|| "the thread no longer exists".to_string())?),
+ None => None,
+ };
+ let teams = state.db.list_teams().await.unwrap_or_default();
+ let team = match (&thread, channel.as_ref().and_then(|c| c.name.strip_prefix("team-"))) {
+ (Some(t), _) => t.team_id.as_ref().and_then(|id| teams.iter().find(|x| &x.id == id).cloned()),
+ (None, Some(name)) => teams.iter().find(|t| t.name.eq_ignore_ascii_case(name)).cloned(),
+ _ => None,
+ };
+ // Threads are one agent's own conversation: nobody to hand the turn to
+ let member_ids: Vec<String> = match (&thread, &team, &channel) {
+ (Some(_), _, _) => Vec::new(),
+ (None, Some(t), _) => serde_json::from_str(&t.member_kwants).unwrap_or_default(),
+ (None, None, Some(c)) if c.name == "general" => all_kwants.iter().map(|k| k.id.clone()).collect(),
+ (None, None, Some(c)) => serde_json::from_str(&c.member_kwants).unwrap_or_default(),
+ (None, None, None) => Vec::new(),
+ };
+ let teammates: Vec<Kwant> = member_ids.iter().filter_map(|id| all_kwants.iter().find(|k| &k.id == id).cloned()).collect();
+ let workspace_dir = match &team {
+ Some(t) => Some(
+ crate::tools::resolve_or_prepare_workspace(&state.config.data_dir, &t.name, t.workspace_path.as_deref(), t.repo_url.as_deref())
+ .await,
+ ),
+ None => None,
+ };
+ Ok(TurnScope {
+ state: state.clone(),
+ kwant_id: if channel_id.is_none() && thread_id.is_none() { Some(kwant.id.clone()) } else { None },
+ channel_id,
+ thread_id,
+ team_keys: team.as_ref().map(|t| (t.id.clone(), t.name.clone())),
+ team_context: team.as_ref().map(team_context),
+ workspace_dir,
+ teammates,
+ cancel_token: job.token.clone(),
+ job_id: job.id.clone(),
+ delegation_depth,
+ })
+}
+
+fn team_context(t: &Team) -> crate::drivers::TeamContext {
+ crate::drivers::TeamContext {
+ id: t.id.clone(),
+ name: t.name.clone(),
+ description: t.description.clone(),
+ workspace_path: t.workspace_path.clone(),
+ repo_url: t.repo_url.clone(),
+ }
}
/// Max follow-up turns kwants may trigger by @mentioning each other for one user message.
@@ -387,44 +498,33 @@ fn execute_single_turn(
state: AppState,
target_kwant: Kwant,
payload: SendChatPayload,
- cancel_token: CancellationToken,
- session_id: String,
+ job: super::turns::JobGuard,
team_keys: Option<(String, String)>,
- kwant_id: Option<String>,
team_context: Option<crate::drivers::TeamContext>,
workspace_dir: Option<std::path::PathBuf>,
teammates: Vec<Kwant>,
) {
- let active_cancellations = state.active_cancellations.clone();
let scope = TurnScope {
channel_id: payload.channel_id.clone(),
- kwant_id: kwant_id.or_else(|| payload.kwant_id.clone()),
+ kwant_id: payload.kwant_id.clone(),
+ thread_id: None,
team_keys,
team_context,
workspace_dir,
teammates,
- cancel_token,
+ cancel_token: job.token.clone(),
+ job_id: job.id.clone(),
+ delegation_depth: 0,
state,
};
let prompt = payload.prompt.clone();
tokio::spawn(async move {
+ // Ends the job (its cancel keys) when the turn and its handoffs are done
+ let _job = job;
if let Some(reply) = run_kwant_turn(&scope, &target_kwant, prompt.clone(), TurnOpts::default()).await {
run_handoffs(&scope, std::slice::from_ref(&target_kwant.id), &[(target_kwant.clone(), reply)], &prompt).await;
}
-
- let mut tokens = active_cancellations.lock().await;
- tokens.remove(&session_id);
- if let Some(cid) = &scope.channel_id {
- tokens.remove(cid);
- }
- if let Some(kid) = &scope.kwant_id {
- tokens.remove(kid);
- }
- if let Some((team_id, team_name)) = &scope.team_keys {
- tokens.remove(team_id);
- tokens.remove(team_name);
- }
});
}
@@ -438,65 +538,15 @@ pub(super) async fn run_routine_turn(
channel_id: Option<String>,
prompt: String,
) -> Result<Option<String>, String> {
- let all_kwants = state.db.list_kwants().await.map_err(|_| "could not load agents".to_string())?;
- let channel = match &channel_id {
- Some(id) => Some(
- state.db.get_channel(id).await.ok().flatten().ok_or_else(|| "the routine's channel no longer exists".to_string())?,
- ),
- None => None,
- };
- let team = match channel.as_ref().and_then(|c| c.name.strip_prefix("team-")) {
- Some(name) => state.db.list_teams().await.unwrap_or_default().into_iter().find(|t| t.name.eq_ignore_ascii_case(name)),
- None => None,
- };
- let member_ids: Vec<String> = match (&team, &channel) {
- (Some(t), _) => serde_json::from_str(&t.member_kwants).unwrap_or_default(),
- (None, Some(c)) if c.name == "general" => all_kwants.iter().map(|k| k.id.clone()).collect(),
- (None, Some(c)) => serde_json::from_str(&c.member_kwants).unwrap_or_default(),
- (None, None) => Vec::new(),
- };
- let teammates: Vec<Kwant> = member_ids.iter().filter_map(|id| all_kwants.iter().find(|k| &k.id == id).cloned()).collect();
- let workspace_dir = match &team {
- Some(t) => Some(
- crate::tools::resolve_or_prepare_workspace(&state.config.data_dir, &t.name, t.workspace_path.as_deref(), t.repo_url.as_deref())
- .await,
- ),
- None => None,
- };
- let cancel_token = CancellationToken::new();
- let keys: Vec<String> = match &channel_id {
- Some(c) => vec![c.clone()],
- None => vec![kwant.id.clone()],
- };
- {
- let mut tokens = state.active_cancellations.lock().await;
- for key in &keys {
- tokens.insert(key.clone(), cancel_token.clone());
- }
- }
- let scope = TurnScope {
- state: state.clone(),
- kwant_id: if channel_id.is_none() { Some(kwant.id.clone()) } else { None },
- channel_id,
- team_keys: team.as_ref().map(|t| (t.id.clone(), t.name.clone())),
- team_context: team.as_ref().map(|t| crate::drivers::TeamContext {
- id: t.id.clone(),
- name: t.name.clone(),
- description: t.description.clone(),
- workspace_path: t.workspace_path.clone(),
- repo_url: t.repo_url.clone(),
- }),
- workspace_dir,
- teammates,
- cancel_token: cancel_token.clone(),
- };
+ let context_key = channel_id.clone().unwrap_or_else(|| kwant.id.clone());
+ let job = state.turns.start_job([context_key.clone()]);
+ let scope = scope_for(state, kwant, channel_id, None, &job, 0).await?;
let reply = try_kwant_turn(&scope, kwant, prompt.clone(), TurnOpts::default()).await;
- let outcome = match reply {
+ match reply {
Ok(text) => {
- let context_id = keys[0].clone();
let reply_id = state
.db
- .list_messages(&context_id, 10)
+ .list_messages(&context_key, 10)
.await
.unwrap_or_default()
.into_iter()
@@ -506,14 +556,9 @@ pub(super) async fn run_routine_turn(
run_handoffs(&scope, std::slice::from_ref(&kwant.id), &[(kwant.clone(), text)], &prompt).await;
Ok(reply_id)
}
- Err(_) if cancel_token.is_cancelled() => Err("stopped by the user".into()),
+ Err(_) if job.token.is_cancelled() => Err("stopped by the user".into()),
Err(why) => Err(format!("the agent's turn failed: {why}")),
- };
- let mut tokens = state.active_cancellations.lock().await;
- for key in &keys {
- tokens.remove(key);
}
- outcome
}
/// Lets teammates that kwants @mentioned in `replies` answer in turn, so kwants can delegate to each other.
@@ -541,11 +586,7 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(
}
let events = scope.state.event_sender.clone();
- let context_id = scope
- .channel_id
- .clone()
- .or_else(|| scope.kwant_id.clone())
- .unwrap_or_else(|| replies[0].0.id.clone());
+ let context_id = scope.context_id(&replies[0].0);
let total = |queue_len: usize, done: usize| (1 + done + queue_len).min(1 + MAX_HANDOFFS);
let _ = events.send(RuntimeEvent::DiscussionStarted {
team_id: context_id,
@@ -709,7 +750,7 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, use
/// Per-turn tweaks for turns that kwnt drives itself (team discussions).
#[derive(Default)]
-struct TurnOpts {
+pub(super) struct TurnOpts {
/// Saved as the message's `reasoning_content` instead of the driver's reasoning.
label: Option<String>,
/// Text checked for a URL to open in the bot browser; defaults to the prompt.
@@ -734,29 +775,49 @@ async fn run_kwant_turn(
const MAX_FAILURE_CHARS: usize = 500;
/// [`run_kwant_turn`], but a failed turn says why: the driver's error or the provider's refusal.
-async fn try_kwant_turn(
+/// The turn first waits for a slot under the per-agent and server-wide caps (see [`super::turns`]).
+pub(super) async fn try_kwant_turn(
scope: &TurnScope,
target_kwant: &Kwant,
prompt: String,
opts: TurnOpts,
) -> Result<String, String> {
- let context_id = scope
- .channel_id
- .clone()
- .or_else(|| scope.kwant_id.clone())
- .unwrap_or_else(|| target_kwant.id.clone());
- let _ = scope.state.event_sender.send(RuntimeEvent::TurnStarted {
+ let tag = crate::drivers::events::TurnTag {
+ turn_id: uuid::Uuid::new_v4().to_string(),
kwant_id: target_kwant.id.clone(),
- context_id: Some(context_id.clone()),
- });
- // Sends turn_ended even if this future is dropped mid-turn
+ context_id: scope.context_id(target_kwant),
+ thread_id: scope.thread_id.clone(),
+ };
+ let turns = &scope.state.turns;
+ turns.add_keys(&scope.job_id, std::slice::from_ref(&tag.turn_id));
+ // Sends turn_ended even if this future is dropped, queued or mid-turn
let mut ended = TurnEndedGuard {
sender: scope.state.event_sender.clone(),
- kwant_id: target_kwant.id.clone(),
- context_id,
+ turns: turns.clone(),
+ tag: tag.clone(),
outcome: "cancelled",
};
- let reply = run_kwant_turn_inner(scope, target_kwant, prompt, opts).await;
+ let Some(_slot) = turns.acquire(&tag, &scope.cancel_token, &scope.state.event_sender).await else {
+ return Err("stopped by the user".into());
+ };
+ turns.set_turn(super::turns::ActiveTurn {
+ turn_id: tag.turn_id.clone(),
+ kwant_id: tag.kwant_id.clone(),
+ context_id: tag.context_id.clone(),
+ thread_id: tag.thread_id.clone(),
+ state: "running".into(),
+ since: chrono::Utc::now(),
+ });
+ let _ = scope.state.event_sender.send(RuntimeEvent::TurnStarted {
+ kwant_id: target_kwant.id.clone(),
+ context_id: Some(tag.context_id.clone()),
+ turn_id: Some(tag.turn_id.clone()),
+ thread_id: tag.thread_id.clone(),
+ });
+ if scope.cancel_token.is_cancelled() {
+ return Err("stopped by the user".into());
+ }
+ let reply = run_kwant_turn_inner(scope, target_kwant, prompt, opts, &tag).await;
ended.outcome = match (&reply, scope.cancel_token.is_cancelled()) {
(Ok(_), _) => "completed",
(Err(_), true) => "cancelled",
@@ -790,29 +851,46 @@ fn scrub_urls(text: &str) -> String {
struct TurnEndedGuard {
sender: tokio::sync::broadcast::Sender<RuntimeEvent>,
- kwant_id: String,
- context_id: String,
+ turns: super::turns::TurnRegistry,
+ tag: crate::drivers::events::TurnTag,
outcome: &'static str,
}
impl Drop for TurnEndedGuard {
fn drop(&mut self) {
+ self.turns.end_turn(&self.tag.turn_id);
+ let tag = std::mem::take(&mut self.tag);
let _ = self.sender.send(RuntimeEvent::TurnEnded {
- kwant_id: std::mem::take(&mut self.kwant_id),
- context_id: Some(std::mem::take(&mut self.context_id)),
+ kwant_id: tag.kwant_id,
+ context_id: Some(tag.context_id),
outcome: self.outcome.to_string(),
+ turn_id: Some(tag.turn_id),
+ thread_id: tag.thread_id,
});
}
}
+/// Sends a turn's events tagged with the turn and its chat.
+struct TurnEvents {
+ sender: tokio::sync::broadcast::Sender<RuntimeEvent>,
+ tag: crate::drivers::events::TurnTag,
+}
+
+impl TurnEvents {
+ fn send(&self, event: RuntimeEvent) {
+ let _ = self.sender.send(RuntimeEvent::Scoped { tag: self.tag.clone(), event: Box::new(event) });
+ }
+}
+
async fn run_kwant_turn_inner(
scope: &TurnScope,
target_kwant: &Kwant,
prompt: String,
opts: TurnOpts,
+ tag: &crate::drivers::events::TurnTag,
) -> Result<String, String> {
let state = &scope.state;
- let event_broadcast = state.event_sender.clone();
+ let event_broadcast = TurnEvents { sender: state.event_sender.clone(), tag: tag.clone() };
let db = state.db.clone();
let router = state.router.clone();
let channel_id = scope.channel_id.clone();
@@ -838,7 +916,7 @@ async fn run_kwant_turn_inner(
let target_model = route.selected_model;
let effort_level = route.effort_level;
- let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta(format!(
+ event_broadcast.send(RuntimeEvent::ThinkingDelta(format!(
"🔮 Laya Router: model='{}', effort='{}' ({:.0}% conf) — {}",
target_model,
effort_level,
@@ -846,11 +924,7 @@ async fn run_kwant_turn_inner(
route.reasoning
)));
- let context_id = channel_id
- .as_deref()
- .or(kwant_id.as_deref())
- .unwrap_or(&target_kwant.id)
- .to_string();
+ let context_id = tag.context_id.clone();
let history = db.list_messages(&context_id, 20).await.unwrap_or_default();
@@ -878,7 +952,7 @@ async fn run_kwant_turn_inner(
let target_url_opt = detect_url_with_context(nav_prompt, active_browser_url.as_deref());
if let Some(target_url) = target_url_opt {
- let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta(format!(
+ event_broadcast.send(RuntimeEvent::ThinkingDelta(format!(
"🌐 Navigating bot browser to {}...",
target_url
)));
@@ -887,14 +961,14 @@ async fn run_kwant_turn_inner(
Ok(nav) => {
let page_text = ctrl.extract_content().await.unwrap_or_default();
let preview = truncate_chars(&page_text, 3000);
- let _ = event_broadcast.send(RuntimeEvent::BrowserNavigated {
+ event_broadcast.send(RuntimeEvent::BrowserNavigated {
team_id: sandbox_target.clone(),
url: nav.url.clone(),
title: nav.title.clone(),
status_code: nav.status_code,
});
if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {
- let _ = event_broadcast.send(RuntimeEvent::BrowserScreenshot {
+ event_broadcast.send(RuntimeEvent::BrowserScreenshot {
team_id: sandbox_target.clone(),
url: nav.url.clone(),
image_base64: b64,
@@ -917,7 +991,7 @@ async fn run_kwant_turn_inner(
Err(crate::sandbox::BrowserError::Navigation(reason)) => {
let shown_url = ctrl.current_url.lock().await.clone().unwrap_or_else(|| target_url.clone());
if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {
- let _ = event_broadcast.send(RuntimeEvent::BrowserScreenshot {
+ event_broadcast.send(RuntimeEvent::BrowserScreenshot {
team_id: sandbox_target.clone(),
url: shown_url,
image_base64: b64,
@@ -958,7 +1032,18 @@ async fn run_kwant_turn_inner(
};
// The agents' own continuity tools, for engines that can call MCP tools
let self_scope = (engine.is_some() && super::continuity::agent_tools_enabled(state).await).then(|| {
- super::continuity::SelfScope { kwant_id: target_kwant.id.clone(), kwant_name: target_kwant.name.clone() }
+ super::continuity::SelfScope {
+ kwant_id: target_kwant.id.clone(),
+ kwant_name: target_kwant.name.clone(),
+ origin: Some(super::continuity::TurnOrigin {
+ channel_id: channel_id.clone(),
+ direct_kwant_id: kwant_id.clone(),
+ thread_id: scope.thread_id.clone(),
+ team_id: scope.team_context.as_ref().map(|t| t.id.clone()),
+ member_ids: scope.teammates.iter().map(|k| k.id.clone()).collect(),
+ depth: scope.delegation_depth,
+ }),
+ }
});
let mcp_turn = super::mcp_runtime::prepare_turn_with_self(
state,
@@ -1047,7 +1132,7 @@ async fn run_kwant_turn_inner(
_ => false,
};
side_effects |= visible;
- let _ = event_broadcast.send(event);
+ event_broadcast.send(event);
}
None => break,
}
@@ -1069,7 +1154,7 @@ async fn run_kwant_turn_inner(
let next = attempts.get(i + 1).and_then(|n| n.as_ref());
if let (Some(from), Some(to), false) = (profile, next, side_effects) {
let notice = super::profile_turn::switch_notice(from, to, &failure);
- let _ = event_broadcast.send(RuntimeEvent::ProfileSwitched {
+ event_broadcast.send(RuntimeEvent::ProfileSwitched {
kwant_id: target_kwant.id.clone(),
from_profile_id: from.id.clone(),
from_name: from.name.clone(),
@@ -1078,7 +1163,7 @@ async fn run_kwant_turn_inner(
class: failure.class.as_str().into(),
retry_at: failure.retry_at,
});
- let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta(notice.clone()));
+ event_broadcast.send(RuntimeEvent::ThinkingDelta(notice.clone()));
tracing::info!(kwant = %target_kwant.id, from = %from.id, to = %to.id, class = failure.class.as_str(), "turn moved to another profile");
notices.push(notice);
continue;
@@ -1094,8 +1179,8 @@ async fn run_kwant_turn_inner(
failure.detail
),
};
- let _ = event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));
- let _ = event_broadcast.send(RuntimeEvent::TurnComplete {
+ 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()),
@@ -1111,14 +1196,14 @@ async fn run_kwant_turn_inner(
}
match &result {
Ok(Err(e)) => {
- let _ = event_broadcast.send(RuntimeEvent::Error {
+ event_broadcast.send(RuntimeEvent::Error {
code: "driver_error".into(),
message: e.to_string(),
kwant_id: Some(target_kwant.id.clone()),
});
}
Err(_) => {
- let _ = event_broadcast.send(RuntimeEvent::Error {
+ event_broadcast.send(RuntimeEvent::Error {
code: "driver_crashed".into(),
message: "the model driver stopped unexpectedly".into(),
kwant_id: Some(target_kwant.id.clone()),
@@ -1127,7 +1212,7 @@ async fn run_kwant_turn_inner(
Ok(Ok(_)) => {}
}
if let Some((tokens, duration_ms)) = held_complete {
- let _ = event_broadcast.send(RuntimeEvent::TurnComplete {
+ event_broadcast.send(RuntimeEvent::TurnComplete {
tokens,
duration_ms,
kwant_id: Some(target_kwant.id.clone()),
@@ -1152,20 +1237,14 @@ async fn run_kwant_turn_inner(
})
};
if cancelled {
- let _ = event_broadcast.send(RuntimeEvent::ThinkingDelta("⏹️ Cancelled by user".into()));
+ event_broadcast.send(RuntimeEvent::ThinkingDelta("⏹️ Cancelled by user".into()));
return Err("stopped by the user".into());
} else if let Some(text) = gave_up {
let msg = NewMessage {
- channel_id: channel_id.clone(),
- direct_kwant_id: kwant_id.clone(),
- sender_role: "kwant".into(),
- sender_id: target_kwant.name.clone(),
- text: text.clone(),
reasoning_content: with_notices(opts.label.clone()),
- tool_calls: None,
- tokens_used: 0,
+ ..scope.message("kwant", &target_kwant.name, text.clone())
};
- let _ = db.insert_message(&msg).await;
+ scope.save(&msg, None).await;
return Err(text);
} else if let Some(Ok(Ok(output))) = driver_result {
// Post-turn sync: If bot response outputs a URL, sync navigation so the user sees it in Sandbox VM
@@ -1174,14 +1253,14 @@ async fn run_kwant_turn_inner(
let curr = ctrl.current_url.lock().await.clone().unwrap_or_default();
if curr != bot_url && !bot_url.contains("localhost") && !bot_url.contains("127.0.0.1") {
if let Ok(nav) = ctrl.navigate(&bot_url).await {
- let _ = event_broadcast.send(RuntimeEvent::BrowserNavigated {
+ event_broadcast.send(RuntimeEvent::BrowserNavigated {
team_id: sandbox_target.clone(),
url: nav.url.clone(),
title: nav.title.clone(),
status_code: nav.status_code,
});
if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {
- let _ = event_broadcast.send(RuntimeEvent::BrowserScreenshot {
+ event_broadcast.send(RuntimeEvent::BrowserScreenshot {
team_id: sandbox_target.clone(),
url: nav.url.clone(),
image_base64: b64,
@@ -1209,16 +1288,12 @@ async fn run_kwant_turn_inner(
};
if let Some((text, reasoning_content)) = saved {
let asst_msg = NewMessage {
- channel_id: channel_id.clone(),
- direct_kwant_id: kwant_id.clone(),
- sender_role: "kwant".into(),
- sender_id: target_kwant.name.clone(),
- text,
reasoning_content,
tool_calls: mcp_records.map(serde_json::Value::Array),
tokens_used: output.tokens_used as i64,
+ ..scope.message("kwant", &target_kwant.name, text)
};
- let _ = db.insert_message(&asst_msg).await;
+ scope.save(&asst_msg, None).await;
}
return Ok(output.text);
}
@@ -1234,6 +1309,9 @@ pub async fn send_chat(
State(state): State<AppState>,
Json(payload): Json<SendChatPayload>,
) -> Result<Json<serde_json::Value>, StatusCode> {
+ if let Some(thread_id) = payload.thread_id.clone() {
+ return send_to_thread(state, thread_id, payload).await;
+ }
let all_kwants = state
.db
.list_kwants()
@@ -1388,22 +1466,13 @@ pub async fn send_chat(
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
- let cancel_token = CancellationToken::new();
- let session_id = saved_user_msg.id.clone();
- {
- let mut tokens = state.active_cancellations.lock().await;
- tokens.insert(session_id.clone(), cancel_token.clone());
- if let Some(cid) = &payload.channel_id {
- tokens.insert(cid.clone(), cancel_token.clone());
- }
- if let Some(kid) = &payload.kwant_id {
- tokens.insert(kid.clone(), cancel_token.clone());
- }
- if let Some(ref team) = target_team {
- tokens.insert(team.id.clone(), cancel_token.clone());
- tokens.insert(team.name.clone(), cancel_token.clone());
- }
+ // Stop answers to this message, chat or team; other dispatches (threads, other chats) keep going
+ let mut keys = vec![saved_user_msg.id.clone()];
+ keys.extend(payload.channel_id.iter().chain(payload.kwant_id.iter()).cloned());
+ if let Some(team) = target_team.as_ref().or(active_team.as_ref()) {
+ keys.extend([team.id.clone(), team.name.clone()]);
}
+ let job = state.turns.start_job(keys);
// Branch: Team routing vs Single Kwant routing
if let Some(team) = target_team {
@@ -1450,15 +1519,12 @@ pub async fn send_chat(
target_kwant.name, target_kwant.title, reason
)));
- let kwant_id_cleanup = payload.kwant_id.clone();
execute_single_turn(
state.clone(),
target_kwant.clone(),
payload,
- cancel_token,
- session_id,
+ job,
Some((team.id.clone(), team.name.clone())),
- kwant_id_cleanup,
active_team_context,
workspace_dir.clone(),
members.clone(),
@@ -1506,36 +1572,21 @@ pub async fn send_chat(
state: state.clone(),
channel_id: payload.channel_id.clone(),
kwant_id: payload.kwant_id.clone(),
+ thread_id: None,
team_keys: Some((team.id.clone(), team.name.clone())),
- team_context: Some(crate::drivers::TeamContext {
- id: team.id.clone(),
- name: team.name.clone(),
- description: team.description.clone(),
- workspace_path: team.workspace_path.clone(),
- repo_url: team.repo_url.clone(),
- }),
+ team_context: Some(team_context(&team)),
workspace_dir: workspace_dir.clone(),
teammates: members.clone(),
- cancel_token: cancel_token.clone(),
+ cancel_token: job.token.clone(),
+ job_id: job.id.clone(),
+ delegation_depth: 0,
};
let team_clone = team.clone();
let prompt = payload.prompt.clone();
- let session_id_clone = session_id.clone();
- let active_cancellations = state.active_cancellations.clone();
tokio::spawn(async move {
+ let _job = job;
run_discussion(&scope, &team_clone, planned, &prompt).await;
-
- let mut tokens = active_cancellations.lock().await;
- tokens.remove(&session_id_clone);
- if let Some(cid) = &scope.channel_id {
- tokens.remove(cid);
- }
- if let Some(kid) = &scope.kwant_id {
- tokens.remove(kid);
- }
- tokens.remove(&team_clone.id);
- tokens.remove(&team_clone.name);
});
Ok(Json(json!({
@@ -1616,15 +1667,12 @@ pub async fn send_chat(
.ok_or(StatusCode::BAD_REQUEST)?;
let team_keys = active_team.as_ref().map(|t| (t.id.clone(), t.name.clone()));
- let kwant_id_cleanup = payload.kwant_id.clone();
execute_single_turn(
state.clone(),
target_kwant.clone(),
payload,
- cancel_token,
- session_id,
+ job,
team_keys,
- kwant_id_cleanup,
active_team_context,
workspace_dir,
chat_teammates,
@@ -1638,6 +1686,51 @@ pub async fn send_chat(
}
}
+/// `/api/chat/send` into a thread: the thread's agent answers there, with only that thread's history.
+async fn send_to_thread(
+ state: AppState,
+ thread_id: String,
+ payload: SendChatPayload,
+) -> Result<Json<serde_json::Value>, StatusCode> {
+ let thread = state.db.get_thread(&thread_id).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?.ok_or(StatusCode::NOT_FOUND)?;
+ if thread.archived {
+ return Err(StatusCode::CONFLICT);
+ }
+ let kwant = state.db.get_kwant(&thread.kwant_id).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?.ok_or(StatusCode::NOT_FOUND)?;
+ let depth = match state.db.delegation_for_thread(&thread.id).await.ok().flatten() {
+ Some(d) => d.depth,
+ None => 0,
+ };
+ let user_msg = NewMessage {
+ channel_id: None,
+ direct_kwant_id: None,
+ sender_role: "user".into(),
+ sender_id: payload.sender_id.clone(),
+ text: payload.prompt.clone(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: payload.prompt.len() as i64 / 4,
+ };
+ let extra = MessageExtra { thread_id: Some(thread.id.clone()), meta: None };
+ let saved = state.db.insert_message_with(&user_msg, &extra).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ let _ = state.db.touch_thread(&thread.id).await;
+
+ let job = state.turns.start_job([saved.id.clone(), thread.id.clone()]);
+ let scope = scope_for(&state, &kwant, None, Some(thread.id.clone()), &job, depth).await.map_err(|_| StatusCode::NOT_FOUND)?;
+ let prompt = payload.prompt;
+ let target = kwant.clone();
+ tokio::spawn(async move {
+ let _job = job;
+ run_kwant_turn(&scope, &target, prompt, TurnOpts::default()).await;
+ });
+ Ok(Json(json!({
+ "status": "dispatched",
+ "user_message_id": saved.id,
+ "kwant": kwant.name,
+ "thread_id": thread.id,
+ })))
+}
+
#[derive(Debug, Deserialize)]
pub struct ResolveApprovalPayload {
pub decision: String, // "allow_once", "always_allow", "deny"
@@ -1690,6 +1783,12 @@ pub struct SettingsResponse {
/// "••••••••" when set: ntfy topics and webhook tokens are secrets.
pub notify_webhook_url: String,
pub notify_on: Vec<String>,
+ /// Turns one agent runs at once (in different chats/threads); more wait in a queue.
+ pub max_turns_per_agent: usize,
+ /// Turns the whole server runs at once.
+ pub max_turns_global: usize,
+ /// Minutes before an unfinished delegation gets a "still working" note; 0 = never.
+ pub delegation_follow_up_minutes: i64,
}
#[derive(Deserialize)]
@@ -1701,6 +1800,9 @@ pub struct SaveSettingsPayload {
/// https only; "" removes it, the mask keeps it.
pub notify_webhook_url: Option<String>,
pub notify_on: Option<Vec<String>>,
+ pub max_turns_per_agent: Option<usize>,
+ pub max_turns_global: Option<usize>,
+ pub delegation_follow_up_minutes: Option<i64>,
}
pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {
@@ -1727,14 +1829,38 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settings
codex_cli_path: codex_bin,
notify_webhook_url,
notify_on,
+ max_turns_per_agent: state.turns.limiter.limits().0,
+ max_turns_global: state.turns.limiter.limits().1,
+ delegation_follow_up_minutes: super::delegation::follow_up_minutes(&state).await,
}))
}
+/// Applies the saved turn limits (at startup); missing or bad values keep the defaults.
+pub async fn load_turn_limits(state: &AppState) {
+ use super::turns::*;
+ let read = |key: &'static str| async move { state.db.get_setting(key).await.ok().flatten().and_then(|v| v.parse::<usize>().ok()) };
+ let per_agent = read(PER_AGENT_SETTING).await.unwrap_or(DEFAULT_PER_AGENT).clamp(1, MAX_PER_AGENT);
+ let global = read(GLOBAL_SETTING).await.unwrap_or(DEFAULT_GLOBAL).clamp(1, MAX_GLOBAL);
+ state.turns.limiter.set_limits(per_agent, global);
+}
+
pub async fn save_settings(
State(state): State<AppState>,
Json(payload): Json<SaveSettingsPayload>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
- // Checked first, so a bad webhook URL saves nothing
+ use super::turns::{GLOBAL_SETTING, MAX_GLOBAL, MAX_PER_AGENT, PER_AGENT_SETTING};
+ let bad = |m: String| Err((StatusCode::BAD_REQUEST, Json(json!({ "error": m }))));
+ // Checked first, so a bad value saves nothing
+ if payload.max_turns_per_agent.is_some_and(|n| !(1..=MAX_PER_AGENT).contains(&n)) {
+ return bad(format!("max_turns_per_agent must be 1–{MAX_PER_AGENT}"));
+ }
+ if payload.max_turns_global.is_some_and(|n| !(1..=MAX_GLOBAL).contains(&n)) {
+ return bad(format!("max_turns_global must be 1–{MAX_GLOBAL}"));
+ }
+ let max_minutes = super::delegation::MAX_FOLLOW_UP_MINUTES;
+ if payload.delegation_follow_up_minutes.is_some_and(|m| !(0..=max_minutes).contains(&m)) {
+ return bad(format!("delegation_follow_up_minutes must be 0–{max_minutes}"));
+ }
if let Err(e) =
super::continuity::save_notify_settings(&state, payload.notify_webhook_url, payload.notify_on).await
{
@@ -1760,6 +1886,17 @@ pub async fn save_settings(
let _ = state.db.set_setting("ollama_url", &url).await;
}
}
+ if payload.max_turns_per_agent.is_some() || payload.max_turns_global.is_some() {
+ let (per_agent, global) = state.turns.limiter.limits();
+ let per_agent = payload.max_turns_per_agent.unwrap_or(per_agent);
+ let global = payload.max_turns_global.unwrap_or(global);
+ let _ = state.db.set_setting(PER_AGENT_SETTING, &per_agent.to_string()).await;
+ let _ = state.db.set_setting(GLOBAL_SETTING, &global.to_string()).await;
+ state.turns.limiter.set_limits(per_agent, global);
+ }
+ if let Some(m) = payload.delegation_follow_up_minutes {
+ let _ = state.db.set_setting(super::delegation::FOLLOW_UP_SETTING, &m.to_string()).await;
+ }
Ok(Json(json!({ "status": "saved" })))
}
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index d28076b6..4a9444e3 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -471,9 +471,12 @@ pub fn spawn(state: AppState, shutdown: CancellationToken) -> tokio::task::JoinH
}
}
let _ = state.db.delete_orphan_routines().await;
+ super::routes::load_turn_limits(&state).await;
+ super::delegation::interrupt_open(&state).await;
reschedule_all(&state, Utc::now()).await;
loop {
tick(&state, Utc::now()).await;
+ super::delegation::follow_ups(&state, Utc::now()).await;
let sleep = match state.db.next_routine_due().await.ok().flatten() {
Some(at) => (at - Utc::now())
.to_std()
diff --git a/src/server/sse.rs b/src/server/sse.rs
index 4ab81264..ab74e94b 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -14,7 +14,7 @@ pub async fn sse_handler(
let rx = state.event_sender.subscribe();
let stream = BroadcastStream::new(rx).filter_map(|msg| match msg {
Ok(event) => {
- let json_str = serde_json::to_string(&event).unwrap_or_default();
+ let json_str = event.to_wire().to_string();
Some(Ok(Event::default().data(json_str)))
}
Err(_) => None,
diff --git a/src/server/turns.rs b/src/server/turns.rs
new file mode 100644
index 00000000..f44a3a09
--- /dev/null
+++ b/src/server/turns.rs
@@ -0,0 +1,396 @@
+//! Running and waiting agent turns: cancellation per job and the per-agent / server-wide caps.
+//!
+//! A *job* is one dispatch (a user message with its handoffs or discussion, a routine run, a
+//! delegation). It has its own cancel token and the keys it answers to: its message id, the chat
+//! (channel, kwant or thread id), its team, its delegation. Stop for a key cancels every job that
+//! holds it, and a finished job removes only itself, so concurrent turns never clobber each other.
+//!
+//! Every turn takes a slot from the [`Limiter`]: at most `per_agent` turns per kwant and `global`
+//! overall. A turn that doesn't fit waits in FIFO order; it is never turned away.
+
+use crate::drivers::events::RuntimeEvent;
+use serde::Serialize;
+use std::collections::{HashMap, VecDeque};
+use std::sync::{Arc, Mutex};
+use tokio::sync::{broadcast, oneshot};
+use tokio_util::sync::CancellationToken;
+
+pub const DEFAULT_PER_AGENT: usize = 3;
+pub const DEFAULT_GLOBAL: usize = 6;
+pub const MAX_PER_AGENT: usize = 16;
+pub const MAX_GLOBAL: usize = 64;
+
+/// Setting keys for the caps.
+pub const PER_AGENT_SETTING: &str = "max_turns_per_agent";
+pub const GLOBAL_SETTING: &str = "max_turns_global";
+
+struct Job {
+ keys: Vec<String>,
+ token: CancellationToken,
+}
+
+/// A turn the UI can show: running, or waiting for a slot.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct ActiveTurn {
+ pub turn_id: String,
+ pub kwant_id: String,
+ pub context_id: String,
+ pub thread_id: Option<String>,
+ /// "queued" or "running".
+ pub state: String,
+ pub since: chrono::DateTime<chrono::Utc>,
+}
+
+#[derive(Default)]
+struct Inner {
+ jobs: HashMap<String, Job>,
+ turns: HashMap<String, ActiveTurn>,
+}
+
+/// Jobs, their cancel tokens and the turns they run.
+#[derive(Clone)]
+pub struct TurnRegistry {
+ inner: Arc<Mutex<Inner>>,
+ pub limiter: Limiter,
+}
+
+impl Default for TurnRegistry {
+ fn default() -> Self {
+ Self::new(DEFAULT_PER_AGENT, DEFAULT_GLOBAL)
+ }
+}
+
+/// Removes its job when dropped, however the job ends.
+pub struct JobGuard {
+ registry: TurnRegistry,
+ pub id: String,
+ pub token: CancellationToken,
+}
+
+impl Drop for JobGuard {
+ fn drop(&mut self) {
+ self.registry.finish_job(&self.id);
+ }
+}
+
+impl TurnRegistry {
+ pub fn new(per_agent: usize, global: usize) -> Self {
+ Self { inner: Default::default(), limiter: Limiter::new(per_agent, global) }
+ }
+
+ /// Registers a job under `keys`; empty keys are skipped.
+ pub fn start_job<I, S>(&self, keys: I) -> JobGuard
+ where
+ I: IntoIterator<Item = S>,
+ S: Into<String>,
+ {
+ let id = uuid::Uuid::new_v4().to_string();
+ let token = CancellationToken::new();
+ let mut keys: Vec<String> = keys.into_iter().map(Into::into).filter(|k: &String| !k.is_empty()).collect();
+ keys.push(id.clone());
+ self.lock().jobs.insert(id.clone(), Job { keys, token: token.clone() });
+ JobGuard { registry: self.clone(), id, token }
+ }
+
+ /// Adds keys to a running job (e.g. a delegation id once it exists).
+ pub fn add_keys(&self, job_id: &str, keys: &[String]) {
+ if let Some(job) = self.lock().jobs.get_mut(job_id) {
+ job.keys.extend(keys.iter().cloned());
+ }
+ }
+
+ fn finish_job(&self, id: &str) {
+ self.lock().jobs.remove(id);
+ }
+
+ /// Cancels every job holding `key` (or every job when `None`); returns how many.
+ pub fn cancel(&self, key: Option<&str>) -> usize {
+ let inner = self.lock();
+ let mut n = 0;
+ for job in inner.jobs.values() {
+ if key.is_none_or(|k| job.keys.iter().any(|j| j == k)) {
+ job.token.cancel();
+ n += 1;
+ }
+ }
+ n
+ }
+
+ pub fn has_job(&self, key: &str) -> bool {
+ self.lock().jobs.values().any(|j| j.keys.iter().any(|k| k == key))
+ }
+
+ pub fn set_turn(&self, turn: ActiveTurn) {
+ self.lock().turns.insert(turn.turn_id.clone(), turn);
+ }
+
+ pub fn end_turn(&self, turn_id: &str) {
+ self.lock().turns.remove(turn_id);
+ }
+
+ /// Running and waiting turns, oldest first.
+ pub fn active_turns(&self) -> Vec<ActiveTurn> {
+ let mut out: Vec<ActiveTurn> = self.lock().turns.values().cloned().collect();
+ out.sort_by(|a, b| a.since.cmp(&b.since).then_with(|| a.turn_id.cmp(&b.turn_id)));
+ out
+ }
+
+ fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
+ self.inner.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ /// Takes a slot for one turn of `kwant_id`, waiting in line if none is free. While it waits,
+ /// `turn_queued` is sent once. `None` if `cancel` fired first.
+ pub async fn acquire(
+ &self,
+ tag: &crate::drivers::events::TurnTag,
+ cancel: &CancellationToken,
+ events: &broadcast::Sender<RuntimeEvent>,
+ ) -> Option<Slot> {
+ let rx = match self.limiter.try_acquire(&tag.kwant_id) {
+ Ok(slot) => return Some(slot),
+ Err(wait) => wait,
+ };
+ self.set_turn(ActiveTurn {
+ turn_id: tag.turn_id.clone(),
+ kwant_id: tag.kwant_id.clone(),
+ context_id: tag.context_id.clone(),
+ thread_id: tag.thread_id.clone(),
+ state: "queued".into(),
+ since: chrono::Utc::now(),
+ });
+ let _ = events.send(RuntimeEvent::TurnQueued {
+ turn_id: tag.turn_id.clone(),
+ kwant_id: tag.kwant_id.clone(),
+ context_id: Some(tag.context_id.clone()),
+ thread_id: tag.thread_id.clone(),
+ position: rx.position,
+ reason: rx.reason.into(),
+ });
+ tokio::select! {
+ slot = rx.rx => slot.ok(),
+ _ = cancel.cancelled() => None,
+ }
+ }
+}
+
+/// One turn's place under the caps; frees it on drop.
+pub struct Slot {
+ limiter: Limiter,
+ kwant_id: String,
+}
+
+impl Drop for Slot {
+ fn drop(&mut self) {
+ self.limiter.release(&self.kwant_id);
+ }
+}
+
+/// Waiting for a slot.
+pub struct Wait {
+ rx: oneshot::Receiver<Slot>,
+ pub position: usize,
+ /// "agent_busy" or "server_busy".
+ pub reason: &'static str,
+}
+
+struct Waiter {
+ kwant_id: String,
+ tx: oneshot::Sender<Slot>,
+}
+
+struct LimiterState {
+ per_agent: usize,
+ global: usize,
+ running: HashMap<String, usize>,
+ total: usize,
+ waiting: VecDeque<Waiter>,
+}
+
+impl LimiterState {
+ fn fits(&self, kwant_id: &str) -> bool {
+ self.total < self.global && self.running.get(kwant_id).copied().unwrap_or(0) < self.per_agent
+ }
+
+ fn take(&mut self, kwant_id: &str) {
+ self.total += 1;
+ *self.running.entry(kwant_id.to_string()).or_default() += 1;
+ }
+
+ fn put_back(&mut self, kwant_id: &str) {
+ self.total = self.total.saturating_sub(1);
+ if let Some(n) = self.running.get_mut(kwant_id) {
+ *n = n.saturating_sub(1);
+ if *n == 0 {
+ self.running.remove(kwant_id);
+ }
+ }
+ }
+}
+
+/// Per-agent and server-wide caps on running turns, with a FIFO line for the rest. A waiter
+/// whose agent is at its cap doesn't hold up waiters for other agents.
+#[derive(Clone)]
+pub struct Limiter {
+ state: Arc<Mutex<LimiterState>>,
+}
+
+impl Limiter {
+ pub fn new(per_agent: usize, global: usize) -> Self {
+ Self {
+ state: Arc::new(Mutex::new(LimiterState {
+ per_agent: per_agent.clamp(1, MAX_PER_AGENT),
+ global: global.clamp(1, MAX_GLOBAL),
+ running: HashMap::new(),
+ total: 0,
+ waiting: VecDeque::new(),
+ })),
+ }
+ }
+
+ fn lock(&self) -> std::sync::MutexGuard<'_, LimiterState> {
+ self.state.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ /// New caps; raising them starts waiting turns right away.
+ pub fn set_limits(&self, per_agent: usize, global: usize) {
+ let returned = {
+ let mut s = self.lock();
+ s.per_agent = per_agent.clamp(1, MAX_PER_AGENT);
+ s.global = global.clamp(1, MAX_GLOBAL);
+ self.dispatch(&mut s)
+ };
+ drop(returned);
+ }
+
+ pub fn limits(&self) -> (usize, usize) {
+ let s = self.lock();
+ (s.per_agent, s.global)
+ }
+
+ /// (running for this kwant, running overall, waiting overall)
+ pub fn load(&self, kwant_id: &str) -> (usize, usize, usize) {
+ let s = self.lock();
+ (s.running.get(kwant_id).copied().unwrap_or(0), s.total, s.waiting.len())
+ }
+
+ /// A slot now, or a place in line. Nobody jumps the line for the same agent.
+ pub fn try_acquire(&self, kwant_id: &str) -> Result<Slot, Wait> {
+ let mut s = self.lock();
+ let ahead_same = s.waiting.iter().any(|w| w.kwant_id == kwant_id && !w.tx.is_closed());
+ if !ahead_same && s.fits(kwant_id) {
+ s.take(kwant_id);
+ return Ok(Slot { limiter: self.clone(), kwant_id: kwant_id.to_string() });
+ }
+ let agent_full = s.running.get(kwant_id).copied().unwrap_or(0) >= s.per_agent;
+ let (tx, rx) = oneshot::channel();
+ s.waiting.push_back(Waiter { kwant_id: kwant_id.to_string(), tx });
+ let position = s.waiting.iter().filter(|w| !w.tx.is_closed()).count();
+ Err(Wait { rx, position, reason: if agent_full || ahead_same { "agent_busy" } else { "server_busy" } })
+ }
+
+ fn release(&self, kwant_id: &str) {
+ let returned = {
+ let mut s = self.lock();
+ s.put_back(kwant_id);
+ self.dispatch(&mut s)
+ };
+ // Slots a waiter gave up on are dropped here, outside the lock (their drop releases again)
+ drop(returned);
+ }
+
+ /// Hands free slots to waiters in line order. Returns slots nobody took any more.
+ fn dispatch(&self, s: &mut LimiterState) -> Vec<Slot> {
+ let mut unclaimed = Vec::new();
+ let mut i = 0;
+ while i < s.waiting.len() && s.total < s.global {
+ if s.waiting[i].tx.is_closed() {
+ s.waiting.remove(i);
+ continue;
+ }
+ let kwant_id = s.waiting[i].kwant_id.clone();
+ if !s.fits(&kwant_id) {
+ i += 1;
+ continue;
+ }
+ let Some(w) = s.waiting.remove(i) else { break };
+ s.take(&kwant_id);
+ if let Err(slot) = w.tx.send(Slot { limiter: self.clone(), kwant_id }) {
+ unclaimed.push(slot);
+ }
+ }
+ unclaimed
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cancel_by_key_hits_every_job_with_it_and_only_those() {
+ let r = TurnRegistry::default();
+ let a = r.start_job(["chat-1", "kwant-a"]);
+ let b = r.start_job(["chat-1"]);
+ let c = r.start_job(["thread-9"]);
+ assert_eq!(r.cancel(Some("chat-1")), 2);
+ assert!(a.token.is_cancelled() && b.token.is_cancelled());
+ assert!(!c.token.is_cancelled());
+ drop(a);
+ assert!(r.has_job("chat-1"), "b still runs");
+ drop(b);
+ assert!(!r.has_job("chat-1"));
+ assert!(r.has_job("thread-9"));
+ }
+
+ #[test]
+ fn finished_job_does_not_remove_a_newer_job_for_the_same_chat() {
+ let r = TurnRegistry::default();
+ let first = r.start_job(["kwant-a"]);
+ let second = r.start_job(["kwant-a"]);
+ drop(first);
+ assert_eq!(r.cancel(Some("kwant-a")), 1);
+ assert!(second.token.is_cancelled());
+ }
+
+ #[tokio::test]
+ async fn per_agent_cap_queues_and_releases_in_order() {
+ let l = Limiter::new(2, 10);
+ let s1 = l.try_acquire("a").ok().unwrap();
+ let _s2 = l.try_acquire("a").ok().unwrap();
+ let w3 = l.try_acquire("a").err().unwrap();
+ assert_eq!(w3.reason, "agent_busy");
+ let w4 = l.try_acquire("a").err().unwrap();
+ // Another agent is not held up
+ let _b = l.try_acquire("b").ok().unwrap();
+ drop(s1);
+ let s3 = w3.rx.await.unwrap();
+ assert_eq!(l.load("a").0, 2);
+ drop(s3);
+ let _s4 = w4.rx.await.unwrap();
+ assert_eq!(l.load("a"), (2, 3, 0));
+ }
+
+ #[tokio::test]
+ async fn global_cap_and_abandoned_waiters() {
+ let l = Limiter::new(3, 1);
+ let s1 = l.try_acquire("a").ok().unwrap();
+ let w = l.try_acquire("b").err().unwrap();
+ assert_eq!(w.reason, "server_busy");
+ let w2 = l.try_acquire("c").err().unwrap();
+ drop(w); // gave up (cancelled)
+ drop(s1);
+ let _s = w2.rx.await.unwrap();
+ assert_eq!(l.load("c"), (1, 1, 0));
+ }
+
+ #[tokio::test]
+ async fn raising_limits_starts_waiters() {
+ let l = Limiter::new(1, 6);
+ let _s1 = l.try_acquire("a").ok().unwrap();
+ let w = l.try_acquire("a").err().unwrap();
+ l.set_limits(2, 6);
+ let _s2 = w.rx.await.unwrap();
+ assert_eq!(l.load("a").0, 2);
+ }
+}
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index d259bbe0..03081a0a 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -665,6 +665,7 @@ async fn self_tools_are_scoped_to_the_turn_and_kwant() {
Some(SelfScope {
kwant_id: k1.id.clone(),
kwant_name: k1.name.clone(),
+ origin: None,
}),
)
.await
@@ -1131,7 +1132,7 @@ async fn webhook_setting_is_https_only_and_masked() {
assert_eq!(s["notify_webhook_url"], "");
assert_eq!(
s["notify_on"],
- json!(["turn_finished", "approval_needed", "routine_failed"])
+ json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled"])
);
let (status, _) = req(
@@ -1200,11 +1201,15 @@ async fn notifications_are_filtered_and_content_free() {
kwant_id: k.id.clone(),
context_id: Some(general.id.clone()),
outcome: "completed".into(),
+ turn_id: None,
+ thread_id: None,
});
let _ = state.event_sender.send(RuntimeEvent::TurnEnded {
kwant_id: k.id.clone(),
context_id: None,
outcome: "failed".into(),
+ turn_id: None,
+ thread_id: None,
});
let _ = state.event_sender.send(RuntimeEvent::ApprovalRequired {
id: "a1".into(),
diff --git a/tests/delegation_test.rs b/tests/delegation_test.rs
new file mode 100644
index 00000000..b541b04c
--- /dev/null
+++ b/tests/delegation_test.rs
@@ -0,0 +1,614 @@
+//! Threads, concurrent turns and delegation (batch 2 / A). A fake claude CLI on PATH records every
+//! prompt and holds a "LONGTASK:<file>" turn until that file exists, so a test can keep a delegated
+//! turn running while it talks to the same agent elsewhere. Its own test binary: it changes PATH.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::Database,
+ router::LayaRouter,
+ server::{continuity, create_router, delegation, AppState},
+ tools::ToolRunner,
+ RuntimeEvent,
+};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tower::ServiceExt;
+
+/// Replies "answer <tag>" for a prompt with "REPLYTAG:<tag>"; a "LONGTASK:<file>" prompt waits
+/// (up to 60 s) for that file first. Every prompt is saved under `$KWNT_TEST_PROMPTS`.
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ auth) echo '{"loggedIn":true}'; exit 0 ;;
+esac
+for a; do last="$a"; done
+printf '%s' "$last" > "$KWNT_TEST_PROMPTS/$$-$(date +%s%N)"
+release=$(printf '%s\n' "$last" | sed -n 's/.*LONGTASK:\([^ ]*\).*/\1/p' | head -n 1)
+if [ -n "$release" ]; then
+ i=0
+ while [ ! -f "$release" ] && [ $i -lt 600 ]; do sleep 0.1; i=$((i+1)); done
+fi
+tag=$(printf '%s\n' "$last" | sed -n 's/.*REPLYTAG:\([A-Za-z0-9_]*\).*/\1/p' | tail -n 1)
+echo "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"answer ${tag:-none}\"}"
+"#;
+
+fn prompts_dir() -> &'static PathBuf {
+ static DIR: OnceLock<PathBuf> = OnceLock::new();
+ DIR.get_or_init(|| {
+ let root = tempfile::tempdir().unwrap().keep();
+ let bin = root.join("bin");
+ let prompts = root.join("prompts");
+ std::fs::create_dir_all(&bin).unwrap();
+ std::fs::create_dir_all(&prompts).unwrap();
+ let fake = bin.join("claude");
+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ std::env::set_var("KWNT_TEST_PROMPTS", &prompts);
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ prompts
+ })
+}
+
+/// Prompts the fake CLI got that contain `marker`.
+fn prompts_with(marker: &str) -> Vec<String> {
+ std::fs::read_dir(prompts_dir())
+ .unwrap()
+ .filter_map(|e| std::fs::read_to_string(e.unwrap().path()).ok())
+ .filter(|p| p.contains(marker))
+ .collect()
+}
+
+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(Value::Null))
+}
+
+struct Env {
+ app: Router,
+ state: AppState,
+ lead: String,
+ specialist: String,
+ tmp: tempfile::TempDir,
+}
+
+impl Env {
+ fn release_file(&self, name: &str) -> PathBuf {
+ self.tmp.path().join(name)
+ }
+}
+
+async fn setup() -> Env {
+ prompts_dir();
+ let tmp = tempfile::tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ // Laya is unreachable: turns use the kwant's preferred model, the fake claude
+ 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()),
+ );
+ let app = create_router(state.clone());
+ let (_, kwants) = call(&app, "GET", "/api/kwants", None).await;
+ let mut ids = Vec::new();
+ for k in kwants.as_array().unwrap().iter().take(2) {
+ let id = k["id"].as_str().unwrap().to_string();
+ let mut body = k.clone();
+ body.as_object_mut()
+ .unwrap()
+ .retain(|key, _| ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str()));
+ body["preferred_model"] = json!("claude");
+ let (s, v) = call(&app, "PUT", &format!("/api/kwants/{id}"), Some(body)).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ ids.push(id);
+ }
+ Env { app, state, lead: ids[0].clone(), specialist: ids[1].clone(), tmp }
+}
+
+async fn wait_for<F, Fut>(what: &str, mut check: F)
+where
+ F: FnMut() -> Fut,
+ Fut: std::future::Future<Output = bool>,
+{
+ for _ in 0..300 {
+ if check().await {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("timed out waiting for {what}");
+}
+
+async fn delegation_status(env: &Env, id: &str) -> String {
+ let (_, d) = call(&env.app, "GET", &format!("/api/delegations/{id}"), None).await;
+ d["status"].as_str().unwrap_or("").to_string()
+}
+
+async fn delegate(env: &Env, task: &str) -> Value {
+ let (s, d) = call(
+ &env.app,
+ "POST",
+ "/api/delegations",
+ Some(json!({
+ "lead_kwant_id": env.lead,
+ "specialist_kwant_id": env.specialist,
+ "task": task,
+ "title": "Deep research",
+ "kwant_id": env.lead,
+ "continue_lead": false,
+ })),
+ )
+ .await;
+ assert_eq!(s, StatusCode::ACCEPTED, "{d}");
+ d
+}
+
+fn meta_kind(m: &kwnt::db::models::Message) -> Option<String> {
+ let meta: Value = serde_json::from_str(m.meta.as_deref()?).ok()?;
+ meta["kind"].as_str().map(str::to_string)
+}
+
+/// The X-post scenario: while a long delegated task runs in the specialist's thread, the user
+/// chats with the specialist directly and gets an answer; then the task reports back to the lead.
+#[tokio::test]
+async fn specialist_answers_direct_chat_while_a_delegated_turn_runs() {
+ let env = setup().await;
+ let release = env.release_file("research-done");
+ let d = delegate(&env, &format!("Research the topic LONGTASK:{} REPLYTAG:research", release.display())).await;
+ let id = d["id"].as_str().unwrap().to_string();
+ let thread_id = d["thread_id"].as_str().unwrap().to_string();
+ assert_eq!(d["status"], "queued");
+ wait_for("the delegated turn to run", || async { delegation_status(&env, &id).await == "running" }).await;
+
+ // The specialist's own chat is not blocked: a direct question gets its answer meanwhile
+ let mut rx = env.state.event_sender.subscribe();
+ let (s, v) = call(
+ &env.app,
+ "POST",
+ "/api/chat/send",
+ Some(json!({"kwant_id": env.specialist, "prompt": "How much disk space is left? REPLYTAG:disk DIRECTMARK", "sender_id": "user"})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let specialist = env.specialist.clone();
+ tokio::time::timeout(Duration::from_secs(30), async {
+ loop {
+ if let Ok(RuntimeEvent::TurnEnded { kwant_id, context_id, outcome, .. }) = rx.recv().await {
+ if kwant_id == specialist && context_id.as_deref() == Some(&specialist) {
+ assert_eq!(outcome, "completed");
+ break;
+ }
+ }
+ }
+ })
+ .await
+ .expect("the direct turn finished while the delegated one was still running");
+ let direct = env.state.db.list_messages(&env.specialist, 20).await.unwrap();
+ assert!(direct.iter().any(|m| m.sender_role == "kwant" && m.text == "answer disk"), "{direct:?}");
+ assert_eq!(delegation_status(&env, &id).await, "running");
+ // Two turns of one agent at once, each tagged with its own chat
+ let (_, turns) = call(&env.app, "GET", "/api/turns", None).await;
+ assert!(turns["turns"].as_array().unwrap().iter().any(|t| t["thread_id"] == thread_id.as_str() && t["state"] == "running"));
+
+ // Engine sessions never mix: neither prompt holds the other chat's text
+ assert!(prompts_with("DIRECTMARK").iter().all(|p| !p.contains("LONGTASK")));
+ assert!(prompts_with("LONGTASK").iter().all(|p| !p.contains("DIRECTMARK")));
+
+ // The task finishes and reports back to the lead's chat, linking the thread
+ std::fs::write(&release, "").unwrap();
+ // `delegation_updated` goes out once the result message is linked
+ wait_for("the delegation to report", || async {
+ let (_, d) = call(&env.app, "GET", &format!("/api/delegations/{id}"), None).await;
+ d["status"] == "completed" && d["result_message_id"].is_string()
+ })
+ .await;
+ let lead_chat = env.state.db.list_messages(&env.lead, 20).await.unwrap();
+ let started = lead_chat.iter().find(|m| meta_kind(m).as_deref() == Some("delegation_started")).expect("started note");
+ assert!(started.text.contains("Deep research"));
+ let result = lead_chat.iter().find(|m| meta_kind(m).as_deref() == Some("delegation_result")).expect("result message");
+ assert_eq!(result.text, "answer research");
+ let meta: Value = serde_json::from_str(result.meta.as_deref().unwrap()).unwrap();
+ assert_eq!(meta["thread_id"], thread_id.as_str());
+ assert_eq!(meta["status"], "completed");
+ let (_, d) = call(&env.app, "GET", &format!("/api/delegations/{id}"), None).await;
+ assert_eq!(d["result_message_id"], result.id.as_str());
+
+ // The thread keeps the whole exchange; the specialist's direct chat never shows it
+ let (s, msgs) = call(&env.app, "GET", &format!("/api/threads/{thread_id}/messages"), None).await;
+ assert_eq!(s, StatusCode::OK);
+ let texts: Vec<&str> = msgs.as_array().unwrap().iter().filter_map(|m| m["text"].as_str()).collect();
+ assert!(texts[0].contains("Research the topic"), "{texts:?}");
+ assert!(texts.contains(&"answer research"));
+ assert!(direct.iter().all(|m| !m.text.contains("answer research")));
+}
+
+/// A turn over the per-agent cap waits in a queue (visible over SSE and /api/turns), never fails.
+#[tokio::test]
+async fn excess_turns_queue_instead_of_failing() {
+ 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 (s, _) = call(&env.app, "POST", "/api/settings", Some(json!({"max_turns_per_agent": 0}))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+ let (_, settings) = call(&env.app, "GET", "/api/settings", None).await;
+ assert_eq!(settings["max_turns_per_agent"], 1);
+ assert_eq!(settings["delegation_follow_up_minutes"], 15);
+
+ let release = env.release_file("queue-release");
+ let d = delegate(&env, &format!("Long one LONGTASK:{} REPLYTAG:long", release.display())).await;
+ let id = d["id"].as_str().unwrap().to_string();
+ wait_for("the delegated turn to run", || async { delegation_status(&env, &id).await == "running" }).await;
+
+ let mut rx = env.state.event_sender.subscribe();
+ let (s, v) = call(
+ &env.app,
+ "POST",
+ "/api/chat/send",
+ Some(json!({"kwant_id": env.specialist, "prompt": "quick one REPLYTAG:quick", "sender_id": "user"})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK, "never rejected: {v}");
+ let queued = tokio::time::timeout(Duration::from_secs(10), async {
+ loop {
+ if let Ok(e) = rx.recv().await {
+ if let RuntimeEvent::TurnQueued { .. } = e.unscoped() {
+ return e.to_wire();
+ }
+ }
+ }
+ })
+ .await
+ .expect("a turn_queued event");
+ assert_eq!(queued["type"], "turn_queued");
+ assert_eq!(queued["data"]["kwant_id"], env.specialist.as_str());
+ assert_eq!(queued["data"]["reason"], "agent_busy");
+ assert_eq!(queued["data"]["position"], 1);
+ let (_, turns) = call(&env.app, "GET", "/api/turns", None).await;
+ assert!(turns["turns"].as_array().unwrap().iter().any(|t| t["state"] == "queued" && t["kwant_id"] == env.specialist.as_str()));
+
+ // Once the long turn ends, the queued one runs on its own
+ std::fs::write(&release, "").unwrap();
+ let specialist = env.specialist.clone();
+ wait_for("the queued turn to answer", || {
+ let state = env.state.clone();
+ let specialist = specialist.clone();
+ async move { state.db.list_messages(&specialist, 20).await.unwrap().iter().any(|m| m.text == "answer quick") }
+ })
+ .await;
+ wait_for("the delegation to complete", || async { delegation_status(&env, &id).await == "completed" }).await;
+}
+
+/// 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() {
+ let env = setup().await;
+ let thread_release = env.release_file("never");
+ let d = delegate(&env, &format!("Slow LONGTASK:{} REPLYTAG:slow", thread_release.display())).await;
+ let id = d["id"].as_str().unwrap().to_string();
+ let thread_id = d["thread_id"].as_str().unwrap().to_string();
+ wait_for("the delegated turn to run", || async { delegation_status(&env, &id).await == "running" }).await;
+
+ let direct_release = env.release_file("direct");
+ let (s, _) = call(
+ &env.app,
+ "POST",
+ "/api/chat/send",
+ Some(json!({"kwant_id": env.specialist, "prompt": format!("also slow LONGTASK:{} REPLYTAG:direct", direct_release.display()), "sender_id": "user"})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK);
+ wait_for("both turns to run", || async {
+ env.state.turns.active_turns().iter().filter(|t| t.state == "running").count() == 2
+ })
+ .await;
+
+ let (s, v) = call(&env.app, "POST", &format!("/api/threads/{thread_id}/cancel"), None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["cancelled"], 1);
+ assert_eq!(delegation_status(&env, &id).await, "cancelled");
+ wait_for("the thread's turn to stop", || async { env.state.turns.active_turns().len() == 1 }).await;
+ let left = env.state.turns.active_turns();
+ assert_eq!(left[0].context_id, env.specialist, "the direct chat's turn is untouched");
+ // Reported once in the lead's chat (by the cancel or the runner, whichever ends it first)
+ wait_for("the stop note", || async {
+ let lead_chat = env.state.db.list_messages(&env.lead, 20).await.unwrap();
+ lead_chat.iter().filter(|m| m.text.contains("Stopped") && meta_kind(m).as_deref() == Some("delegation_result")).count() == 1
+ })
+ .await;
+
+ std::fs::write(&direct_release, "").unwrap();
+ wait_for("the direct turn to answer", || {
+ let state = env.state.clone();
+ let specialist = env.specialist.clone();
+ async move { state.db.list_messages(&specialist, 20).await.unwrap().iter().any(|m| m.text == "answer direct") }
+ })
+ .await;
+ // Cancelling again is a no-op; unknown ids are 404
+ let (s, d) = call(&env.app, "POST", &format!("/api/delegations/{id}/cancel"), None).await;
+ assert_eq!((s, d["status"].as_str()), (StatusCode::OK, Some("cancelled")));
+ let (s, _) = call(&env.app, "POST", "/api/delegations/nope/cancel", None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+ let (s, _) = call(&env.app, "POST", "/api/threads/nope/cancel", None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+}
+
+/// A user-made thread is its own conversation: own history, own engine prompt, can be archived.
+#[tokio::test]
+async fn threads_keep_their_own_history() {
+ let env = setup().await;
+ let (s, _) = call(
+ &env.app,
+ "POST",
+ "/api/chat/send",
+ Some(json!({"kwant_id": env.specialist, "prompt": "secret plan SIDECHAT REPLYTAG:side", "sender_id": "user"})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK);
+ wait_for("the direct reply", || async {
+ env.state.db.list_messages(&env.specialist, 20).await.unwrap().iter().any(|m| m.text == "answer side")
+ })
+ .await;
+
+ let (s, t) = call(&env.app, "POST", &format!("/api/kwants/{}/threads", env.specialist), Some(json!({"title": " Wifi\nhelp "}))).await;
+ assert_eq!(s, StatusCode::CREATED, "{t}");
+ assert_eq!(t["title"], "Wifi help");
+ let tid = t["id"].as_str().unwrap().to_string();
+ let (s, v) = call(
+ &env.app,
+ "POST",
+ "/api/chat/send",
+ Some(json!({"thread_id": tid, "kwant_id": env.lead, "prompt": "wifi question THREADMARK REPLYTAG:wifi", "sender_id": "user"})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["kwant"].as_str(), env.state.db.get_kwant(&env.specialist).await.unwrap().map(|k| k.name).as_deref(), "the thread's owner answers");
+ wait_for("the thread reply", || async {
+ env.state.db.list_messages(&tid, 20).await.unwrap().iter().any(|m| m.text == "answer wifi")
+ })
+ .await;
+ assert!(prompts_with("THREADMARK").iter().all(|p| !p.contains("SIDECHAT")), "thread prompt saw the direct chat");
+ let direct = env.state.db.list_messages(&env.specialist, 20).await.unwrap();
+ assert!(direct.iter().all(|m| !m.text.contains("THREADMARK") && m.text != "answer wifi"));
+ let lead_direct = env.state.db.list_messages(&env.lead, 20).await.unwrap();
+ assert!(lead_direct.iter().all(|m| !m.text.contains("THREADMARK")));
+
+ let (_, list) = call(&env.app, "GET", &format!("/api/kwants/{}/threads", env.specialist), None).await;
+ assert_eq!(list.as_array().unwrap().len(), 1);
+ let (s, _) = call(&env.app, "PATCH", &format!("/api/threads/{tid}"), Some(json!({"archived": true}))).await;
+ assert_eq!(s, StatusCode::OK);
+ let (_, list) = call(&env.app, "GET", &format!("/api/kwants/{}/threads", env.specialist), None).await;
+ assert!(list.as_array().unwrap().is_empty());
+ let (s, _) = call(&env.app, "POST", "/api/chat/send", Some(json!({"thread_id": tid, "prompt": "hi", "sender_id": "user"}))).await;
+ assert_eq!(s, StatusCode::CONFLICT, "archived threads take no new messages");
+ let (s, _) = call(&env.app, "POST", "/api/chat/send", Some(json!({"thread_id": "missing", "prompt": "hi", "sender_id": "user"}))).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+ let (s, _) = call(&env.app, "GET", "/api/kwants/missing/threads", None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+}
+
+/// The agent tools act only for the calling lead, within the rules (no self, depth, own records).
+#[tokio::test]
+async fn delegation_tools_enforce_their_rules() {
+ let env = setup().await;
+ let call_tool = |token: &'static str, name: &'static str, args: Value| {
+ let app = env.app.clone();
+ async move {
+ let resp = app
+ .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)
+ }
+ };
+ let names: Vec<String> = env.state.db.list_kwants().await.unwrap().into_iter().map(|k| k.name).collect();
+ {
+ let mut tools = env.state.self_tools.lock().await;
+ tools.insert(
+ "lead-token".into(),
+ continuity::SelfScope {
+ kwant_id: env.lead.clone(),
+ kwant_name: names[0].clone(),
+ origin: Some(continuity::TurnOrigin { direct_kwant_id: Some(env.lead.clone()), ..Default::default() }),
+ },
+ );
+ tools.insert(
+ "deep-token".into(),
+ continuity::SelfScope {
+ kwant_id: env.lead.clone(),
+ kwant_name: names[0].clone(),
+ origin: Some(continuity::TurnOrigin { direct_kwant_id: Some(env.lead.clone()), depth: 2, ..Default::default() }),
+ },
+ );
+ tools.insert(
+ "other-token".into(),
+ continuity::SelfScope { kwant_id: env.specialist.clone(), kwant_name: names[1].clone(), origin: None },
+ );
+ }
+ // Offered only to turns that know their chat
+ let list = |token: &'static str| {
+ let app = env.app.clone();
+ async move {
+ let resp = app
+ .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/list"}).to_string()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let v: Value = serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap();
+ v["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect::<Vec<_>>()
+ }
+ };
+ assert!(list("lead-token").await.contains(&"delegate".to_string()));
+ assert!(!list("other-token").await.contains(&"delegate".to_string()));
+
+ let (text, err) = call_tool("lead-token", "delegate", json!({"to": names[0], "task": "x"})).await;
+ assert!(err && text.contains("itself"), "{text}");
+ let (text, err) = call_tool("lead-token", "delegate", json!({"to": "Nobody", "task": "x"})).await;
+ assert!(err && text.contains(&names[1]), "lists who can take it: {text}");
+ let (text, err) = call_tool("deep-token", "delegate", json!({"to": names[1], "task": "x"})).await;
+ assert!(err && text.contains("delegated further"), "{text}");
+ let (text, err) = call_tool("lead-token", "delegate", json!({"to": "", "task": "x".repeat(8001)})).await;
+ assert!(err, "{text}");
+
+ let (text, err) = call_tool("lead-token", "delegate", json!({"to": format!("@{}", names[1]), "task": "Check it REPLYTAG:tool", "title": "Tool task"})).await;
+ assert!(!err, "{text}");
+ let id = text.split('[').nth(1).and_then(|s| s.split(']').next()).unwrap().to_string();
+ let (text, err) = call_tool("lead-token", "delegation_status", json!({})).await;
+ assert!(!err && text.contains(&id), "{text}");
+ // Another agent can't see or stop it
+ let (_, err) = call_tool("other-token", "delegation_status", json!({"id": id})).await;
+ assert!(err);
+ let (_, err) = call_tool("other-token", "delegation_cancel", json!({"id": id})).await;
+ assert!(err);
+ // Finished delegations from the tool continue the lead's turn in its chat
+ wait_for("the tool delegation to complete", || async { delegation_status(&env, &id).await == "completed" }).await;
+ wait_for("the lead's continuation turn", || async { !prompts_with("finished the task you delegated (“Tool task”)").is_empty() }).await;
+ let (text, _) = call_tool("lead-token", "delegation_cancel", json!({"id": id})).await;
+ assert!(text.contains("already finished"), "{text}");
+}
+
+/// The stall hook posts one note per delegation; a restart marks open ones interrupted.
+#[tokio::test]
+async fn follow_ups_and_restarts_report_in_the_origin_chat() {
+ let env = setup().await;
+ let release = env.release_file("stall");
+ let d = delegate(&env, &format!("Stalls LONGTASK:{} REPLYTAG:late", release.display())).await;
+ let id = d["id"].as_str().unwrap().to_string();
+ assert!(d["follow_up_at"].is_string());
+ wait_for("the delegated turn to run", || async { delegation_status(&env, &id).await == "running" }).await;
+ assert_eq!(delegation::follow_ups(&env.state, chrono::Utc::now()).await, 0, "not due yet");
+ let later = chrono::Utc::now() + chrono::Duration::minutes(16);
+ assert_eq!(delegation::follow_ups(&env.state, later).await, 1);
+ assert_eq!(delegation::follow_ups(&env.state, later).await, 0, "only once");
+ let lead_chat = env.state.db.list_messages(&env.lead, 20).await.unwrap();
+ assert!(lead_chat.iter().any(|m| meta_kind(m).as_deref() == Some("delegation_stalled") && m.text.contains("still working")));
+
+ // Turned off: no follow-up time is set
+ let (s, _) = call(&env.app, "POST", "/api/settings", Some(json!({"delegation_follow_up_minutes": 0}))).await;
+ assert_eq!(s, StatusCode::OK);
+ let d2 = delegate(&env, "Another REPLYTAG:two").await;
+ assert!(d2["follow_up_at"].is_null());
+
+ std::fs::write(&release, "").unwrap();
+ wait_for("both to complete", || async {
+ delegation_status(&env, &id).await == "completed"
+ && delegation_status(&env, d2["id"].as_str().unwrap()).await == "completed"
+ })
+ .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();
+ delegation::interrupt_open(&env.state).await;
+ assert_eq!(delegation_status(&env, &open.id).await, "interrupted");
+ 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")));
+}
+
+/// The new columns and tables are additive: rows written the old way still load, and init twice
+/// is a no-op.
+#[tokio::test]
+async fn migration_is_additive_and_idempotent() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ drop(db);
+ let url = format!("sqlite://{}?mode=rwc", tmp.path().join("kwnt.db").display());
+ {
+ let pool = sqlx::SqlitePool::connect(&url).await.unwrap();
+ // What the previous binary writes: no thread_id, no meta
+ sqlx::query("INSERT INTO messages (id, direct_kwant_id, sender_role, sender_id, text) VALUES ('old1', 'k', 'user', 'you', 'from the old binary')")
+ .execute(&pool)
+ .await
+ .unwrap();
+ pool.close().await;
+ }
+ let db = Database::init(tmp.path()).await.unwrap();
+ let db = {
+ drop(db);
+ Database::init(tmp.path()).await.unwrap()
+ };
+ {
+ let msgs = db.list_messages("k", 10).await.unwrap();
+ assert_eq!(msgs.len(), 1);
+ assert!(msgs[0].thread_id.is_none() && msgs[0].meta.is_none());
+ }
+ // Tagged SSE events flatten for clients
+ let wire = RuntimeEvent::Scoped {
+ tag: kwnt::drivers::events::TurnTag {
+ turn_id: "t1".into(),
+ kwant_id: "k".into(),
+ context_id: "th".into(),
+ thread_id: Some("th".into()),
+ },
+ event: Box::new(RuntimeEvent::TextDelta("hi".into())),
+ }
+ .to_wire();
+ assert_eq!(wire["type"], "TextDelta");
+ assert_eq!(wire["data"], "hi");
+ assert_eq!((wire["turn_id"].as_str(), wire["context_id"].as_str(), wire["thread_id"].as_str()), (Some("t1"), Some("th"), Some("th")));
+}
diff --git a/tests/profile_failover_test.rs b/tests/profile_failover_test.rs
index eed2f9c5..8f04c022 100644
--- a/tests/profile_failover_test.rs
+++ b/tests/profile_failover_test.rs
@@ -66,7 +66,8 @@ async fn run_turn(app: &Router, state: &AppState, kwant_id: &str) -> Vec<Runtime
tokio::time::timeout(Duration::from_secs(60), async {
while let Ok(e) = rx.recv().await {
let end = matches!(&e, RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == kwant_id);
- events.push(e);
+ // Turn events arrive tagged with their turn; the test looks at what happened
+ events.push(e.unscoped().clone());
if end {
break;
}
diff --git a/tests/server_test.rs b/tests/server_test.rs
index d65cdd06..b0471dbc 100644
--- a/tests/server_test.rs
+++ b/tests/server_test.rs
@@ -252,8 +252,6 @@ async fn test_chat_routing_with_team_mention_and_cancellation() {
#[tokio::test]
async fn test_cancel_chat_with_null_fields_only_cancels_target_kwant() {
- use tokio_util::sync::CancellationToken;
-
let tmp = tempdir().unwrap();
let db = Database::init(tmp.path()).await.unwrap();
let config = Config { data_dir: tmp.path().to_path_buf(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };
@@ -264,14 +262,10 @@ async fn test_cancel_chat_with_null_fields_only_cancels_target_kwant() {
let state = AppState::new(config, db, tools, broker, router);
let app = create_router(state.clone());
- // Insert two distinct tokens in active_cancellations
- let target_token = CancellationToken::new();
- let other_token = CancellationToken::new();
- {
- let mut tokens = state.active_cancellations.lock().await;
- tokens.insert("test-kwant".to_string(), target_token.clone());
- tokens.insert("other-session".to_string(), other_token.clone());
- }
+ // Two running dispatches: one for the target agent's direct chat, one elsewhere
+ let target = state.turns.start_job(["msg-1", "test-kwant"]);
+ let other = state.turns.start_job(["other-session"]);
+ let (target_token, other_token) = (target.token.clone(), other.token.clone());
// Cancel with payload containing null channel_id and team_id, but specific kwant_id
let cancel_body = json!({
@@ -294,10 +288,12 @@ async fn test_cancel_chat_with_null_fields_only_cancels_target_kwant() {
// Other token must NOT be cancelled (no global drain!)
assert!(!other_token.is_cancelled(), "Other session token must NOT be cancelled by targeted cancellation");
- // active_cancellations map must still contain other_token and not test-kwant
- let tokens = state.active_cancellations.lock().await;
- assert!(!tokens.contains_key("test-kwant"));
- assert!(tokens.contains_key("other-session"));
+ // Only the target's job answers to its keys any more
+ assert!(state.turns.has_job("test-kwant"));
+ drop(target);
+ assert!(!state.turns.has_job("test-kwant"));
+ assert!(state.turns.has_job("other-session"));
+ drop(other);
}
#[tokio::test]