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.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(host): work in the agent's own modes, Auto by default
leepokai80fb813f62c4
diff --git a/host/src/agent/auth/models.rs b/host/src/agent/auth/models.rsindex cab5805f..16d8ebfd 100644--- a/host/src/agent/auth/models.rs+++ b/host/src/agent/auth/models.rs@@ -117,7 +117,8 @@ pub(crate) fn model_ids(session: &Value) -> Vec<String> {catalog["models"].as_array().into_iter().flatten().filter_map(|m| text(&m["id"])).collect()}-/// `{models: [{id, name, description, options}], currentModelId, fastMode}`; `options` is+/// `{models: [{id, name, description, options}], currentModelId, fastMode, modes: [{id, name, description}],+/// currentModeId}` (modes: see `agent::modes`); `options` is/// Cursor's `cursor/list_available_models` answer (`Null` for other agents).fn model_catalog(session: &Value, options: &Value) -> Value {fn collect(options: &Value, out: &mut Vec<Value>) {@@ -152,9 +153,12 @@ fn model_catalog(session: &Value, options: &Value) -> Value {let own = model_options(options, model["id"].as_str().unwrap_or_default());model["options"] = json!(if options.is_null() { initial_options.clone() } else { own });}+ let agent_modes = crate::agent::modes::Modes::from_session(session)+ .map_or_else(|| json!({"modes": [], "currentModeId": null}), |m| m.catalog());json!({"models": models, "currentModelId": current,"defaultModelOptions": true,- "fastMode": crate::agent::config::fast_mode_config(session).is_some()})+ "fastMode": crate::agent::config::fast_mode_config(session).is_some(),+ "modes": agent_modes["modes"], "currentModeId": agent_modes["currentModeId"]})}/// One model's options as `[{id, name, values: [{id, name}], default}]`, from Cursor's@@ -263,7 +267,8 @@ mod tests {assert_eq!(result["models"][0]["description"], "Available here");assert_eq!(model_catalog(&json!({}), &Value::Null),- json!({"models": [], "currentModelId": null, "fastMode": false, "defaultModelOptions": true})+ json!({"models": [], "currentModelId": null, "fastMode": false, "defaultModelOptions": true,+ "modes": [], "currentModeId": null}));}diff --git a/host/src/agent/bot/fast_mode.rs b/host/src/agent/bot/fast_mode.rsindex dabd68d1..667ab040 100644--- a/host/src/agent/bot/fast_mode.rs+++ b/host/src/agent/bot/fast_mode.rs@@ -17,8 +17,9 @@ pub(super) enum Listing {}impl Actor {- /// Records a session's options from an agent answer or a `config_option_update`.+ /// Records a session's options from an agent answer or a `config_option_update`: its modes, and Fast mode.pub(super) fn note_options(&mut self, sid: &str, options: &Value, listing: Listing) {+ self.note_modes(sid, options);if !options["configOptions"].is_array() {// A session without config options has no Fast mode to offer; other answers that// leave them out say nothing, and neither overrides what the agent listed before.diff --git a/host/src/agent/bot/launch.rs b/host/src/agent/bot/launch.rsindex a68c5c39..9d712a9b 100644--- a/host/src/agent/bot/launch.rs+++ b/host/src/agent/bot/launch.rs@@ -161,6 +161,8 @@ pub(crate) async fn start_agent(command: &str, cwd: &str, env: &[(String, Stringstarted: Instant::now(),opening: false,fast_options: HashMap::new(),+ modes: HashMap::new(),+ mode_set: std::collections::HashSet::new(),reports_compaction: false,usage: HashMap::new(),renamed: HashMap::new(),diff --git a/host/src/agent/bot/lifecycle.rs b/host/src/agent/bot/lifecycle.rsindex 56ef9ab2..95b8cc3f 100644--- a/host/src/agent/bot/lifecycle.rs+++ b/host/src/agent/bot/lifecycle.rs@@ -122,6 +122,8 @@ impl Actor {tracing::info!(bot = %self.cfg.id, session = sid, "closed a session");conn.loaded.remove(sid);conn.fast_options.remove(sid);+ conn.modes.remove(sid);+ conn.mode_set.remove(sid);conn.usage.remove(sid);conn.renamed.remove(sid);self.applied_system.remove(sid);diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex 6b8295cd..0152dfe1 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -24,6 +24,7 @@ mod fast_mode;mod files;mod launch;mod lifecycle;+mod modes;mod queue;mod session;mod tool_entry;@@ -183,6 +184,9 @@ pub(crate) struct Conn {opening: bool,/// Each live session's Fast mode option, as the agent last listed it.fast_options: HashMap<String, Value>,+ /// Each live session's modes, as the agent last listed them, and the sessions already switched to the bot's.+ modes: HashMap<String, crate::agent::modes::Modes>,+ mode_set: HashSet<String>,/// The agent reports compactions (`compaction_update`); until it does, a fall in usage stands in for them.reports_compaction: bool,/// Each session's context use and window size at its last `usage_update`.diff --git a/host/src/agent/bot/modes.rs b/host/src/agent/bot/modes.rsnew file mode 100644index 00000000..91e38ffc--- /dev/null+++ b/host/src/agent/bot/modes.rs@@ -0,0 +1,52 @@+//! 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.++use super::{Actor, NoticeStyle};+use crate::agent::modes::Modes;+use serde_json::{Value, json};++impl Actor {+ /// Records the session's modes from an agent answer or a `config_option_update`.+ pub(super) fn note_modes(&mut self, sid: &str, options: &Value) {+ if let (Some(conn), Some(modes)) = (self.conn.as_mut(), Modes::from_session(options)) {+ conn.modes.insert(sid.to_owned(), modes);+ }+ }++ /// 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;+ }+ 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;+ };+ if modes.current.as_deref() == Some(id.as_str()) {+ return;+ }+ let (method, params) = match &modes.config_id {+ 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);+ }+ }+ }++ /// The user picked another mode: every live session switches before its next turn.+ pub(super) fn mode_changed(&mut self) {+ if let Some(conn) = self.conn.as_mut() {+ conn.mode_set.clear();+ }+ }+}diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex aed34621..7b6d7c7a 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -89,12 +89,16 @@ impl Actor {|| memory_changed;// Live sessions switch before their next turn (see `fast_mode`).let fast_changed = cfg.fast_mode != self.cfg.fast_mode;+ let mode_changed = cfg.mode != self.cfg.mode;// Name, description and skill changes reach the agent as a profile update// on the next message (see `context`).self.cfg = cfg;if fast_changed {self.fast_mode_changed();}+ if mode_changed {+ self.mode_changed();+ }if memory_changed {// Claude Code's notes come or go on the memory screen.memory::screen_changed(&self.hub, &self.cfg.id);diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex 39ee6eef..7a229a8e 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -174,6 +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_fast_mode(&sid).await;}if hidden && self.session_fresh {diff --git a/host/src/agent/mod.rs b/host/src/agent/mod.rsindex b229a0a3..b53578b6 100644--- a/host/src/agent/mod.rs+++ b/host/src/agent/mod.rs@@ -8,6 +8,7 @@ pub mod bot;pub mod config;pub mod fallback;pub mod gear;+pub mod modes;pub mod new_bot;pub mod node;pub mod own_memory;diff --git a/host/src/agent/modes.rs b/host/src/agent/modes.rsnew file mode 100644index 00000000..3f78c6ad--- /dev/null+++ b/host/src/agent/modes.rs@@ -0,0 +1,143 @@+//! The agent's session modes: how it asks before it acts (Claude's Manual / Accept edits / Plan / Auto, Codex's+//! Read-only / Auto review / Full access…), as its `mode` config option or the older `modes` field lists them.+//! A bot names the one it wants (`BotConfig::mode`); what still reaches Codync follows the bot's Approvals.++use serde_json::{Value, json};++/// The mode where the agent itself decides what is safe and asks only about the rest. Codync's name for it,+/// and Claude's id: an agent that calls it something else (Codex's `agent`, "Auto review") is listed under it.+pub const AUTO: &str = "auto";++/// A session's modes as the agent last listed them.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Modes {+ /// The config option that switches them; none for an agent that lists only the older `modes` field.+ pub config_id: Option<String>,+ pub current: Option<String>,+ /// `{id, name, description}`, the agent's ids, in its order.+ pub list: Vec<Value>,+}++impl Modes {+ /// From a `session/new` / `session/load` answer or a `config_option_update`; none when the agent lists no modes.+ pub fn from_session(session: &Value) -> Option<Self> {+ if let Some(option) =+ session["configOptions"].as_array().into_iter().flatten().find(|o| o["category"] == "mode")+ {+ let mut list = Vec::new();+ flatten(&option["options"], &mut list);+ return (!list.is_empty()).then(|| Self {+ config_id: text(&option["id"]),+ current: text(&option["currentValue"]),+ list,+ });+ }+ let modes = &session["modes"];+ let list: Vec<Value> =+ modes["availableModes"].as_array().into_iter().flatten().filter_map(|m| entry(&m["id"], m)).collect();+ (!list.is_empty()).then(|| Self { config_id: None, current: text(&modes["currentModeId"]), list })+ }++ /// The agent's id for the mode a bot wants: its own id, or for [`AUTO`] the agent's Auto mode under any name.+ pub fn resolve(&self, wanted: &str) -> Option<&str> {+ let ids = || self.list.iter().filter_map(|m| m["id"].as_str());+ ids().find(|id| *id == wanted).or_else(|| (wanted == AUTO).then(|| self.auto()).flatten())+ }++ /// The agent's Auto mode: Claude's `auto`, or one named "Auto review" (Codex's `agent`).+ fn auto(&self) -> Option<&str> {+ let named = |m: &&Value| m["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case("auto review"));+ self.list.iter().find(|m| m["id"] == AUTO).or_else(|| self.list.iter().find(named))?["id"].as_str()+ }++ /// What clients offer: `{modes, currentModeId}`, the Auto mode first and listed as [`AUTO`], so a bot's choice+ /// carries over to another agent that has one.+ pub fn catalog(&self) -> Value {+ let auto = self.auto();+ let current = self.current.as_deref();+ let current = if current.is_some() && current == auto { Some(AUTO) } else { current };+ let mut modes: Vec<Value> = self.list.clone();+ modes.sort_by_key(|m| m["id"].as_str() != auto);+ for mode in &mut modes {+ if mode["id"].as_str() == auto {+ mode["id"] = AUTO.into();+ }+ }+ json!({"modes": modes, "currentModeId": current})+ }+}++fn flatten(options: &Value, out: &mut Vec<Value>) {+ for option in options.as_array().into_iter().flatten() {+ if option["options"].is_array() {+ flatten(&option["options"], out);+ } else if let Some(mode) = entry(&option["value"], option)+ && !out.iter().any(|m| m["id"] == mode["id"])+ {+ out.push(mode);+ }+ }+}++fn entry(id: &Value, mode: &Value) -> Option<Value> {+ let id = text(id)?;+ Some(+ json!({"name": text(&mode["name"]).unwrap_or_else(|| id.clone()), "description": text(&mode["description"]), "id": id}),+ )+}++fn text(v: &Value) -> Option<String> {+ v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn claude() -> Value {+ json!({"configOptions": [+ {"id": "model", "category": "model", "type": "select", "options": []},+ {"id": "mode", "category": "mode", "type": "select", "currentValue": "default", "options": [+ {"value": "default", "name": "Manual", "description": "Always ask before making changes"},+ {"value": "acceptEdits", "name": "Accept edits"},+ {"value": "plan", "name": "Plan"},+ {"value": "auto", "name": "Auto", "description": "Claude handles permission decisions"}]}]})+ }++ fn codex() -> Value {+ json!({"configOptions": [{"id": "mode", "category": "mode", "type": "select", "currentValue": "agent", "options": [+ {"value": "read-only", "name": "Read-only"},+ {"value": "agent", "name": "Auto review", "description": "Only ask for actions detected as potentially unsafe"},+ {"value": "agent-full-access", "name": "Full access"}]}]})+ }++ #[test]+ fn auto_is_the_agents_own_auto_mode_under_any_id() {+ let claude = Modes::from_session(&claude()).unwrap();+ assert_eq!(claude.config_id.as_deref(), Some("mode"));+ assert_eq!(claude.resolve(AUTO), Some("auto"));+ assert_eq!(claude.resolve("plan"), Some("plan"));+ assert_eq!(claude.resolve("agent"), None, "another agent's id");+ let codex = Modes::from_session(&codex()).unwrap();+ assert_eq!(codex.resolve(AUTO), Some("agent"));+ assert_eq!(codex.resolve("read-only"), Some("read-only"));+ let manual = json!({"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]}});+ let legacy = Modes::from_session(&manual).unwrap();+ assert_eq!((legacy.config_id.as_deref(), legacy.current.as_deref()), (None, Some("ask")));+ assert_eq!(legacy.resolve(AUTO), None, "no Auto mode: the bot asks the user");+ assert!(Modes::from_session(&json!({"configOptions": [{"id": "model", "category": "model"}]})).is_none());+ }++ #[test]+ fn clients_get_the_auto_mode_first_and_under_codyncs_name() {+ let codex = Modes::from_session(&codex()).unwrap().catalog();+ let ids: Vec<&str> = codex["modes"].as_array().unwrap().iter().filter_map(|m| m["id"].as_str()).collect();+ assert_eq!(ids, ["auto", "read-only", "agent-full-access"]);+ assert_eq!(codex["modes"][0]["name"], "Auto review");+ assert_eq!(codex["currentModeId"], "auto");+ let claude = Modes::from_session(&claude()).unwrap().catalog();+ assert_eq!(claude["modes"][0]["id"], "auto");+ assert_eq!(claude["modes"][1]["name"], "Manual");+ assert_eq!(claude["currentModeId"], "default");+ }+}diff --git a/host/src/agent/new_bot.rs b/host/src/agent/new_bot.rsindex 4d32ec7a..95b97ef3 100644--- a/host/src/agent/new_bot.rs+++ b/host/src/agent/new_bot.rs@@ -30,6 +30,10 @@ pub async fn with_defaults(hub: &Arc<Hub>, mut b: Value) -> Result<BotConfig> {if b["skills"].is_null() && b["kind"] != "group" {b["skills"] = json!(market::Installed::Skills.ids(&hub.store)?);}+ // A bot works in its agent's Auto mode and asks about the rest, unless the client picked how it approves.+ if b["permission"].is_null() && b["mode"].is_null() && b["kind"] != "group" {+ b["mode"] = crate::agent::modes::AUTO.into();+ }// And the agent, when the client names none.if b["backend"].as_str().is_none_or(str::is_empty) && b["kind"] != "group" {let agents = tokio::task::spawn_blocking(super::backends::list).await?;diff --git a/host/src/analytics/observe/tests.rs b/host/src/analytics/observe/tests.rsindex aaa6b7f3..1fa283d1 100644--- a/host/src/analytics/observe/tests.rs+++ b/host/src/analytics/observe/tests.rs@@ -222,7 +222,7 @@ async fn store_lookups_add_fields_choice_and_platform() {let (hub, dir) = temp_hub();let cfg = serde_json::from_value(json!({"id": "b1", "name": "b", "backend": "codex", "cwd": "/tmp"})).unwrap();hub.store.save_bot(&cfg).unwrap();- let (_, p) = observe_call(&hub, &Caller::Local, "updateBot", &json!({"id": "b1", "permission": "ask"})).unwrap();+ let (_, p) = observe_call(&hub, &Caller::Local, "updateBot", &json!({"id": "b1", "permission": "auto"})).unwrap();assert_eq!(p["fields"], json!(["permission"]));let card = json!({"status": "pending", "options": [{"optionId": "o1", "name": "Allow", "kind": "allow_always"}]});diff --git a/host/src/chat/calls/context.rs b/host/src/chat/calls/context.rsindex e9f1f3ff..e7bb6366 100644--- a/host/src/chat/calls/context.rs+++ b/host/src/chat/calls/context.rs@@ -360,6 +360,7 @@ pub(super) mod tests {command: None,cwd: cwd.into(),permission: Permission::Ask,+ mode: None,model: Some("opus".into()),model_options: std::collections::BTreeMap::new(),fast_mode: false,diff --git a/host/src/chat/manage.rs b/host/src/chat/manage.rsindex 180eed0e..9977b041 100644--- a/host/src/chat/manage.rs+++ b/host/src/chat/manage.rs@@ -37,13 +37,14 @@ standing instructions: it doesn't share your conversation. The user may approvewhen they deny one, don't retry it unasked. Deleting bots is the user's.";/// The setup a manager sets, by wire name, with its label on approval cards and notices.-const FIELDS: [(&str, &str); 11] = [+const FIELDS: [(&str, &str); 12] = [("name", "Name"),("backend", "Agent"),("model", "Model"),("fallbacks", "Fallbacks"),("cwd", "Folder"),("permission", "Approvals"),+ ("mode", "Mode"),("manageTeam", "Manage the team"),("avatarColor", "Color"),("avatarShape", "Shape"),@@ -144,6 +145,7 @@ async fn create(hub: &Arc<Hub>, source: &BotConfig, args: &Value) -> Result<Valu// A bot's bots act as freely as it does, no more: they manage the team too, under Ask they ask, and they reach// only the connectors and skills it does.fields.insert("permission".into(), json!(source.permission));+ fields.insert("mode".into(), json!(source.mode));fields.insert("manageTeam".into(), true.into());let mut body = Value::Object(fields.clone());body["connectors"] = json!(source.connectors);@@ -231,7 +233,7 @@ fn setup(hub: &Hub, cfg: &BotConfig) -> Value {json!({"id": cfg.id, "name": cfg.name, "instructions": cfg.description, "agent": cfg.backend, "model": cfg.model,"modelOptions": cfg.model_options, "fallbacks": crate::chat::fallbacks::wire(&cfg.fallbacks), "avatarColor": cfg.avatar_color, "avatarShape": cfg.avatar_shape,- "folder": folder, "hidden": cfg.hidden, "approvals": cfg.permission, "manageTeam": cfg.manage_team, "createdBy": cfg.created_by,+ "folder": folder, "hidden": cfg.hidden, "approvals": cfg.permission, "mode": cfg.mode, "manageTeam": cfg.manage_team, "createdBy": cfg.created_by,"routines": hub.routines.list(&cfg.id)["routines"],})}diff --git a/host/src/chat/manage/tests.rs b/host/src/chat/manage/tests.rsindex a125f78e..1b533214 100644--- a/host/src/chat/manage/tests.rs+++ b/host/src/chat/manage/tests.rs@@ -6,7 +6,8 @@ fn hub(dir: &std::path::Path) -> Arc<Hub> {let store = Store::open(std::path::Path::new(":memory:")).unwrap();for (id, manage) in [("lead", true), ("dev", false)] {let cfg: BotConfig = serde_json::from_value(json!({"id": id, "name": id, "backend": "claude",- "cwd": dir.to_string_lossy(), "manageTeam": manage, "connectors": ["github"], "skills": []}))+ "cwd": dir.to_string_lossy(), "manageTeam": manage, "connectors": ["github"], "skills": [],+ "permission": "auto", "mode": "plan"})).unwrap();store.save_bot(&cfg).unwrap();}@@ -48,6 +49,7 @@ async fn a_manager_creates_and_changes_bots_that_record_who_made_them() {);// It manages the team like the bot that made it, and asks no less.assert_eq!((cfg.created_by.as_deref(), cfg.permission, cfg.manage_team), (Some("lead"), Permission::Auto, true));+ assert_eq!(cfg.mode.as_deref(), Some("plan"), "in the same mode");// And reaches only the connectors and skills it does, not every installed one.assert_eq!((cfg.connectors, cfg.skills), (vec!["github".to_owned()], vec![]));assert_eq!(made["routines"][0]["triggerDescriptions"][0], "Every 30 minutes");diff --git a/host/src/hub/validate.rs b/host/src/hub/validate.rsindex 41ba9a8e..44036649 100644--- a/host/src/hub/validate.rs+++ b/host/src/hub/validate.rs@@ -22,5 +22,9 @@ pub(crate) fn validate(cfg: &BotConfig) -> Result<()> {{bail!("unknown backend {}", cfg.backend);}+ // An id the agent listed (`agent::modes`), sent back to it as is.+ if cfg.mode.as_deref().is_some_and(|m| m.trim().is_empty() || m.len() > 64) {+ bail!("mode must be one of the agent's mode ids, or null for its default");+ }crate::agent::fallback::check(cfg)}diff --git a/host/src/store/bots.rs b/host/src/store/bots.rsindex ca4a0df0..1cc8313a 100644--- a/host/src/store/bots.rs+++ b/host/src/store/bots.rs@@ -173,6 +173,7 @@ mod tests {command: None,cwd: "/tmp".into(),permission: Permission::Ask,+ mode: None,model: None,model_options: std::collections::BTreeMap::new(),fast_mode: false,diff --git a/host/src/store/model.rs b/host/src/store/model.rsindex 8929a86e..1077fcaf 100644--- a/host/src/store/model.rs+++ b/host/src/store/model.rs@@ -4,14 +4,15 @@ use serde::{Deserialize, Serialize};use serde_json::Value;use std::collections::BTreeMap;-/// How a bot handles the agent's permission requests (wire values `ask` / `auto`).+/// How a bot handles the permission requests that reach Codync (wire values `ask` / `auto`). Which ones reach it is+/// the agent's mode (`BotConfig::mode`).#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]#[serde(rename_all = "lowercase")]pub enum Permission {- /// Every request becomes an approval card on the phone.- Ask,- /// Requests are approved once, automatically. New bots start here.+ /// Every request becomes an approval card on the phone. New bots start here, in the agent's Auto mode.#[default]+ Ask,+ /// Requests are approved once, automatically.Auto,}@@ -79,6 +80,10 @@ pub struct BotConfig {pub cwd: String,#[serde(default)]pub permission: Permission,+ /// The agent mode to work in (see `agent::modes`): its own id, or `auto` for its Auto mode under any id. None+ /// keeps the agent's default, as do agents without that mode.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mode: Option<String>,#[serde(default)]pub model: Option<String>,/// The model's own settings (effort, fast…): ACP config option id → value.diff --git a/host/src/tui/app/approvals.rs b/host/src/tui/app/approvals.rsnew file mode 100644index 00000000..035b3ae4--- /dev/null+++ b/host/src/tui/app/approvals.rs@@ -0,0 +1,124 @@+//! The bot form's Approvals: the agent's modes, its Auto mode first (`agent::modes`), then Codync approving+//! everything. An agent without modes offers Ask me instead; one whose list hasn't come yet, Auto and Ask me.++use super::{App, Form, cycle};+use crate::agent::modes::AUTO;+use serde_json::Value;++/// The modes an agent's model list came with (`agentModels`).+#[derive(Clone, Debug, Default)]+pub struct AgentModes {+ /// `(id, name)`, Auto first and listed as `auto`.+ pub list: Vec<(String, String)>,+ /// The mode its sessions start in.+ pub current: Option<String>,+}++impl AgentModes {+ pub fn parse(v: &Value) -> Self {+ let list = v["modes"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|m| {+ let id = m["id"].as_str()?;+ Some((id.to_owned(), m["name"].as_str().unwrap_or(id).to_owned()))+ })+ .collect();+ Self { list, current: v["currentModeId"].as_str().map(str::to_owned) }+ }+}++/// One Approvals choice: the mode to work in and whether Codync approves what still asks.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Approval {+ pub mode: Option<String>,+ pub auto: bool,+ pub label: String,+}++impl Approval {+ fn new(mode: Option<&str>, auto: bool, label: &str) -> Self {+ Self { mode: mode.map(str::to_owned), auto, label: label.to_owned() }+ }+}++impl App {+ /// What the form offers for `backend`.+ pub fn approvals(&self, backend: &str) -> Vec<Approval> {+ let ask = Approval::new(None, false, "Ask me");+ let approve = Approval::new(None, true, "Approve automatically");+ match self.modes.get(backend) {+ None => vec![Approval::new(Some(AUTO), false, "Auto"), ask, approve],+ Some(m) if m.list.is_empty() => vec![ask, approve],+ Some(m) => m+ .list+ .iter()+ .map(|(id, name)| Approval::new(Some(id), false, name))+ .chain(std::iter::once(approve))+ .collect(),+ }+ }++ /// The choice the form's setting shows as: an unset mode is the one the agent starts in.+ pub fn approval(&self, f: &Form) -> Approval {+ let choices = self.approvals(&f.backend);+ let current = self.modes.get(&f.backend).and_then(|m| m.current.as_deref());+ let mode = f.mode.as_deref().or(current);+ let pick = |c: &&Approval| {+ if f.auto {+ c.auto+ } else {+ !c.auto && (c.mode.as_deref() == mode || (c.mode.is_none() && f.mode.is_none()))+ }+ };+ let first = choices.iter().find(|c| !c.auto).cloned();+ choices.iter().find(pick).cloned().or(first).unwrap_or_else(|| Approval::new(None, f.auto, "Ask me"))+ }++ pub(super) fn cycle_approval(&self, f: &mut Form, d: isize) {+ let choices = self.approvals(&f.backend);+ let now = self.approval(f);+ let i = choices.iter().position(|c| *c == now).unwrap_or(0);+ let next = &choices[cycle(i, d, choices.len())];+ (f.mode, f.auto) = (next.mode.clone(), next.auto);+ }+}++#[cfg(test)]+mod tests {+ use super::super::{Overlay, test_app};+ use super::*;+ use serde_json::json;++ fn form(app: &mut App, bot: &Value) -> Form {+ app.bots.insert("b".into(), super::super::Bot::parse(bot).expect("a bot"));+ app.selected = Some("b".into());+ app.edit_bot();+ let Some(Overlay::Form(f)) = app.overlays.pop() else { panic!("the editor opens") };+ *f+ }++ #[tokio::test]+ async fn approvals_list_the_agents_modes_then_approve_automatically() {+ let mut app = test_app();+ let codex = json!({"modes": [{"id": "auto", "name": "Auto review"}, {"id": "read-only", "name": "Read-only"}],+ "currentModeId": "auto"});+ app.modes.insert("codex".into(), AgentModes::parse(&codex));+ let mut f = form(&mut app, &json!({"id": "b", "backend": "codex", "permission": "ask", "mode": "auto"}));+ assert_eq!(app.approval(&f).label, "Auto review");+ let labels: Vec<String> = app.approvals("codex").into_iter().map(|c| c.label).collect();+ assert_eq!(labels, ["Auto review", "Read-only", "Approve automatically"]);+ app.cycle_approval(&mut f, 1);+ assert_eq!((f.mode.as_deref(), f.auto), (Some("read-only"), false));+ app.cycle_approval(&mut f, 1);+ assert_eq!((f.mode.as_deref(), f.auto), (None, true));+ assert_eq!(f.changes(), json!({"permission": "auto", "mode": null}));++ // An agent without modes asks about everything; one whose list hasn't come yet offers Auto too.+ app.modes.insert("gemini".into(), AgentModes::default());+ let f = form(&mut app, &json!({"id": "b", "backend": "gemini", "permission": "ask", "mode": "auto"}));+ assert_eq!(app.approval(&f).label, "Ask me");+ assert_eq!(app.approvals("other").len(), 3);+ }+}diff --git a/host/src/tui/app/bot.rs b/host/src/tui/app/bot.rsindex d908ff11..2a4f848a 100644--- a/host/src/tui/app/bot.rs+++ b/host/src/tui/app/bot.rs@@ -30,6 +30,8 @@ pub struct Bot {pub cwd: String,pub managed_workspace: bool,pub auto: bool,+ /// The agent mode it works in (`agent::modes`); none for the agent's default.+ pub mode: Option<String>,pub model: Option<String>,/// The model's own settings (effort, fast…): option id → value.pub model_options: BTreeMap<String, String>,@@ -173,6 +175,7 @@ impl Bot {cwd: s("cwd"),managed_workspace: v["managedWorkspace"] == true,auto: v["permission"] == "auto",+ mode: v["mode"].as_str().map(str::to_owned),model: v["model"].as_str().filter(|m| !m.is_empty()).map(str::to_owned),model_options: v["modelOptions"].as_object()diff --git a/host/src/tui/app/forms.rs b/host/src/tui/app/forms.rsindex a249db23..f3e7d928 100644--- a/host/src/tui/app/forms.rs+++ b/host/src/tui/app/forms.rs@@ -1,12 +1,12 @@-//! The bot settings form and the new/edit group chat form.+//! The bot settings form.use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};use serde_json::{Value, json};use std::collections::BTreeMap;use super::{- After, App, Bot, COLORS, Editor, FIELDS, Field, Form, GroupField, GroupForm, Overlay, PairCode, SHAPES, Toggle,- cycle, merge_toggles,+ After, App, COLORS, Editor, FIELDS, Field, Form, GroupField, GroupForm, Overlay, PairCode, SHAPES, Toggle, cycle,+ merge_toggles,};use crate::tui::manage::Page;@@ -16,92 +16,6 @@ impl App {self.call("pairing", json!({}), After::Pairing);}- pub(super) fn new_group(&mut self) {- self.overlays.push(Overlay::Group(GroupForm {- group_id: None,- name: Editor::default(),- about: Editor::default(),- members: vec![],- field: GroupField::Bots,- cursor: 0,- error: None,- saving: false,- }));- }-- /// Bots a group can hold: the roster's agents, plus hidden ones already in it.- pub fn group_candidates(&self, members: &[String]) -> Vec<&Bot> {- let mut v: Vec<&Bot> = self.roster().into_iter().filter(|b| !b.group).collect();- v.extend(self.bots.values().filter(|b| b.hidden && !b.group && members.contains(&b.id)));- v- }-- /// "Alice, Bob" when no name is typed.- pub fn group_default_name(&self, members: &[String]) -> String {- let names: Vec<&str> = members.iter().filter_map(|m| self.bots.get(m)).map(|b| b.name.as_str()).collect();- names.join(", ")- }-- pub(super) fn group_key(&mut self, mut g: GroupForm, k: KeyEvent) -> Option<Overlay> {- let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);- let n = self.group_candidates(&g.members).len();- let about = g.group_id.is_some();- match k.code {- KeyCode::Esc => return None,- KeyCode::Enter => self.save_group(&mut g),- KeyCode::Char('s') if ctrl => self.save_group(&mut g),- KeyCode::Tab => g.field = g.field.next(about),- KeyCode::BackTab => g.field = g.field.prev(about),- KeyCode::Down if g.field != GroupField::Bots => g.field = g.field.next(about),- KeyCode::Down => g.cursor = (g.cursor + 1).min(n.saturating_sub(1)),- KeyCode::Up if g.field == GroupField::About => g.field = GroupField::Name,- KeyCode::Up if g.field == GroupField::Bots && g.cursor == 0 => g.field = g.field.prev(about),- KeyCode::Up if g.field == GroupField::Bots => g.cursor -= 1,- KeyCode::Char(' ') if g.field == GroupField::Bots => {- let id = self.group_candidates(&g.members).get(g.cursor).map(|b| b.id.clone());- if let Some(id) = id {- g.error = None;- if let Some(i) = g.members.iter().position(|m| *m == id) {- g.members.remove(i);- } else {- g.members.push(id);- }- }- }- _ if g.field == GroupField::Name => {- g.name.key(k);- }- _ if g.field == GroupField::About => {- g.about.key(k);- }- _ => {}- }- Some(Overlay::Group(g))- }-- fn save_group(&mut self, g: &mut GroupForm) {- if g.saving {- return;- }- if g.members.is_empty() {- g.error = Some("Pick at least one bot.".into());- return;- }- let typed = g.name.text.trim();- let name = if typed.is_empty() { self.group_default_name(&g.members) } else { typed.to_owned() };- let mut body = json!({"name": name, "members": g.members, "description": g.about.text.trim()});- g.saving = true;- g.error = None;- if let Some(id) = &g.group_id {- body["id"] = id.clone().into();- self.call("updateBot", body, After::Saved);- } else {- body["id"] = "".into();- body["kind"] = "group".into();- self.call("createBot", body, After::Saved);- }- }-pub(in crate::tui) fn edit_bot(&mut self) {if let Some(id) = self.selected.clone() {self.edit_bot_of(&id);@@ -136,6 +50,7 @@ impl App {self_fallbacks: b.self_fallbacks,cwd: if b.managed_workspace { String::new() } else { b.cwd.clone() },auto: b.auto,+ mode: b.mode.clone(),notify: b.notify,computer: b.computer,manage_team: b.manage_team,@@ -261,12 +176,14 @@ impl App {f.model_options = Default::default();let own = f.backend.clone();f.fallbacks.retain(|x| x.backend != own);+ // Nor its mode ids: its Auto mode, if it has one, is the only choice that carries over.+ f.mode = f.mode.take().filter(|m| m == crate::agent::modes::AUTO);self.want_models(&f.backend);}}Field::Fast => f.fast = !f.fast,Field::SelfFallbacks => f.self_fallbacks = !f.self_fallbacks,- Field::Approvals => f.auto = !f.auto,+ Field::Approvals => self.cycle_approval(&mut f, d),Field::Notify => f.notify = !f.notify,Field::Computer => f.computer = !f.computer,Field::Team => f.manage_team = f.manage_team.map(|on| !on),@@ -360,6 +277,7 @@ impl Form {"backend": self.backend,"cwd": self.cwd,"permission": if self.auto { "auto" } else { "ask" },+ "mode": self.mode,"model": if model.is_empty() { Value::Null } else { model.into() },"modelOptions": self.model_options().cloned().unwrap_or_default(),"fastMode": self.fast,@@ -384,7 +302,7 @@ impl Form {/// What changed since the form opened, as `updateBot` takes it: a change made elsewhere meanwhile (a bot that/// manages the team, another device) stays.- fn changes(&self) -> Value {+ pub(super) fn changes(&self) -> Value {let mut body = self.body();if let (Some(now), Some(opened)) = (body.as_object_mut(), self.opened.as_object()) {now.retain(|key, value| opened.get(key) != Some(value));@@ -395,7 +313,7 @@ impl Form {#[cfg(test)]mod tests {- use super::super::{AgentModel, test_app};+ use super::super::{AgentModel, Bot, test_app};use super::*;#[tokio::test]@@ -467,34 +385,4 @@ mod tests {assert_eq!(changed.get("offeredToNetwork").cloned(), offered.map(Value::from), "{changed}");}}-- #[test]- fn a_new_group_has_no_about_and_an_edited_one_keeps_it() {- let mut app = test_app();- app.bots.insert("a".into(), Bot::parse(&json!({"id": "a", "name": "Ada"})).expect("a bot"));- app.new_group();- let Some(Overlay::Group(mut g)) = app.overlays.pop() else { panic!("the group form opens") };- let mut fields = vec![];- for code in [KeyCode::Tab, KeyCode::Tab, KeyCode::BackTab, KeyCode::Down, KeyCode::Up] {- let Some(Overlay::Group(next)) = app.group_key(g, KeyEvent::from(code)) else { panic!("stays open") };- g = next;- fields.push(g.field);- }- let (n, b) = (GroupField::Name, GroupField::Bots);- assert_eq!(fields, [n, b, n, b, n], "creating skips About");- let Some(Overlay::Group(g)) = app.group_key(g, KeyEvent::from(KeyCode::Char('x'))) else { panic!("stays") };- assert_eq!(g.name.text, "x");- let group = json!({"id": "g", "kind": "group", "name": "Team", "members": ["a"]});- app.bots.insert("g".into(), Bot::parse(&group).expect("a group"));- app.selected = Some("g".into());- app.edit_bot();- let Some(Overlay::Group(mut g)) = app.overlays.pop() else { panic!("the group editor opens") };- let mut fields = vec![];- for _ in 0..3 {- let Some(Overlay::Group(next)) = app.group_key(g, KeyEvent::from(KeyCode::Tab)) else { panic!("stays") };- g = next;- fields.push(g.field);- }- assert_eq!(fields, [GroupField::About, b, n]);- }}diff --git a/host/src/tui/app/group_form.rs b/host/src/tui/app/group_form.rsnew file mode 100644index 00000000..bcfdfa3f--- /dev/null+++ b/host/src/tui/app/group_form.rs@@ -0,0 +1,130 @@+//! The new/edit group chat form.++use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};+use serde_json::json;++use super::{After, App, Bot, Editor, GroupField, GroupForm, Overlay};++impl App {+ pub(super) fn new_group(&mut self) {+ self.overlays.push(Overlay::Group(GroupForm {+ group_id: None,+ name: Editor::default(),+ about: Editor::default(),+ members: vec![],+ field: GroupField::Bots,+ cursor: 0,+ error: None,+ saving: false,+ }));+ }++ /// Bots a group can hold: the roster's agents, plus hidden ones already in it.+ pub fn group_candidates(&self, members: &[String]) -> Vec<&Bot> {+ let mut v: Vec<&Bot> = self.roster().into_iter().filter(|b| !b.group).collect();+ v.extend(self.bots.values().filter(|b| b.hidden && !b.group && members.contains(&b.id)));+ v+ }++ /// "Alice, Bob" when no name is typed.+ pub fn group_default_name(&self, members: &[String]) -> String {+ let names: Vec<&str> = members.iter().filter_map(|m| self.bots.get(m)).map(|b| b.name.as_str()).collect();+ names.join(", ")+ }++ pub(super) fn group_key(&mut self, mut g: GroupForm, k: KeyEvent) -> Option<Overlay> {+ let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);+ let n = self.group_candidates(&g.members).len();+ let about = g.group_id.is_some();+ match k.code {+ KeyCode::Esc => return None,+ KeyCode::Enter => self.save_group(&mut g),+ KeyCode::Char('s') if ctrl => self.save_group(&mut g),+ KeyCode::Tab => g.field = g.field.next(about),+ KeyCode::BackTab => g.field = g.field.prev(about),+ KeyCode::Down if g.field != GroupField::Bots => g.field = g.field.next(about),+ KeyCode::Down => g.cursor = (g.cursor + 1).min(n.saturating_sub(1)),+ KeyCode::Up if g.field == GroupField::About => g.field = GroupField::Name,+ KeyCode::Up if g.field == GroupField::Bots && g.cursor == 0 => g.field = g.field.prev(about),+ KeyCode::Up if g.field == GroupField::Bots => g.cursor -= 1,+ KeyCode::Char(' ') if g.field == GroupField::Bots => {+ let id = self.group_candidates(&g.members).get(g.cursor).map(|b| b.id.clone());+ if let Some(id) = id {+ g.error = None;+ if let Some(i) = g.members.iter().position(|m| *m == id) {+ g.members.remove(i);+ } else {+ g.members.push(id);+ }+ }+ }+ _ if g.field == GroupField::Name => {+ g.name.key(k);+ }+ _ if g.field == GroupField::About => {+ g.about.key(k);+ }+ _ => {}+ }+ Some(Overlay::Group(g))+ }++ fn save_group(&mut self, g: &mut GroupForm) {+ if g.saving {+ return;+ }+ if g.members.is_empty() {+ g.error = Some("Pick at least one bot.".into());+ return;+ }+ let typed = g.name.text.trim();+ let name = if typed.is_empty() { self.group_default_name(&g.members) } else { typed.to_owned() };+ let mut body = json!({"name": name, "members": g.members, "description": g.about.text.trim()});+ g.saving = true;+ g.error = None;+ if let Some(id) = &g.group_id {+ body["id"] = id.clone().into();+ self.call("updateBot", body, After::Saved);+ } else {+ body["id"] = "".into();+ body["kind"] = "group".into();+ self.call("createBot", body, After::Saved);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::super::test_app;+ use super::*;++ #[test]+ fn a_new_group_has_no_about_and_an_edited_one_keeps_it() {+ let mut app = test_app();+ app.bots.insert("a".into(), Bot::parse(&json!({"id": "a", "name": "Ada"})).expect("a bot"));+ app.new_group();+ let Some(Overlay::Group(mut g)) = app.overlays.pop() else { panic!("the group form opens") };+ let mut fields = vec![];+ for code in [KeyCode::Tab, KeyCode::Tab, KeyCode::BackTab, KeyCode::Down, KeyCode::Up] {+ let Some(Overlay::Group(next)) = app.group_key(g, KeyEvent::from(code)) else { panic!("stays open") };+ g = next;+ fields.push(g.field);+ }+ let (n, b) = (GroupField::Name, GroupField::Bots);+ assert_eq!(fields, [n, b, n, b, n], "creating skips About");+ let Some(Overlay::Group(g)) = app.group_key(g, KeyEvent::from(KeyCode::Char('x'))) else { panic!("stays") };+ assert_eq!(g.name.text, "x");+ let group = json!({"id": "g", "kind": "group", "name": "Team", "members": ["a"]});+ app.bots.insert("g".into(), Bot::parse(&group).expect("a group"));+ app.selected = Some("g".into());+ app.edit_bot();+ let Some(Overlay::Group(mut g)) = app.overlays.pop() else { panic!("the group editor opens") };+ let mut fields = vec![];+ for _ in 0..3 {+ let Some(Overlay::Group(next)) = app.group_key(g, KeyEvent::from(KeyCode::Tab)) else { panic!("stays") };+ g = next;+ fields.push(g.field);+ }+ assert_eq!(fields, [GroupField::About, b, n]);+ }+}diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rsindex ebd8834b..891076a6 100644--- a/host/src/tui/app/mod.rs+++ b/host/src/tui/app/mod.rs@@ -1,12 +1,14 @@//! TUI state and everything that changes it: host events, keys, mouse, replies.mod analytics;+mod approvals;mod bot;mod editor;mod events;mod exchange;mod fallbacks;mod forms;+mod group_form;mod input;mod model;mod navigate;@@ -18,6 +20,7 @@ mod slash;mod steps;mod ui;+pub use approvals::AgentModes;pub use bot::{AgentModel, Bot, ModelOption, OwnMemory};pub use editor::Editor;pub use exchange::{ConversationRow, Exchange, Item, Outcome, conversation, group, rows};@@ -125,6 +128,8 @@ pub struct App {pub models: HashMap<String, Option<Vec<AgentModel>>>,/// Agents whose model list came with Fast mode.pub fast_mode: HashSet<String>,+ /// The modes each agent's model list came with.+ pub modes: HashMap<String, AgentModes>,/// A setup terminal holding the screen.pub shell: Option<Shell>,/// Chats marked read since their bot's unread count last changed.@@ -200,6 +205,7 @@ impl App {plugins: (vec![], vec![]),models: HashMap::new(),fast_mode: HashSet::new(),+ modes: HashMap::new(),shell: None,reading: HashSet::new(),history_busy: HashSet::new(),diff --git a/host/src/tui/app/new_bot.rs b/host/src/tui/app/new_bot.rsindex cbcfda84..a4cc0123 100644--- a/host/src/tui/app/new_bot.rs+++ b/host/src/tui/app/new_bot.rs@@ -54,13 +54,12 @@ impl App {}impl NewBot {- /// A personal workspace, automatic approvals, notifications on. The agent, connectors and- /// skills are left unset: the host picks the agent and turns on every installed plugin.+ /// A personal workspace, notifications on. The agent, approvals, connectors and skills are left unset: the+ /// host picks the agent, its Auto mode and every installed plugin.fn body(&self) -> Value {json!({"name": self.name.text.trim(),"cwd": "",- "permission": "auto","notify": true,"avatarColor": COLORS[self.color],"avatarShape": SHAPES[self.shape],diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rsindex 721fdac7..b88b2b0d 100644--- a/host/src/tui/app/ui.rs+++ b/host/src/tui/app/ui.rs@@ -232,7 +232,9 @@ pub struct Form {pub fallbacks: Vec<crate::store::Fallback>,pub self_fallbacks: bool,pub cwd: String,+ /// Approvals: Codync approves what still asks, and the agent mode (`agent::modes`).pub auto: bool,+ pub mode: Option<String>,pub notify: bool,pub computer: bool,/// `None`: the host has no Manage the team.diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rsindex cd0d2c42..83dc1c11 100644--- a/host/src/tui/manage/replies.rs+++ b/host/src/tui/manage/replies.rs@@ -219,6 +219,7 @@ impl App {if v["fastMode"] == true {self.fast_mode.insert(backend.clone());}+ self.modes.insert(backend.clone(), crate::tui::app::AgentModes::parse(&v));self.models.insert(backend, Some(list));}Reply::Downloaded => {diff --git a/host/src/tui/view/chat.rs b/host/src/tui/view/chat.rsindex 25ef56d6..a6467f90 100644--- a/host/src/tui/view/chat.rs+++ b/host/src/tui/view/chat.rs@@ -47,7 +47,7 @@ pub(super) fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {let names: Vec<String> = b.members.iter().map(|m| app.author_name(Some(m))).collect();put(buf, x, r.y, room, &truncate(&format!("group · {}", names.join(", ")), usize::from(room)), t.secondary);} else if !narrow {- let mode = if b.auto { "auto" } else { "ask" };+ let mode = if b.auto { "approve all" } else { b.mode.as_deref().unwrap_or("ask") };let fast = match (b.fast_mode, b.fast_refusal().is_some()) {(true, true) => " · ⚡ refused",(true, false) => " · ⚡ fast",diff --git a/host/src/tui/view/forms.rs b/host/src/tui/view/forms.rsindex 844d48b3..ab48136a 100644--- a/host/src/tui/view/forms.rs+++ b/host/src/tui/view/forms.rs@@ -210,8 +210,7 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {);}Field::Approvals => {- let s = if f.auto { "○ Ask ◉ Auto (approve every request)" } else { "◉ Ask ○ Auto" };- put(buf, vx, y, vw, s, t.text.patch(base));+ put(buf, vx, y, vw, &format!("‹ {} ›", tr(&app.approval(f).label)), t.text.patch(base));}Field::Computer => {let s = if f.computer { "◉ On ○ Off" } else { "○ On ◉ Off" };diff --git a/host/tests/fixtures/mode_agent.py b/host/tests/fixtures/mode_agent.pynew file mode 100644index 00000000..e9bca3f8--- /dev/null+++ b/host/tests/fixtures/mode_agent.py@@ -0,0 +1,58 @@+"""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)."""++import json+import os+import sys++mode = "read-only"+++def send(value):+ print(json.dumps({"jsonrpc": "2.0", **value}), flush=True)+++def log(value):+ with open("calls.jsonl", "a", encoding="utf-8") as f:+ f.write(json.dumps(value) + "\n")+++def options():+ return {"configOptions": [{+ "id": "mode", "name": "Mode", "category": "mode", "type": "select", "currentValue": mode,+ "options": [+ {"value": "read-only", "name": "Read-only"},+ {"value": "agent", "name": "Auto review", "description": "Only ask for actions detected as potentially unsafe"},+ {"value": "agent-full-access", "name": "Full access"},+ ],+ }]}+++for line in sys.stdin:+ message = json.loads(line)+ method, rid = message.get("method"), message.get("id")+ if method is None or rid is None:+ continue+ params = message.get("params", {})+ if method == "initialize":+ send({"id": rid, "result": {"protocolVersion": 1, "agentCapabilities": {"loadSession": True}}})+ elif method in ("session/new", "session/load"):+ log({"method": method})+ send({"id": rid, "result": {"sessionId": "s1", **options()}})+ elif method == "session/set_config_option":+ log({"method": method, "configId": params["configId"], "value": params["value"]})+ mode = params["value"]+ send({"id": rid, "result": options()})+ elif method == "session/prompt":+ text = " ".join(b.get("text", "") for b in params.get("prompt", []))+ update = {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": f"mode {mode} · {text}"}}+ send({"method": "session/update", "params": {"sessionId": "s1", "update": update}})+ if os.path.exists("planless"):+ mode = "agent-full-access"+ update = {"sessionUpdate": "config_option_update", **options()}+ send({"method": "session/update", "params": {"sessionId": "s1", "update": update}})+ send({"id": rid, "result": {"stopReason": "end_turn"}})+ else:+ send({"id": rid, "result": {}})diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.jsonindex b6d58e1b..81ae1cb1 100644--- a/host/tests/fixtures/wire-shape.json+++ b/host/tests/fixtures/wire-shape.json@@ -33,6 +33,7 @@"event:bot.bot.managedWorkspace": "bool","event:bot.bot.members": "array","event:bot.bot.memoryRev": "number",+ "event:bot.bot.mode": "string","event:bot.bot.model": "null","event:bot.bot.modelOptions": "object","event:bot.bot.name": "string",diff --git a/host/tests/turns_e2e.rs b/host/tests/turns_e2e.rsindex 33cc1acc..b35c8830 100644--- a/host/tests/turns_e2e.rs+++ b/host/tests/turns_e2e.rs@@ -1,5 +1,6 @@//! A real host driving scripted ACP agents: Stop on an agent that ignores it, room turns-//! that a newer group message replaced, a reaction as the whole reply, and Fast mode across session resumes.+//! that a newer group message replaced, a reaction as the whole reply, Fast mode across session resumes, and the+//! agent mode a bot works in.#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]@@ -296,6 +297,43 @@ async fn a_refused_fast_mode_is_reported_and_not_asked_for_again() {assert_eq!(log().matches(FAST_ON).count(), 2);}+#[tokio::test]+async fn a_new_bot_works_in_its_agents_auto_mode_until_the_user_picks_another() {+ if python_missing() {+ return;+ }+ let host = Host::start().await;+ let cwd = host.home.join("Moded");+ std::fs::create_dir_all(&cwd).unwrap();+ // The agent leaves the mode by itself during a turn, as Claude leaves Plan.+ std::fs::write(cwd.join("planless"), "").unwrap();+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mode_agent.py");+ let bot = json!({"name": "Moded", "backend": "custom", "command": common::python_agent(&agent), "cwd": cwd, "notify": false});+ let created = host.call("createBot", bot).await["bot"].clone();+ assert_eq!(+ (&created["permission"], &created["mode"]),+ (&json!("ask"), &json!("auto")),+ "the default: Auto, then ask"+ );+ let bot = created["id"].as_str().unwrap().to_owned();+ let log = || std::fs::read_to_string(cwd.join("calls.jsonl")).unwrap();++ // `auto` is the agent's Auto mode under its own id.+ host.call("send", json!({"botId": bot, "text": "one"})).await;+ host.wait_for(&bot, Duration::from_mins(1), speed_reply("mode agent ", "one")).await;+ // Leaving it stands for the rest of the session: the mode is set once per session.+ host.call("send", json!({"botId": bot, "text": "two"})).await;+ host.wait_for(&bot, Duration::from_mins(1), speed_reply("mode agent-full-access ", "two")).await;+ assert_eq!(log().matches(r#""configId": "mode""#).count(), 1, "{}", log());++ // The user's pick switches the live session before its next turn.+ host.call("updateBot", json!({"id": bot, "mode": "read-only"})).await;+ host.call("send", json!({"botId": bot, "text": "three"})).await;+ host.wait_for(&bot, Duration::from_mins(1), speed_reply("mode read-only ", "three")).await;+ let log = log();+ assert!(!log.contains("session/load"), "{log}");+}+#[tokio::test]async fn a_session_that_ended_in_the_agent_is_closed_and_loaded_again() {if python_missing() {