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.

Carry hand-off cards on when unblocked or retried; Continue past hand-off caps

Lin (kwant bot)89a07b5228fe
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 74359219..c04261fc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
limit gets **Remove limit and continue**, on its board card and in its panel, plus **Raise limit**.
Settings → Usage has a **Token limits** group for the default on new tasks and missions, "No limit"
unless you pick one.
+- **Unblocking or retrying a hand-off card carries the work on.** A hand-off card sent back to Ready
+ used to sit there because nothing runs hand-offs from the board. Now the teammate picks it up again in
+ the hand-off's own thread ("carry on from where you stopped") and the card is back to working, or it
+ goes to review if the hand-off had already finished while the card was blocked. A hand-off cut short
+ by two restarts now fails its card so it offers Retry, and a card that can't carry on is blocked with
+ the reason. Cards already stuck in Ready are picked up automatically.
+- **Teams can hand on more before kwant pauses them.** One teammate can now be asked by mention up to 4
+ times per message (was 2), and one message can start up to 16 hand-offs (was 8). Past that, instead of
+ "Send a new message to go on", the chat shows a notice with a Continue button (or say "continue").
## [Mac 0.2.0] - 2026-10-28
diff --git a/docs/mission-control.md b/docs/mission-control.md
index e9ec53c4..67dd78af 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -600,10 +600,52 @@ Token budgets are opt-in. `budget_tokens` 0 means no limit, for tasks and missio
- **Unblocking a task blocked for its budget** (`state` `blocked`, `blocked_reason` `budget`):
`PATCH /api/tasks/:id {"budget_tokens": 0}` (or a higher limit), then `POST /api/tasks/:id/unblock`.
The task goes `blocked → backlog → ready` when its dependencies are verified and its mission is
- active. (Hand-off tasks are not restarted by the board; that is a separate fix.)
+ active. A hand-off task then carries on (§16).
- Migration (once, when the stored table still has `CHECK (budget_tokens > 0)`): `tasks` and
`missions` are rebuilt with `CHECK (budget_tokens >= 0)`, keeping every column, index and trigger,
and in the same transaction rows still at the old silent defaults lose them:
`UPDATE tasks SET budget_tokens = 0 WHERE budget_tokens = 50000` and
`UPDATE missions SET budget_tokens = 0 WHERE budget_tokens = 200000`. Task states are not changed.
- The hand-off loop guard (`chain_token_budget`) is separate and unchanged.
+
+## 16. Hand-off cards that go on
+
+A hand-off task (`source_kind` `delegation`, `source_id` the delegation) is held by kwant with a
+system claim whose context is the hand-off's thread. The mission runner never starts hand-offs, so
+the listener (`missions::listener`) does it when such a card reaches `ready` (unblock, person retry,
+AutoFix retry; also the scheduler's reconcile, for cards left in Ready earlier) and isn't held by a
+restore (`held_at`):
+
+| Hand-off status | What happens |
+| --- | --- |
+| `queued` / `running` | kwant takes the card again → `working` |
+| `completed` | → `working` → `review` (its result was already delivered; the work isn't run again) |
+| `failed` / `cancelled` / `interrupted` | the delegation is reopened (`queued`, error and times cleared) and the teammate gets a carry-on turn in the same thread ("carry on from where you stopped", with why it stopped); the card goes back to `working`; the new result is posted to the origin chat and the lead is resumed with it alone |
+| can't carry on (a bot is gone, or another call reopened it first) | `ready → blocked`, reason `listener::CANT_CARRY_ON` |
+
+A card still over its own token limit is blocked again (`blocked_reason` `budget`) instead.
+
+- A budget block lands at turn end, so it never stops the live hand-off: the hand-off finishes (or
+ fails) and its result reaches the lead as usual. While the card is blocked, its end is logged once
+ as a `handoff_ended` task event (`{"status", "note"}`); unblocking then follows the table.
+- A hand-off cut short by two restarts (`interrupted`) fails its card (AutoFix records it as a
+ `handoff` error) instead of returning it to Ready.
+
+### Capped hand-offs: the Continue notice
+
+One person message starts at most `routes::MAX_DELEGATIONS_PER_REQUEST` (16) hand-offs by mention,
+at most `routes::MAX_MENTION_DELEGATIONS_PER_BOT` (4) to one teammate; `chain_token_budget` still
+stops real loops. Mentions past a cap are not dropped: kwant saves one system message in the channel
+with meta
+
+```json
+{"kind": "handoff_capped", "lead": "<lead id>", "waiting": ["<name>"], "waiting_ids": ["<id>"],
+ "sent": 16, "text": "<the lead's reply>", "user_prompt": "<the person's message>", "resumed": false}
+```
+
+and text "Paused after N hand-offs so it doesn't loop: A, B not sent yet. Press Continue or say
+"continue" to hand it on." It works like the `budget_paused` notice: `POST
+/api/chains/:message_id/continue` (person only; 409 once continued, 410 if the lead is gone), or the
+person typing "continue" while it's the newest bot message. Continuing sets `resumed` true and hands
+only the waiting teammates the lead's reply, with a fresh allowance.
+
diff --git a/src/db/threads.rs b/src/db/threads.rs
index 7a97d7e4..b05127e6 100644
--- a/src/db/threads.rs
+++ b/src/db/threads.rs
@@ -420,6 +420,21 @@ impl Database {
Ok(res.rows_affected() > 0)
}
+ /// Opens an ended delegation again (failed, cancelled or interrupted) to carry on in its
+ /// thread: back to `queued`, with its restart count and end cleared (and no "still working"
+ /// note for its old follow-up time). `false` if it was open or completed, or someone else
+ /// reopened it first.
+ pub async fn reopen_delegation(&self, id: &str) -> Result<bool, DbError> {
+ let res = sqlx::query(
+ "UPDATE delegations SET status = 'queued', error = NULL, ended_at = NULL, started_at = NULL, retries = 0, followed_up = 1 \
+ WHERE id = ? AND status IN ('failed', 'cancelled', 'interrupted')",
+ )
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected() > 0)
+ }
+
/// Parks a queued delegation until `after` (another delegation) ends.
pub async fn set_delegation_after(&self, id: &str, after: &str) -> Result<(), DbError> {
sqlx::query("UPDATE delegations SET after_delegation_id = ? WHERE id = ? AND status = 'queued'")
diff --git a/src/server/budget.rs b/src/server/budget.rs
index b68f8ef3..abe73863 100644
--- a/src/server/budget.rs
+++ b/src/server/budget.rs
@@ -21,6 +21,10 @@ pub const DEFAULT: u64 = 200_000;
pub const MAX: u64 = 100_000_000;
/// Message meta kind of the notice.
pub const KIND: &str = "budget_paused";
+/// Message meta kind of the notice a lead's @mentions leave past the hand-off caps
+/// ([`super::routes::MAX_MENTION_DELEGATIONS_PER_BOT`], [`super::routes::MAX_DELEGATIONS_PER_REQUEST`]).
+/// Carried on like a paused chain: Continue on it, or "continue" typed after it.
+pub const CAPPED_KIND: &str = "handoff_capped";
/// The budget in fresh tokens; 0 when the guard is off.
pub async fn limit(state: &AppState) -> u64 {
@@ -88,13 +92,38 @@ pub(super) async fn pause_if_over(scope: &TurnScope, spoken: &[String], replies:
true
}
-/// The newest paused-chain notice in a channel that hasn't been carried on, if it's the newest
-/// message from a bot or kwant (a later reply means the chat moved on).
+/// A lead's @mentions went past a hand-off cap: saves one notice naming the teammates `capped`
+/// (`sent` hand-offs so far for this request), which the person carries on with one press.
+pub(super) async fn pause_capped(scope: &TurnScope, lead: &Kwant, capped: &[&Kwant], sent: usize, text: &str, user_prompt: &str) {
+ let names: Vec<String> = capped.iter().map(|k| k.name.clone()).collect();
+ tracing::info!(lead = %lead.id, sent, waiting = ?names, "hand-off caps reached: waiting for Continue");
+ let line = format!(
+ "Paused after {sent} hand-offs so it doesn't loop: {} not sent yet. Press Continue or say \"continue\" to hand it on.",
+ names.join(", "),
+ );
+ let meta = json!({
+ "kind": CAPPED_KIND,
+ "lead": lead.id,
+ "waiting": names,
+ "waiting_ids": capped.iter().map(|k| k.id.clone()).collect::<Vec<_>>(),
+ "sent": sent,
+ "text": text,
+ "user_prompt": user_prompt,
+ "resumed": false,
+ });
+ if let Some(saved) = scope.save(&scope.message("system", "kwnt", line), Some(meta)).await {
+ let _ = scope.state.event_sender.send(crate::drivers::events::RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or_default() });
+ }
+}
+
+/// The newest notice in a channel that can be carried on (a paused chain or capped hand-offs) and
+/// hasn't been, if it's the newest message from a bot or kwant (a later reply means the chat
+/// moved on).
async fn open_pause(state: &AppState, channel_id: &str) -> Option<crate::db::models::Message> {
let recent = state.db.list_messages(channel_id, 10).await.ok()?;
let last = recent.into_iter().rev().find(|m| m.sender_role != "user")?;
let meta: serde_json::Value = serde_json::from_str(last.meta.as_deref()?).ok()?;
- (meta["kind"] == KIND && meta["resumed"] != true).then_some(last)
+ ((meta["kind"] == KIND || meta["kind"] == CAPPED_KIND) && meta["resumed"] != true).then_some(last)
}
/// Carries a paused chain on from its notice: marks it resumed and hands the turn to the bots
@@ -103,13 +132,16 @@ async fn resume(state: &AppState, notice_id: &str) -> Result<(), (StatusCode, &'
let notice = state.db.get_message(notice_id).await.ok().flatten().ok_or((StatusCode::NOT_FOUND, "no such message"))?;
let mut meta: serde_json::Value =
notice.meta.as_deref().and_then(|m| serde_json::from_str(m).ok()).ok_or((StatusCode::BAD_REQUEST, "not a paused chain"))?;
- if meta["kind"] != KIND {
+ if meta["kind"] != KIND && meta["kind"] != CAPPED_KIND {
return Err((StatusCode::BAD_REQUEST, "not a paused chain"));
}
if meta["resumed"] == true {
return Err((StatusCode::CONFLICT, "this chain was already continued"));
}
let channel_id = notice.channel_id.clone().ok_or((StatusCode::BAD_REQUEST, "not a channel message"))?;
+ if meta["kind"] == CAPPED_KIND {
+ return resume_capped(state, notice_id, meta, channel_id).await;
+ }
let channel = state.db.get_channel(&channel_id).await.ok().flatten().ok_or((StatusCode::NOT_FOUND, "the channel is gone"))?;
let space = crate::db::spaces::SpaceId::new(&channel.space_id);
let all: Vec<Kwant> = state.db.list_kwants(&space).await.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not load the bots"))?;
@@ -141,6 +173,28 @@ async fn resume(state: &AppState, notice_id: &str) -> Result<(), (StatusCode, &'
Ok(())
}
+/// Carries capped hand-offs on: the lead hands the waiting teammates their work, with a fresh
+/// allowance of hand-offs.
+async fn resume_capped(state: &AppState, notice_id: &str, mut meta: serde_json::Value, channel_id: String) -> Result<(), (StatusCode, &'static str)> {
+ let lead_id = meta["lead"].as_str().unwrap_or_default().to_string();
+ let lead = state.db.get_kwant(&lead_id).await.ok().flatten().ok_or((StatusCode::GONE, "the lead of this chat is gone"))?;
+ let waiting: Vec<String> = meta["waiting_ids"].as_array().into_iter().flatten().filter_map(|s| s.as_str().map(str::to_string)).collect();
+ let text = meta["text"].as_str().unwrap_or_default().to_string();
+ let user_prompt = meta["user_prompt"].as_str().unwrap_or_default().to_string();
+ meta["resumed"] = json!(true);
+ let _ = state.db.set_message_meta(notice_id, &meta).await;
+
+ let job = state.turns.start_job([channel_id.clone(), notice_id.to_string()]);
+ let scope = super::routes::scope_for(state, &lead, Some(channel_id), None, &job, 0)
+ .await
+ .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not set up the chat"))?;
+ tokio::spawn(async move {
+ let _job = job;
+ super::routes::delegate_mentions(&scope, &lead, &text, &user_prompt, &[], Some(&waiting)).await;
+ });
+ Ok(())
+}
+
/// For `send_chat`: the person's "continue" right after a paused chain carries it on. Returns the
/// notice's id when it did. Bots' tokens never get here (`from_person` false).
pub async fn resume_if_continue(state: &AppState, channel_id: &str, prompt: &str, from_person: bool) -> Option<String> {
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index d6038a5b..64aebd40 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -331,7 +331,7 @@ pub async fn start(state: &AppState, req: StartRequest) -> Result<Delegation, (S
fn spawn_run(state: &AppState, d: Delegation, lead: Kwant, specialist: Kwant) {
let job = state.turns.start_job([d.id.clone(), d.thread_id.clone()]);
let runner_state = state.clone();
- tokio::spawn(async move { run(runner_state, job, d, lead, specialist, false, false).await });
+ tokio::spawn(async move { run(runner_state, job, d, lead, specialist, RunAs::default()).await });
}
/// What a parked task gets of the result it waited for, at most.
@@ -447,21 +447,12 @@ pub(super) fn is_parked(d: &Delegation) -> bool {
}
/// The background part: the specialist's turn in the thread, then the report in the origin chat.
-/// `retried`: the run after a usage limit reset, which never waits for one again.
-/// The task's prompt says so when a restart cut an earlier run short (`after_restart`): that run
-/// may have done part of the work already.
-async fn run(
- state: AppState,
- job: super::turns::JobGuard,
- d: Delegation,
- lead: Kwant,
- specialist: Kwant,
- retried: bool,
- after_restart: bool,
-) {
+async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead: Kwant, specialist: Kwant, how: RunAs) {
+ let RunAs { retried, after_restart, carry_on } = how;
+ let carried_on = carry_on.is_some();
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,
+ Err(why) => return finish(&state, &d, &specialist, Err(why), carried_on).await,
};
// Queued until the specialist's turn gets its slot: a busy specialist runs one turn at a time
let (started_state, started_id) = (state.clone(), d.id.clone());
@@ -472,10 +463,24 @@ async fn run(
}
}
});
+ let opening = match &carry_on {
+ Some(why) => format!(
+ "{lead} delegated this task to you earlier, and it stopped before it was done ({why}). The person sent it \
+ back to you: carry on from where you stopped. Your earlier work is above in this thread, so check what is \
+ already done instead of starting over, and don't repeat a step that can't be undone (sending, posting, deleting, \
+ paying) unless you've confirmed it didn't happen. When you finish, your reply is posted back to {lead} and the chat it \
+ came from, so make it a complete, self-contained answer.",
+ lead = lead.name,
+ why = clip(why, 300),
+ ),
+ None => 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.",
+ lead = lead.name,
+ ),
+ };
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\n{task}{origin}{again}",
- lead = lead.name,
+ "{opening}\n\n{task}{origin}{again}",
task = crate::drivers::peer_message(&lead.name, &format!("Task: {}\n\n{}", d.title, d.task)),
origin = origin_brief(&state, &d).await,
again = if after_restart { RESTARTED_NOTE } else { "" },
@@ -512,7 +517,20 @@ async fn run(
return;
}
}
- finish(&state, &d, &specialist, outcome).await;
+ finish(&state, &d, &specialist, outcome, carried_on).await;
+}
+
+/// How [`run`] runs a delegation's task.
+#[derive(Default)]
+struct RunAs {
+ /// The run after a usage limit reset, which never waits for one again.
+ retried: bool,
+ /// A restart cut an earlier run short, so it may have done part of the work already (the
+ /// prompt says so).
+ after_restart: bool,
+ /// The person sent an ended task back (unblocked or retried its board card): why it stopped.
+ /// The specialist carries on in its thread, and the lead hears the new result on its own.
+ carry_on: Option<String>,
}
/// Most of the person's request, and of the origin chat's instructions, a delegated task quotes.
@@ -592,7 +610,9 @@ pub const RESTARTED_NOTE: &str = "\n\n[kwnt restarted while an earlier run of th
files may already be written, messages sent or settings changed. Check what is already done before redoing anything, \
and don't repeat a step that can't be undone (sending, posting, deleting, paying) unless you've confirmed it didn't happen.]";
-async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: Result<String, String>) {
+/// Ends `d` with `outcome`: the result in the origin chat, then the lead (with its batch, or on
+/// its own when the person sent the task back: `carried_on`).
+async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: Result<String, String>, carried_on: bool) {
let (status, error) = match &outcome {
Ok(_) => ("completed", None),
Err(e) if e == "stopped" => ("cancelled", Some("stopped by the user".to_string())),
@@ -648,7 +668,14 @@ async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: R
)
.await;
release_dependents(state, &done.id).await;
- report_to_lead(state, &done, None).await;
+ if !carried_on {
+ return report_to_lead(state, &done, None).await;
+ }
+ // Its batch already went to the lead: this result goes on its own (a stop was the person's)
+ if done.continue_lead && status != "cancelled" {
+ let opening = format!("{} carried on with the task you delegated (“{}”) after the person sent it back.", specialist.name, done.title);
+ continue_lead(state, &done, std::slice::from_ref(&done), Some(opening)).await;
+ }
}
/// Resumes the lead once `d` ended, if it was the last of its batch to end (see
@@ -902,7 +929,7 @@ pub fn handoff_rules() -> String {
a teammate who just reported, too. Only say you're handing off, asking or waiting for someone when you @mention them \
with a task in this reply; to merely refer to a teammate, write the name without @. Limits for this user message: each \
teammate gets at most {per_bot} tasks by mention and all teammates at most {total} in total. Past that the mention is \
- not sent and a \"Not sent to …\" notice says so; then tell the person what's left instead of claiming a handoff.",
+ not sent yet: a notice asks the person to press Continue, so tell them what's waiting instead of claiming a handoff.",
per_bot = super::routes::MAX_MENTION_DELEGATIONS_PER_BOT,
total = super::routes::MAX_DELEGATIONS_PER_REQUEST,
)
@@ -1083,7 +1110,42 @@ async fn restart(state: &AppState, d: Delegation, retried: bool, after_restart:
};
let job = state.turns.start_job([d.id.clone(), d.thread_id.clone()]);
tracing::info!(delegation = %d.id, retried, "delegation restarted");
- tokio::spawn(run(state.clone(), job, d, lead, specialist, retried, after_restart));
+ tokio::spawn(run(state.clone(), job, d, lead, specialist, RunAs { retried, after_restart, carry_on: None }));
+ true
+}
+
+/// The person sent an ended hand-off back from its board card (unblocked or retried it): the
+/// specialist carries on in the delegation's own thread from where it stopped, and the new
+/// result goes to the origin chat and the lead. `false` when it can't: it is still open or
+/// completed (a completed one has its result already), a bot is gone, or another call reopened it
+/// first.
+pub async fn carry_on(state: &AppState, d: &Delegation) -> bool {
+ if d.is_open() || d.status == "completed" {
+ return false;
+ }
+ let (Ok(Some(lead)), Ok(Some(specialist))) =
+ (state.db.get_kwant(&d.lead_kwant_id).await, state.db.get_kwant(&d.specialist_kwant_id).await)
+ else {
+ return false;
+ };
+ let why = d.error.clone().filter(|e| !e.trim().is_empty()).unwrap_or_else(|| format!("it {}", d.status));
+ if !state.db.reopen_delegation(&d.id).await.unwrap_or(false) {
+ return false;
+ }
+ let Ok(Some(open)) = state.db.get_delegation(&d.id).await else { return false };
+ emit_delegation(state, &open);
+ post_to_origin(
+ state,
+ &open,
+ "system",
+ "kwnt",
+ format!("{} is carrying on with “{}”.", specialist.name, open.title),
+ meta("delegation_started", &open, &specialist.name),
+ )
+ .await;
+ let job = state.turns.start_job([open.id.clone(), open.thread_id.clone()]);
+ tracing::info!(delegation = %open.id, "delegation carried on");
+ tokio::spawn(run(state.clone(), job, open, lead, specialist, RunAs { carry_on: Some(why), ..Default::default() }));
true
}
diff --git a/src/server/missions/listener.rs b/src/server/missions/listener.rs
index 1cd82c97..56446137 100644
--- a/src/server/missions/listener.rs
+++ b/src/server/missions/listener.rs
@@ -58,6 +58,14 @@ pub async fn reconcile(state: &AppState) {
if !super::enabled(state).await {
return;
}
+ // A hand-off card the person (or AutoFix) put back in Ready, whose hand-off had ended
+ for t in state.db.tasks_in_state("ready").await.unwrap_or_default() {
+ if t.source_kind == "delegation" && t.held_at.is_none() {
+ if let Some(id) = t.source_id.as_deref() {
+ on_delegation(state, id).await;
+ }
+ }
+ }
for t in state.db.system_held().await.unwrap_or_default() {
match (t.source_kind.as_str(), t.source_id.as_deref()) {
("delegation", Some(id)) => on_delegation(state, id).await,
@@ -172,6 +180,18 @@ async fn finish(state: &AppState, task: &Task, to: &str, why: &str) -> bool {
moved
}
+/// A hand-off card just went to Ready: the board's runner never starts hand-offs, so the
+/// hand-off goes on (or the card to review) without waiting for the next tick. In the
+/// background: the caller may hold [`SERIAL`].
+pub fn kick_handoff(state: &AppState, task: &Task) {
+ if task.source_kind != "delegation" || task.held_at.is_some() {
+ return;
+ }
+ let Some(id) = task.source_id.clone() else { return };
+ let state = state.clone();
+ tokio::spawn(async move { on_delegation(&state, &id).await });
+}
+
pub async fn on_delegation(state: &AppState, delegation_id: &str) {
if !super::enabled(state).await {
return;
@@ -189,10 +209,48 @@ pub async fn on_delegation(state: &AppState, delegation_id: &str) {
start_held(state, &space, mission, &title, &d.task, &d.specialist_kwant_id, "delegation", &d.id, place, &d.thread_id).await;
}
(Some(t), _) if live && t.state == "ready" => hold(state, &t, &d.specialist_kwant_id, &d.thread_id).await,
+ // Sent back to Ready after the hand-off ended (the person unblocked or retried the card,
+ // or AutoFix retried it): the board never runs hand-offs itself, so it goes on here
+ (Some(t), status) if t.state == "ready" => {
+ if t.held_at.is_some() {
+ return;
+ }
+ if super::over(t.spent_tokens, t.budget_tokens) {
+ // Unblocked over its token limit (kwant couldn't take it back): blocked again, so
+ // the person raises or removes the limit instead of the card sitting in Ready
+ let change = TaskChange {
+ kind: "budget".into(),
+ reason: Some("budget".into()),
+ detail: Some(serde_json::json!({"spent_tokens": t.spent_tokens, "budget_tokens": t.budget_tokens})),
+ ..Default::default()
+ };
+ let _ = transition(state, &t.id, "ready", "blocked", Actor::Kwant, "kwant", change).await;
+ return;
+ }
+ if status == "completed" {
+ // It finished while the card was blocked: its result is in, so it goes to review
+ hold(state, &t, &d.specialist_kwant_id, &d.thread_id).await;
+ if let Ok(Some(t)) = state.db.get_task(&t.id).await {
+ finish(state, &t, "review", "the hand-off had finished").await;
+ }
+ } else if !crate::server::delegation::carry_on(state, &d).await {
+ let change = TaskChange { reason: Some(CANT_CARRY_ON.into()), ..Default::default() };
+ let _ = transition(state, &t.id, "ready", "blocked", Actor::Kwant, "kwant", change).await;
+ }
+ }
(Some(t), _) if live => {
// Still going: keep kwant's lease on it
let _ = state.db.refresh_claim(&t.id, lease_ms(state).await).await;
}
+ // It ended while its card was blocked (over its token limit, or by the person): the
+ // card says so, and unblocking it goes on from there (see the `ready` arm)
+ (Some(t), status) if t.state == "blocked" => {
+ let note = if status == "completed" { "the hand-off finished; unblock to review its result" } else { "the hand-off stopped; unblock to carry on" };
+ if !ended_noted(state, &t.id, status).await {
+ let _ = state.db.log_task_event(&t.id, "handoff_ended", "kwant", &serde_json::json!({"status": status, "note": note})).await;
+ super::emit_task(state, &t).await;
+ }
+ }
(Some(t), "completed") => {
finish(state, &t, "review", "the hand-off finished").await;
}
@@ -205,13 +263,28 @@ pub async fn on_delegation(state: &AppState, delegation_id: &str) {
(Some(t), "cancelled") => {
finish(state, &t, "cancelled", "the hand-off was cancelled").await;
}
+ // Cut short by two restarts: failed, so the card offers Retry (a Ready card would wait for
+ // nobody)
(Some(t), "interrupted") => {
- finish(state, &t, "ready", "a restart interrupted the hand-off").await;
+ let why = "kwnt restarted twice while the hand-off ran";
+ if finish(state, &t, "failed", why).await {
+ super::autofix::record(state, &t.id, "handoff", "error", why, why).await;
+ }
}
_ => {}
}
}
+/// Why a hand-off card sent back to Ready can't go on, so it is blocked for the person instead.
+pub const CANT_CARRY_ON: &str = "the hand-off can't carry on (a bot is gone or it was restarted elsewhere): ask the lead again";
+
+/// Whether the hand-off's end (`status`) was already noted on a blocked task.
+async fn ended_noted(state: &AppState, task_id: &str, status: &str) -> bool {
+ let events = state.db.task_events(task_id, 50).await.unwrap_or_default();
+ let since_block = events.iter().rposition(|e| e.to_state.as_deref() == Some("blocked")).unwrap_or(0);
+ events[since_block..].iter().any(|e| e.kind == "handoff_ended" && e.detail.contains(&format!("\"status\":\"{status}\"")))
+}
+
pub async fn on_routine_run(state: &AppState, routine_id: &str, run_id: &str, status: &str) {
if !super::enabled(state).await {
return;
diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rs
index ec9673da..1625182e 100644
--- a/src/server/missions/mod.rs
+++ b/src/server/missions/mod.rs
@@ -233,6 +233,9 @@ pub async fn transition(
}
async fn after_move(state: &AppState, task: &Task, to: &str) {
+ if to == "ready" {
+ listener::kick_handoff(state, task);
+ }
autofix::settle(state, task, to).await;
// A task parked for AutoFix isn't done failing: no "failed" line until it is
let to = if to == "failed" && autofix::parked(state, task).await { "parked" } else { to };
@@ -273,6 +276,9 @@ async fn to_ready(state: &AppState, task_id: &str) {
let change = TaskChange { reason: Some("nothing it waits on is open".into()), ..Default::default() };
if state.db.move_task(task_id, "backlog", "ready", "kwant", &change).await.unwrap_or(false) {
emit_task_id(state, task_id).await;
+ if let Ok(Some(t)) = state.db.get_task(task_id).await {
+ listener::kick_handoff(state, &t);
+ }
}
}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index c4af1499..80d5bfae 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -787,10 +787,12 @@ fn team_context(t: &Team) -> crate::drivers::TeamContext {
const MAX_HANDOFFS: usize = 4;
/// Delegations a lead's @mentions may start for one user message, follow-up rounds included:
/// a lead resumed with results can hand on again, but never in an endless loop.
-pub const MAX_DELEGATIONS_PER_REQUEST: usize = 8;
+pub const MAX_DELEGATIONS_PER_REQUEST: usize = 16;
/// How often one teammate may be handed work by @mention for one user message, so two bots
-/// naming each other stop after a couple of rounds instead of running to the total cap.
-pub const MAX_MENTION_DELEGATIONS_PER_BOT: usize = 2;
+/// naming each other stop after a few rounds instead of running to the total cap. A mention past
+/// either cap leaves a Continue notice ([`super::budget::CAPPED_KIND`]); the chain token budget
+/// still pauses a long chain on its own.
+pub const MAX_MENTION_DELEGATIONS_PER_BOT: usize = 4;
#[allow(clippy::too_many_arguments)]
fn execute_single_turn(
@@ -926,7 +928,7 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(
}
if let [(from, text)] = replies {
if is_team_channel_lead(scope, from).await {
- return delegate_mentions(scope, from, text, user_prompt, already_spoken).await;
+ return delegate_mentions(scope, from, text, user_prompt, already_spoken, None).await;
}
}
if scope.teammates.is_empty() {
@@ -1195,9 +1197,19 @@ async fn is_team_channel_lead(scope: &TurnScope, kwant: &Kwant) -> bool {
/// results it is about): a mention there is a correction or the next step, unless it only credits
/// them ([`crate::router::only_credited`]). One user message starts at most
/// [`MAX_DELEGATIONS_PER_REQUEST`], at most [`MAX_MENTION_DELEGATIONS_PER_BOT`] to any one
-/// teammate, which is what ends a loop. Every mention that hands nothing on is said in the channel.
-/// Teammates the lead already delegated to from this channel (with the tool) aren't sent it twice.
-async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_prompt: &str, just_reported: &[String]) {
+/// teammate, which is what ends a loop; mentions past a cap wait on a Continue notice
+/// ([`super::budget::pause_capped`]). Every other mention that hands nothing on is said in the
+/// channel. Teammates the lead already delegated to from this channel (with the tool) aren't sent
+/// it twice. `resumed`: the person pressed Continue on such a notice: only these teammates are
+/// handed the work, with a fresh allowance.
+pub(super) async fn delegate_mentions(
+ scope: &TurnScope,
+ lead: &Kwant,
+ text: &str,
+ user_prompt: &str,
+ just_reported: &[String],
+ resumed: Option<&[String]>,
+) {
let Some(cid) = scope.channel_id.clone() else { return };
let names: Vec<&str> = scope.teammates.iter().map(|k| k.name.as_str()).collect();
let found = crate::router::handoff_mentions(text, &names);
@@ -1224,14 +1236,19 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_pro
// Delegations this user message already started, counting earlier follow-up rounds
let messages = scope.state.db.list_messages(&cid, 100).await.unwrap_or_default();
let since = messages.iter().rev().find(|m| m.sender_role == "user").or(messages.first()).and_then(|m| m.created_at);
- let this_request: Vec<_> = mine.iter().filter(|d| d.continue_lead && since.is_some_and(|t| d.created_at >= t)).collect();
+ let this_request: Vec<_> = match resumed {
+ Some(_) => Vec::new(),
+ None => mine.iter().filter(|d| d.continue_lead && since.is_some_and(|t| d.created_at >= t)).collect(),
+ };
let mut room = MAX_DELEGATIONS_PER_REQUEST.saturating_sub(this_request.len());
let asked = |id: &str| this_request.iter().filter(|d| d.specialist_kwant_id == id).count();
let mut targets: Vec<&Kwant> = Vec::new();
+ // Past a cap: they wait on a Continue notice instead of a dead end
+ let mut capped: Vec<&Kwant> = Vec::new();
for &i in &found.targets {
let k = &scope.teammates[i];
- if k.id == lead.id || targets.iter().any(|t| t.id == k.id) {
+ if k.id == lead.id || targets.iter().any(|t| t.id == k.id) || resumed.is_some_and(|ids| !ids.contains(&k.id)) {
continue;
}
if just_reported.contains(&k.id) && crate::router::only_credited(text, &k.name) {
@@ -1239,10 +1256,7 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_pro
} else if open.contains(&k.id.as_str()) {
skipped.push((k.name.clone(), "still working on an earlier task from this chat".to_string()));
} else if asked(&k.id) >= MAX_MENTION_DELEGATIONS_PER_BOT {
- skipped.push((
- k.name.clone(),
- format!("already asked {MAX_MENTION_DELEGATIONS_PER_BOT} times for this request. Send a new message to go on"),
- ));
+ capped.push(k);
} else {
targets.push(k);
}
@@ -1272,10 +1286,7 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_pro
continue;
}
if room == 0 {
- skipped.push((
- specialist.name.clone(),
- format!("this request has already gone to {MAX_DELEGATIONS_PER_REQUEST} teammates. Send a new message to go on"),
- ));
+ capped.push(specialist);
continue;
}
// Waits for a teammate started here, or for one still on an earlier task from this chat
@@ -1314,6 +1325,9 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_pro
}
}
report_skipped(scope, skipped).await;
+ if !capped.is_empty() {
+ super::budget::pause_capped(scope, lead, &capped, this_request.len() + started.len(), text, user_prompt).await;
+ }
}
/// Whether the teammate with `id` is among the @mentioned `targets` (indices into the teammates).
diff --git a/tests/delegation_test.rs b/tests/delegation_test.rs
index b092ed19..33423a03 100644
--- a/tests/delegation_test.rs
+++ b/tests/delegation_test.rs
@@ -1017,20 +1017,68 @@ fn refusals(msgs: &[kwnt::db::models::Message]) -> Vec<String> {
msgs.iter().filter(|m| meta_kind(m).as_deref() == Some("handoff_refused")).map(|m| m.text.clone()).collect()
}
+/// The Continue notices mentions past a hand-off cap left.
+fn capped(msgs: &[kwnt::db::models::Message]) -> Vec<kwnt::db::models::Message> {
+ msgs.iter().filter(|m| meta_kind(m).as_deref() == Some(kwnt::server::budget::CAPPED_KIND)).cloned().collect()
+}
+
+/// `n` ended rounds from the lead to `to` in `channel` that count for the current request (dated
+/// ahead, so they are after any message of it). The fake CLI's markers fall out of the lead's
+/// recent history after a few rounds, so rounds up to a cap are seeded rather than run.
+async fn seed_rounds(env: &Env, channel: &str, to: &str, n: usize) {
+ let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", env.tmp.path().join("data/kwnt.db").display())).await.unwrap();
+ for _ in 0..n {
+ let (_, d) = env
+ .state
+ .db
+ .create_delegation(&kwnt::db::threads::NewDelegation {
+ lead_kwant_id: env.lead.clone(),
+ specialist_kwant_id: to.to_string(),
+ origin_channel_id: Some(channel.to_string()),
+ origin_kwant_id: None,
+ origin_thread_id: None,
+ team_id: None,
+ task: "earlier round".into(),
+ title: "Earlier round".into(),
+ continue_lead: true,
+ depth: 1,
+ follow_up_at: None,
+ })
+ .await
+ .unwrap();
+ assert!(env.state.db.finish_delegation(&d.id, "completed", None, None).await.unwrap());
+ sqlx::query("UPDATE delegations SET created_at = ? WHERE id = ?")
+ .bind(chrono::Utc::now() + chrono::Duration::hours(1))
+ .bind(&d.id)
+ .execute(&pool)
+ .await
+ .unwrap();
+ }
+ pool.close().await;
+}
+
+fn meta_of(m: &kwnt::db::models::Message) -> Value {
+ serde_json::from_str(m.meta.as_deref().unwrap_or("null")).unwrap()
+}
+
/// Bug 3 (team-Startup, 2026-10-21): the lead's follow-up after results came back said "`@Growth`,
/// please draft the launch plan" and Growth never ran. The follow-up now hands on like any lead
/// reply and a name in inline code counts. Mentioning the teammate who just reported back with a
-/// task hands it a second round (2026-10-24); the third is refused in one line.
+/// task hands it another round (2026-10-24), up to the per-teammate cap. Past it (2026-10-28,
+/// "send a new message to go on"??? so it stuck without my message??) a Continue notice waits:
+/// pressing it hands Growth the work again, and the chain still stops at the cap.
#[tokio::test]
async fn a_leads_follow_up_after_results_hands_on_to_the_next_teammate() {
let env = setup().await;
let growth = add_bot(&env, "Growth").await;
let channel = team_channel_with(&env, "startup-follow", &[&env.lead, &env.specialist, &growth]).await;
+ // Growth already ran all but two of its rounds for this request
+ seed_rounds(&env, &channel, &growth, per_bot_limit() - 2).await;
let first = delegate_from(&env, &channel, &env.specialist, "Review the app REPLYTAG:reviewed", "Security review FOLLOWUP:Growth").await;
wait_for("the review to complete", || async { delegation_status(&env, &first).await == "completed" }).await;
let to_growth = || async {
- env.state.db.list_delegations(Some(&env.lead), None, 20).await.unwrap().into_iter().find(|d| d.specialist_kwant_id == growth)
+ env.state.db.list_delegations(Some(&env.lead), None, 20).await.unwrap().into_iter().find(|d| d.specialist_kwant_id == growth && d.title != "Earlier round")
};
wait_for("the follow-up's delegation to Growth", || async { to_growth().await.is_some() }).await;
let d = to_growth().await.unwrap();
@@ -1039,18 +1087,37 @@ async fn a_leads_follow_up_after_results_hands_on_to_the_next_teammate() {
assert!(d.task.contains("`@Growth`"), "Growth gets the lead's words: {}", d.task);
wait_for("Growth's result", || async { delegation_status(&env, &d.id).await == "completed" }).await;
- // Growth's own follow-up names Growth again with a task: a second round, then the limit
- wait_for("the limit notice", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;
+ // Growth's own follow-up names Growth again with a task: more rounds, then the cap
+ wait_for("the Continue notice", || async { !capped(&channel_messages(&env, &channel).await).is_empty() }).await;
tokio::time::sleep(Duration::from_millis(1500)).await;
- let notes = refusals(&channel_messages(&env, &channel).await);
- assert_eq!(notes, vec![format!("Not sent to Growth: already asked {} times for this request. Send a new message to go on", per_bot_limit())]);
+ let msgs = channel_messages(&env, &channel).await;
+ assert!(refusals(&msgs).is_empty(), "past the cap is not a dead end: {:?}", refusals(&msgs));
+ let notices = capped(&msgs);
+ assert_eq!(notices.len(), 1, "one notice, no flood");
+ let notice = &notices[0];
+ assert!(notice.text.starts_with("Paused after ") && notice.text.contains("Growth not sent yet. Press Continue"), "{}", notice.text);
+ let meta = meta_of(notice);
+ assert_eq!((meta["lead"].as_str(), meta["waiting_ids"].clone(), meta["resumed"].clone()), (Some(env.lead.as_str()), json!([growth]), json!(false)));
+ let to_growth_count = || async {
+ env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap().iter().filter(|d| d.specialist_kwant_id == growth).count()
+ };
let all = env.state.db.list_delegations(Some(&env.lead), None, 20).await.unwrap();
- assert_eq!(all.len(), 1 + per_bot_limit(), "the review and Growth's two rounds, no loop: {all:?}");
+ assert_eq!(all.len(), 1 + per_bot_limit(), "the review and Growth's rounds up to the cap, no loop: {all:?}");
assert!(all.iter().all(|d| d.status == "completed"), "{all:?}");
+
+ // One press carries it on: Growth is handed the work again
+ let (s, body) = call(&env.app, "POST", &format!("/api/chains/{}/continue", notice.id), None).await;
+ assert_eq!(s, StatusCode::OK, "{body}");
+ wait_for("Growth's next round", || async { to_growth_count().await > per_bot_limit() }).await;
+ let (s, _) = call(&env.app, "POST", &format!("/api/chains/{}/continue", notice.id), None).await;
+ assert_eq!(s, StatusCode::CONFLICT, "a notice carries on once");
+ // A fresh allowance, still bounded by the cap
+ tokio::time::sleep(Duration::from_millis(3000)).await;
+ assert!(to_growth_count().await <= 2 * per_bot_limit() + 1, "still bounded");
}
-/// Mentions that hand nothing on are said in the channel: a name no teammate has, and a follow-up
-/// after the request already went to the most teammates one message may reach.
+/// Mentions that hand nothing on are said in the channel: a name no teammate has. A follow-up after
+/// the request already went to the most teammates one message may reach leaves a Continue notice.
#[tokio::test]
async fn mentions_that_hand_nothing_on_are_said_in_the_channel() {
let env = setup().await;
@@ -1087,31 +1154,23 @@ async fn mentions_that_hand_nothing_on_are_said_in_the_channel() {
}
let last = delegate_from(&env, &channel, &env.specialist, "One more REPLYTAG:more", "Last part FOLLOWUP:Growth").await;
wait_for("the last part", || async { delegation_status(&env, &last).await == "completed" }).await;
- let limit_note = || async {
- refusals(&channel_messages(&env, &channel).await).into_iter().find(|n| n.contains("Growth: "))
- };
- for _ in 0..100 {
- if limit_note().await.is_some() {
- break;
- }
- tokio::time::sleep(Duration::from_millis(100)).await;
- }
- let msgs: Vec<String> = channel_messages(&env, &channel).await.iter().map(|m| format!("{}: {}", m.sender_id, m.text)).collect();
- let note = limit_note().await.unwrap_or_else(|| panic!("no limit notice: {msgs:#?}"));
- // One line for the reply's refused mentions: the unknown name again, and Growth past the limit
- assert_eq!(
- note,
- format!("Not sent to Marketer: no teammate has that name here; Growth: this request has already gone to {} teammates. Send a new message to go on", routes_limit())
- );
+ wait_for("the Continue notice", || async { !capped(&channel_messages(&env, &channel).await).is_empty() }).await;
+ let msgs = channel_messages(&env, &channel).await;
+ let notes = refusals(&msgs);
+ // The reply's unknown name is still refused; Growth past the limit waits on Continue
+ assert_eq!(notes.last().map(String::as_str), Some("Not sent to Marketer: no teammate has that name here"), "{notes:?}");
+ assert!(notes.iter().all(|n| !n.contains("Growth")), "{notes:?}");
+ let notice = &capped(&msgs)[0];
+ assert_eq!(notice.text, format!("Paused after {} hand-offs so it doesn't loop: Growth not sent yet. Press Continue or say \"continue\" to hand it on.", routes_limit() + 1));
let delegated_growth = env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap().iter().any(|d| d.specialist_kwant_id == growth);
assert!(!delegated_growth, "over the limit, Growth isn't asked");
}
/// Rigel's ping-pong (2026-10-21): two bots naming each other ran all 8 rounds of a request. One
-/// teammate is now handed work by mention at most twice per user message; the third mention is
-/// said in the channel and starts nothing.
+/// teammate is handed work by mention at most [`per_bot_limit`] times per user message; the next
+/// mention starts nothing and leaves one Continue notice.
#[tokio::test]
-async fn one_teammate_is_asked_by_mention_at_most_twice_per_request() {
+async fn one_teammate_is_asked_by_mention_at_most_the_cap_per_request() {
let env = setup().await;
let lead = name(&env, &env.lead).await;
let growth = add_bot(&env, "Growth").await;
@@ -1119,7 +1178,7 @@ async fn one_teammate_is_asked_by_mention_at_most_twice_per_request() {
say_in(&env, &channel, &format!("@{lead} Plan the launch REPLYTAG:plan")).await;
wait_for("the lead's reply", || async { channel_messages(&env, &channel).await.iter().any(|m| m.text.contains("answer plan")) }).await;
- // Growth already ran twice for this message (earlier rounds, both ended)
+ // Growth already ran up to the cap for this message (earlier rounds, all ended)
for _ in 0..per_bot_limit() {
let (_, d) = env
.state
@@ -1141,23 +1200,24 @@ async fn one_teammate_is_asked_by_mention_at_most_twice_per_request() {
.unwrap();
assert!(env.state.db.finish_delegation(&d.id, "completed", None, None).await.unwrap());
}
- // The specialist reports back and the lead's follow-up names Growth a third time
+ // The specialist reports back and the lead's follow-up names Growth once more
let last = delegate_from(&env, &channel, &env.specialist, "Review REPLYTAG:rev", "Review FOLLOWUP:Growth").await;
wait_for("the review", || async { delegation_status(&env, &last).await == "completed" }).await;
- let note = || async { refusals(&channel_messages(&env, &channel).await).into_iter().find(|n| n.starts_with("Not sent to Growth")) };
- wait_for("the per-teammate notice", || async { note().await.is_some() }).await;
- let note = note().await.unwrap();
- assert_eq!(note, "Not sent to Growth: already asked 2 times for this request. Send a new message to go on");
+ wait_for("the per-teammate notice", || async { !capped(&channel_messages(&env, &channel).await).is_empty() }).await;
tokio::time::sleep(Duration::from_millis(1000)).await;
+ let msgs = channel_messages(&env, &channel).await;
+ let notices = capped(&msgs);
+ assert_eq!(notices.len(), 1, "one notice, no flood");
+ assert!(notices[0].text.contains("Growth not sent yet"), "{}", notices[0].text);
+ assert!(refusals(&msgs).is_empty(), "{:?}", refusals(&msgs));
let to_growth = env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap().iter().filter(|d| d.specialist_kwant_id == growth).count();
- assert_eq!(to_growth, per_bot_limit(), "no third delegation to Growth");
- assert_eq!(refusals(&channel_messages(&env, &channel).await).len(), 1, "one notice, no flood");
+ assert_eq!(to_growth, per_bot_limit(), "nothing past the cap until Continue");
}
/// Oleks's screenshot (2026-10-24): the Marketing lead's follow-up said "Handing off now: @Social …,
/// @Writer …, @SEO …" and nobody was asked, because all three had just reported. Now a 4-bot team
-/// runs: lead → three teammates → follow-up hands each a correction → they run a second round →
-/// the lead's next follow-up asks again, which is past the per-teammate limit: ONE line names all
+/// runs: lead → three teammates → each follow-up hands each a correction → they run rounds up to
+/// the per-teammate limit → the lead's next follow-up asks again: ONE Continue notice names all
/// three and nothing loops. Every result is posted in the channel and the lead answers each round.
#[tokio::test]
async fn a_follow_up_hands_corrections_back_to_teammates_who_just_reported() {
@@ -1165,31 +1225,38 @@ async fn a_follow_up_hands_corrections_back_to_teammates_who_just_reported() {
let lead = name(&env, &env.lead).await;
let ids = [add_bot(&env, "Social").await, add_bot(&env, "Writer").await, add_bot(&env, "SEO").await];
let channel = team_channel_with(&env, "marketing-rounds", &[&env.lead, &ids[0], &ids[1], &ids[2]]).await;
+ // Each already ran all but two of its rounds for this request
+ for id in &ids {
+ seed_rounds(&env, &channel, id, per_bot_limit() - 2).await;
+ }
say_in(&env, &channel, &format!("@{lead} Marketing plan ROUNDSMARK REPLYTAG:plan MENTION:Social+Writer+SEO FOLLOWUP:Social+Writer+SEO")).await;
- let notes = || async { refusals(&channel_messages(&env, &channel).await) };
- wait_for("the limit notice after two rounds", || async { !notes().await.is_empty() }).await;
+ let notes = || async { capped(&channel_messages(&env, &channel).await) };
+ wait_for("the Continue notice after the last round", || async { !notes().await.is_empty() }).await;
tokio::time::sleep(Duration::from_millis(1500)).await;
+ let notes = notes().await;
+ assert_eq!(notes.len(), 1, "one notice for all three");
+ let (rounds_total, run) = (3 * per_bot_limit(), 6);
assert_eq!(
- notes().await,
- vec![format!("Not sent to Social, Writer, SEO: already asked {} times for this request. Send a new message to go on", per_bot_limit())],
- "one line for all three"
+ notes[0].text,
+ format!("Paused after {rounds_total} hand-offs so it doesn't loop: Social, Writer, SEO not sent yet. Press Continue or say \"continue\" to hand it on.")
);
+ assert!(refusals(&channel_messages(&env, &channel).await).is_empty());
let all = env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap();
for id in &ids {
let rounds = all.iter().filter(|d| &d.specialist_kwant_id == id).count();
- assert_eq!(rounds, per_bot_limit(), "each teammate ran twice: {all:?}");
+ assert_eq!(rounds, per_bot_limit(), "each teammate ran up to the cap: {all:?}");
}
assert!(all.iter().all(|d| d.status == "completed" && d.origin_channel_id.as_deref() == Some(channel.as_str())), "{all:?}");
let second = all.iter().filter(|d| d.task.contains("please revise your part")).count();
- assert_eq!(second, 3, "the second round carries the lead's correction");
+ assert_eq!(second, 3, "the second round run carries the lead's correction");
let msgs = channel_messages(&env, &channel).await;
let kinds: Vec<Option<String>> = msgs.iter().map(meta_kind).collect();
- assert_eq!(kinds.iter().filter(|k| k.as_deref() == Some("delegation_started")).count(), 6, "a Sent-to chip per task");
- assert_eq!(kinds.iter().filter(|k| k.as_deref() == Some("delegation_result")).count(), 6, "every result in the channel");
+ assert_eq!(kinds.iter().filter(|k| k.as_deref() == Some("delegation_started")).count(), run, "a Sent-to chip per task");
+ assert_eq!(kinds.iter().filter(|k| k.as_deref() == Some("delegation_result")).count(), run, "every result in the channel");
let lead_replies = msgs.iter().filter(|m| m.sender_role == "kwant" && m.sender_id == lead).count();
- assert_eq!(lead_replies, 3, "the handoff, the follow-up after round one and the one after round two");
+ assert_eq!(lead_replies, 3, "the handoff and a follow-up after each round run");
let resumes = prompts_with("ROUNDSMARK").into_iter().filter(|p| p.contains("tasks you delegated have ended")).count();
assert_eq!(resumes, 2, "the lead is resumed once per round");
assert!(
@@ -1262,6 +1329,11 @@ fn per_bot_limit() -> usize {
kwnt::server::routes::MAX_MENTION_DELEGATIONS_PER_BOT
}
+#[test]
+fn hand_off_caps_leave_room_for_a_team() {
+ assert_eq!((per_bot_limit(), routes_limit()), (4, 16));
+}
+
fn routes_limit() -> usize {
kwnt::server::routes::MAX_DELEGATIONS_PER_REQUEST
}
diff --git a/tests/handoff_continue_test.rs b/tests/handoff_continue_test.rs
new file mode 100644
index 00000000..0890718c
--- /dev/null
+++ b/tests/handoff_continue_test.rs
@@ -0,0 +1,318 @@
+//! A hand-off's board card and the real work agree (2026-10-28: "When I unblock tasks they are
+//! going to ready, but nothing happening with them after"). The board's runner never starts
+//! hand-offs, so a hand-off card the person retries or unblocks carries on in the hand-off's own
+//! thread, or goes to review when the hand-off already finished; a budget block doesn't stop the
+//! live hand-off, and its end is noted on the card. A fake claude CLI on PATH fails a "FAILTASK"
+//! prompt unless it is a carry-on turn and holds a "LONGTASK:<file>" turn until that file exists.
+//! Its own test binary: it changes PATH.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{missions::Task, Database},
+ router::LayaRouter,
+ server::{create_router, missions, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tower::ServiceExt;
+
+const CARRY_ON: &str = "carry on from where you stopped";
+
+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)"
+case "$last" in
+ *"carry on from where you stopped"*) ;;
+ *FAILTASK*) echo "boom" >&2; exit 1 ;;
+esac
+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
+echo '{"type":"result","is_error":false,"num_turns":1,"result":"done"}'
+"#;
+
+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 every one of `markers`.
+fn prompts_with(markers: &[&str]) -> Vec<String> {
+ std::fs::read_dir(prompts_dir())
+ .unwrap()
+ .filter_map(|e| std::fs::read_to_string(e.unwrap().path()).ok())
+ .filter(|p| markers.iter().all(|m| p.contains(m)))
+ .collect()
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ let body = body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).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))
+}
+
+async fn person(env: &Env, method: &str, uri: &str, body: Option<Value>) -> Value {
+ let (s, v) = call(&env.app, method, uri, body).await;
+ assert!(s.is_success(), "{method} {uri}: {s} {v}");
+ v
+}
+
+struct Env {
+ app: Router,
+ state: AppState,
+ lead: String,
+ specialist: String,
+ tmp: tempfile::TempDir,
+}
+
+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);
+ }
+ let (s, v) = call(&app, "POST", "/api/settings", Some(json!({"mission_board": true}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ // The board follows hand-offs on the event bus, as the scheduler starts it in kwnt
+ missions::listener::spawn(state.clone(), tokio_util::sync::CancellationToken::new());
+ 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}");
+}
+
+/// A hand-off from the lead to the specialist that reports back to the lead.
+async fn delegate(env: &Env, task: &str, title: &str) -> Value {
+ let body = json!({"lead_kwant_id": env.lead, "specialist_kwant_id": env.specialist, "task": task, "title": title, "kwant_id": env.lead});
+ let (s, d) = call(&env.app, "POST", "/api/delegations", Some(body)).await;
+ assert_eq!(s, StatusCode::ACCEPTED, "{d}");
+ d
+}
+
+/// A hand-off row that runs nothing until something starts it.
+async fn quiet_delegation(env: &Env, title: &str) -> kwnt::db::threads::Delegation {
+ let new = 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: format!("{title} quietly"),
+ title: title.into(),
+ continue_lead: true,
+ depth: 1,
+ follow_up_at: None,
+ };
+ env.state.db.create_delegation(&new).await.unwrap().1
+}
+
+async fn status_of(env: &Env, id: &str) -> String {
+ env.state.db.get_delegation(id).await.unwrap().map(|d| d.status).unwrap_or_default()
+}
+
+async fn card(env: &Env, delegation_id: &str) -> Option<Task> {
+ env.state.db.task_by_source("delegation", delegation_id).await.unwrap()
+}
+
+async fn card_state(env: &Env, delegation_id: &str) -> String {
+ card(env, delegation_id).await.map(|t| t.state).unwrap_or_default()
+}
+
+fn id(v: &Value) -> String {
+ v["id"].as_str().unwrap().to_string()
+}
+
+/// Moves of the task, as "from>to".
+async fn moves(env: &Env, task_id: &str) -> Vec<String> {
+ let events = env.state.db.task_events(task_id, 200).await.unwrap();
+ events.iter().filter_map(|e| Some(format!("{}>{}", e.from_state.as_deref()?, e.to_state.as_deref()?))).collect()
+}
+
+/// Oleks (2026-10-28): a hand-off card unblocked or retried went to Ready and nothing happened.
+/// Retrying a failed hand-off now carries it on in its own thread: the card is back to working,
+/// the teammate gets a carry-on turn, and its new result reaches the lead.
+#[tokio::test]
+async fn retrying_a_failed_hand_off_carries_it_on_and_the_card_works_again() {
+ let env = setup().await;
+ let d = delegate(&env, "Audit the pricing page FAILTASK RETRYMARK", "Pricing audit").await;
+ let did = id(&d);
+ wait_for("the hand-off to fail", || async { status_of(&env, &did).await == "failed" }).await;
+ wait_for("the card to fail", || async { card_state(&env, &did).await == "failed" }).await;
+ let task = card(&env, &did).await.unwrap();
+
+ person(&env, "POST", &format!("/api/tasks/{}/retry", task.id), None).await;
+ wait_for("the hand-off to finish", || async { status_of(&env, &did).await == "completed" }).await;
+ let carried = prompts_with(&[CARRY_ON, "RETRYMARK"]);
+ assert_eq!(carried.len(), 1, "one carry-on turn");
+ assert!(carried[0].contains("stopped before it was done"), "{}", carried[0]);
+ let reopened = env.state.db.get_delegation(&did).await.unwrap().unwrap();
+ assert_eq!((reopened.thread_id.as_str(), reopened.error.as_deref()), (d["thread_id"].as_str().unwrap(), None), "same thread");
+
+ wait_for("the card to leave working", || async { matches!(card_state(&env, &did).await.as_str(), "review" | "verified") }).await;
+ let m = moves(&env, &task.id).await;
+ let retried = m.iter().position(|x| x == "failed>ready").unwrap();
+ assert!(m[retried..].iter().any(|x| x == "ready>working"), "the card works again: {m:?}");
+ wait_for("the lead's turn", || async { !prompts_with(&["carried on with the task you delegated", "Pricing audit"]).is_empty() }).await;
+}
+
+/// A budget block lands at turn end and never stops the live hand-off: it finishes, and the card
+/// notes it. Unblocked while still over its limit, the card is blocked again (not stuck in Ready);
+/// with the limit removed, unblocking sends it to review without running the work again.
+#[tokio::test]
+async fn a_budget_blocked_hand_off_is_noted_and_goes_on_when_unblocked() {
+ let env = setup().await;
+ let release = env.tmp.path().join("release-budget");
+ let d = delegate(&env, &format!("Long job BUDGETMARK LONGTASK:{}", release.display()), "Long job").await;
+ let did = id(&d);
+ wait_for("the card to work", || async { card_state(&env, &did).await == "working" }).await;
+ let task = card(&env, &did).await.unwrap();
+ person(&env, "PATCH", &format!("/api/tasks/{}", task.id), Some(json!({"budget_tokens": 100}))).await;
+ let started_ms = chrono::Utc::now().timestamp_millis() - 1000;
+ missions::spend(&env.state, &env.specialist, d["thread_id"].as_str().unwrap(), None, started_ms, 150, 0).await;
+ let t = env.state.db.get_task(&task.id).await.unwrap().unwrap();
+ assert_eq!(t.state, "blocked");
+ assert!(matches!(status_of(&env, &did).await.as_str(), "queued" | "running"), "the hand-off goes on");
+
+ std::fs::write(&release, "go").unwrap();
+ wait_for("the hand-off to finish", || async { status_of(&env, &did).await == "completed" }).await;
+ let noted = || async {
+ env.state.db.task_events(&task.id, 50).await.unwrap().into_iter().filter(|e| e.kind == "handoff_ended").count()
+ };
+ wait_for("the card's note", || async { noted().await == 1 }).await;
+ missions::listener::reconcile(&env.state).await;
+ assert_eq!(noted().await, 1, "noted once");
+ assert_eq!(card_state(&env, &did).await, "blocked");
+
+ // Still over its limit: blocked again for the person, not left in Ready
+ person(&env, "POST", &format!("/api/tasks/{}/unblock", task.id), None).await;
+ wait_for("the card to block again", || async { moves(&env, &task.id).await.iter().filter(|m| m.ends_with(">blocked")).count() == 2 }).await;
+ assert_eq!(card_state(&env, &did).await, "blocked");
+
+ // "Remove limit and continue": its result is in, so it goes to review
+ person(&env, "PATCH", &format!("/api/tasks/{}", task.id), Some(json!({"budget_tokens": 0}))).await;
+ person(&env, "POST", &format!("/api/tasks/{}/unblock", task.id), None).await;
+ wait_for("the card to reach review", || async { matches!(card_state(&env, &did).await.as_str(), "review" | "verified") }).await;
+ assert!(prompts_with(&[CARRY_ON, "BUDGETMARK"]).is_empty(), "a finished hand-off isn't run again");
+}
+
+/// Two restarts cut a hand-off short: its card fails (offering Retry) instead of waiting in Ready
+/// for nobody, and a retry carries it on.
+#[tokio::test]
+async fn an_interrupted_hand_off_fails_its_card_and_a_retry_carries_it_on() {
+ let env = setup().await;
+ let d = quiet_delegation(&env, "Cut short INTERRUPTMARK").await;
+ missions::listener::on_delegation(&env.state, &d.id).await;
+ assert_eq!(card_state(&env, &d.id).await, "working");
+ assert!(env.state.db.finish_delegation(&d.id, "interrupted", Some("kwnt restarted"), None).await.unwrap());
+ missions::listener::on_delegation(&env.state, &d.id).await;
+ let task = card(&env, &d.id).await.unwrap();
+ assert_eq!(task.state, "failed");
+
+ person(&env, "POST", &format!("/api/tasks/{}/retry", task.id), None).await;
+ wait_for("the hand-off to finish", || async { status_of(&env, &d.id).await == "completed" }).await;
+ assert_eq!(prompts_with(&[CARRY_ON, "INTERRUPTMARK"]).len(), 1);
+ wait_for("the card to reach review", || async { matches!(card_state(&env, &d.id).await.as_str(), "review" | "verified") }).await;
+}
+
+/// A card left in Ready before this fix, with its hand-off over, doesn't stay stuck: the next
+/// reconcile carries it on, or blocks it with a reason when it can't (here, the teammate is gone).
+#[tokio::test]
+async fn a_stuck_ready_hand_off_card_is_carried_on_or_blocked_with_a_reason() {
+ let env = setup().await;
+ let stuck = |d: &str| format!("UPDATE tasks SET state = 'ready' WHERE source_kind = 'delegation' AND source_id = '{d}'");
+
+ let d = quiet_delegation(&env, "Stuck card STUCKMARK").await;
+ missions::listener::on_delegation(&env.state, &d.id).await;
+ assert!(env.state.db.finish_delegation(&d.id, "failed", Some("the engine stopped"), None).await.unwrap());
+ env.state.db.exec_raw_for_test(&stuck(&d.id)).await.unwrap();
+ env.state.db.exec_raw_for_test("UPDATE agent_claims SET released_at = 1").await.unwrap();
+ missions::listener::reconcile(&env.state).await;
+ wait_for("the hand-off to finish", || async { status_of(&env, &d.id).await == "completed" }).await;
+ let carried = prompts_with(&[CARRY_ON, "STUCKMARK"]);
+ assert_eq!(carried.len(), 1);
+ assert!(carried[0].contains("(the engine stopped)"), "{}", carried[0]);
+
+ // A completed hand-off can't be reopened; one whose teammate is gone can't carry on
+ assert!(!env.state.db.reopen_delegation(&d.id).await.unwrap(), "only an ended, unfinished hand-off reopens");
+ let gone = quiet_delegation(&env, "Gone teammate").await;
+ missions::listener::on_delegation(&env.state, &gone.id).await;
+ assert!(env.state.db.finish_delegation(&gone.id, "cancelled", None, None).await.unwrap());
+ env.state.db.exec_raw_for_test(&stuck(&gone.id)).await.unwrap();
+ env.state.db.exec_raw_for_test("UPDATE agent_claims SET released_at = 1 WHERE released_at IS NULL").await.unwrap();
+ env.state.db.exec_raw_for_test(&format!("UPDATE delegations SET specialist_kwant_id = 'nobody' WHERE id = '{}'", gone.id)).await.unwrap();
+ missions::listener::reconcile(&env.state).await;
+ let t = card(&env, &gone.id).await.unwrap();
+ assert_eq!((t.state.as_str(), t.blocked_reason.as_deref()), ("blocked", Some(missions::listener::CANT_CARRY_ON)));
+}