Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(macrod): support native Herdr commands, models, and effort (#7370)
Eric Hayes6049c53a8639
diff --git a/crates/coding_agent_worker/README.md b/crates/coding_agent_worker/README.mdindex d0f81abe6c..97bb7b84dd 100644--- a/crates/coding_agent_worker/README.md+++ b/crates/coding_agent_worker/README.md@@ -29,10 +29,50 @@ forwarded in order, including multiple local turns between polls.### Native controls and MCP-Model selection from Macro applies before native launch. Change a running-session's model in its native TUI; macrod rejects remote model changes it cannot-confirm. Unconfirmed prompt submission is reported as an error, never retried by-pressing Enter. Cancellation sends Escape without a delayed input-clearing key.+Model selection from Macro applies before launch and to idle native sessions.+Claude receives `/model <id>`; Codex opens its native model picker, selects the+exact model row, and retains the reasoning level selected by the native picker.+Each key requires the expected dialog, session identity, and unchanged screen+and state generation. Only native confirmation reports success; unexpected+screens require completing the selection in Herdr. The session is not restarted.++The model label follows native transcript metadata, including after a reload.+Codex also reports its live footer model before a turn and reads available models+from its installed CLI catalog. Until the native agent identifies its model, an+unconfigured session reports the native default. Claude identifies the actual+model when its first assistant record arrives.++Unconfirmed prompt submission is reported as an error, never retried by pressing+Enter. Cancellation sends Escape without a delayed input-clearing key.++New and reloaded sessions advertise `/compact`, `/init`, and `/fast` in Macro;+Codex also advertises `/ultrafast`. Speed controls are delivered unchanged to+the native TUI. Macro acknowledges delivery without claiming the setting+changed: check the response in Herdr, including any confirmation or unavailable+mode message. Claude accepts `/fast on` and `/fast off`; bare `/fast` opens its+native controls. Codex's speed commands toggle tiers available to its current+model and account. Claude also advertises `/effort`, with an optional level,+`auto`, or `status`. Codex advertises `/model`, which opens its native model and+reasoning effort picker; choose the level in Herdr. These native controls need not+generate an assistant turn, so they do not wait for transcript output. Ordinary+prompts still require confirmation.++For Codex, `/effort` or `/effort status` reports the active model, effort, and+available levels directly in Macro. `/effort high` (or another supported level)+selects that level in the current model's native picker and waits for the footer+to confirm it. `/effort default` restores the model's catalog default. Explicit+`max` and `ultra` requests can navigate the advanced reasoning picker. Additional+warnings or unrecognized dialogs require native interaction; they are not+accepted automatically. These commands keep the current model and session.++Effort choices are validated by the native agent. Macro's model dropdown only+projects the ACP model option; it does not currently expose a separate effort+selector or mirror effort changes made inside Herdr.++Herdr does not provide command discovery; this is a curated built-in list, not+the full set of native commands or installed skills. Session-switching commands+such as `/resume`, `/new`, and `/fork` are not advertised because Macro tracks a+specific native session. Automatic recovery still resumes that saved session.Remote permission answers require a recognized approval shortcut, the samevisible dialog, and the same Herdr state generation. Sign-in prompts and otherdiff --git a/crates/coding_agent_worker/src/herdr/acp_agent.rs b/crates/coding_agent_worker/src/herdr/acp_agent.rsindex d9b773bcdd..b79c71e9eb 100644--- a/crates/coding_agent_worker/src/herdr/acp_agent.rs+++ b/crates/coding_agent_worker/src/herdr/acp_agent.rs@@ -36,6 +36,10 @@ use agent_fold::domain::transcript::{Fold, LogEvent};use claude_fold::ClaudeLog;use codex_fold::CodexLog;+mod commands;+mod effort;+mod models;+/// The subcommand macrod's harness config names to run this adapter.pub(crate) const SUBCOMMAND: &str = "herdr-acp";@@ -242,8 +246,7 @@ pub async fn run(options: AdapterOptions) -> rootcause::Result<()> {);return;}- let result = adapter.request(&method, params).await;- adapter.respond(id, result);+ adapter.respond_to_request(id, &method, params).await;if let Some(session) = prompt_session {session.prompt_pending.store(false, Ordering::SeqCst);}@@ -284,6 +287,7 @@ struct Session {cwd: PathBuf,mcp_servers: Vec<Value>,model: Mutex<String>,+ effort: Mutex<Option<String>>,native_id: Mutex<Option<String>>,prompt_pending: AtomicBool,live: tokio::sync::Mutex<Option<Live>>,@@ -423,30 +427,14 @@ impl Adapter {"session/load" => self.load_session(¶ms).await,"session/set_config_option" => {let session = self.session(¶ms)?;- let config = params.get("configId").and_then(Value::as_str);- let value = params.get("value").and_then(Value::as_str);- match (config, value) {- (Some(MODEL_CONFIG_ID), Some(model))- if self- .options- .kind- .models()- .iter()- .any(|(id, _)| *id == model)- || self.options.model.as_deref() == Some(model) =>- {- let live = session- .live- .try_lock()- .map_err(|_| RpcError::invalid("cannot change model during a turn"))?;- if live.is_some() && model != *lock(&session.model) {- return Err(RpcError::invalid(- "change the model in the native Herdr session, or select it when starting a new session",- ));- }- model.clone_into(&mut lock(&session.model));- self.save(&session, live.as_ref())?;- Ok(json!({"configOptions": config_options(self.options.kind, model)}))+ let value = params+ .get("value")+ .and_then(Value::as_str)+ .ok_or_else(|| RpcError::invalid("missing configuration value"))?;+ match params.get("configId").and_then(Value::as_str) {+ Some(MODEL_CONFIG_ID) => self.set_model(&session, value).await,+ Some(effort::CONFIG_ID) if self.options.kind == TuiAgent::Codex => {+ self.set_effort(&session, value).await}_ => Err(RpcError::invalid("unsupported configuration option")),}@@ -487,6 +475,7 @@ impl Adapter {.unwrap_or_else(|| DEFAULT_MODEL.to_owned()),),native_id: Mutex::new(None),+ effort: Mutex::new(None),prompt_pending: AtomicBool::new(false),live: tokio::sync::Mutex::new(None),cancel: Mutex::new(None),@@ -494,9 +483,7 @@ impl Adapter {self.save(&session, None)?;lock(&self.sessions).insert(id.clone(), session.clone());self.observe(&session);- Ok(- json!({"sessionId": id, "configOptions": config_options(self.options.kind, &lock(&session.model))}),- )+ Ok(json!({"sessionId": id, "configOptions": self.session_options(&session)}))}fn save(&self, session: &Session, live: Option<&Live>) -> Result<(), RpcError> {@@ -569,6 +556,7 @@ impl Adapter {.cloned().unwrap_or_default(),model: Mutex::new(record.model.clone()),+ effort: Mutex::new(None),native_id: Mutex::new(record.native_id),prompt_pending: AtomicBool::new(false),live: tokio::sync::Mutex::new(None),@@ -582,10 +570,11 @@ impl Adapter {break;}}+ self.sync_model(&session, &live).await;*session.live.lock().await = Some(live);lock(&self.sessions).insert(id.to_owned(), session.clone());self.observe(&session);- Ok(json!({"configOptions": config_options(self.options.kind, &record.model)}))+ Ok(json!({"configOptions": self.session_options(&session)}))}fn observe(self: &Arc<Self>, session: &Arc<Session>) {@@ -593,6 +582,7 @@ impl Adapter {let session = Arc::downgrade(session);let shutdown = self.shutdown.clone();tokio::spawn(async move {+ let mut ticks = 0u32;loop {tokio::select! {() = shutdown.cancelled() => break,@@ -611,11 +601,15 @@ impl Adapter {let Some(live) = guard.as_mut() else {continue;};+ ticks = ticks.wrapping_add(1);if let Err(error) = adapter.forward(&session, live, &mut None) {tracing::warn!(session = %session.id, error = %error.message, "native transcript observation stopped");adapter.turn_complete(&session.id, "failed");break;}+ if ticks.is_multiple_of(STATUS_EVERY) {+ adapter.sync_model(&session, live).await;+ }}});}@@ -688,12 +682,51 @@ impl Adapter {if live.pending.is_empty() {live.pending = self.drain(live)?.into();}+ while let Some(LogEvent::ModelChanged(_)) = live.pending.front() {+ let Some(LogEvent::ModelChanged(model)) = live.pending.pop_front() else {+ unreachable!()+ };+ self.report_model(session, live, &model)?;+ }if !live.pending.is_empty() {return Err(RpcError::invalid("the native transcript has new activity; retry once it has synchronized",));}+ // The observer cannot acquire this session until the turn ends. Publish+ // native settings now, while the freshly started composer is visible.+ self.sync_model(session, live).await;+ if self.options.kind == TuiAgent::Codex+ && let Some(requested) = effort::command(text)+ {+ let requested = requested?;+ let message = tokio::select! {+ () = cancel.cancelled() => return Ok("cancelled"),+ result = tokio::time::timeout(Duration::from_secs(20), self.codex_effort(session, live, requested)) => {+ result.map_err(|_| RpcError::internal("effort change was not confirmed; check the native session in Herdr"))??+ }+ };+ self.notify_update(+ &session.id,+ json!({+ "sessionUpdate":"agent_message_chunk", "content":{"type":"text","text":message},+ }),+ );+ return Ok("end_turn");+ }herdr.prompt_agent(&live.name, text).await?;+ if let Some(command) = commands::native_control(self.options.kind, text) {+ // Herdr acknowledges PTY delivery, not the resulting setting. These+ // commands need not write a transcript entry or start a model turn.+ self.notify_update(&session.id, json!({+ "sessionUpdate": "agent_message_chunk",+ "content": {"type": "text", "text": format!(+ "Sent `{command}` to {} in Herdr. Check its response and complete any confirmation there.",+ self.options.kind.herdr_kind(),+ )},+ }));+ return Ok("end_turn");+ }let outcome = self.follow(herdr, session, live, &cancel).await;*lock(&session.cancel) = None;self.save(session, guard.as_ref())?;@@ -858,6 +891,12 @@ impl Adapter {if !ticks.is_multiple_of(STATUS_EVERY) {continue;}+ // A startup screen may have hidden the footer before submission.+ // Retry without waiting for a model response to release the observer.+ let needs_settings = lock(&session.effort).is_none();+ if needs_settings {+ self.sync_model(session, live).await;+ }let info = match herdr.agent_info(&live.name).await {Ok(info) => {missing = 0;@@ -936,6 +975,9 @@ impl Adapter {}while let Some(event) = live.pending.pop_front() {match event {+ LogEvent::ModelChanged(model) => {+ self.report_model(session, live, &model)?;+ }LogEvent::Update(update) => {moved = true;// Codex logs a command only once it has run, so its logdiff --git a/crates/coding_agent_worker/src/herdr/acp_agent/commands.rs b/crates/coding_agent_worker/src/herdr/acp_agent/commands.rsnew file mode 100644index 0000000000..21c75f4694--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/commands.rs@@ -0,0 +1,100 @@+//! Native command discovery and completion at the ACP boundary. Herdr does+//! not expose a command catalog, so advertise the built-ins we can dispatch.++use super::{Adapter, Arc, TuiAgent, Value, json};++impl Adapter {+ /// Advertise after the successful response: the shared runtime router needs+ /// that response to bind a new ACP session before it can route notifications.+ pub(super) async fn respond_to_request(+ self: &Arc<Self>,+ id: Value,+ method: &str,+ params: Value,+ ) {+ let loading = (method == "session/load")+ .then(|| {+ params+ .get("sessionId")+ .and_then(Value::as_str)+ .map(str::to_owned)+ })+ .flatten();+ let result = self.request(method, params).await;+ let session = result.as_ref().ok().and_then(|response| {+ if method == "session/new" {+ response+ .get("sessionId")+ .and_then(Value::as_str)+ .map(str::to_owned)+ } else {+ loading+ }+ });+ self.respond(id, result);+ if let Some(session) = session {+ self.notify_update(&session, available(self.options.kind));+ }+ }+}++fn available(kind: TuiAgent) -> Value {+ let mut commands = vec![+ json!({"name": "compact", "description": "Compact the native session's context"}),+ json!({"name": "init", "description": "Create repository instructions with the native agent"}),+ ];+ match kind {+ TuiAgent::Claude => commands.extend([+ json!({+ "name": "fast",+ "description": "Set Claude fast mode; without an argument, opens its controls in Herdr",+ "input": {"hint": "on|off (optional)"},+ }),+ json!({+ "name": "effort",+ "description": "Set Claude's reasoning effort or view its current level in Herdr",+ "input": {"hint": "low|medium|high|xhigh|max|auto|status (optional)"},+ }),+ ]),+ TuiAgent::Codex => {+ commands.extend([+ json!({"name": "fast", "description": "Toggle Codex's fast service tier when available for the current model"}),+ json!({"name": "ultrafast", "description": "Toggle Codex's ultrafast service tier when available for the current model"}),+ json!({"name": "effort", "description": "Show or change this session's Codex reasoning effort in Macro", "input":{"hint":"low|medium|high|xhigh|max|ultra|default|status (optional)"}}),+ json!({"name": "model", "description": "Open Codex's model and reasoning effort picker in Herdr"}),+ ]);+ }+ }+ // In particular, do not advertise /resume, /new or /fork: changing the+ // native session identity would detach it from Macro's saved session.+ json!({"sessionUpdate": "available_commands_update", "availableCommands": commands})+}++/// Only standalone native controls may finish on delivery. Ordinary prompts,+/// skills and commands that run the model still require a confirmed turn.+pub(super) fn native_control(kind: TuiAgent, text: &str) -> Option<&str> {+ let text = text.trim();+ if text.contains(['\n', '\r']) {+ return None;+ }+ let mut words = text.split_whitespace();+ let command = words.next()?;+ let argument = words.next();+ let recognized = match kind {+ TuiAgent::Claude => match command {+ "/fast" => matches!(argument, None | Some("on" | "off")),+ "/effort" => matches!(+ argument,+ None | Some("low" | "medium" | "high" | "xhigh" | "max" | "auto" | "status")+ ),+ _ => false,+ },+ TuiAgent::Codex => {+ matches!(command, "/fast" | "/ultrafast" | "/model") && argument.is_none()+ }+ };+ (recognized && words.next().is_none()).then_some(text)+}++#[cfg(test)]+mod test;diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/commands/test.rs b/crates/coding_agent_worker/src/herdr/acp_agent/commands/test.rsnew file mode 100644index 0000000000..13cec857b3--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/commands/test.rs@@ -0,0 +1,86 @@+use super::*;+use agent_fold::domain::fold::FoldMachineImpl;+use agent_fold::domain::log::{AgentSessionId, AgentSessionLog};+use agent_fold::domain::ports::FoldMachine as _;++#[test]+fn advertised_commands_reach_macro_metadata_for_each_provider() {+ for (kind, expected) in [+ (TuiAgent::Claude, vec!["compact", "init", "fast", "effort"]),+ (+ TuiAgent::Codex,+ vec!["compact", "init", "fast", "ultrafast", "effort", "model"],+ ),+ ] {+ let mut fold = FoldMachineImpl::new();+ fold.push(AgentSessionLog {+ agent_session_id: AgentSessionId::new(),+ user_id: None,+ content: serde_json::from_value(json!({+ "direction": "to_server",+ "content": {+ "type": "acp", "jsonrpc": "2.0", "method": "session/update",+ "params": {"sessionId": "test", "update": available(kind)},+ },+ }))+ .unwrap(),+ });+ let names: Vec<_> = fold+ .metadata()+ .available_commands+ .iter()+ .map(|command| command.name.as_str())+ .collect();+ assert_eq!(names, expected);+ assert!(!names.contains(&"resume"));+ assert!(!names.contains(&"new"));+ assert!(!names.contains(&"fork"));+ }+}++#[test]+fn only_standalone_provider_controls_complete_on_delivery() {+ for (kind, text) in [+ (TuiAgent::Claude, "/fast"),+ (TuiAgent::Claude, " /fast on "),+ (TuiAgent::Claude, "/fast off"),+ (TuiAgent::Codex, "/fast"),+ (TuiAgent::Codex, "/ultrafast"),+ (TuiAgent::Claude, "/effort"),+ (TuiAgent::Claude, "/effort low"),+ (TuiAgent::Claude, "/effort medium"),+ (TuiAgent::Claude, "/effort high"),+ (TuiAgent::Claude, "/effort xhigh"),+ (TuiAgent::Claude, "/effort max"),+ (TuiAgent::Claude, "/effort auto"),+ (TuiAgent::Claude, "/effort status"),+ (TuiAgent::Codex, "/model"),+ ] {+ assert_eq!(native_control(kind, text), Some(text.trim()));+ }+ for kind in [TuiAgent::Claude, TuiAgent::Codex] {+ for text in [+ "",+ "hi",+ "/compact",+ "/init",+ "/custom-skill",+ "/fastest",+ "explain /fast",+ "/fast explain this",+ "/fast\nfix the bug",+ "/fast\roff",+ "/effort high explain this",+ "/effort\nfix the bug",+ "/effortful",+ ] {+ assert_eq!(native_control(kind, text), None, "{kind:?}: {text:?}");+ }+ }+ assert_eq!(native_control(TuiAgent::Claude, "/ultrafast"), None);+ assert_eq!(native_control(TuiAgent::Claude, "/fast on extra"), None);+ assert_eq!(native_control(TuiAgent::Codex, "/fast on"), None);+ assert_eq!(native_control(TuiAgent::Claude, "/effort invalid"), None);+ assert_eq!(native_control(TuiAgent::Codex, "/effort high"), None);+ assert_eq!(native_control(TuiAgent::Codex, "/model extra"), None);+}diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/effort.rs b/crates/coding_agent_worker/src/herdr/acp_agent/effort.rsnew file mode 100644index 0000000000..23f0844667--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/effort.rs@@ -0,0 +1,241 @@+//! Session-side Codex effort commands. Codex has no native `/effort` command;+//! translate it through the same guarded native picker as model selection.+use super::models::{Stage, codex_footer, same_session};+use super::*;++const LEVELS: &[(&str, &str)] = &[+ ("none", "None"),+ ("minimal", "Minimal"),+ ("low", "Low"),+ ("medium", "Medium"),+ ("high", "High"),+ ("xhigh", "Extra high"),+ ("max", "Max"),+ ("ultra", "Ultra"),+];+const FOOTER: &str = "Press enter to confirm or esc to go back";+pub(super) const CONFIG_ID: &str = "reasoning_effort";++/// Never reinterpret multiline prompts or longer prose as a setting change.+pub(super) fn command(text: &str) -> Option<Result<Option<&str>, RpcError>> {+ let text = text.trim();+ if text.contains(['\n', '\r']) {+ return None;+ }+ let mut words = text.split_whitespace();+ if words.next()? != "/effort" {+ return None;+ }+ let argument = words.next();+ if words.next().is_some() {+ return None;+ }+ Some(match argument {+ None | Some("status") => Ok(None),+ Some("default" | "auto") => Ok(Some("default")),+ Some(value) if LEVELS.iter().any(|(id, _)| *id == value) => Ok(Some(value)),+ _ => Err(RpcError::invalid(+ "unknown effort; use /effort to see the session's choices",+ )),+ })+}++impl Adapter {+ /// Return the complete ACP snapshot consumed by Macro's model/effort menu.+ /// Until the native footer confirms an effort, don't guess from defaults.+ pub(super) fn session_options(&self, session: &Session) -> Value {+ let model = lock(&session.model).clone();+ let mut options = self.model_options(&model);+ if self.options.kind == TuiAgent::Codex+ && let Some(current) = lock(&session.effort).as_deref()+ && let Some(preset) = self.codex_preset(&model)+ && let Some(levels) = preset["supported_reasoning_levels"].as_array()+ {+ let mut choices: Vec<_> = levels+ .iter()+ .filter_map(|level| {+ let value = level["effort"].as_str()?;+ let name = LEVELS.iter().find(|(id, _)| *id == value)?.1;+ Some(json!({"value":value,"name":name}))+ })+ .collect();+ if !choices.is_empty() {+ if !choices.iter().any(|choice| choice["value"] == current) {+ choices.push(json!({"value":current,"name":current}));+ }+ options+ .as_array_mut()+ .expect("model options are an array")+ .push(json!({+ "id":CONFIG_ID,"name":"Reasoning effort","category":"thought_level",+ "type":"select","currentValue":current,"options":choices,+ }));+ }+ }+ options+ }++ fn codex_preset(&self, model: &str) -> Option<Value> {+ let bytes = std::fs::read(self.home.as_ref()?.join(".codex/models_cache.json")).ok()?;+ let cache: Value = serde_json::from_slice(&bytes).ok()?;+ cache["models"]+ .as_array()?+ .iter()+ .find(|entry| entry["slug"] == model)+ .cloned()+ }++ pub(super) async fn set_effort(+ &self,+ session: &Session,+ value: &str,+ ) -> Result<Value, RpcError> {+ tokio::time::timeout(Duration::from_secs(20), async {+ if session.prompt_pending.load(Ordering::SeqCst) {+ return Err(RpcError::invalid("cannot change effort during a turn"));+ }+ let guard = tokio::time::timeout(Duration::from_secs(3), session.live.lock())+ .await+ .map_err(|_| RpcError::invalid("native session is busy; retry the selection"))?;+ if session.prompt_pending.load(Ordering::SeqCst) {+ return Err(RpcError::invalid("cannot change effort during a turn"));+ }+ let live = guard.as_ref().ok_or_else(|| {+ RpcError::invalid("start the native session before selecting effort")+ })?;+ self.codex_effort(session, live, Some(value)).await?;+ Ok(json!({"configOptions":self.session_options(session)}))+ })+ .await+ .map_err(|_| {+ RpcError::internal("effort change was not confirmed; check the native session in Herdr")+ })?+ }++ pub(super) async fn codex_effort(+ &self,+ session: &Session,+ live: &Live,+ requested: Option<&str>,+ ) -> Result<String, RpcError> {+ let herdr = self+ .herdr+ .as_ref()+ .ok_or_else(|| RpcError::internal("Herdr is unavailable"))?;+ let info = herdr.agent_info(&live.name).await?;+ if !same_session(session, &info) || !matches!(info.status.as_str(), "idle" | "done") {+ return Err(RpcError::invalid(+ "finish the current native turn or dialog before changing effort",+ ));+ }+ let screen = herdr.read_agent(&live.name).await?;+ let (model, current) = codex_footer(&screen).ok_or_else(|| {+ RpcError::invalid(+ "cannot read Codex's active model and effort; return to its composer in Herdr",+ )+ })?;+ let preset = self.codex_preset(model);+ let preset = preset.as_ref();+ let choices: Vec<_> = preset+ .and_then(|preset| preset["supported_reasoning_levels"].as_array())+ .into_iter()+ .flatten()+ .filter_map(|level| level["effort"].as_str())+ .collect();+ let Some(requested) = requested else {+ self.report_settings(session, live, model, Some(current))?;+ let options = if choices.is_empty() {+ "Use /effort <level>, e.g. /effort high. The native picker validates availability."+ .to_owned()+ } else {+ format!(+ "Available: {}. Use /effort <level> or /effort default.",+ choices.join(", ")+ )+ };+ return Ok(format!(+ "Codex is using **{model}** with **{current}** effort. {options}"+ ));+ };+ let wanted = if requested == "default" {+ preset+ .and_then(|preset| preset["default_reasoning_level"].as_str())+ .ok_or_else(|| {+ RpcError::invalid(+ "Codex's default effort is unavailable; choose an explicit level",+ )+ })?+ } else {+ requested+ };+ if !LEVELS.iter().any(|(id, _)| *id == wanted)+ || (!choices.is_empty() && !choices.contains(&wanted) && current != wanted)+ {+ return Err(RpcError::invalid(format!(+ "{model} supports: {}",+ choices.join(", ")+ )));+ }+ if current != wanted {+ self.native_selection(session, live, model, Some(wanted))+ .await?;+ }+ self.report_settings(session, live, model, Some(wanted))?;+ Ok(format!(+ "Codex is now using **{wanted}** effort with **{model}**."+ ))+ }+}++pub(super) fn picker_key(+ stage: Stage,+ model: &str,+ effort: &str,+ screen: &str,+) -> Option<(String, Stage)> {+ if matches!(stage, Stage::Model) {+ return super::models::picker_key(stage, model, screen);+ }+ if !screen.trim_end().ends_with(FOOTER) {+ return None;+ }+ let standard = screen+ .lines()+ .any(|line| line.trim() == format!("Select Reasoning Level for {model}"));+ let advanced = screen+ .lines()+ .any(|line| line.trim() == "Advanced Reasoning");+ if !(matches!(stage, Stage::Effort) && standard || matches!(stage, Stage::Advanced) && advanced)+ {+ return None;+ }+ let label = LEVELS.iter().find(|(id, _)| *id == effort)?.1;+ if let Some(key) = row(screen, label) {+ return Some((key, Stage::Confirmation));+ }+ if matches!(stage, Stage::Effort) && matches!(effort, "max" | "ultra") {+ return row(screen, "More reasoning…").map(|key| (key, Stage::Advanced));+ }+ None+}++fn row(screen: &str, label: &str) -> Option<String> {+ screen.lines().find_map(|line| {+ let (number, text) = line+ .trim()+ .trim_start_matches('›')+ .trim()+ .split_once(". ")?;+ if number.len() != 1 || !matches!(number.parse::<u8>(), Ok(1..=9)) {+ return None;+ }+ (text == label+ || text+ .strip_prefix(label)+ .is_some_and(|rest| rest.starts_with(' ')))+ .then(|| number.to_owned())+ })+}++#[cfg(test)]+mod test;diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/effort/fixtures/herdr.sh b/crates/coding_agent_worker/src/herdr/acp_agent/effort/fixtures/herdr.shnew file mode 100644index 0000000000..4d66a3e0a7--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/effort/fixtures/herdr.sh@@ -0,0 +1,21 @@+#!/bin/sh+cd ROOT+printf '%s\n' "$*" >> calls+stage=$(cat stage)+case "$2" in+ get)+ status=idle+ if [ "$stage" = 3 ] && [ -e fail ]; then status=working; fi+ printf '{"result":{"agent":{"agent_status":"%s","state_change_seq":1}}}\n' "$status" ;;+ read) cat "screen$stage" ;;+ prompt)+ [ "$4" = /model ] || exit 1+ printf 1 > stage ;;+ send-keys)+ case "$stage:$4" in+ 1:2) printf 2 > stage ;;+ 2:3) printf 3 > stage ;;+ *) exit 1 ;;+ esac ;;+ *) exit 1 ;;+esacdiff --git a/crates/coding_agent_worker/src/herdr/acp_agent/effort/fixtures/startup.sh b/crates/coding_agent_worker/src/herdr/acp_agent/effort/fixtures/startup.shnew file mode 100644index 0000000000..19a0f1d27d--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/effort/fixtures/startup.sh@@ -0,0 +1,20 @@+#!/bin/sh+cd ROOT+printf '%s\n' "$*" >> calls+case "$1:$2" in+ tab:create)+ printf '{"result":{"root_pane":{"tab_id":"w1:t1","pane_id":"w1:p1"}}}\n' ;;+ agent:start) touch started ;;+ agent:get)+ status=idle+ if [ -e submitted ]; then status=working; fi+ printf '{"result":{"agent":{"agent_status":"%s","state_change_seq":1}}}\n' "$status" ;;+ agent:read)+ if [ -e delayed ] && [ ! -e submitted ]; then+ printf 'Starting Codex\n'+ else+ cat footer+ fi ;;+ agent:prompt) touch submitted ;;+ *) exit 1 ;;+esacdiff --git a/crates/coding_agent_worker/src/herdr/acp_agent/effort/test.rs b/crates/coding_agent_worker/src/herdr/acp_agent/effort/test.rsnew file mode 100644index 0000000000..2c2f1e48a3--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/effort/test.rs@@ -0,0 +1,431 @@+use super::*;+use crate::herdr::acp_agent::test::{save_transcript, test_adapter};+use std::os::unix::fs::PermissionsExt as _;++const PICKER: &str = include_str!("../models/fixtures/codex-effort.txt");++async fn startup_settings(delayed: bool) {+ let root = tempfile::tempdir().unwrap();+ std::fs::create_dir(root.path().join(".codex")).unwrap();+ std::fs::write(+ root.path().join(".codex/models_cache.json"),+ json!({"models":[{+ "slug":"gpt-6-sol", "supported_reasoning_levels":[{"effort":"medium"},{"effort":"high"}]+ }]})+ .to_string(),+ )+ .unwrap();+ std::fs::write(+ root.path().join("footer"),+ include_str!("../models/fixtures/codex-after.txt"),+ )+ .unwrap();+ if delayed {+ std::fs::write(root.path().join("delayed"), "").unwrap();+ }+ let script = root.path().join("herdr");+ std::fs::write(+ &script,+ include_str!("fixtures/startup.sh")+ .replace("ROOT", &shell_words::quote(&root.path().to_string_lossy())),+ )+ .unwrap();+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();+ let (mut adapter, mut output) = test_adapter(root.path());+ let inner = Arc::get_mut(&mut adapter).unwrap();+ inner.options.kind = TuiAgent::Codex;+ inner.herdr = Some(HerdrCli::new(script, None));+ inner.home = Some(root.path().to_owned());+ // Settings must arrive from the foreground path while the observer is blocked.+ adapter.shutdown.cancel();+ let created = adapter.new_session(&json!({"cwd":root.path()})).unwrap();+ assert_eq!(created["configOptions"].as_array().unwrap().len(), 1);+ assert!(+ !root.path().join("started").exists(),+ "model discovery must remain lazy"+ );+ let id = created["sessionId"].as_str().unwrap().to_owned();+ let session = adapter.session(&json!({"sessionId":id})).unwrap();+ session.prompt_pending.store(true, Ordering::SeqCst);+ let prompt = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {+ adapter+ .request(+ "session/prompt",+ json!({"sessionId":id,"prompt":[{"type":"text","text":"first prompt"}]}),+ )+ .await+ }));+ let update = tokio::time::timeout(Duration::from_secs(5), output.recv())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(+ update["params"]["update"]["sessionUpdate"],+ "config_option_update"+ );+ assert_eq!(+ update["params"]["update"]["configOptions"][0]["currentValue"],+ "gpt-6-sol"+ );+ assert_eq!(+ update["params"]["update"]["configOptions"][1]["currentValue"],+ "medium"+ );+ assert!(+ !prompt.is_finished(),+ "settings must arrive before the first reply"+ );+ tokio::time::timeout(Duration::from_secs(2), async {+ while !root.path().join("submitted").exists() {+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .unwrap();+ let calls = std::fs::read_to_string(root.path().join("calls")).unwrap();+ let reads: Vec<_> = calls.match_indices("agent read").map(|(i, _)| i).collect();+ let submitted = calls.find("agent prompt").unwrap();+ assert!(reads[0] < submitted);+ assert_eq!(reads.iter().any(|i| *i > submitted), delayed);+ prompt.abort();+ let _ = prompt.await;+}++#[tokio::test]+async fn first_prompt_publishes_native_effort_before_the_first_reply() {+ startup_settings(false).await;+}++#[tokio::test]+async fn startup_footer_is_retried_while_the_first_prompt_is_running() {+ startup_settings(true).await;+}++#[test]+fn only_standalone_effort_commands_are_intercepted() {+ for text in ["/effort", " /effort status "] {+ assert_eq!(command(text).unwrap().unwrap(), None);+ }+ for level in ["low", "high", "xhigh", "max", "ultra"] {+ let text = format!("/effort {level}");+ assert_eq!(command(&text).unwrap().unwrap(), Some(level));+ }+ assert_eq!(command("/effort auto").unwrap().unwrap(), Some("default"));+ assert!(command("/effort bogus").unwrap().is_err());+ for text in [+ "/effort high explain this",+ "/effort\nfix this",+ "/effortful",+ "explain /effort",+ ] {+ assert!(command(text).is_none());+ }+}++#[test]+fn explicit_effort_selects_its_row_instead_of_the_highlighted_default() {+ assert_eq!(+ picker_key(Stage::Effort, "gpt-6-sol", "high", PICKER)+ .unwrap()+ .0,+ "3"+ );+ assert_eq!(+ picker_key(Stage::Effort, "gpt-6-sol", "xhigh", PICKER)+ .unwrap()+ .0,+ "4"+ );+ assert!(picker_key(Stage::Effort, "gpt-6-astra", "high", PICKER).is_none());+ assert!(picker_key(Stage::Effort, "gpt-6-sol", "none", PICKER).is_none());+ assert!(picker_key(Stage::Confirmation, "gpt-6-sol", "high", PICKER).is_none());+ assert!(+ picker_key(+ Stage::Effort,+ "gpt-6-sol",+ "high",+ &format!("{PICKER}\nConfirm access to this directory?")+ )+ .is_none()+ );+}++#[test]+fn advanced_effort_requires_the_explicit_requested_level() {+ assert_eq!(+ picker_key(Stage::Effort, "gpt-6-sol", "ultra", PICKER)+ .unwrap()+ .0,+ "5"+ );+ let advanced = "Advanced Reasoning\n⚠ Consumes usage limits faster\n› 1. Max\n 2. Ultra\nPress enter to confirm or esc to go back";+ assert_eq!(+ picker_key(Stage::Advanced, "gpt-6-sol", "max", advanced)+ .unwrap()+ .0,+ "1"+ );+ assert_eq!(+ picker_key(Stage::Advanced, "gpt-6-sol", "ultra", advanced)+ .unwrap()+ .0,+ "2"+ );+ assert!(picker_key(Stage::Effort, "gpt-6-sol", "ultra", advanced).is_none());+ assert!(picker_key(Stage::Advanced, "gpt-6-sol", "high", advanced).is_none());+ assert!(+ picker_key(+ Stage::Advanced,+ "gpt-6-sol",+ "ultra",+ "Allow multiple agents?\n› 1. Yes"+ )+ .is_none()+ );+}++async fn run_command(text: &str, fail: bool) -> (Result<Value, RpcError>, Vec<Value>, String) {+ run_request(Request::Prompt(text), fail).await+}++enum Request<'a> {+ Prompt(&'a str),+ Select(&'a str),+ BusySelect(&'a str),+ Observe,+}++async fn run_request(+ request: Request<'_>,+ fail: bool,+) -> (Result<Value, RpcError>, Vec<Value>, String) {+ let root = tempfile::tempdir().unwrap();+ let id = uuid::Uuid::new_v4().to_string();+ save_transcript(root.path(), &id);+ let mut record = Store(root.path().to_owned()).load(&id).unwrap();+ record.kind = TuiAgent::Codex;+ Store(root.path().to_owned()).save(&record).unwrap();+ let initial = include_str!("../models/fixtures/codex-after.txt");+ for (i, screen) in [+ initial,+ include_str!("../models/fixtures/codex-model.txt"),+ PICKER,+ &initial.replace("medium", "high"),+ ]+ .iter()+ .enumerate()+ {+ std::fs::write(root.path().join(format!("screen{i}")), screen).unwrap();+ }+ std::fs::write(root.path().join("stage"), "0").unwrap();+ if fail {+ std::fs::write(root.path().join("fail"), "").unwrap();+ }+ std::fs::create_dir(root.path().join(".codex")).unwrap();+ std::fs::write(+ root.path().join(".codex/models_cache.json"),+ json!({"models":[{+ "slug":"gpt-6-sol","default_reasoning_level":"high",+ "supported_reasoning_levels":[{"effort":"medium"},{"effort":"high"}]+ }]})+ .to_string(),+ )+ .unwrap();+ let script = root.path().join("herdr");+ std::fs::write(+ &script,+ include_str!("fixtures/herdr.sh")+ .replace("ROOT", &shell_words::quote(&root.path().to_string_lossy())),+ )+ .unwrap();+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();+ let (mut adapter, mut output) = test_adapter(root.path());+ let inner = Arc::get_mut(&mut adapter).unwrap();+ inner.options.kind = TuiAgent::Codex;+ inner.herdr = Some(HerdrCli::new(script, None));+ inner.home = Some(root.path().to_owned());+ adapter.shutdown.cancel();+ let loaded = adapter+ .load_session(&json!({"sessionId":id,"cwd":root.path()}))+ .await+ .unwrap();+ assert_eq!(loaded["configOptions"][1]["id"], CONFIG_ID);+ assert_eq!(loaded["configOptions"][1]["category"], "thought_level");+ assert_eq!(loaded["configOptions"][1]["currentValue"], "medium");+ assert_eq!(+ loaded["configOptions"][1]["options"],+ json!([+ {"value":"medium","name":"Medium"}, {"value":"high","name":"High"}+ ])+ );+ // Production holds this flag during every session/prompt, including commands.+ let session = adapter.session(&json!({"sessionId":id})).unwrap();+ session+ .prompt_pending+ .store(!matches!(request, Request::Select(_)), Ordering::SeqCst);+ if matches!(request, Request::Observe) {+ std::fs::write(root.path().join("stage"), "3").unwrap();+ let guard = session.live.lock().await;+ adapter.sync_model(&session, guard.as_ref().unwrap()).await;+ }+ let (method, params) = match request {+ Request::Prompt(text) => (+ "session/prompt",+ json!({"sessionId":id,"prompt":[{"type":"text","text":text}]}),+ ),+ Request::Select(value) | Request::BusySelect(value) => (+ "session/set_config_option",+ json!({"sessionId":id,"configId":CONFIG_ID,"value":value}),+ ),+ Request::Observe => ("session/load", json!({"sessionId":id,"cwd":root.path()})),+ };+ if matches!(request, Request::Observe) {+ session.prompt_pending.store(false, Ordering::SeqCst);+ }+ let response = adapter.request(method, params).await;+ let mut updates = Vec::new();+ while let Ok(update) = output.try_recv() {+ updates.push(update);+ }+ let calls = std::fs::read_to_string(root.path().join("calls")).unwrap();+ (response, updates, calls)+}++#[tokio::test]+async fn local_effort_changes_are_observed_and_preserved_on_reload() {+ let (response, updates, calls) = run_request(Request::Observe, false).await;+ assert_eq!(+ response.unwrap()["configOptions"][1]["currentValue"],+ "high"+ );+ assert!(+ updates+ .iter()+ .any(|event| event["params"]["update"]["configOptions"][1]["currentValue"] == "high")+ );+ assert!(!calls.contains("agent prompt"));+ assert!(!calls.contains("send-keys"));+}++#[tokio::test]+async fn effort_rpc_selects_current_model_and_requested_effort_and_confirms_in_macro() {+ for text in ["/effort high", "/effort default"] {+ let (response, updates, calls) = run_command(text, false).await;+ assert_eq!(response.unwrap()["stopReason"], "end_turn");+ assert!(updates.iter().any(|event| {+ event["params"]["update"]["content"]["text"]+ .as_str()+ .is_some_and(|text| text.contains("**high** effort with **gpt-6-sol**"))+ }));+ assert!(!calls.contains("/effort"));+ assert!(updates.iter().any(|event| {+ event["params"]["update"]["configOptions"][1]["currentValue"] == "high"+ }));+ let keys: Vec<_> = calls+ .lines()+ .filter(|line| line.starts_with("agent send-keys"))+ .map(|line| line.split_whitespace().last().unwrap())+ .collect();+ assert_eq!(keys, ["2", "3"]);+ }+}++#[tokio::test]+async fn graphical_effort_selection_returns_full_confirmed_configuration_without_chat() {+ let (response, updates, calls) = run_request(Request::Select("high"), false).await;+ let config = response.unwrap()["configOptions"].clone();+ assert_eq!(config[0]["currentValue"], "gpt-6-sol");+ assert_eq!(config[1]["currentValue"], "high");+ assert!(+ updates+ .iter()+ .any(|event| event["params"]["update"]["configOptions"] == config)+ );+ assert!(+ !updates+ .iter()+ .any(|event| event["params"]["update"]["sessionUpdate"] == "agent_message_chunk")+ );+ assert!(calls.contains("agent prompt"));+ assert!(!calls.contains("/effort"));+}++#[tokio::test]+async fn graphical_selection_rejects_busy_unsupported_and_unconfirmed_changes() {+ for (request, fail) in [+ (Request::BusySelect("high"), false),+ (Request::Select("ultra"), false),+ (Request::Select("bogus"), false),+ (Request::Select("high"), true),+ ] {+ let (response, updates, calls) = run_request(request, fail).await;+ assert!(response.is_err());+ assert!(+ !updates.iter().any(+ |event| event["params"]["update"]["configOptions"][1]["currentValue"] == "high"+ )+ );+ if !fail {+ assert!(!calls.contains("agent prompt"));+ assert!(!calls.contains("send-keys"));+ }+ }+}++#[tokio::test]+async fn graphical_selection_of_current_effort_does_not_send_native_input() {+ let (response, _, calls) = run_request(Request::Select("medium"), false).await;+ assert_eq!(+ response.unwrap()["configOptions"][1]["currentValue"],+ "medium"+ );+ assert!(!calls.contains("agent prompt"));+ assert!(!calls.contains("send-keys"));+}++#[tokio::test]+async fn status_and_existing_effort_require_no_native_input() {+ for text in ["/effort", "/effort status", "/effort medium"] {+ let (response, updates, calls) = run_command(text, false).await;+ assert!(response.is_ok());+ assert!(!calls.contains("agent prompt"));+ assert!(!calls.contains("send-keys"));+ assert!(updates.iter().any(|event| {+ event["params"]["update"]["content"]["text"]+ .as_str()+ .is_some_and(|text| text.contains("**medium**"))+ }));+ if text == "/effort" {+ assert!(updates.iter().any(|event| {+ event["params"]["update"]["content"]["text"]+ .as_str()+ .is_some_and(|text| text.contains("Available: medium, high"))+ }));+ }+ }+}++#[tokio::test]+async fn failed_or_unsupported_effort_never_claims_success() {+ for (text, fail) in [+ ("/effort high", true),+ ("/effort ultra", false),+ ("/effort bogus", false),+ ] {+ let (response, updates, _) = run_command(text, fail).await;+ assert!(response.is_err());+ assert!(+ !updates+ .iter()+ .any(|event| event["params"]["update"]["sessionUpdate"] == "agent_message_chunk")+ );+ }+}++#[test]+fn ultra_effort_uses_the_double_chevron_composer() {+ assert_eq!(+ codex_footer("» Ask Codex to do anything\n gpt-6-astra ultra · /repo"),+ Some(("gpt-6-astra", "ultra"))+ );+}diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/models.rs b/crates/coding_agent_worker/src/herdr/acp_agent/models.rsnew file mode 100644index 0000000000..dc45582499--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/models.rs@@ -0,0 +1,395 @@+//! Model configuration translated to the running native TUI. The picker is+//! driven only while its expected screen and session identity still match.++use super::*;++impl Adapter {+ pub(super) fn model_options(&self, current: &str) -> Value {+ let mut config = config_options(self.options.kind, current);+ if self.options.kind == TuiAgent::Codex+ && let Some(home) = &self.home+ && let Ok(bytes) = std::fs::read(home.join(".codex/models_cache.json"))+ && let Ok(cache) = serde_json::from_slice::<Value>(&bytes)+ && let Some(models) = cache.get("models").and_then(Value::as_array)+ {+ let mut choices: Vec<_> = models+ .iter()+ .filter_map(|model| {+ let id = model.get("slug")?.as_str()?;+ if !valid_model(id)+ || model.get("visibility").and_then(Value::as_str) == Some("hide")+ {+ return None;+ }+ let name = model+ .get("display_name")+ .and_then(Value::as_str)+ .unwrap_or(id);+ Some(json!({"value":id,"name":name}))+ })+ .collect();+ if !choices.is_empty() {+ if !choices.iter().any(|option| option["value"] == current) {+ choices.insert(0, json!({"value":current,"name":if current == DEFAULT_MODEL {"Native default (resolved when the agent starts)"} else {current}}));+ }+ config[0]["options"] = json!(choices);+ }+ }+ if current != DEFAULT_MODEL {+ // "default" is a launch policy, not a model the live native picker can select.+ if let Some(options) = config[0]["options"].as_array_mut() {+ options.retain(|option| option["value"] != DEFAULT_MODEL);+ }+ }+ config+ }++ pub(super) fn report_model(+ &self,+ session: &Session,+ live: &Live,+ model: &str,+ ) -> Result<(), RpcError> {+ if *lock(&session.model) == model {+ return Ok(());+ }+ self.report_settings(session, live, model, None)+ }++ pub(super) fn report_settings(+ &self,+ session: &Session,+ live: &Live,+ model: &str,+ effort: Option<&str>,+ ) -> Result<(), RpcError> {+ if *lock(&session.model) == model && lock(&session.effort).as_deref() == effort {+ return Ok(());+ }+ model.clone_into(&mut lock(&session.model));+ *lock(&session.effort) = effort.map(str::to_owned);+ self.save(session, Some(live))?;+ self.notify_update(+ &session.id,+ json!({+ "sessionUpdate":"config_option_update", "configOptions":self.session_options(session),+ }),+ );+ Ok(())+ }++ pub(super) async fn sync_model(&self, session: &Session, live: &Live) {+ // Codex displays the effective model in its live footer even before the+ // first turn_context record. Claude's assistant records carry its ID.+ if self.options.kind != TuiAgent::Codex {+ return;+ }+ let Some(herdr) = &self.herdr else { return };+ let snapshot = tokio::time::timeout(Duration::from_secs(2), async {+ let info = herdr.agent_info(&live.name).await.ok()?;+ if !same_session(session, &info) {+ return None;+ }+ herdr.read_agent(&live.name).await.ok()+ })+ .await;+ let Ok(Some(screen)) = snapshot else { return };+ if let Some((model, effort)) = codex_footer(&screen)+ && let Err(error) = self.report_settings(session, live, model, Some(effort))+ {+ tracing::warn!(error = %error.message, "could not save native model");+ }+ }++ pub(super) async fn set_model(+ &self,+ session: &Arc<Session>,+ model: &str,+ ) -> Result<Value, RpcError> {+ tokio::time::timeout(Duration::from_secs(20), self.apply_model(session, model))+ .await+ .map_err(|_| {+ RpcError::internal(+ "model change was not confirmed; check the native session in Herdr",+ )+ })?+ }++ async fn apply_model(&self, session: &Arc<Session>, model: &str) -> Result<Value, RpcError> {+ let current = lock(&session.model).clone();+ if !valid_model(model)+ || !self.model_options(¤t)[0]["options"]+ .as_array()+ .is_some_and(|options| options.iter().any(|option| option["value"] == model))+ {+ return Err(RpcError::invalid("unsupported model"));+ }+ if session.prompt_pending.load(Ordering::SeqCst) {+ return Err(RpcError::invalid("cannot change model during a turn"));+ }+ // A short observer poll must not cause an otherwise idle model change+ // to fail. Active Macro prompts are rejected before and after waiting.+ let mut guard = tokio::time::timeout(Duration::from_secs(3), session.live.lock())+ .await+ .map_err(|_| RpcError::invalid("native session is busy; retry the selection"))?;+ if session.prompt_pending.load(Ordering::SeqCst) {+ return Err(RpcError::invalid("cannot change model during a turn"));+ }+ let Some(live) = guard.as_mut() else {+ model.clone_into(&mut lock(&session.model));+ *lock(&session.effort) = None;+ self.save(session, None)?;+ return Ok(json!({"configOptions":self.session_options(session)}));+ };+ if model == DEFAULT_MODEL {+ return Err(RpcError::invalid(+ "choose a specific model for a running native session",+ ));+ }+ let herdr = self+ .herdr+ .as_ref()+ .ok_or_else(|| RpcError::internal("Herdr is unavailable"))?;+ let info = herdr.agent_info(&live.name).await?;+ if !same_session(session, &info) || !matches!(info.status.as_str(), "idle" | "done") {+ return Err(RpcError::invalid(+ "finish the current native turn or dialog before changing model",+ ));+ }+ // Synchronize earlier model facts before applying the new setting.+ loop {+ let offset = live.cursor.offset;+ self.forward(session, live, &mut None)?;+ if live.cursor.offset == offset && live.pending.is_empty() {+ break;+ }+ }+ self.sync_model(session, live).await;+ if *lock(&session.model) == model {+ return Ok(json!({"configOptions":self.session_options(session)}));+ }+ let effort = self.native_selection(session, live, model, None).await?;+ self.report_settings(session, live, model, effort.as_deref())?;+ Ok(json!({"configOptions":self.session_options(session)}))+ }+ /// Drive only the recognized native picker, verifying the resulting setting.+ pub(super) async fn native_selection(+ &self,+ session: &Session,+ live: &Live,+ model: &str,+ effort: Option<&str>,+ ) -> Result<Option<String>, RpcError> {+ let herdr = self+ .herdr+ .as_ref()+ .ok_or_else(|| RpcError::internal("Herdr is unavailable"))?;+ let info = herdr.agent_info(&live.name).await?;+ if !same_session(session, &info) || !matches!(info.status.as_str(), "idle" | "done") {+ return Err(RpcError::invalid(+ "finish the current native turn or dialog before changing settings",+ ));+ }+ let before = herdr.read_agent(&live.name).await?;+ let check = herdr.agent_info(&live.name).await?;+ if !same_session(session, &check)+ || info.state_change_seq != check.state_change_seq+ || !matches!(check.status.as_str(), "idle" | "done")+ {+ return Err(RpcError::invalid(+ "native session changed; retry the selection",+ ));+ }+ tokio::time::timeout(Duration::from_secs(15), async {+ herdr+ .prompt_agent(+ &live.name,+ &match self.options.kind {+ TuiAgent::Claude => format!("/model {model}"),+ TuiAgent::Codex => "/model".to_owned(),+ },+ )+ .await?;+ let mut stage = Stage::Model;+ loop {+ tokio::time::sleep(POLL).await;+ let info = herdr.agent_info(&live.name).await?;+ if !same_session(session, &info)+ || !matches!(info.status.as_str(), "idle" | "done" | "blocked")+ {+ return Err(RpcError::invalid(+ "native session changed while selecting a model",+ ));+ }+ let screen = herdr.read_agent(&live.name).await?;+ if (self.options.kind == TuiAgent::Claude || matches!(stage, Stage::Confirmation))+ && confirmed(self.options.kind, model, &before, &screen)+ && effort.is_none_or(|wanted| {+ codex_footer(&screen).is_some_and(|(_, actual)| wanted == actual)+ })+ {+ return Ok(codex_footer(&screen).map(|(_, effort)| effort.to_owned()));+ }+ if self.options.kind == TuiAgent::Codex+ && let Some((key, next)) = effort.map_or_else(+ || picker_key(stage, model, &screen),+ |effort| super::effort::picker_key(stage, model, effort, &screen),+ )+ {+ let check = herdr.agent_info(&live.name).await?;+ if !same_session(session, &check)+ || info.state_change_seq != check.state_change_seq+ || herdr.read_agent(&live.name).await? != screen+ {+ return Err(RpcError::invalid(+ "native model picker changed; retry the selection",+ ));+ }+ herdr.send_keys(&live.name, &[&key]).await?;+ stage = next;+ }+ }+ })+ .await+ .map_err(|_| {+ RpcError::internal(+ "model or effort change was not confirmed; check the native picker in Herdr",+ )+ })?+ }+}++fn valid_model(model: &str) -> bool {+ !model.is_empty()+ && !model.starts_with('/')+ && !model.chars().any(char::is_whitespace)+ && !model.chars().any(char::is_control)+}++pub(super) fn same_session(session: &Session, info: &super::super::cli::AgentInfo) -> bool {+ info.cwd.as_ref().is_none_or(|cwd| cwd == &session.cwd)+ && info+ .session_id+ .as_ref()+ .zip(lock(&session.native_id).as_ref())+ .is_none_or(|(actual, expected)| actual == expected)+}++#[derive(Clone, Copy)]+pub(super) enum Stage {+ Model,+ Effort,+ Confirmation,+ Advanced,+}++pub(super) fn picker_key(stage: Stage, model: &str, screen: &str) -> Option<(String, Stage)> {+ match stage {+ Stage::Model+ if screen+ .lines()+ .any(|line| line.trim() == "Select Model and Effort")+ && screen+ .trim_end()+ .ends_with("Press enter to confirm or esc to go back") =>+ {+ let section = screen.split_once("Select Model and Effort")?.1;+ for line in section.lines() {+ let line = line.trim().trim_start_matches('›').trim();+ let Some((number, rest)) = line.split_once(". ") else {+ continue;+ };+ if number.len() == 1+ && matches!(number.parse::<u8>(), Ok(1..=9))+ && rest.split_whitespace().next() == Some(model)+ {+ return Some((number.to_owned(), Stage::Effort));+ }+ }+ None+ }+ Stage::Effort+ if screen+ .lines()+ .any(|line| line.trim() == format!("Select Reasoning Level for {model}"))+ && screen+ .trim_end()+ .ends_with("Press enter to confirm or esc to go back") =>+ {+ // Do not accept a warning or the nested "More reasoning" menu.+ let selected = screen+ .lines()+ .find_map(|line| line.trim().strip_prefix('›'))?;+ let (_, level) = selected.trim().split_once(". ")?;+ if !["Low", "Medium", "High", "Extra high", "Max", "Ultra"]+ .iter()+ .any(|level_name| {+ level == *level_name+ || level+ .strip_prefix(level_name)+ .is_some_and(|rest| rest.starts_with(' '))+ })+ {+ return None;+ }+ Some(("enter".to_owned(), Stage::Confirmation))+ }+ _ => None,+ }+}++fn codex_footer_model(screen: &str) -> Option<&str> {+ codex_footer(screen).map(|(model, _)| model)+}++pub(super) fn codex_footer(screen: &str) -> Option<(&str, &str)> {+ let (_, footer) = screen.rsplit_once(['›', '»'])?;+ footer.lines().skip(1).find_map(|line| {+ let (left, _) = line.trim().split_once('·')?;+ let mut words = left.split_whitespace();+ let model = words.next()?;+ let effort = words.next()?;+ (valid_model(model)+ && matches!(+ effort,+ "default"+ | "none"+ | "minimal"+ | "low"+ | "medium"+ | "high"+ | "xhigh"+ | "max"+ | "ultra"+ ))+ .then_some((model, effort))+ })+}++fn confirmed(kind: TuiAgent, model: &str, before: &str, screen: &str) -> bool {+ match kind {+ TuiAgent::Codex => codex_footer_model(screen) == Some(model),+ TuiAgent::Claude => {+ // Old scrollback is not confirmation. Require a new native result+ // line; ambiguous/repeated screens stay unconfirmed.+ let result = |text: &str| {+ text.lines().rev().find_map(|line| {+ let line = line.trim().trim_start_matches('⎿').trim();+ line.strip_prefix("Set model to ").map(str::to_owned)+ })+ };+ let Some(selected) = result(screen) else {+ return false;+ };+ if result(before).as_deref() == Some(&selected) {+ return false;+ }+ let selected = selected.split(['(', ' ']).next().unwrap_or("");+ selected.eq_ignore_ascii_case(model)+ || selected.eq_ignore_ascii_case(model.strip_prefix("claude-").unwrap_or(model))+ }+ }+}++#[cfg(test)]+mod test;diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/models/fixtures/codex-after.txt b/crates/coding_agent_worker/src/herdr/acp_agent/models/fixtures/codex-after.txtnew file mode 100644index 0000000000..14a85fac8c--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/models/fixtures/codex-after.txt@@ -0,0 +1,4 @@+│ model: gpt-6-astra /model to change │+• Model changed to gpt-6-sol medium+› Ask Codex to do anything+ gpt-6-sol medium · /repo\ No newline at end of filediff --git a/crates/coding_agent_worker/src/herdr/acp_agent/models/fixtures/codex-before.txt b/crates/coding_agent_worker/src/herdr/acp_agent/models/fixtures/codex-before.txtnew file mode 100644index 0000000000..5d3ebf1896--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/models/fixtures/codex-before.txt@@ -0,0 +1,3 @@+│ model: gpt-6-astra /model to change │+› Ask Codex to do anything+ gpt-6-astra default · /repo\ No newline at end of filediff --git a/crates/coding_agent_worker/src/herdr/acp_agent/models/fixtures/codex-effort.txt b/crates/coding_agent_worker/src/herdr/acp_agent/models/fixtures/codex-effort.txtnew file mode 100644index 0000000000..c64a89e853--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/models/fixtures/codex-effort.txt@@ -0,0 +1,7 @@+Select Reasoning Level for gpt-6-sol+ 1. Low+› 2. Medium (default)+ 3. High+ 4. Extra high+ 5. More reasoning… Max and Ultra consume usage limits faster+Press enter to confirm or esc to go back\ No newline at end of filediff --git a/crates/coding_agent_worker/src/herdr/acp_agent/models/fixtures/codex-model.txt b/crates/coding_agent_worker/src/herdr/acp_agent/models/fixtures/codex-model.txtnew file mode 100644index 0000000000..a0be726076--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/models/fixtures/codex-model.txt@@ -0,0 +1,8 @@+Select Model and Effort+Access legacy models by running codex -m <model_name> or in your config.toml++› 1. gpt-6-astra (current) Frontier intelligence+ 2. gpt-6-sol Previous generation+ 3. gpt-6-luna++Press enter to confirm or esc to go back\ No newline at end of filediff --git a/crates/coding_agent_worker/src/herdr/acp_agent/models/test.rs b/crates/coding_agent_worker/src/herdr/acp_agent/models/test.rsnew file mode 100644index 0000000000..0dcb8433d1--- /dev/null+++ b/crates/coding_agent_worker/src/herdr/acp_agent/models/test.rs@@ -0,0 +1,347 @@+use super::*;+use crate::herdr::acp_agent::test::{save_transcript, test_adapter};+use std::os::unix::fs::PermissionsExt as _;++const MODEL_PICKER: &str = include_str!("fixtures/codex-model.txt");+const EFFORT_PICKER: &str = include_str!("fixtures/codex-effort.txt");+const INITIAL: &str = include_str!("fixtures/codex-before.txt");+const CHANGED: &str = include_str!("fixtures/codex-after.txt");++#[test]+fn model_selection_uses_exact_rows_and_preserves_native_effort_selection() {+ assert_eq!(+ picker_key(Stage::Model, "gpt-6-sol", MODEL_PICKER)+ .unwrap()+ .0,+ "2"+ );+ assert_eq!(+ picker_key(Stage::Effort, "gpt-6-sol", EFFORT_PICKER)+ .unwrap()+ .0,+ "enter"+ );+ assert!(picker_key(Stage::Model, "gpt-6", MODEL_PICKER).is_none());+ assert!(picker_key(Stage::Effort, "gpt-6-astra", EFFORT_PICKER).is_none());+ assert!(picker_key(Stage::Confirmation, "gpt-6-sol", EFFORT_PICKER).is_none());+ for screen in [+ "Would you like to run the following command?\n› 1. Yes, proceed\n2. No",+ "Select Reasoning Level for gpt-6-sol\n› 1. Accept additional charges\nPress enter to confirm or esc to go back",+ "Select Reasoning Level for gpt-6-sol\n› 5. More reasoning…\nPress enter to confirm or esc to go back",+ ] {+ assert!(picker_key(Stage::Model, "gpt-6-sol", screen).is_none());+ assert!(picker_key(Stage::Effort, "gpt-6-sol", screen).is_none());+ }+}++#[test]+fn effective_model_comes_from_live_footer_not_stale_banner_or_picker() {+ assert_eq!(codex_footer_model(CHANGED), Some("gpt-6-sol"));+ assert_eq!(codex_footer_model(MODEL_PICKER), None);+ assert_eq!(+ codex_footer_model("│ model: gpt-6-astra /model to change │"),+ None+ );+ assert!(!confirmed(+ TuiAgent::Codex,+ "gpt-6-sol",+ INITIAL,+ MODEL_PICKER+ ));+ assert!(confirmed(TuiAgent::Codex, "gpt-6-sol", INITIAL, CHANGED));+}++#[test]+fn claude_requires_a_fresh_native_confirmation() {+ let confirmation = "❯ /model opus\n ⎿ Set model to Opus 5 (1M context) and saved as your default for new sessions";+ assert!(confirmed(TuiAgent::Claude, "opus", "", confirmation));+ assert!(!confirmed(TuiAgent::Claude, "sonnet", "", confirmation));+ assert!(!confirmed(+ TuiAgent::Claude,+ "opus",+ confirmation,+ confirmation+ ));+ assert!(!confirmed(+ TuiAgent::Claude,+ "opus",+ "",+ "assistant said Set model to Opus 5"+ ));+ assert!(!confirmed(+ TuiAgent::Claude,+ "opus",+ "",+ "Set model to OpusNext"+ ));+}++fn catalog(root: &Path) {+ std::fs::create_dir(root.join(".codex")).unwrap();+ std::fs::write(+ root.join(".codex/models_cache.json"),+ json!({"models":[+ {"slug":"gpt-6-astra","display_name":"GPT-6 Astra","visibility":"list",+ "supported_reasoning_levels":[{"effort":"low"}]},+ {"slug":"gpt-6-sol","display_name":"GPT-6 Sol","visibility":"list",+ "supported_reasoning_levels":[{"effort":"medium"},{"effort":"high"}]},+ {"slug":"hidden-model","visibility":"hide"}+ ]})+ .to_string(),+ )+ .unwrap();+}++#[test]+fn installed_catalog_includes_new_models_and_retains_current_custom_model() {+ let root = tempfile::tempdir().unwrap();+ catalog(root.path());+ let (mut adapter, _) = test_adapter(root.path());+ let inner = Arc::get_mut(&mut adapter).unwrap();+ inner.home = Some(root.path().to_owned());+ inner.options.kind = TuiAgent::Codex;+ let options = adapter.model_options("my-model");+ assert_eq!(options[0]["currentValue"], "my-model");+ let values: Vec<_> = options[0]["options"]+ .as_array()+ .unwrap()+ .iter()+ .map(|option| option["value"].as_str().unwrap())+ .collect();+ assert_eq!(values, ["my-model", "gpt-6-astra", "gpt-6-sol"]);+}++async fn model_change(kind: TuiAgent, fails: bool) {+ let root = tempfile::tempdir().unwrap();+ let id = uuid::Uuid::new_v4().to_string();+ save_transcript(root.path(), &id);+ let mut record = Store(root.path().to_owned()).load(&id).unwrap();+ record.kind = kind;+ record.model = DEFAULT_MODEL.to_owned();+ Store(root.path().to_owned()).save(&record).unwrap();+ catalog(root.path());+ for (index, screen) in [INITIAL, MODEL_PICKER, EFFORT_PICKER, CHANGED]+ .iter()+ .enumerate()+ {+ std::fs::write(root.path().join(format!("screen{index}")), screen).unwrap();+ }+ if kind == TuiAgent::Claude {+ std::fs::write(+ root.path().join("screen1"),+ "⎿ Set model to Opus 5 (1M context)",+ )+ .unwrap();+ }+ std::fs::write(root.path().join("stage"), "0").unwrap();+ let script = root.path().join("herdr");+ std::fs::write(+ &script,+ format!(+ r#"#!/bin/sh+cd {root}+printf '%s\n' "$*" >> calls+stage=$(cat stage)+case "$2" in+ get)+ status=idle+ if [ '{fails}' = true ] && [ "$stage" != 0 ]; then status=working; fi+ printf '{{"result":{{"agent":{{"agent_status":"%s","state_change_seq":1}}}}}}\n' "$status" ;;+ read) cat "screen$stage" ;;+ prompt) printf '1' > stage ;;+ send-keys)+ case "$stage:$4" in+ 1:2) printf '2' > stage ;;+ 2:enter) printf '3' > stage ;;+ *) exit 1 ;;+ esac ;;+ *) exit 1 ;;+esac+"#,+ root = shell_words::quote(&root.path().to_string_lossy()),+ fails = fails+ ),+ )+ .unwrap();+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();+ let (mut adapter, mut output) = test_adapter(root.path());+ let inner = Arc::get_mut(&mut adapter).unwrap();+ inner.options.kind = kind;+ inner.home = Some(root.path().to_owned());+ inner.herdr = Some(HerdrCli::new(script, None));+ // Exercise RPCs without background polling racing the scripted native TUI.+ adapter.shutdown.cancel();+ adapter+ .load_session(&json!({"sessionId":id,"cwd":root.path()}))+ .await+ .unwrap();+ let wanted = if kind == TuiAgent::Codex {+ "gpt-6-sol"+ } else {+ "opus"+ };+ let result = adapter+ .request(+ "session/set_config_option",+ json!({"sessionId":id,"configId":"model","value":wanted}),+ )+ .await;+ let saved = adapter.store.load(&id).unwrap();+ if fails {+ assert!(result.is_err());+ assert_ne!(saved.model, wanted);+ } else {+ let config = result.unwrap()["configOptions"].clone();+ assert_eq!(config[0]["currentValue"], wanted);+ if kind == TuiAgent::Codex {+ assert_eq!(config[1]["currentValue"], "medium");+ assert_eq!(+ config[1]["options"],+ json!([+ {"value":"medium","name":"Medium"}, {"value":"high","name":"High"}+ ])+ );+ } else {+ assert_eq!(config.as_array().unwrap().len(), 1);+ }+ assert_eq!(saved.model, wanted);+ let mut models = Vec::new();+ while let Ok(update) = output.try_recv() {+ if let Some(model) = update+ .pointer("/params/update/configOptions/0/currentValue")+ .and_then(Value::as_str)+ {+ models.push(model.to_owned());+ }+ }+ assert_eq!(models.last().map(String::as_str), Some(wanted));+ }+ let calls = std::fs::read_to_string(root.path().join("calls")).unwrap();+ assert_eq!(+ calls+ .lines()+ .filter(|line| line.starts_with("agent prompt"))+ .count(),+ 1+ );+ let keys: Vec<_> = calls+ .lines()+ .filter(|line| line.starts_with("agent send-keys"))+ .map(|line| line.split_whitespace().last().unwrap())+ .collect();+ assert_eq!(+ keys,+ if kind == TuiAgent::Codex && !fails {+ vec!["2", "enter"]+ } else {+ vec![]+ }+ );+}++#[tokio::test]+async fn codex_model_rpc_drives_native_picker_and_only_reports_confirmed_model() {+ model_change(TuiAgent::Codex, false).await;+}++#[tokio::test]+async fn claude_model_rpc_submits_direct_model_command_and_waits_for_confirmation() {+ model_change(TuiAgent::Claude, false).await;+}++#[tokio::test]+async fn interrupted_native_selection_does_not_report_success_or_send_keys() {+ model_change(TuiAgent::Codex, true).await;+}++#[tokio::test]+async fn replay_returns_and_persists_actual_model_instead_of_saved_default() {+ for kind in [TuiAgent::Claude, TuiAgent::Codex] {+ let root = tempfile::tempdir().unwrap();+ let id = uuid::Uuid::new_v4().to_string();+ let transcript = save_transcript(root.path(), &id);+ let model = if kind == TuiAgent::Claude {+ "claude-opus-5"+ } else {+ "gpt-6-sol"+ };+ let event = if kind == TuiAgent::Claude {+ json!({"type":"assistant","uuid":"answer","message":{"model":model,"content":[]}})+ } else {+ json!({"type":"turn_context","payload":{"model":model}})+ };+ std::fs::write(transcript, format!("{event}\n")).unwrap();+ let mut record = Store(root.path().to_owned()).load(&id).unwrap();+ record.kind = kind;+ record.model = DEFAULT_MODEL.to_owned();+ Store(root.path().to_owned()).save(&record).unwrap();+ let (mut adapter, _) = test_adapter(root.path());+ Arc::get_mut(&mut adapter).unwrap().options.kind = kind;+ adapter.shutdown.cancel();+ let response = adapter+ .load_session(&json!({"sessionId":id,"cwd":root.path()}))+ .await+ .unwrap();+ assert_eq!(response["configOptions"][0]["currentValue"], model);+ assert_eq!(adapter.store.load(&id).unwrap().model, model);+ }+}++#[tokio::test]+async fn an_observer_lock_does_not_reject_an_idle_model_selection() {+ let root = tempfile::tempdir().unwrap();+ let (adapter, _) = test_adapter(root.path());+ adapter.shutdown.cancel();+ let response = adapter+ .new_session(&json!({"cwd":root.path(),"mcpServers":[]}))+ .unwrap();+ let session = adapter.session(&response).unwrap();+ let guard = session.live.lock().await;+ let waiting = adapter.set_model(&session, "opus");+ let unlock = async {+ tokio::time::sleep(Duration::from_millis(10)).await;+ drop(guard);+ };+ let (result, ()) = tokio::join!(waiting, unlock);+ assert_eq!(result.unwrap()["configOptions"][0]["currentValue"], "opus");+ session.prompt_pending.store(true, Ordering::SeqCst);+ assert!(adapter.set_model(&session, "sonnet").await.is_err());+ assert_eq!(*lock(&session.model), "opus");+}++#[tokio::test]+async fn native_identity_changes_are_rejected_and_metadata_is_not_a_turn() {+ let root = tempfile::tempdir().unwrap();+ let id = uuid::Uuid::new_v4().to_string();+ save_transcript(root.path(), &id);+ let (adapter, mut output) = test_adapter(root.path());+ adapter.shutdown.cancel();+ adapter+ .load_session(&json!({"sessionId":id,"cwd":root.path()}))+ .await+ .unwrap();+ let session = adapter.session(&json!({"sessionId":id})).unwrap();+ let mut info = super::super::super::cli::AgentInfo {+ cwd: Some(root.path().to_owned()),+ session_id: Some(id),+ status: "idle".to_owned(),+ state_change_seq: 1,+ };+ assert!(same_session(&session, &info));+ info.cwd = Some(root.path().join("other"));+ assert!(!same_session(&session, &info));+ info.cwd = Some(root.path().to_owned());+ info.session_id = Some("another-session".to_owned());+ assert!(!same_session(&session, &info));+ let mut guard = session.live.lock().await;+ let live = guard.as_mut().unwrap();+ live.pending+ .push_back(LogEvent::ModelChanged("claude-opus-5".to_owned()));+ assert_eq!(+ adapter.forward(&session, live, &mut None).unwrap(),+ (false, None)+ );+ while let Ok(event) = output.try_recv() {+ assert_ne!(event["method"], "_session/turn_complete");+ }+}diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs b/crates/coding_agent_worker/src/herdr/acp_agent/test.rsindex 96382dcb51..bce8712b07 100644--- a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs+++ b/crates/coding_agent_worker/src/herdr/acp_agent/test.rs@@ -154,7 +154,7 @@ fn codex_permission_dialogs_are_titled_from_the_screen() {);}-fn test_adapter(root: &Path) -> (Arc<Adapter>, mpsc::UnboundedReceiver<Value>) {+pub(super) fn test_adapter(root: &Path) -> (Arc<Adapter>, mpsc::UnboundedReceiver<Value>) {let (out, receiver) = mpsc::unbounded_channel();(Arc::new(Adapter {@@ -173,7 +173,7 @@ fn test_adapter(root: &Path) -> (Arc<Adapter>, mpsc::UnboundedReceiver<Value>) {)}-fn save_transcript(root: &Path, id: &str) -> PathBuf {+pub(super) fn save_transcript(root: &Path, id: &str) -> PathBuf {let transcript = root.join(format!("{id}.jsonl"));std::fs::write(&transcript, "").unwrap();Store(root.to_owned())@@ -374,3 +374,130 @@ fn configured_models_are_advertised_even_when_not_in_the_builtin_catalog() {.any(|option| option["value"] == "custom-model"));}++#[tokio::test]+async fn commands_are_advertised_after_successful_new_and_load_responses() {+ let root = tempfile::tempdir().unwrap();+ let (adapter, mut output) = test_adapter(root.path());+ adapter+ .respond_to_request(json!(1), "session/new", json!({"cwd":root.path()}))+ .await;+ let response = output.try_recv().unwrap();+ let id = response["result"]["sessionId"].as_str().unwrap();+ assert_eq!(response["id"], 1);+ let commands = output.try_recv().unwrap();+ assert_eq!(commands["params"]["sessionId"], id);+ assert_eq!(+ commands["params"]["update"]["sessionUpdate"],+ "available_commands_update"+ );+ assert!(output.try_recv().is_err());++ adapter+ .respond_to_request(+ json!(2),+ "session/load",+ json!({"sessionId":id, "cwd":root.path()}),+ )+ .await;+ assert_eq!(output.try_recv().unwrap()["id"], 2);+ assert_eq!(output.try_recv().unwrap(), commands);+ assert!(output.try_recv().is_err());++ adapter+ .respond_to_request(+ json!(3),+ "session/load",+ json!({"sessionId":id, "cwd":"/wrong"}),+ )+ .await;+ assert!(output.try_recv().unwrap().get("error").is_some());+ assert!(output.try_recv().is_err());+ adapter.shutdown.cancel();+}++#[tokio::test]+async fn native_controls_submit_once_and_acknowledge_delivery_without_a_model_turn() {+ for (kind, command) in [+ (TuiAgent::Claude, "/fast"),+ (TuiAgent::Claude, "/fast on"),+ (TuiAgent::Claude, "/fast off"),+ (TuiAgent::Codex, "/fast"),+ (TuiAgent::Codex, "/ultrafast"),+ (TuiAgent::Claude, "/effort"),+ (TuiAgent::Claude, "/effort high"),+ (TuiAgent::Claude, "/effort auto"),+ (TuiAgent::Claude, "/effort status"),+ (TuiAgent::Codex, "/model"),+ ] {+ for reject in [false, true] {+ check_control_delivery(kind, command, reject).await;+ }+ }+}++async fn check_control_delivery(kind: TuiAgent, command: &str, reject: bool) {+ use std::os::unix::fs::PermissionsExt as _;+ let root = tempfile::tempdir().unwrap();+ let calls = root.path().join("calls");+ let script = root.path().join("herdr");+ let exit_code = if reject { 1 } else { 0 };+ std::fs::write(&script, format!(+ "#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\ncase \"$2\" in\n get) printf '%s\\n' '{{\"result\":{{\"agent\":{{\"agent_status\":\"idle\"}}}}}}';;\n prompt) exit {exit_code};;\n *) exit 2;;\nesac\n",+ shell_words::quote(&calls.to_string_lossy()),+ )).unwrap();+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();+ let id = uuid::Uuid::new_v4().to_string();+ save_transcript(root.path(), &id);+ let (mut adapter, mut output) = test_adapter(root.path());+ let adapter_mut = Arc::get_mut(&mut adapter).unwrap();+ adapter_mut.herdr = Some(HerdrCli::new(script, None));+ adapter_mut.options.kind = kind;+ let mut record = adapter.store.load(&id).unwrap();+ record.kind = kind;+ adapter.store.save(&record).unwrap();+ adapter+ .load_session(&json!({"sessionId":id,"cwd":root.path()}))+ .await+ .unwrap();+ // Loading may inspect the native footer; only command delivery is under test.+ std::fs::write(&calls, "").unwrap();+ let session = adapter.session(&json!({"sessionId":id})).unwrap();+ let outcome = tokio::time::timeout(Duration::from_secs(2), adapter.prompt(&session, command))+ .await+ .expect("native controls do not wait for transcript output");+ if reject {+ assert!(outcome.is_err());+ assert!(+ output.try_recv().is_err(),+ "failed delivery must not be acknowledged"+ );+ } else {+ assert_eq!(outcome.unwrap(), "end_turn");+ let acknowledgment = output.try_recv().unwrap();+ assert_eq!(+ acknowledgment["params"]["update"]["sessionUpdate"],+ "agent_message_chunk"+ );+ assert!(+ acknowledgment["params"]["update"]["content"]["text"]+ .as_str()+ .unwrap()+ .starts_with(&format!("Sent `{command}`"))+ );+ assert!(output.try_recv().is_err());+ }+ let name = agent_name(&id);+ let settings_read = if kind == TuiAgent::Codex {+ format!("agent get {name}\nagent read {name} --source visible\n")+ } else {+ String::new()+ };+ assert_eq!(+ std::fs::read_to_string(calls).unwrap(),+ format!("agent get {name}\n{settings_read}agent prompt {name} {command}\n")+ );+ assert!(lock(&session.cancel).is_none());+ assert_eq!(adapter.store.load(&id).unwrap().native_id, Some(id));+ adapter.shutdown.cancel();+}diff --git a/crates/folds/agent_fold/src/domain/transcript.rs b/crates/folds/agent_fold/src/domain/transcript.rsindex 591a1decd4..c1c544acfe 100644--- a/crates/folds/agent_fold/src/domain/transcript.rs+++ b/crates/folds/agent_fold/src/domain/transcript.rs@@ -15,6 +15,8 @@ const TOOL_OUTPUT_LIMIT: usize = 4_000;/// What one transcript line means for the ACP session.#[derive(Debug, Clone, PartialEq, serde::Serialize)]pub enum LogEvent {+ /// The native transcript identifies the model actually used by the session.+ ModelChanged(String),/// A `session/update` payload to send.Update(Value),/// The turn is over, with this ACP stop reason.diff --git a/crates/folds/claude_fold/fixtures/models.jsonl b/crates/folds/claude_fold/fixtures/models.jsonlnew file mode 100644index 0000000000..71f0faa55e--- /dev/null+++ b/crates/folds/claude_fold/fixtures/models.jsonl@@ -0,0 +1,5 @@+{"type":"assistant","uuid":"a","message":{"model":"claude-opus-5","content":[]}}+{"type":"assistant","uuid":"a","message":{"model":"claude-opus-5","content":[]}}+{"type":"assistant","uuid":"sub","isSidechain":true,"message":{"model":"claude-haiku-4-5","content":[]}}+{"type":"assistant","uuid":"synthetic","message":{"model":"<synthetic>","content":[]}}+{"type":"assistant","uuid":"b","message":{"model":"claude-sonnet-4-6","content":[]}}diff --git a/crates/folds/claude_fold/src/lib.rs b/crates/folds/claude_fold/src/lib.rsindex a9542c0103..a978398963 100644--- a/crates/folds/claude_fold/src/lib.rs+++ b/crates/folds/claude_fold/src/lib.rs@@ -88,6 +88,13 @@ fn assistant(message: &Value) -> Vec<LogEvent> {}).map(LogEvent::Update).collect();+ if let Some(model) = message+ .get("model")+ .and_then(Value::as_str)+ .filter(|model| !model.is_empty() && !model.starts_with('<'))+ {+ events.insert(0, LogEvent::ModelChanged(model.to_owned()));+ }let stop = match message.get("stop_reason").and_then(Value::as_str) {Some("end_turn" | "stop_sequence") => Some("end_turn"),Some("max_tokens") => Some("max_tokens"),diff --git a/crates/folds/claude_fold/src/snapshots/claude_fold__test__model_changes_snapshot.snap b/crates/folds/claude_fold/src/snapshots/claude_fold__test__model_changes_snapshot.snapnew file mode 100644index 0000000000..35503ce2f9--- /dev/null+++ b/crates/folds/claude_fold/src/snapshots/claude_fold__test__model_changes_snapshot.snap@@ -0,0 +1,12 @@+---+source: crates/folds/claude_fold/src/test.rs+expression: events+---+[+ {+ "ModelChanged": "claude-opus-5"+ },+ {+ "ModelChanged": "claude-sonnet-4-6"+ }+]diff --git a/crates/folds/claude_fold/src/test.rs b/crates/folds/claude_fold/src/test.rsindex 368cf5bfcb..780890a553 100644--- a/crates/folds/claude_fold/src/test.rs+++ b/crates/folds/claude_fold/src/test.rs@@ -146,6 +146,7 @@ fn api_messages_snapshot() {.flat_map(|line| native.entry(line)){let (method, params) = match event {+ LogEvent::ModelChanged(_) => continue,LogEvent::Update(update) => {("session/update", json!({"sessionId":"s", "update":update}))}@@ -161,3 +162,13 @@ fn api_messages_snapshot() {assert!(messages.len() >= 3, "native turns must reach API messages");insta::assert_json_snapshot!(messages);}++#[test]+fn model_changes_snapshot() {+ let mut fold = ClaudeLog::default();+ let events: Vec<_> = include_str!("../fixtures/models.jsonl")+ .lines()+ .flat_map(|line| fold.entry(line))+ .collect();+ insta::assert_json_snapshot!(events);+}diff --git a/crates/folds/codex_fold/fixtures/models.jsonl b/crates/folds/codex_fold/fixtures/models.jsonlnew file mode 100644index 0000000000..686432496b--- /dev/null+++ b/crates/folds/codex_fold/fixtures/models.jsonl@@ -0,0 +1,4 @@+{"type":"turn_context","payload":{"model":"gpt-6-astra"}}+{"type":"turn_context","payload":{}}+{"type":"turn_context","payload":{"model":""}}+{"type":"turn_context","payload":{"model":"gpt-6-sol"}}diff --git a/crates/folds/codex_fold/src/lib.rs b/crates/folds/codex_fold/src/lib.rsindex 54b422dbbe..1d7a411209 100644--- a/crates/folds/codex_fold/src/lib.rs+++ b/crates/folds/codex_fold/src/lib.rs@@ -30,6 +30,15 @@ impl Fold for CodexLog {let Ok(entry) = serde_json::from_str::<Value>(line) else {return Vec::new();};+ if entry.get("type").and_then(Value::as_str) == Some("turn_context") {+ return entry+ .pointer("/payload/model")+ .and_then(Value::as_str)+ .filter(|model| !model.is_empty())+ .map(|model| LogEvent::ModelChanged(model.to_owned()))+ .into_iter()+ .collect();+ }if entry.get("type").and_then(Value::as_str) != Some("event_msg") {return Vec::new();}diff --git a/crates/folds/codex_fold/src/snapshots/codex_fold__test__model_changes_snapshot.snap b/crates/folds/codex_fold/src/snapshots/codex_fold__test__model_changes_snapshot.snapnew file mode 100644index 0000000000..c3613388bf--- /dev/null+++ b/crates/folds/codex_fold/src/snapshots/codex_fold__test__model_changes_snapshot.snap@@ -0,0 +1,12 @@+---+source: crates/folds/codex_fold/src/test.rs+expression: events+---+[+ {+ "ModelChanged": "gpt-6-astra"+ },+ {+ "ModelChanged": "gpt-6-sol"+ }+]diff --git a/crates/folds/codex_fold/src/test.rs b/crates/folds/codex_fold/src/test.rsindex 55a829ffbc..61fb15836e 100644--- a/crates/folds/codex_fold/src/test.rs+++ b/crates/folds/codex_fold/src/test.rs@@ -151,6 +151,7 @@ fn api_messages_snapshot() {.flat_map(|line| native.entry(line)){let (method, params) = match event {+ LogEvent::ModelChanged(_) => continue,LogEvent::Update(update) => {("session/update", json!({"sessionId":"s", "update":update}))}@@ -166,3 +167,13 @@ fn api_messages_snapshot() {assert!(messages.len() >= 3, "native turns must reach API messages");insta::assert_json_snapshot!(messages);}++#[test]+fn model_changes_snapshot() {+ let mut fold = CodexLog::default();+ let events: Vec<_> = include_str!("../fixtures/models.jsonl")+ .lines()+ .flat_map(|line| fold.entry(line))+ .collect();+ insta::assert_json_snapshot!(events);+}diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex 9ef3bec8fa..a7fb872dd8 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -358,6 +358,26 @@ the shimmer.TUI. The session page streams its tool calls and replies, and its permissionprompts appear as approvals. Other runtimes started inside herdr get a liveview tab per session that can prompt and interrupt it; approvals stay in Macro.+ Native Herdr sessions offer `/compact`, `/init`, and `/fast` in the slash menu;+ Codex also offers `/ultrafast`. Macro confirms delivery of speed commands;+ check their result and any confirmation in Herdr. For Claude, use `/fast on`+ or `/fast off`, or bare `/fast` to open its native controls. Available speed+ tiers depend on the native agent, model, and account. Claude also offers+ `/effort` with an optional level, `auto`, or `status`. In Codex sessions,+ `/effort` shows the current effort and available choices in Macro. Send+ `/effort high` (or another supported level) to change it and wait for native+ confirmation; `/effort default` restores the model's default. This preserves+ the current model. `/model` still opens the picker in Herdr. Macro's model dropdown+ changes the model of an idle native session after native confirmation and+ displays the model identified by the session (Codex's live footer, or native+ transcript metadata). Unexpected native dialogs must be completed in Herdr.+ For Codex, open the current model's submenu to select **Reasoning effort**.+ Choices come from the installed Codex catalog; the selected effort is confirmed+ from the native session and shown beside the model. Local Herdr changes and+ `/effort` also update this menu. The effort submenu appears once the native+ session starts on the first prompt, before its first reply; a startup screen+ that temporarily hides the footer is retried during the turn. The menu does not list+ installed native skills or session-switching commands such as `/resume`.The agent form retains sharing, name, `@tag`, runtime, default model, connections,channels, instructions, and permission policy.Runtime and short model lists use styled dropdown buttons: open the field and