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): queue Macro prompts behind a busy native session (#9176)
Wolf Mermelstein3edb8ee38b6d
diff --git a/crates/coding_agent_worker/README.md b/crates/coding_agent_worker/README.mdindex 5286f38719..5259854a62 100644--- a/crates/coding_agent_worker/README.md+++ b/crates/coding_agent_worker/README.md@@ -49,6 +49,14 @@ turn) presses Escape until Herdr reports the agent stopped, at most three timesnever sends an input-clearing key. The turn reports `cancelled` only once theagent has stopped; if it keeps running, macrod follows it to its real end.+A prompt from Macro while the native agent is working or showing a dialog+waits, like input typed into the TUI mid-turn. The running turn keeps streaming+and its permission dialogs still reach Macro; the prompt is typed once the turn+ends. Stopping from Macro while it waits interrupts the native turn and drops+the prompt. Claude Code's exit confirmation, left by a second Ctrl-C while+background work runs, is dismissed with Escape ("Stay") before the prompt is+typed.+New and reloaded sessions advertise `/compact`, `/init`, and `/fast` in Macro;Codex also advertises `/ultrafast`. Speed controls are delivered unchanged tothe native TUI. Macro acknowledges delivery without claiming the settingdiff --git a/crates/coding_agent_worker/src/herdr/acp_agent.rs b/crates/coding_agent_worker/src/herdr/acp_agent.rsindex fa5015b952..7d2ab603ad 100644--- a/crates/coding_agent_worker/src/herdr/acp_agent.rs+++ b/crates/coding_agent_worker/src/herdr/acp_agent.rs@@ -27,6 +27,7 @@ use serde_json::{Value, json};use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader};use tokio::sync::{mpsc, oneshot};use tokio_util::sync::CancellationToken;+use tracing::Instrument as _;use super::HerdrSession;use super::cli::{HerdrCli, HerdrError};@@ -659,13 +660,58 @@ impl Adapter {let _cancellation = PromptCancellation(&session.cancel);let mut guard = session.live.lock().await;- if let Some(live) = guard.as_ref() {- match herdr.agent_info(&live.name).await {- Ok(info) if matches!(info.status.as_str(), "working" | "blocked") => {- return Err(RpcError::invalid(- "the native session is busy; finish its current turn in Herdr first",- ));+ if let Some(live) = guard.as_mut() {+ // Queued like input typed into the TUI mid-turn: the prompt waits+ // for the native turn, which streams and asks for permission+ // meanwhile, and a stop interrupts that turn.+ let wait = tracing::info_span!(+ "macrod.herdr.prompt_wait",+ session_id = %session.id,+ native_turns = 0u32,+ exit_dismissed = false,+ outcome = tracing::field::Empty,+ );+ let waited = async {+ let mut native_turns = 0u32;+ loop {+ if cancel.is_cancelled() {+ return Ok(None);+ }+ let info = herdr.agent_info(&live.name).await;+ if !info+ .as_ref()+ .is_ok_and(|info| matches!(info.status.as_str(), "working" | "blocked"))+ {+ return Ok(Some(info));+ }+ if info.as_ref().is_ok_and(|info| info.status == "blocked")+ && self.stay(herdr, &live.name).await?+ {+ tracing::Span::current().record("exit_dismissed", true);+ continue;+ }+ native_turns += 1;+ tracing::Span::current().record("native_turns", native_turns);+ // An interrupted native turn ends "cancelled" too; only a+ // Stop from Macro drops the waiting prompt.+ self.follow(herdr, session, live, &cancel, true).await?;+ if cancel.is_cancelled() {+ return Ok(None);+ }}+ }+ .instrument(wait.clone())+ .await+ .inspect_err(|error: &RpcError| {+ wait.record("outcome", "failed");+ tracing::warn!(parent: &wait, error = %error.message, "queued prompt failed while waiting");+ })?;+ let Some(info) = waited else {+ wait.record("outcome", "cancelled");+ return Ok("cancelled");+ };+ wait.record("outcome", "ready");+ match info {Ok(info) => {if info.cwd.as_ref().is_some_and(|cwd| cwd != &session.cwd)|| info@@ -700,19 +746,17 @@ impl Adapter {return Err(RpcError::internal("the Claude Code window did not start"));};- 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)?;+ // Relay whatever the native session did before this prompt, so a+ // turn end already in the transcript never ends this prompt's turn.+ loop {+ let offset = live.cursor.offset;+ self.forward(session, live, &mut None)?;+ if offset == live.cursor.offset && live.pending.is_empty() {+ break;+ }}- if !live.pending.is_empty() {- return Err(RpcError::invalid(- "the native transcript has new activity; retry once it has synchronized",- ));+ if cancel.is_cancelled() {+ return Ok("cancelled");}// The observer cannot acquire this session until the turn ends. Publish// native settings now, while the freshly started composer is visible.@@ -748,12 +792,40 @@ impl Adapter {}));return Ok("end_turn");}- let outcome = self.follow(herdr, session, live, &cancel).await;+ let outcome = self.follow(herdr, session, live, &cancel, false).await;*lock(&session.cancel) = None;self.save(session, guard.as_ref())?;outcome}+ /// Dismiss the exit confirmation a second Ctrl-C in Herdr leaves behind,+ /// so the prompt waiting on it can run. Returns whether it pressed Esc.+ async fn stay(&self, herdr: &HerdrCli, name: &str) -> Result<bool, RpcError> {+ let before = herdr.agent_info(name).await?;+ let screen = herdr.read_agent(name).await?;+ if !super::controls::exit_confirmation(self.options.kind, &screen) {+ return Ok(false);+ }+ let after = herdr.agent_info(name).await?;+ let current = herdr.read_agent(name).await?;+ if !super::controls::same_dialog(+ &screen,+ ¤t,+ before.state_change_seq,+ after.state_change_seq,+ &after.status,+ ) {+ return Ok(false);+ }+ herdr.send_keys(name, &["esc"]).await?;+ tracing::info!(+ agent = name,+ "dismissed the native exit confirmation for a queued prompt"+ );+ tokio::time::sleep(POLL).await;+ Ok(true)+ }+/// Open the session's herdr window and start the agent in it.async fn launch(&self,@@ -878,19 +950,22 @@ impl Adapter {Ok(Some(path))}- /// Stream the turn from the transcript until it ends.+ /// Stream the turn from the transcript until it ends. `running` says+ /// the native turn is known to have started, so it may end without+ /// ever reporting `working` (a dialog dismissed in Herdr).async fn follow(self: &Arc<Self>,herdr: &HerdrCli,session: &Arc<Session>,live: &mut Live,cancel: &CancellationToken,+ running: bool,) -> Result<&'static str, RpcError> {let started = Instant::now();let mut ticks = 0u32;let mut settled = 0u32;let mut missing = 0u32;- let mut active = false;+ let mut active = running;let mut open_tool: Option<OpenTool> = None;// Bumped whenever a dialog is asked about or goes away, so a late// answer from Macro never presses keys into a different dialog.diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs b/crates/coding_agent_worker/src/herdr/acp_agent/test.rsindex 45aa0cf63d..ecda1b3294 100644--- a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs+++ b/crates/coding_agent_worker/src/herdr/acp_agent/test.rs@@ -357,6 +357,7 @@ async fn an_unconfirmed_submission_never_sends_an_extra_enter_or_reports_success&session,guard.as_mut().unwrap(),&CancellationToken::new(),+ false,).await.unwrap_err();@@ -679,3 +680,150 @@ async fn a_late_codex_item_never_answers_a_waiting_macro_prompt() {);adapter.shutdown.cancel();}++/// A herdr whose agent status is the `status` file. Typing a prompt starts+/// a turn that the transcript records as already answered.+fn queueing_herdr(root: &Path, transcript: &Path, status: &str) -> HerdrCli {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::write(root.join("status"), status).unwrap();+ std::fs::write(+ root.join("macro-turn"),+ format!(+ "{}\n{}\n",+ json!({"type":"user", "uuid":"macro-user", "message":{"content":"from macro"}}),+ json!({"type":"assistant", "uuid":"macro-agent", "message":{"content":[{"type":"text", "text":"answered"}], "stop_reason":"end_turn"}}),+ ),+ )+ .unwrap();+ let script = root.join("herdr");+ std::fs::write(+ &script,+ format!(+ r#"#!/bin/sh+cd {}+printf '%s\n' "$*" >> calls+case "$1:$2" in+ agent:get) printf '{{"result":{{"agent":{{"agent_status":"%s","state_change_seq":1}}}}}}\n' "$(cat status)" ;;+ agent:read) if [ "$(cat status)" = blocked ]; then cat dialog; fi ;;+ agent:send-keys) printf idle > status ;;+ agent:prompt) printf working > status; cat macro-turn >> {} ;;+ *) exit 1 ;;+esac+"#,+ shell_words::quote(&root.to_string_lossy()),+ shell_words::quote(&transcript.to_string_lossy()),+ ),+ )+ .unwrap();+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();+ HerdrCli::new(script, None)+}++#[tokio::test]+async fn a_prompt_to_a_busy_native_session_waits_for_its_turn_then_submits() {+ use std::io::Write as _;+ let root = tempfile::tempdir().unwrap();+ let id = uuid::Uuid::new_v4().to_string();+ let transcript = save_transcript(root.path(), &id);+ let (mut adapter, mut output) = test_adapter(root.path());+ Arc::get_mut(&mut adapter).unwrap().herdr =+ Some(queueing_herdr(root.path(), &transcript, "working"));+ adapter+ .load_session(&json!({"sessionId":id,"cwd":root.path()}))+ .await+ .unwrap();+ let session = adapter.session(&json!({"sessionId":id})).unwrap();+ session.prompt_pending.store(true, Ordering::SeqCst);+ let mut file = std::fs::OpenOptions::new()+ .append(true)+ .open(&transcript)+ .unwrap();+ writeln!(+ file,+ "{}",+ json!({"type":"user", "uuid":"local-user", "message":{"content":"typed in herdr"}})+ )+ .unwrap();++ let prompt = tokio::spawn({+ let adapter = adapter.clone();+ let session = session.clone();+ async move { adapter.prompt(&session, "from macro").await }+ });+ let mut next = async || {+ tokio::time::timeout(Duration::from_secs(5), output.recv())+ .await+ .unwrap()+ .unwrap()+ };+ // The native turn keeps streaming while the Macro prompt waits for it.+ assert_eq!(+ next().await["params"]["update"]["content"]["text"],+ "typed in herdr"+ );+ std::fs::write(root.path().join("status"), "idle").unwrap();+ writeln!(file, "{}", json!({"type":"assistant", "uuid":"local-agent", "message":{"content":[{"type":"text", "text":"local answer"}], "stop_reason":"end_turn"}})).unwrap();+ assert_eq!(+ next().await["params"]["update"]["content"]["text"],+ "local answer"+ );+ assert_eq!(next().await["method"], "_session/turn_complete");+ assert_eq!(+ next().await["params"]["update"]["content"]["text"],+ "from macro"+ );+ assert_eq!(+ next().await["params"]["update"]["content"]["text"],+ "answered"+ );+ assert_eq!(prompt.await.unwrap().unwrap(), "end_turn");+ let name = agent_name(&id);+ let calls = std::fs::read_to_string(root.path().join("calls")).unwrap();+ assert_eq!(+ calls+ .matches(&format!("agent prompt {name} from macro\n"))+ .count(),+ 1+ );+ adapter.shutdown.cancel();+}++#[tokio::test]+async fn a_prompt_dismisses_the_exit_confirmation_a_second_ctrl_c_left() {+ let root = tempfile::tempdir().unwrap();+ let id = uuid::Uuid::new_v4().to_string();+ let transcript = save_transcript(root.path(), &id);+ std::fs::write(+ root.path().join("dialog"),+ " Background work is running\n ❯ 1. Exit and stop tasks\n 2. Move to background and exit\n 3. Stay\n Enter to confirm · Esc to cancel\n",+ )+ .unwrap();+ let (mut adapter, _output) = test_adapter(root.path());+ Arc::get_mut(&mut adapter).unwrap().herdr =+ Some(queueing_herdr(root.path(), &transcript, "blocked"));+ adapter+ .load_session(&json!({"sessionId":id,"cwd":root.path()}))+ .await+ .unwrap();+ let session = adapter.session(&json!({"sessionId":id})).unwrap();+ session.prompt_pending.store(true, Ordering::SeqCst);++ let outcome = tokio::time::timeout(+ Duration::from_secs(5),+ adapter.prompt(&session, "from macro"),+ )+ .await+ .unwrap();++ assert_eq!(outcome.unwrap(), "end_turn");+ let name = agent_name(&id);+ let calls = std::fs::read_to_string(root.path().join("calls")).unwrap();+ let stayed = calls+ .find(&format!("agent send-keys {name} esc\n"))+ .unwrap();+ let prompted = calls+ .find(&format!("agent prompt {name} from macro\n"))+ .unwrap();+ assert!(stayed < prompted);+ adapter.shutdown.cancel();+}diff --git a/crates/coding_agent_worker/src/herdr/controls.rs b/crates/coding_agent_worker/src/herdr/controls.rsindex 27e0e9eb99..c779ccbb8e 100644--- a/crates/coding_agent_worker/src/herdr/controls.rs+++ b/crates/coding_agent_worker/src/herdr/controls.rs@@ -23,6 +23,15 @@ pub(crate) fn approve_key(kind: TuiAgent, screen: &str) -> Option<&'static str>}}+/// Claude Code's exit confirmation, shown when Ctrl-C is pressed again while+/// background work runs. Its Esc answer is "Stay", which keeps the session.+pub(crate) fn exit_confirmation(kind: TuiAgent, screen: &str) -> bool {+ kind == TuiAgent::Claude+ && screen.contains("Exit and stop tasks")+ && screen.contains("Stay")+ && screen.contains("Esc to cancel")+}+/// A dialog's own "don't ask again" answer.#[derive(Debug, Clone, PartialEq, Eq)]pub(crate) struct NativeAlways {diff --git a/crates/coding_agent_worker/src/herdr/controls/test.rs b/crates/coding_agent_worker/src/herdr/controls/test.rsindex 5952c087d8..b1eb2d1a34 100644--- a/crates/coding_agent_worker/src/herdr/controls/test.rs+++ b/crates/coding_agent_worker/src/herdr/controls/test.rs@@ -63,3 +63,14 @@ fn dont_ask_again_answers_are_found_with_the_key_that_picks_them() {None);}++#[test]+fn only_claudes_exit_confirmation_is_dismissed_to_stay() {+ let exit = " Background work is running\n The following will stop when you exit:\n shell · Sleep for 30 seconds in background\n ❯ 1. Exit and stop tasks\n 2. Move to background and exit\n 3. Stay\n Enter to confirm · Esc to cancel\n";+ assert!(exit_confirmation(TuiAgent::Claude, exit));+ assert!(!exit_confirmation(TuiAgent::Codex, exit));+ assert!(!exit_confirmation(+ TuiAgent::Claude,+ " Do you want to proceed?\n ❯ 1. Yes\n 2. No\n Esc to cancel\n"+ ));+}