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): stop native Herdr sessions showing as working after the turn ends (#9235)

Eric Hayes24d0aa2b2268
diff --git a/crates/coding_agent_worker/README.md b/crates/coding_agent_worker/README.md
index 5259854a62..eb22cdc6c9 100644
--- a/crates/coding_agent_worker/README.md
+++ b/crates/coding_agent_worker/README.md
@@ -26,6 +26,11 @@ A background reader forwards local TUI turns even without a Macro prompt.
Complete JSONL records are read in bounded batches. Partial lines wait for the
next append; truncation or replacement requires a reload. Turn boundaries are
forwarded in order, including multiple local turns between polls.
+Only typed prompts start a local turn; Claude Code's own transcript lines
+(reminders, compaction summaries, local slash command output) do not, and an
+Esc interrupt ends the turn as cancelled. A local turn whose transcript never
+records an end, such as one cut short by a closed CLI, ends once Herdr reports
+the agent idle and the transcript has been quiet for a few seconds.
### Native controls and MCP
diff --git a/crates/coding_agent_worker/src/herdr/acp_agent.rs b/crates/coding_agent_worker/src/herdr/acp_agent.rs
index 7d2ab603ad..7e9b73c89b 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent.rs
@@ -70,6 +70,8 @@ const STATUS_EVERY: u32 = 4;
/// Consecutive ready status checks, with no transcript ending, that end a
/// turn anyway (slash commands and interrupted turns write no final message).
const SETTLED_CHECKS: u32 = 3;
+/// How long the transcript must stay quiet before a ready status ends a turn.
+const SETTLED_QUIET: Duration = Duration::from_secs(3);
/// How long a new tab's shell may take to reach its prompt.
const SHELL_READY_TIMEOUT: Duration = Duration::from_secs(10);
const QUIET_START: Duration = Duration::from_secs(20);
@@ -605,6 +607,11 @@ impl Adapter {
let shutdown = self.shutdown.clone();
tokio::spawn(async move {
let mut ticks = 0u32;
+ // A turn started in the TUI: only its transcript or a settled
+ // native status can end it.
+ let mut open = false;
+ let mut settled = 0u32;
+ let mut last_output = Instant::now();
loop {
tokio::select! {
() = shutdown.cancelled() => break,
@@ -624,18 +631,53 @@ impl Adapter {
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;
+ match adapter.forward(&session, live, &mut None) {
+ Ok((moved, ended)) => {
+ if moved {
+ last_output = Instant::now();
+ settled = 0;
+ }
+ open = ended.is_none() && (open || moved);
+ }
+ Err(error) => {
+ 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;
+ // Interrupted turns, killed CLIs, and CLI events nothing
+ // answers write no turn end; herdr still sees the TUI idle.
+ if open {
+ settled = if adapter.native_idle(live).await {
+ settled + 1
+ } else {
+ 0
+ };
+ if settled >= SETTLED_CHECKS && last_output.elapsed() >= SETTLED_QUIET {
+ tracing::info!(session = %session.id, "native turn settled without a transcript ending");
+ adapter.turn_complete(&session.id, "end_turn");
+ open = false;
+ settled = 0;
+ }
+ }
}
}
});
}
+ /// Whether herdr reports the session's native agent done with its turn.
+ async fn native_idle(&self, live: &Live) -> bool {
+ let Some(herdr) = &self.herdr else {
+ return false;
+ };
+ herdr
+ .agent_info(&live.name)
+ .await
+ .is_ok_and(|info| matches!(info.status.as_str(), "idle" | "done"))
+ }
+
fn turn_complete(&self, session: &str, stop: &str) {
let outcome = match stop {
"cancelled" => json!({"kind":"cancelled"}),
@@ -1052,9 +1094,7 @@ impl Adapter {
}
"idle" | "done" => {
settled += 1;
- if active
- && settled >= SETTLED_CHECKS
- && last_output.elapsed() >= Duration::from_secs(3)
+ if active && settled >= SETTLED_CHECKS && last_output.elapsed() >= SETTLED_QUIET
{
self.forward(session, live, &mut open_tool)?;
return Ok("end_turn");
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 9be1fcef9e..ad568031b7 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent/test.rs
@@ -828,3 +828,58 @@ async fn a_prompt_dismisses_the_exit_confirmation_a_second_ctrl_c_left() {
assert!(stayed < prompted);
adapter.shutdown.cancel();
}
+
+#[tokio::test]
+async fn a_local_turn_without_a_transcript_ending_settles_once_herdr_is_idle() {
+ 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();
+ // A turn typed in the TUI whose CLI exits before answering: the
+ // transcript never records its end.
+ 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::time::timeout(Duration::from_secs(2), output.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ prompt["params"]["update"]["content"]["text"],
+ "typed in herdr"
+ );
+ // Still working natively: the turn stays open past the quiet period.
+ assert!(
+ tokio::time::timeout(SETTLED_QUIET + Duration::from_secs(2), output.recv())
+ .await
+ .is_err()
+ );
+ std::fs::write(root.path().join("status"), "idle").unwrap();
+ let settled = tokio::time::timeout(Duration::from_secs(8), output.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(settled["method"], "_session/turn_complete");
+ assert_eq!(settled["params"]["outcome"]["kind"], "finished");
+ // Ended once, not again on every idle check.
+ assert!(
+ tokio::time::timeout(Duration::from_secs(5), output.recv())
+ .await
+ .is_err()
+ );
+ adapter.shutdown.cancel();
+}
diff --git a/crates/folds/claude_fold/src/lib.rs b/crates/folds/claude_fold/src/lib.rs
index a9d747610f..e822c2544f 100644
--- a/crates/folds/claude_fold/src/lib.rs
+++ b/crates/folds/claude_fold/src/lib.rs
@@ -43,7 +43,7 @@ impl Fold for ClaudeLog {
};
match entry.get("type").and_then(Value::as_str) {
Some("assistant") => assistant(message),
- Some("user") => user_message(message, origin(&entry)),
+ Some("user") => user_message(&entry, message),
_ => Vec::new(),
}
}
@@ -112,7 +112,21 @@ fn origin(entry: &Value) -> Option<&str> {
entry.pointer("/origin/kind").and_then(Value::as_str)
}
-fn user_message(message: &Value, origin: Option<&str>) -> Vec<LogEvent> {
+/// Marks the CLI writes as a user line when Esc stops a turn. Newer CLIs also
+/// tag the line with `interruptedMessageId`; older ones only write the text.
+const INTERRUPTED: &str = "[Request interrupted by user";
+
+/// Local slash commands (`/model`, `/clear`, `/compact`) echo their name and
+/// output as untagged user lines. No assistant turn answers them.
+const LOCAL_COMMAND_TAGS: &[&str] = &[
+ "<command-name>",
+ "<command-message>",
+ "<local-command-stdout>",
+ "<local-command-stderr>",
+ "<local-command-caveat>",
+];
+
+fn user_message(entry: &Value, message: &Value) -> Vec<LogEvent> {
let mut events = tool_results(message);
let text = match message.get("content") {
Some(Value::String(text)) => text.clone(),
@@ -122,12 +136,25 @@ fn user_message(message: &Value, origin: Option<&str>) -> Vec<LogEvent> {
.collect::<Vec<_>>()
.join("\n"),
};
- if !text.is_empty() {
+ if entry.get("interruptedMessageId").is_some() || text.starts_with(INTERRUPTED) {
+ events.push(LogEvent::TurnEnded("cancelled"));
+ return events;
+ }
+ // Only a prompt may open a turn: a user chunk outside a Macro prompt
+ // starts one, and CLI bookkeeping is never followed by the `end_turn`
+ // that would close it.
+ let flag = |key| entry.get(key).and_then(Value::as_bool) == Some(true);
+ let bookkeeping = flag("isMeta")
+ || flag("isCompactSummary")
+ || LOCAL_COMMAND_TAGS
+ .iter()
+ .any(|tag| text.trim_start().starts_with(tag));
+ if !text.is_empty() && !bookkeeping {
let mut update = json!({
"sessionUpdate": "user_message_chunk",
"content": {"type": "text", "text": text},
});
- if let Some(origin) = origin {
+ if let Some(origin) = origin(entry) {
update["_meta"] = json!({"claudeCode": {"origin": origin}});
}
events.push(LogEvent::Update(update));
diff --git a/crates/folds/claude_fold/src/test.rs b/crates/folds/claude_fold/src/test.rs
index bad1cc3181..9c9d6dbd0c 100644
--- a/crates/folds/claude_fold/src/test.rs
+++ b/crates/folds/claude_fold/src/test.rs
@@ -191,3 +191,87 @@ fn cli_injected_user_lines_carry_their_origin() {
}))]
);
}
+
+#[test]
+fn cli_bookkeeping_lines_never_read_as_prompts() {
+ let mut log = ClaudeLog::default();
+ for (uuid, entry) in [
+ (
+ "m",
+ json!({"isMeta": true, "message": {"content": "Base directory for this skill: /s"}}),
+ ),
+ (
+ "p",
+ json!({"isMeta": true, "origin": {"kind": "peer"}, "message": {"content": "Another Claude session sent a message"}}),
+ ),
+ (
+ "c",
+ json!({"isCompactSummary": true, "isVisibleInTranscriptOnly": true, "message": {"content": "This session is being continued from a previous conversation"}}),
+ ),
+ (
+ "n",
+ json!({"message": {"content": "<command-name>/model</command-name>\n<command-message>model</command-message>\n<command-args></command-args>"}}),
+ ),
+ (
+ "o",
+ json!({"message": {"content": "<local-command-stdout>Set model to opus</local-command-stdout>"}}),
+ ),
+ (
+ "v",
+ json!({"isMeta": true, "message": {"content": "<local-command-caveat>Caveat: the messages below were generated by the user while running local commands.</local-command-caveat>"}}),
+ ),
+ ] {
+ let mut entry = entry;
+ entry["type"] = json!("user");
+ entry["uuid"] = json!(uuid);
+ assert!(log.entry(&line(entry)).is_empty(), "{uuid} opened a turn");
+ }
+}
+
+#[test]
+fn an_interrupt_cancels_the_turn_instead_of_opening_one() {
+ let mut log = ClaudeLog::default();
+ let tagged = line(json!({
+ "type": "user", "uuid": "i1", "interruptedMessageId": "msg_1",
+ "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}
+ }));
+ assert_eq!(log.entry(&tagged), [LogEvent::TurnEnded("cancelled")]);
+
+ // Older CLIs write the marker without the tag, after the refused tool.
+ let untagged = line(json!({
+ "type": "user", "uuid": "i2",
+ "message": {"content": [
+ {"type": "tool_result", "tool_use_id": "t", "is_error": true, "content": "The user doesn't want to proceed"},
+ {"type": "text", "text": "[Request interrupted by user for tool use]"},
+ ]}
+ }));
+ assert_eq!(
+ log.entry(&untagged),
+ [
+ LogEvent::Update(json!({
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "t",
+ "status": "failed",
+ "content": [{"type": "content", "content": {"type": "text", "text": "The user doesn't want to proceed"}}],
+ })),
+ LogEvent::TurnEnded("cancelled"),
+ ]
+ );
+}
+
+#[test]
+fn a_typed_prompt_still_opens_a_turn() {
+ let mut log = ClaudeLog::default();
+ let prompt = line(json!({
+ "type": "user", "uuid": "h", "origin": {"kind": "human"},
+ "message": {"content": "fix the login bug"}
+ }));
+ assert_eq!(
+ log.entry(&prompt),
+ [LogEvent::Update(json!({
+ "sessionUpdate": "user_message_chunk",
+ "content": {"type": "text", "text": "fix the login bug"},
+ "_meta": {"claudeCode": {"origin": "human"}},
+ }))]
+ );
+}