Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(host): wait for the agent's answer to a steer before ending a turn

leepokaie29bdaad99bd
diff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.md
index 581696a9..41155a43 100644
--- a/docs/features/context-and-memory.md
+++ b/docs/features/context-and-memory.md
@@ -190,9 +190,10 @@ Claude Code's own memory; the rules live in the `codync-mem` crate, and `chat/me
- Messages sent while the agent works wait above the composer and are folded into one next turn, joined by blank
lines. *Send now* (`steer`) hands one to the agent at once: an agent with `_session/steering` (Claude, Codex, omp)
takes it into the running turn of the user's own chat, and the message joins that turn (its `turn`, its reply,
- memory, a fallback's retry); another agent's turn in the user's chat stops for it, and behind a routine, a room or
- another bot's request it goes first in line. *Remove* (`unqueue`) takes it back: it never goes out, its files are
- deleted and the chat hides it (`removed`).
+ memory, a fallback's retry). The turn's end waits for the agent's answer, at most 15 seconds, so a late `injected`
+ still counts as joined and the bot stays working until then. Another agent's turn in the user's chat stops for it,
+ and behind a routine, a room or another bot's request it goes first in line. *Remove* (`unqueue`) takes it back: it
+ never goes out, its files are deleted and the chat hides it (`removed`).
- Bot-to-bot requests and the replies to them occupy separate turns in the same queue (replies waiting together are one turn); user messages are only folded together up to the next request or reply. Neither feeds dreaming. See [bot collaboration](bot-collaboration.md).
- A request turn (the recipient's) doesn't set the restart marker: its pending notices become interrupted errors instead of automatically replaying work. A reply turn is the sender's own chat turn and sets it, so it resumes like a user turn.
- Stop sends `session/cancel`; an agent still running 15 seconds later is stopped (it resumes its session on
diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rs
index 7c109645..7eff88a6 100644
--- a/host/src/agent/bot/mod.rs
+++ b/host/src/agent/bot/mod.rs
@@ -113,6 +113,7 @@ pub fn spawn(hub: Arc<Hub>, base: BotConfig) -> BotHandle {
turn: None,
queue: VecDeque::new(),
steers_in_flight: HashMap::new(),
+ held_done: None,
active_request: None,
reply_hops: None,
active_prompt: false,
@@ -290,6 +291,8 @@ struct Actor {
queue: VecDeque<Queued>,
/// Queued messages handed to the agent to join the running turn, by entry id, until it answers (`steer`).
steers_in_flight: HashMap<String, steer::InFlight>,
+ /// How the running turn ended, while the agent still owes an answer to a steer (`turn_ended`).
+ held_done: Option<Done>,
active_request: Option<crate::chat::team::BotRequest>,
/// During a turn that takes bot replies: the hops of their chain (see `chat::team::BotReply`).
reply_hops: Option<u8>,
@@ -343,6 +346,32 @@ struct RoutineCompletion {
type Done = Result<Value>;
impl Actor {
+ /// The running turn is over, with every steer answered (`turn_ended`): it finishes or goes on with the next agent.
+ async fn on_turn_done(&mut self, done: Done, done_tx: &mpsc::UnboundedSender<Done>) {
+ // Updates sent before the prompt response are already queued; apply them first.
+ while let Some(inc) = self.conn.as_mut().and_then(|c| c.rx.try_recv().ok()) {
+ match inc {
+ // No agent ends a turn it waits on: a request queued here is for work after it.
+ Incoming::Request { id, method, params } => self.answer_outside_turn(id, &method, &params).await,
+ inc => self.on_incoming(Some(inc)).await,
+ }
+ }
+ if let Err(error) = &done
+ && self.fall_back(error, done_tx).await
+ {
+ return;
+ }
+ let (session, routine) = (self.turn_session.clone(), self.active_routine.is_some());
+ let failed = done.as_ref().is_err_and(acp::may_end_session);
+ self.finish_turn(&done);
+ match session {
+ Some(sid) if routine => self.release_spent(&sid).await,
+ Some(sid) if failed => self.close_reloadable(&sid).await,
+ _ => {}
+ }
+ self.next_in_queue(done_tx).await;
+ }
+
/// `interrupted`: the previous host process stopped a turn in the bot's chat; resume it first.
async fn run(mut self, mut rx: mpsc::UnboundedReceiver<Cmd>, interrupted: Option<Lane>) {
let (done_tx, mut done_rx) = mpsc::unbounded_channel::<Done>();
@@ -362,28 +391,7 @@ impl Actor {
}
Some(file) = self.files.rx.recv() => self.finish_file(file),
inc = recv_incoming(&mut self.conn) => self.on_incoming(inc).await,
- Some(done) = done_rx.recv() => {
- // Updates sent before the prompt response are already queued; apply them first.
- while let Some(inc) = self.conn.as_mut().and_then(|c| c.rx.try_recv().ok()) {
- match inc {
- // No agent ends a turn it waits on: a request queued here is for work after it.
- Incoming::Request { id, method, params } => self.answer_outside_turn(id, &method, &params).await,
- inc => self.on_incoming(Some(inc)).await,
- }
- }
- if let Err(error) = &done && self.fall_back(error, &done_tx).await {
- continue;
- }
- let (session, routine) = (self.turn_session.clone(), self.active_routine.is_some());
- let failed = done.as_ref().is_err_and(acp::may_end_session);
- self.finish_turn(&done);
- match session {
- Some(sid) if routine => self.release_spent(&sid).await,
- Some(sid) if failed => self.close_reloadable(&sid).await,
- _ => {}
- }
- self.next_in_queue(&done_tx).await;
- }
+ Some(done) = done_rx.recv() => self.turn_ended(done, &done_tx).await,
_ = flush_tick.tick() => {
self.flush(false);
self.expire_abandoned().await;
diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rs
index 54440074..44c709d9 100644
--- a/host/src/agent/bot/queue.rs
+++ b/host/src/agent/bot/queue.rs
@@ -20,7 +20,7 @@ impl Actor {
Cmd::Routine(id) => self.enqueue(Queued::Routine(id), done_tx).await,
Cmd::Send { lane, entry_id, text } => self.enqueue(Queued::User { lane, entry_id, text }, done_tx).await,
Cmd::Steer { entry_id } => self.steer(entry_id).await,
- Cmd::Steered { entry_id, outcome } => self.steered(&entry_id, &outcome),
+ Cmd::Steered { entry_id, outcome } => self.steer_answered(&entry_id, &outcome, done_tx).await,
Cmd::Unqueue { entry_id } => self.unqueue(&entry_id),
Cmd::Group(turn) => {
// The room asks again: this turn answers for any still waiting there.
@@ -186,12 +186,7 @@ impl Actor {
self.restart_agent().await;
}
let main = Lane::main(&self.cfg.id);
- // A message being steered is the running turn's or the next one's once the agent answers (`steer`).
- while self.turn.is_none()
- && self.routine_completion.is_none()
- && self.steers_in_flight.is_empty()
- && !self.queue.is_empty()
- {
+ while self.turn.is_none() && self.routine_completion.is_none() && !self.queue.is_empty() {
match self.queue.front() {
Some(Queued::Routine(_)) => {
let Some(Queued::Routine(id)) = self.queue.pop_front() else { unreachable!("front is a routine") };
diff --git a/host/src/agent/bot/steer.rs b/host/src/agent/bot/steer.rs
index f48aa7b1..db6f03dc 100644
--- a/host/src/agent/bot/steer.rs
+++ b/host/src/agent/bot/steer.rs
@@ -1,6 +1,6 @@
//! The user's queued messages before their turn comes: handled now (`steer`) or taken back (`unqueue`).
-use super::{Actor, Cmd, Queued};
+use super::{Actor, Cmd, Done, Queued};
use crate::analytics::{self, Steer, TurnSource};
use crate::chat::team::RequestStatus;
use crate::chat::uploads;
@@ -8,14 +8,13 @@ use crate::store::Lane;
use anyhow::{Result, anyhow};
use serde_json::{Value, json};
use std::time::Duration;
+use tokio::sync::mpsc;
/// How long the agent may take to say whether a steered message joined its turn.
const STEER_ANSWER: Duration = Duration::from_secs(15);
/// A queued message handed to the agent to join its running turn, until the agent answers.
pub(super) struct InFlight {
- /// The turn it joins, even one that ends before the answer comes.
- turn: i64,
/// The user took it back meanwhile (`unqueue`): it goes unless the agent took it.
taken_back: bool,
}
@@ -71,8 +70,7 @@ impl Actor {
/// Hands the message to the agent to join its running turn (`steered` gets the answer); false when it can't steer.
fn hand_to_agent(&mut self, entry_id: String, text: &str) -> bool {
- let (Some(turn), Some(conn), Some(sid)) =
- (self.turn, self.conn.as_ref().filter(|c| c.sessions.steering), self.turn_session.clone())
+ let (Some(conn), Some(sid)) = (self.conn.as_ref().filter(|c| c.sessions.steering), self.turn_session.clone())
else {
return false;
};
@@ -85,7 +83,7 @@ impl Actor {
});
// What the agent writes from here may answer it: a reply of its own, after the message in the chat.
self.close_seg();
- self.steers_in_flight.insert(entry_id.clone(), InFlight { turn, taken_back: false });
+ self.steers_in_flight.insert(entry_id.clone(), InFlight { taken_back: false });
tokio::spawn(async move {
let answer = tokio::time::timeout(STEER_ANSWER, acp.request("_session/steering", params)).await;
let outcome = answer.unwrap_or_else(|_| Err(anyhow!("the agent didn't answer the steer")));
@@ -123,9 +121,34 @@ impl Actor {
}
}
- /// The agent's answer to a steer: a message it took is that turn's, sent; one it left for later goes next; any
- /// other stays queued, unless the user took it back meanwhile.
- pub(super) fn steered(&mut self, entry_id: &str, outcome: &Result<Value>) {
+ /// The agent ended the running turn. Its answer to a steer travels apart from this, and a message it took belongs
+ /// to this turn, so the end waits for every answer (at most `STEER_ANSWER`).
+ pub(super) async fn turn_ended(&mut self, done: Done, done_tx: &mpsc::UnboundedSender<Done>) {
+ if self.steers_in_flight.is_empty() {
+ self.on_turn_done(done, done_tx).await;
+ } else {
+ self.held_done = Some(done);
+ }
+ }
+
+ /// The agent's answer to a steer; the last one lets a held turn end (`turn_ended`).
+ pub(super) async fn steer_answered(
+ &mut self,
+ entry_id: &str,
+ outcome: &Result<Value>,
+ done_tx: &mpsc::UnboundedSender<Done>,
+ ) {
+ self.steered(entry_id, outcome);
+ if self.steers_in_flight.is_empty()
+ && let Some(done) = self.held_done.take()
+ {
+ self.on_turn_done(done, done_tx).await;
+ }
+ }
+
+ /// A message the agent took is the running turn's, sent; one it left for later goes next; any other stays queued,
+ /// unless the user took it back meanwhile.
+ fn steered(&mut self, entry_id: &str, outcome: &Result<Value>) {
let Some(steer) = self.steers_in_flight.remove(entry_id) else { return };
if let Err(error) = outcome {
tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't steer; the message waits");
@@ -146,20 +169,18 @@ impl Actor {
// The host's copy, never `removed`, also brings it back to a client that took it back meanwhile.
if let Some(mut e) = self.hub.store.entry(entry_id) {
e.data["status"] = json!(RequestStatus::Sent);
- self.hub.set_entry_turn(entry_id, Some(steer.turn), &e.data);
+ self.hub.set_entry_turn(entry_id, self.turn, &e.data);
}
- if self.turn == Some(steer.turn) {
- self.joined = true;
- self.turn_entries.push(entry_id.to_owned());
- if let Some(turn_text) = &mut self.turn_text {
- turn_text.push_str("\n\n");
- turn_text.push_str(&text);
- }
- self.relay_joined(entry_id, &text);
- // `send --wait` learns a started message's turn from the bot's next event, and a status and activity that
- // stay the same send none.
- self.hub.emit_bot(&self.cfg.id);
+ self.joined = true;
+ self.turn_entries.push(entry_id.to_owned());
+ if let Some(turn_text) = &mut self.turn_text {
+ turn_text.push_str("\n\n");
+ turn_text.push_str(&text);
}
+ self.relay_joined(entry_id, &text);
+ // `send --wait` learns a started message's turn from the bot's next event, and a status and activity that stay
+ // the same send none.
+ self.hub.emit_bot(&self.cfg.id);
}
/// `unqueue`: the message never goes out, the chat no longer shows it, and its files leave the bot's folder.
diff --git a/host/tests/common/mod.rs b/host/tests/common/mod.rs
index 52a21f6a..aaa45bc5 100644
--- a/host/tests/common/mod.rs
+++ b/host/tests/common/mod.rs
@@ -1,6 +1,7 @@
//! Shared by the end-to-end tests.
pub mod host;
+pub mod steer;
use std::path::Path;
use std::process::{Child, Command, Stdio};
diff --git a/host/tests/common/steer.rs b/host/tests/common/steer.rs
new file mode 100644
index 00000000..3c16db12
--- /dev/null
+++ b/host/tests/common/steer.rs
@@ -0,0 +1,48 @@
+//! A real host's chat with the user's messages queued behind a running turn (`steer_agent.py`).
+
+#![allow(dead_code)]
+
+use super::eventually;
+use super::host::Host;
+use serde_json::{Value, json};
+use std::time::Duration;
+
+pub async fn entries(host: &Host, bot: &str) -> Vec<Value> {
+ host.call("history", json!({"botId": bot})).await["entries"].as_array().unwrap().clone()
+}
+
+pub async fn entry(host: &Host, bot: &str, id: &str) -> Value {
+ entries(host, bot).await.into_iter().find(|e| e["id"] == id).unwrap()
+}
+
+/// Whether `history` no longer lists a message: one taken back.
+pub async fn gone(host: &Host, bot: &str, id: &str) -> bool {
+ entries(host, bot).await.iter().all(|e| e["id"] != id)
+}
+
+/// Sends "first" and waits until its turn runs at the agent: its id.
+pub async fn turn_running(host: &Host, bot: &str) -> String {
+ let first =
+ host.call("send", json!({"botId": bot, "text": "first"})).await["entry"]["id"].as_str().unwrap().to_owned();
+ eventually("the agent got the first prompt", Duration::from_mins(1), async || {
+ host.requests(bot, "session/prompt").len() == 1
+ })
+ .await;
+ first
+}
+
+/// Sends "first" (its turn running at the agent) and then "second", which waits: the ids of both.
+pub async fn queue_behind_a_turn(host: &Host, bot: &str) -> (String, String) {
+ let first = turn_running(host, bot).await;
+ let second = host.call("send", json!({"botId": bot, "text": "second"})).await["entry"].clone();
+ assert_eq!(second["data"]["status"], "queued");
+ (first, second["id"].as_str().unwrap().to_owned())
+}
+
+pub async fn idle(host: &Host, bot: &str) -> bool {
+ super::bot(&host.snapshot().await, bot)["status"] == "idle"
+}
+
+pub async fn status(host: &Host, bot: &str, id: &str) -> Value {
+ entry(host, bot, id).await["data"]["status"].clone()
+}
diff --git a/host/tests/fixtures/steer_agent.py b/host/tests/fixtures/steer_agent.py
index 824b850f..35b18aba 100644
--- a/host/tests/fixtures/steer_agent.py
+++ b/host/tests/fixtures/steer_agent.py
@@ -1,12 +1,13 @@
"""ACP agent whose turn waits: a steered message joins it, a cancel stops it, or it ends after `seconds`.
-Args: `steer|sends|late|limit|next|refuse|lingers|plain seconds [answer_delay]`. With `steer` it advertises
+Args: `steer|sends|late|sends-late|limit|next|refuse|lingers|plain seconds [answer_delay]`. With `steer` it advertises
`_session/steering` (top-level `_meta`, as Claude's and Codex's adapters do) and takes a steered message into its
running turn; with `sends` it also calls `send_message` before it takes the message and again after, before its last
-text; with `late` it ends that turn before answering; with `limit` that turn then fails the way Claude's adapter
-reports a usage limit; with `next` it advertises steering too but always answers that the message needs a turn of its
-own; with `refuse` it answers a steer with an error; with `lingers` it takes two seconds to wind down after a cancel. It
-answers a steer after `answer_delay` seconds. Every request is logged to requests.jsonl in its folder.
+text; with `late` it ends that turn before answering; `sends-late` does both, calling `send_message` once; with `limit`
+that turn then fails the way Claude's adapter reports a usage limit; with `next` it advertises steering too but always
+answers that the message needs a turn of its own; with `refuse` it answers a steer with an error; with `lingers` it
+takes two seconds to wind down after a cancel. It answers a steer after `answer_delay` seconds, so a turn shorter than
+that ends first. Every request is logged to requests.jsonl in its folder.
"""
import json
@@ -57,7 +58,7 @@ def run(rid):
wake = threading.Event()
turn.update(wake=wake, steered=None, cancelled=False)
say("Working")
- if MODE == "sends":
+ if MODE in ("sends", "sends-late"):
send_message("Before it joined")
wake.wait(SECONDS)
turn["wake"] = None
@@ -86,7 +87,7 @@ def steer(message):
send({"id": message["id"], "result": {"outcome": "promptRequired", "reason": "noRunningTurn"}})
return
turn["steered"] = message["params"]["prompt"][0]["text"]
- if MODE == "late":
+ if MODE in ("late", "sends-late"):
wake.set()
time.sleep(0.5)
send({"id": message["id"], "result": {"outcome": "injected"}})
diff --git a/host/tests/steer_e2e.rs b/host/tests/steer_e2e.rs
index 2a933da2..ceef97ca 100644
--- a/host/tests/steer_e2e.rs
+++ b/host/tests/steer_e2e.rs
@@ -1,57 +1,17 @@
-//! A real host with the user's messages queued behind a running turn: steered into it (and on to a fallback with it),
-//! interrupting a turn whose agent can't steer, first in line behind other work, left for the next turn when the agent
-//! says so or refuses, or taken back.
+//! A real host with the user's messages queued behind a running turn: steered into it, interrupting a turn whose agent
+//! can't steer, first in line behind other work, left for the next turn when the agent says so or refuses, or taken
+//! back. A turn that ends before the agent answers: `steer_turn_end_e2e`.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod common;
use common::host::Host;
+use common::steer::{entries, entry, gone, idle, queue_behind_a_turn, status, turn_running};
use common::{eventually, python_missing};
use serde_json::{Value, json};
-use std::path::PathBuf;
use std::time::Duration;
-async fn entries(host: &Host, bot: &str) -> Vec<Value> {
- host.call("history", json!({"botId": bot})).await["entries"].as_array().unwrap().clone()
-}
-
-async fn entry(host: &Host, bot: &str, id: &str) -> Value {
- entries(host, bot).await.into_iter().find(|e| e["id"] == id).unwrap()
-}
-
-/// Whether `history` no longer lists a message: one taken back.
-async fn gone(host: &Host, bot: &str, id: &str) -> bool {
- entries(host, bot).await.iter().all(|e| e["id"] != id)
-}
-
-/// Sends "first" and waits until its turn runs at the agent: its id.
-async fn turn_running(host: &Host, bot: &str) -> String {
- let first =
- host.call("send", json!({"botId": bot, "text": "first"})).await["entry"]["id"].as_str().unwrap().to_owned();
- eventually("the agent got the first prompt", Duration::from_mins(1), async || {
- host.requests(bot, "session/prompt").len() == 1
- })
- .await;
- first
-}
-
-/// Sends "first" (its turn running at the agent) and then "second", which waits: the ids of both.
-async fn queue_behind_a_turn(host: &Host, bot: &str) -> (String, String) {
- let first = turn_running(host, bot).await;
- let second = host.call("send", json!({"botId": bot, "text": "second"})).await["entry"].clone();
- assert_eq!(second["data"]["status"], "queued");
- (first, second["id"].as_str().unwrap().to_owned())
-}
-
-async fn idle(host: &Host, bot: &str) -> bool {
- common::bot(&host.snapshot().await, bot)["status"] == "idle"
-}
-
-async fn status(host: &Host, bot: &str, id: &str) -> Value {
- entry(host, bot, id).await["data"]["status"].clone()
-}
-
#[tokio::test]
async fn a_steered_message_joins_the_running_turn() {
if python_missing() {
@@ -113,45 +73,6 @@ async fn a_steered_message_gets_its_reply_even_after_the_bot_used_send_message()
assert!(reply["seq"].as_i64() > entry(&host, &bot, &second).await["seq"].as_i64());
}
-#[tokio::test]
-async fn a_steered_message_keeps_a_turn_that_ends_before_the_agent_answers() {
- if python_missing() {
- return;
- }
- let host = Host::start().await;
- let bot = host.fixture_bot("Late", "steer_agent.py", "late 30").await;
- let (first, second) = queue_behind_a_turn(&host, &bot).await;
- host.call("steer", json!({"botId": bot, "entryId": second})).await;
- eventually("the agent took it", Duration::from_secs(20), async || status(&host, &bot, &second).await == "sent")
- .await;
- assert_eq!(host.requests(&bot, "session/prompt").len(), 1, "no turn of its own");
- let (first, second) = (entry(&host, &bot, &first).await, entry(&host, &bot, &second).await);
- assert_eq!(second["turn"], first["turn"], "it stays the turn's");
-}
-
-#[tokio::test]
-async fn a_steered_message_goes_with_its_turn_to_the_next_agent() {
- if python_missing() {
- return;
- }
- let host = Host::start().await;
- let bot = host.fixture_bot("Carries", "steer_agent.py", "limit 30").await;
- let standin = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relay_agent.py");
- let standin = format!("{} standin", common::python_agent(&standin));
- let fallbacks = json!([{"backend": "codex", "command": standin}]);
- host.call("updateBot", json!({"id": bot, "fallbacks": fallbacks})).await;
- let (_, second) = queue_behind_a_turn(&host, &bot).await;
- host.call("steer", json!({"botId": bot, "entryId": second})).await;
- let prompt = async || {
- let log = host.log(&bot, "standin.jsonl");
- log.iter().find(|r| r["method"] == "session/prompt").map(|r| r["params"]["prompt"][0]["text"].clone())
- };
- eventually("the next agent took the turn on", Duration::from_secs(30), async || prompt().await.is_some()).await;
- let prompt = prompt().await.unwrap();
- assert!(prompt.as_str().unwrap().contains("first") && prompt.as_str().unwrap().contains("second"), "{prompt}");
- assert_eq!(status(&host, &bot, &second).await, "sent");
-}
-
#[tokio::test]
async fn behind_other_work_a_steered_message_goes_first_in_line() {
if python_missing() {
@@ -420,25 +341,3 @@ async fn a_stop_while_the_agent_decides_keeps_the_message_dropped() {
assert_eq!(dropped["data"]["removed"], Value::Null, "the chat says it wasn't sent");
assert_eq!(host.requests(&bot, "session/prompt").len(), 1);
}
-
-#[tokio::test]
-async fn a_steered_message_is_in_the_exchange_the_bot_learns_from() {
- if python_missing() {
- return;
- }
- let host = Host::start().await;
- let script = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/steer_agent.py");
- let command = format!("{} steer 30", common::python_agent(&script));
- let created = json!({"name": "", "backend": "custom", "command": command, "connectors": [], "notify": false});
- let bot = host.call("createBot", created).await["bot"]["id"].as_str().unwrap().to_owned();
- let (_, second) = queue_behind_a_turn(&host, &bot).await;
- host.call("steer", json!({"botId": bot, "entryId": second})).await;
- let db = rusqlite::Connection::open(host.home.join("codync.db")).unwrap();
- let observed = || -> Option<String> {
- db.query_row("SELECT v FROM kv WHERE k = ?", [format!("naming.turns.{bot}")], |r| r.get(0)).ok()
- };
- eventually("the turn's exchange was recorded", Duration::from_secs(20), async || observed().is_some()).await;
- let turns: Value = serde_json::from_str(&observed().unwrap()).unwrap();
- let user = turns[0]["user"].as_str().unwrap();
- assert!(user.contains("first") && user.contains("second"), "{user}");
-}
diff --git a/host/tests/steer_turn_end_e2e.rs b/host/tests/steer_turn_end_e2e.rs
new file mode 100644
index 00000000..4d5a191a
--- /dev/null
+++ b/host/tests/steer_turn_end_e2e.rs
@@ -0,0 +1,155 @@
+//! A real host where a steered message meets the end of its turn: the end waits for the agent's answer, so a late yes
+//! still makes the message that turn's (its reply, memory, a fallback's retry), and anything else, no answer included,
+//! leaves it for the next turn.
+
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+mod common;
+
+use common::host::Host;
+use common::steer::{entries, entry, idle, queue_behind_a_turn, status};
+use common::{eventually, python_missing};
+use serde_json::{Value, json};
+use std::path::PathBuf;
+use std::time::Duration;
+
+/// What a nameless bot's finished turns recorded, for it to learn from.
+async fn recorded_exchange(host: &Host, bot: &str) -> Value {
+ let db = rusqlite::Connection::open(host.home.join("codync.db")).unwrap();
+ let recorded = || -> Option<String> {
+ db.query_row("SELECT v FROM kv WHERE k = ?", [format!("naming.turns.{bot}")], |r| r.get(0)).ok()
+ };
+ eventually("the turn's exchange was recorded", Duration::from_secs(20), async || recorded().is_some()).await;
+ serde_json::from_str(&recorded().unwrap()).unwrap()
+}
+
+/// `args` make the agent end the turn and then answer without taking the message, or not answer in time: the bot stays
+/// at the turn until then, and the message has the next one.
+async fn it_goes_next(args: &str) {
+ let host = Host::start().await;
+ let bot = host.fixture_bot("Late", "steer_agent.py", args).await;
+ let (first, second) = queue_behind_a_turn(&host, &bot).await;
+ host.call("steer", json!({"botId": bot, "entryId": second})).await;
+ eventually("the message started its own turn", Duration::from_secs(30), async || {
+ host.requests(&bot, "session/prompt").len() == 2
+ })
+ .await;
+ let prompt = &host.requests(&bot, "session/prompt")[1]["params"]["prompt"][0]["text"];
+ assert!(prompt.as_str().unwrap().contains("second"), "{prompt}");
+ let (first, second) = (entry(&host, &bot, &first).await, entry(&host, &bot, &second).await);
+ assert_eq!(second["data"]["status"], "sent");
+ assert_ne!(second["turn"], first["turn"], "a turn of its own");
+ eventually("the bot finished", Duration::from_secs(20), async || idle(&host, &bot).await).await;
+}
+
+/// `args` make the agent's turn fail with a usage limit: the message goes along to the next agent.
+async fn it_goes_with_its_turn_to_the_next_agent(args: &str) {
+ let host = Host::start().await;
+ let bot = host.fixture_bot("Carries", "steer_agent.py", args).await;
+ let standin = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relay_agent.py");
+ let standin = format!("{} standin", common::python_agent(&standin));
+ let fallbacks = json!([{"backend": "codex", "command": standin}]);
+ host.call("updateBot", json!({"id": bot, "fallbacks": fallbacks})).await;
+ let (_, second) = queue_behind_a_turn(&host, &bot).await;
+ host.call("steer", json!({"botId": bot, "entryId": second})).await;
+ let prompt = async || {
+ let log = host.log(&bot, "standin.jsonl");
+ log.iter().find(|r| r["method"] == "session/prompt").map(|r| r["params"]["prompt"][0]["text"].clone())
+ };
+ eventually("the next agent took the turn on", Duration::from_secs(30), async || prompt().await.is_some()).await;
+ let prompt = prompt().await.unwrap();
+ assert!(prompt.as_str().unwrap().contains("first") && prompt.as_str().unwrap().contains("second"), "{prompt}");
+ assert_eq!(status(&host, &bot, &second).await, "sent");
+}
+
+#[tokio::test]
+async fn a_steered_message_keeps_a_turn_that_ends_before_the_agent_answers() {
+ if python_missing() {
+ return;
+ }
+ let host = Host::start().await;
+ let bot = host.fixture_bot("Late", "steer_agent.py", "late 30").await;
+ let (first, second) = queue_behind_a_turn(&host, &bot).await;
+ host.call("steer", json!({"botId": bot, "entryId": second})).await;
+ eventually("the agent took it", Duration::from_secs(20), async || status(&host, &bot, &second).await == "sent")
+ .await;
+ assert_eq!(host.requests(&bot, "session/prompt").len(), 1, "no turn of its own");
+ let (first, second) = (entry(&host, &bot, &first).await, entry(&host, &bot, &second).await);
+ assert_eq!(second["turn"], first["turn"], "it stays the turn's");
+}
+
+#[tokio::test]
+async fn a_turn_that_ends_before_the_agent_answers_still_answers_the_message() {
+ if python_missing() {
+ return;
+ }
+ let host = Host::start().await;
+ let bot = host.fixture_bot("", "steer_agent.py", "sends-late 30").await;
+ let (_, second) = queue_behind_a_turn(&host, &bot).await;
+ eventually("the bot told the user something", Duration::from_secs(20), async || {
+ entries(&host, &bot).await.iter().any(|e| e["data"]["text"].as_str() == Some("Before it joined"))
+ })
+ .await;
+ host.call("steer", json!({"botId": bot, "entryId": second})).await;
+ eventually("the turn ended", Duration::from_secs(20), async || {
+ status(&host, &bot, &second).await == "sent" && idle(&host, &bot).await
+ })
+ .await;
+
+ let reply = entries(&host, &bot)
+ .await
+ .into_iter()
+ .find(|e| e["data"]["text"].as_str().is_some_and(|t| t.contains("Got: ")));
+ assert_eq!(reply.unwrap()["data"]["final"], true, "its reply reaches the chat");
+ let turns = recorded_exchange(&host, &bot).await;
+ assert!(turns[0]["user"].as_str().unwrap().contains("second"), "{turns}");
+}
+
+#[tokio::test]
+async fn a_late_answer_that_leaves_the_message_for_later_gives_it_the_next_turn() {
+ if !python_missing() {
+ it_goes_next("next 3 6").await;
+ }
+}
+
+#[tokio::test]
+async fn a_late_refusal_gives_the_message_the_next_turn() {
+ if !python_missing() {
+ it_goes_next("refuse 3 6").await;
+ }
+}
+
+#[tokio::test]
+async fn an_agent_that_never_answers_only_holds_the_turn_until_the_message_goes_next() {
+ if !python_missing() {
+ it_goes_next("steer 3 60").await;
+ }
+}
+
+#[tokio::test]
+async fn a_steered_message_goes_with_its_turn_to_the_next_agent() {
+ if !python_missing() {
+ it_goes_with_its_turn_to_the_next_agent("limit 30").await;
+ }
+}
+
+#[tokio::test]
+async fn a_message_the_agent_takes_after_its_turn_failed_goes_on_to_the_next_agent() {
+ if !python_missing() {
+ it_goes_with_its_turn_to_the_next_agent("limit 3 6").await;
+ }
+}
+
+#[tokio::test]
+async fn a_steered_message_is_in_the_exchange_the_bot_learns_from() {
+ if python_missing() {
+ return;
+ }
+ let host = Host::start().await;
+ let bot = host.fixture_bot("", "steer_agent.py", "steer 30").await;
+ let (_, second) = queue_behind_a_turn(&host, &bot).await;
+ host.call("steer", json!({"botId": bot, "entryId": second})).await;
+ let turns = recorded_exchange(&host, &bot).await;
+ let user = turns[0]["user"].as_str().unwrap();
+ assert!(user.contains("first") && user.contains("second"), "{user}");
+}