Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(macrod): keep pressing Esc until a native Herdr turn actually stops (#9188)

Wolf Mermelsteinfdf87d12c2a1
diff --git a/crates/coding_agent_worker/README.md b/crates/coding_agent_worker/README.md
index 2df084af7e..5286f38719 100644
--- a/crates/coding_agent_worker/README.md
+++ b/crates/coding_agent_worker/README.md
@@ -43,7 +43,11 @@ 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.
+Enter. Cancellation (Stop in Macro, for a Macro prompt or an observed native
+turn) presses Escape until Herdr reports the agent stopped, at most three times
+(Claude Code's vim editor mode spends the first Escape leaving insert mode), and
+never sends an input-clearing key. The turn reports `cancelled` only once the
+agent has stopped; if it keeps running, macrod follows it to its real end.
New and reloaded sessions advertise `/compact`, `/init`, and `/fast` in Macro;
Codex also advertises `/ultrafast`. Speed controls are delivered unchanged to
diff --git a/crates/coding_agent_worker/src/herdr/acp_agent.rs b/crates/coding_agent_worker/src/herdr/acp_agent.rs
index 14056a40d7..fa5015b952 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent.rs
@@ -73,6 +73,10 @@ const SETTLED_CHECKS: u32 = 3;
const SHELL_READY_TIMEOUT: Duration = Duration::from_secs(10);
const QUIET_START: Duration = Duration::from_secs(20);
const MISSING_AGENT_CHECKS: u32 = 5;
+/// Esc presses a cancel spends before the native turn is left to run.
+const INTERRUPT_PRESSES: u32 = 3;
+/// Status checks, one per [`POLL`], after each Esc press.
+const INTERRUPT_CHECKS: u32 = 4;
/// Which coding-agent TUI each session runs.
#[derive(
Debug,
@@ -413,12 +417,16 @@ impl Adapter {
let Ok(info) = herdr.agent_info(&name).await else {
return;
};
- if native_id.is_some()
- && info.session_id == native_id
- && matches!(info.status.as_str(), "working" | "blocked")
- && let Err(error) = herdr.send_keys(&name, &["esc"]).await
+ if native_id.is_none()
+ || info.session_id != native_id
+ || !matches!(info.status.as_str(), "working" | "blocked")
{
- tracing::warn!(%error, "could not interrupt native turn");
+ return;
+ }
+ match interrupt(&herdr, &name).await {
+ Ok(true) => {}
+ Ok(false) => tracing::warn!(%name, "the native turn kept running after Esc"),
+ Err(error) => tracing::warn!(%error, "could not interrupt native turn"),
}
});
}
@@ -890,14 +898,19 @@ impl Adapter {
let mut asking = false;
let mut last_output = Instant::now();
let mut asked_seq = None;
+ let mut interrupt_failed = false;
let _epoch = PermissionEpoch(generation.clone());
loop {
tokio::select! {
- () = cancel.cancelled() => {
- herdr.send_keys(&live.name, &["esc"]).await?;
- tokio::time::sleep(Duration::from_secs(1)).await;
- self.forward(session, live, &mut open_tool)?;
- return Ok("cancelled");
+ () = cancel.cancelled(), if !interrupt_failed => {
+ if interrupt(herdr, &live.name).await? {
+ self.forward(session, live, &mut open_tool)?;
+ return Ok("cancelled");
+ }
+ // Answering `cancelled` now would end the turn in Macro
+ // while the agent keeps working; follow it to its end.
+ tracing::warn!(session = %session.id, "the native turn kept running after Esc");
+ interrupt_failed = true;
}
() = tokio::time::sleep(POLL) => {}
}
@@ -1066,6 +1079,34 @@ impl Adapter {
}
/// A herdr agent name for the session: `[a-z][a-z0-9_-]{0,31}`.
+/// Press Esc until herdr reports the agent `idle` or `done`, and say whether
+/// it is. One press is not proof: in Claude Code's vim editor mode the first
+/// Esc only leaves insert mode. No press follows a stop, since Esc at an idle
+/// Claude Code prompt opens its rewind menu.
+#[tracing::instrument(
+ name = "macrod.herdr.interrupt",
+ skip(herdr),
+ fields(herdr.agent = name, presses, stopped),
+ err
+)]
+async fn interrupt(herdr: &HerdrCli, name: &str) -> Result<bool, HerdrError> {
+ let span = tracing::Span::current();
+ for press in 1..=INTERRUPT_PRESSES {
+ span.record("presses", press);
+ herdr.send_keys(name, &["esc"]).await?;
+ for _ in 0..INTERRUPT_CHECKS {
+ tokio::time::sleep(POLL).await;
+ let status = herdr.agent_info(name).await?.status;
+ if matches!(status.as_str(), "idle" | "done") {
+ span.record("stopped", true);
+ return Ok(true);
+ }
+ }
+ }
+ span.record("stopped", false);
+ Ok(false)
+}
+
pub(crate) fn agent_name(session: &str) -> String {
let short: String = session
.chars()
diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs b/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
index 31534d7bf7..45aa0cf63d 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
@@ -369,6 +369,50 @@ async fn an_unconfirmed_submission_never_sends_an_extra_enter_or_reports_success
adapter.shutdown.cancel();
}
+/// Claude Code in vim editor mode spends the first Esc leaving insert mode;
+/// the turn keeps running until the second.
+#[tokio::test]
+async fn a_cancelled_turn_presses_esc_until_the_native_agent_stops() {
+ use std::os::unix::fs::PermissionsExt as _;
+ let root = tempfile::tempdir().unwrap();
+ let presses = root.path().join("presses");
+ let script = root.path().join("herdr");
+ std::fs::write(
+ &script,
+ format!(
+ "#!/bin/sh\npresses={}\ncase \"$2\" in\n send-keys) printf '%s\\n' \"$4\" >> \"$presses\";;\n get) if [ \"$(wc -l < \"$presses\" 2>/dev/null || echo 0)\" -ge 2 ]; then status=done; else status=working; fi\n printf '{{\"result\":{{\"agent\":{{\"agent_status\":\"%s\"}}}}}}\\n' \"$status\";;\n *) exit 2;;\nesac\n",
+ shell_words::quote(&presses.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 (adapter, _) = test_adapter(root.path());
+ adapter
+ .load_session(&json!({"sessionId":id,"cwd":root.path()}))
+ .await
+ .unwrap();
+ let session = adapter.session(&json!({"sessionId":id})).unwrap();
+ let mut guard = session.live.lock().await;
+ let cancel = CancellationToken::new();
+ cancel.cancel();
+
+ let stop = adapter
+ .follow(
+ &HerdrCli::new(script, None),
+ &session,
+ guard.as_mut().unwrap(),
+ &cancel,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(stop, "cancelled");
+ assert_eq!(std::fs::read_to_string(presses).unwrap(), "esc\nesc\n");
+ adapter.shutdown.cancel();
+}
+
#[test]
fn configured_models_are_advertised_even_when_not_in_the_builtin_catalog() {
let options = config_options(TuiAgent::Codex, "custom-model");