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): never start a turn in a mode the agent refused to switch to

leepokai9c04b11fc79d
diff --git a/host/src/agent/bot/modes.rs b/host/src/agent/bot/modes.rs
index 91e38ffc..abba6d51 100644
--- a/host/src/agent/bot/modes.rs
+++ b/host/src/agent/bot/modes.rs
@@ -1,9 +1,11 @@
//! Keeps each live session in the bot's mode (`BotConfig::mode`, see `agent::modes`): set once per session, and
//! again after the user picks another. The agent may leave it during the session (Plan, once the plan is approved;
-//! Auto, on a model without it), and that stands until the next session.
+//! Auto, on a model without it), and that stands until the next session. An agent without that mode keeps its own,
+//! and Codync asks about whatever it asks.
-use super::{Actor, NoticeStyle};
+use super::Actor;
use crate::agent::modes::Modes;
+use anyhow::{Context, Result};
use serde_json::{Value, json};
impl Actor {
@@ -14,33 +16,38 @@ impl Actor {
}
}
- /// Switches a live session to the bot's mode before its turn, once per session.
- pub(super) async fn sync_mode(&mut self, sid: &str) {
- let Some(wanted) = self.cfg.mode.clone() else { return };
- let Some(conn) = self.conn.as_mut() else { return };
- if !conn.mode_set.insert(sid.to_owned()) {
- return;
+ /// Switches a live session to the bot's mode before its turn, once per session. A switch the agent refuses
+ /// fails the turn: the bot never works in a mode the user didn't pick.
+ pub(super) async fn sync_mode(&mut self, sid: &str) -> Result<()> {
+ let Some(wanted) = self.cfg.mode.clone() else { return Ok(()) };
+ let Some(conn) = self.conn.as_mut() else { return Ok(()) };
+ if conn.mode_set.contains(sid) {
+ return Ok(());
}
- let Some(modes) = conn.modes.get(sid) else { return };
- let Some(id) = modes.resolve(&wanted).map(str::to_owned) else {
- // An agent without that mode (or without Auto) keeps its own, and asks as it does.
- tracing::info!(bot = %self.cfg.id, mode = wanted, "the agent doesn't offer this mode");
- return;
+ let target = conn.modes.get(sid).map(|modes| {
+ let id = modes.resolve(&wanted).map(str::to_owned);
+ let current = id.is_some() && modes.current == id;
+ let name = modes.list.iter().find(|m| m["id"].as_str() == id.as_deref()).and_then(|m| m["name"].as_str());
+ (id, current, modes.config_id.clone(), name.map(str::to_owned))
+ });
+ let (Some(id), false, config, name) = target.unwrap_or_default() else {
+ // Already in it, or an agent without that mode (or without Auto): it keeps its own and asks as it does.
+ conn.mode_set.insert(sid.to_owned());
+ return Ok(());
};
- if modes.current.as_deref() == Some(id.as_str()) {
- return;
- }
- let (method, params) = match &modes.config_id {
+ let (method, params) = match config {
Some(config) => ("session/set_config_option", json!({"sessionId": sid, "configId": config, "value": id})),
None => ("session/set_mode", json!({"sessionId": sid, "modeId": id})),
};
- match self.session_request(method, params).await {
- Ok(answer) => self.note_options(sid, &answer, super::fast_mode::Listing::Switch),
- Err(error) => {
- tracing::warn!(bot = %self.cfg.id, mode = id, error = format!("{error:#}"), "couldn't set the mode");
- self.notice(&format!("Couldn't switch the agent to its {id} mode: {error:#}"), NoticeStyle::Info);
- }
+ let answer = self.session_request(method, params).await.with_context(|| {
+ let mode = name.unwrap_or_else(|| id.clone());
+ format!("Couldn't switch the agent to {mode}, the mode this bot works in, so this turn didn't start")
+ })?;
+ self.note_options(sid, &answer, super::fast_mode::Listing::Switch);
+ if let Some(conn) = self.conn.as_mut() {
+ conn.mode_set.insert(sid.to_owned());
}
+ Ok(())
}
/// The user picked another mode: every live session switches before its next turn.
diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rs
index 7a229a8e..842585c4 100644
--- a/host/src/agent/bot/turn.rs
+++ b/host/src/agent/bot/turn.rs
@@ -174,7 +174,7 @@ impl Actor {
let session = self.turn_session.clone();
self.hub.set_runtime(&self.id(), |r| r.session.clone_from(&session));
if let Some(sid) = session {
- self.sync_mode(&sid).await;
+ self.sync_mode(&sid).await?;
self.sync_fast_mode(&sid).await;
}
if hidden && self.session_fresh {
diff --git a/host/tests/fixtures/mode_agent.py b/host/tests/fixtures/mode_agent.py
index e9bca3f8..e92f627c 100644
--- a/host/tests/fixtures/mode_agent.py
+++ b/host/tests/fixtures/mode_agent.py
@@ -1,7 +1,8 @@
"""ACP agent with session modes like Codex's adapter: Read-only, Auto review (id `agent`) and Full access, as a
`mode` config option that starts on Read-only. It logs session calls to calls.jsonl in its folder and answers each
prompt with its mode and the prompt text. With a `planless` file in its folder, a prompt moves the session to
-Full access by itself (the way Claude leaves Plan once the plan is approved)."""
+Full access by itself (the way Claude leaves Plan once the plan is approved); with a `stuck` file it refuses
+every mode switch."""
import json
import os
@@ -41,6 +42,8 @@ for line in sys.stdin:
elif method in ("session/new", "session/load"):
log({"method": method})
send({"id": rid, "result": {"sessionId": "s1", **options()}})
+ elif method == "session/set_config_option" and os.path.exists("stuck"):
+ send({"id": rid, "error": {"code": -32603, "message": "mode switch refused"}})
elif method == "session/set_config_option":
log({"method": method, "configId": params["configId"], "value": params["value"]})
mode = params["value"]
diff --git a/host/tests/turns_e2e.rs b/host/tests/turns_e2e.rs
index b35c8830..9d123813 100644
--- a/host/tests/turns_e2e.rs
+++ b/host/tests/turns_e2e.rs
@@ -334,6 +334,33 @@ async fn a_new_bot_works_in_its_agents_auto_mode_until_the_user_picks_another()
assert!(!log.contains("session/load"), "{log}");
}
+#[tokio::test]
+async fn a_bot_never_works_in_a_mode_its_agent_refused_to_switch_to() {
+ if python_missing() {
+ return;
+ }
+ let host = Host::start().await;
+ let bot = host.bot("Stuck", "tests/fixtures/mode_agent.py").await;
+ let folder = host.home.join("Stuck");
+ std::fs::write(folder.join("stuck"), "").unwrap();
+ host.call("updateBot", json!({"id": bot, "mode": "auto"})).await;
+
+ host.call("send", json!({"botId": bot, "text": "one"})).await;
+ let refused = |e: &Value| e["data"]["text"].as_str().is_some_and(|t| t.contains("mode switch refused"));
+ let notice = host.wait_for(&bot, Duration::from_mins(1), refused).await;
+ assert_eq!(notice["kind"], "notice", "{notice}");
+ // Once the agent switches, the next turn runs in the bot's mode.
+ std::fs::remove_file(folder.join("stuck")).unwrap();
+ host.call("send", json!({"botId": bot, "text": "two"})).await;
+ host.wait_for(&bot, Duration::from_mins(1), speed_reply("mode agent ", "two")).await;
+ let entries = host.entries(&bot).await;
+ assert!(
+ !entries
+ .iter()
+ .any(|e| e["kind"] == "agent" && e["data"]["text"].as_str().is_some_and(|t| t.contains("· one")))
+ );
+}
+
#[tokio::test]
async fn a_session_that_ended_in_the_agent_is_closed_and_loaded_again() {
if python_missing() {