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
chore(agents): steer channel follow-ups with stop, flush, and Magic Chip (#6463)
Wolf Mermelsteinb77a608ca85e
diff --git a/crates/agent_harness/src/domain/queue.rs b/crates/agent_harness/src/domain/queue.rsindex 3b406963b7..f2ae6bb5c3 100644--- a/crates/agent_harness/src/domain/queue.rs+++ b/crates/agent_harness/src/domain/queue.rs@@ -3,9 +3,12 @@//! Prompts (and compaction) occupy a whole agent turn, and ACP runs one turn//! at a time - so while a turn runs, further turn-occupying actions wait here//! rather than interleaving on the wire. Entries hold the *raw* user text:-//! composition and announcement happen at dispatch, which is what makes a-//! queued prompt editable and gives it fresh channel context when it actually-//! runs.+//! composition happens at dispatch, which is what makes a queued prompt+//! editable and gives it fresh channel context when it actually runs. The+//! chip is usually announced then too, except a channel follow-up that+//! steers a running turn: it goes to the front and posts its chip when it is+//! accepted, so the reply sits on the follow-up rather than after the+//! cancelled turn or behind work queued earlier.//!//! In-memory on purpose. The queue lives beside the session's live actor on//! the replica that manages it, and dies with the process - a restart loses@@ -142,11 +145,31 @@ impl SessionQueues {/// Append an entry to its session's queue.pub fn enqueue(&self, session: AgentSessionId, entry: QueuedEntry) -> Result<(), QueueError> {+ self.insert(session, entry, VecDeque::push_back)+ }++ /// Put an entry ahead of everything already waiting, for a channel+ /// follow-up that steers the running turn: it runs next, not after work+ /// that was queued before it.+ pub fn enqueue_front(+ &self,+ session: AgentSessionId,+ entry: QueuedEntry,+ ) -> Result<(), QueueError> {+ self.insert(session, entry, VecDeque::push_front)+ }++ fn insert(+ &self,+ session: AgentSessionId,+ entry: QueuedEntry,+ push: fn(&mut VecDeque<QueuedEntry>, QueuedEntry),+ ) -> Result<(), QueueError> {let mut queue = self.queues.entry(session).or_default();if queue.len() >= QUEUE_CAP {return Err(QueueError::Full);}- queue.push_back(entry);+ push(&mut queue, entry);Ok(())}@@ -187,6 +210,23 @@ impl SessionQueues {.is_some_and(|queue| queue.iter().any(|entry| entry.action_id == action_id))}+ /// Remember that this entry's chip has been posted, so dispatch does not+ /// announce it a second time.+ pub fn mark_announced(+ &self,+ session: AgentSessionId,+ action_id: AgentActionId,+ message_id: Uuid,+ ) -> Result<(), QueueError> {+ let mut queue = self.queues.get_mut(&session).ok_or(QueueError::NotFound)?;+ let entry = queue+ .iter_mut()+ .find(|entry| entry.action_id == action_id)+ .ok_or(QueueError::NotFound)?;+ entry.announced = Some(message_id);+ Ok(())+ }+/// Replace a queued prompt's text. The entry keeps its place and its id.////// `actor` becomes the entry's actor: the user who rewrote the text isdiff --git a/crates/agent_harness/src/domain/queue/test.rs b/crates/agent_harness/src/domain/queue/test.rsindex 5a8b040ff1..f742f82fce 100644--- a/crates/agent_harness/src/domain/queue/test.rs+++ b/crates/agent_harness/src/domain/queue/test.rs@@ -160,6 +160,24 @@ fn removal_skips_the_removed_entry_at_dispatch() {);}+#[test]+fn mark_announced_remembers_the_chip_on_the_waiting_entry() {+ let queues = SessionQueues::new();+ let session = AgentSessionId::TEST_A;+ let first = prompt_entry("first");+ let second = prompt_entry("second");+ queues.enqueue(session, first.clone()).unwrap();+ queues.enqueue(session, second.clone()).unwrap();++ let chip = Uuid::from_u128(0xc1);+ queues+ .mark_announced(session, second.action_id, chip)+ .unwrap();++ assert_eq!(queues.claim_next(session).unwrap().announced, None);+ assert_eq!(queues.claim_next(session).unwrap().announced, Some(chip));+}+#[test]fn a_requeued_entry_is_next_in_line() {let queues = SessionQueues::new();@@ -178,6 +196,33 @@ fn a_requeued_entry_is_next_in_line() {);}+#[test]+fn enqueue_front_puts_the_entry_ahead_of_waiting_work() {+ let queues = SessionQueues::new();+ let session = AgentSessionId::TEST_A;+ let waiting = prompt_entry("queued earlier");+ let steer = prompt_entry("steer");+ queues.enqueue(session, waiting.clone()).unwrap();+ queues.enqueue_front(session, steer.clone()).unwrap();++ assert_eq!(+ queues+ .list(session)+ .iter()+ .map(|entry| entry.action_id)+ .collect::<Vec<_>>(),+ [steer.action_id, waiting.action_id]+ );+ assert_eq!(+ queues.claim_next(session).unwrap().action_id,+ steer.action_id+ );+ assert_eq!(+ queues.claim_next(session).unwrap().action_id,+ waiting.action_id+ );+}+#[test]fn the_cap_refuses_the_overflowing_entry() {let queues = SessionQueues::new();@@ -192,4 +237,8 @@ fn the_cap_refuses_the_overflowing_entry() {queues.enqueue(session, prompt_entry("one too many")),Err(QueueError::Full));+ assert_eq!(+ queues.enqueue_front(session, prompt_entry("nor at the front")),+ Err(QueueError::Full)+ );}diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rsindex 72d4fd572d..4dbb4883e8 100644--- a/crates/agent_harness/src/domain/service/queue.rs+++ b/crates/agent_harness/src/domain/service/queue.rs@@ -489,6 +489,11 @@ where/// necessarily: entries can linger from a drain that failed, and FIFO/// order holds regardless. The outcome reports what happened to *this*/// action - still waiting, or on the wire.+ ///+ /// A channel follow-up (`announce` set) that lands on a running turn+ /// steers: it goes to the front of the queue, a stop cancels the current+ /// turn, and the chip is posted on that follow-up immediately - so it+ /// flushes next, ahead of anything queued before it.pub(super) async fn enqueue_then_dispatch(&self,session_id: AgentSessionId,@@ -500,27 +505,35 @@ where_ => None,};let actor = command.actor.clone();- queue_result(- self.queues.enqueue(- session_id,- QueuedEntry {- action_id,- action: command.action,- actor: command.actor,- announce: command.announce,- announced: None,- created_at: chrono::Utc::now(),- },- ),- session_id,- )?;+ let announce = command.announce.clone();+ let action = command.action.clone();+ let steers = announce.is_some() && self.busy.turn(session_id).is_some();+ let entry = QueuedEntry {+ action_id,+ action: command.action,+ actor: command.actor,+ announce: command.announce,+ announced: None,+ created_at: chrono::Utc::now(),+ };+ let enqueued = if steers {+ self.queues.enqueue_front(session_id, entry)+ } else {+ self.queues.enqueue(session_id, entry)+ };+ queue_result(enqueued, session_id)?;// Mentions are a fact about the prompt, not the turn: published as// soon as the prompt is accepted, whether it dispatches now or waits.if let Some(prompt) = prompt {- self.publish_mentions(session_id, action_id, actor, &prompt)+ self.publish_mentions(session_id, action_id, actor.clone(), &prompt).await;}+ if steers {+ self.steer_channel_follow_up(session_id, action_id, &action, actor.as_ref(), announce)+ .await?;+ }+let dispatched = if self.busy.is_pending(session_id) {Ok(())} else {@@ -550,6 +563,58 @@ where})}+ /// Cancel a running turn and post the chip on the channel follow-up that+ /// interrupted it. The follow-up is already at the front of the queue,+ /// so it flushes as the next prompt once the cancelled turn ends.+ ///+ /// Stop is delivered first: the fold records it as its own control turn,+ /// and the chip has to name the prompt turn that comes after that, not+ /// the id the fold would have handed out before the cancel. A failed+ /// cancel is best-effort — the prompt is already queued and still drains+ /// when the current turn ends on its own.+ async fn steer_channel_follow_up(+ &self,+ session_id: AgentSessionId,+ action_id: AgentActionId,+ action: &AgentAction,+ actor: Option<&MacroUserIdStr<'static>>,+ announce: Option<AnnounceOrigin>,+ ) -> Result<()> {+ if let Err(error) = self+ .deliver(+ session_id,+ DeliverAction {+ id: AgentActionId::mint(),+ action: AgentAction::Stop,+ actor: actor.cloned(),+ announce: None,+ },+ )+ .await+ {+ tracing::warn!(+ error = ?error,+ %session_id,+ "failed to stop the running turn for a channel follow-up"+ );+ }++ // Front of the queue, so the next prompt turn is this one's.+ let prompted_message_id = self.sessions.next_prompt_message_id(session_id).await?;+ let announcement = self+ .announcement(session_id, action, actor, announce, prompted_message_id)+ .await?;+ if let Some(announcement) = announcement {+ let announced = self.announcer.announce(announcement).await?;+ queue_result(+ self.queues+ .mark_announced(session_id, action_id, announced.message_id),+ session_id,+ )?;+ }+ Ok(())+ }+/// Push the queue as it now stands to the session's viewers.////// Best-effort, like every realtime publish: a dropped snapshot costs adiff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex ed270d9994..456b41e57e 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -6,8 +6,9 @@ use std::sync::{Arc, Mutex};use agent_client_protocol::RawJsonRpcMessage;use agent_client_protocol::schema::v1::{- AgentCapabilities, ClientRequest, ContentBlock, InitializeResponse, NewSessionResponse,- ResumeSessionResponse, SessionCapabilities, SessionId, SessionResumeCapabilities,+ AgentCapabilities, ClientNotification, ClientRequest, ContentBlock, InitializeResponse,+ NewSessionResponse, ResumeSessionResponse, SessionCapabilities, SessionId,+ SessionResumeCapabilities,};use agent_fold::domain::model::TurnSignal;use agent_fold::domain::model::{AuthorKind, MessageId};@@ -767,34 +768,20 @@ async fn open_announces_while_the_container_is_still_booting() {#[tokio::test]async fn forward_to_a_live_session_reuses_the_transport() {let composer = PromptComposerMock::default();- let (service, _repo, containers, announcer, _runtimes) =- harness_with_edges(PromptContextMock::default(), composer.clone());- let command = open_command();+ let ((service, _repo, containers, announcer, _runtimes), mut turns) =+ harness_with_signals(PromptContextMock::default(), composer.clone());let id = AgentSessionId::new();- let open = service.execute(id, HarnessCommand::Open(command));- let drive = async {- loop {- if containers.spawned() == 1 {- break;- }- tokio::task::yield_now().await;- }- let container = containers- .container(session_of(&containers))- .expect("the spawned container is findable");- complete_handshake(&container).await;- container- };- let (opened, container) = tokio::join!(open, drive);- opened.expect("open should succeed");+ let container = live_session(&service, &containers, id).await;+ turns.settled(id).await;- let forward = service.execute(- id,- HarnessCommand::Deliver(forward_message("and add a regression test")),- );- let agent = container.agent();- let (result, ()) = tokio::join!(forward, agent.completes_prompt());- result.expect("forward to a live session should succeed");+ service+ .execute(+ id,+ HarnessCommand::Deliver(forward_message("and add a regression test")),+ )+ .await+ .expect("forward to a live session should succeed");+ container.agent().wait_for_requests(4).await;assert_eq!(containers.spawned(), 1, "no second container");assert_eq!(containers.resumed(), 0, "no resume for a live session");@@ -1020,19 +1007,16 @@ async fn concurrent_forwards_share_one_session_recovery() {vec![ContentBlock::from(context_prompt("second"))],]);- assert_eq!(- announcer- .announced()- .into_iter()- .map(|announcement| announcement.prompted_message_id)- .collect::<Vec<_>>(),- [- MessageId::first(AuthorKind::User),- MessageId {- turn: agent_session::domain::model::TurnId(1),- author: AuthorKind::User,- },- ]+ let announced_turns: Vec<_> = announcer+ .announced()+ .into_iter()+ .map(|announcement| announcement.prompted_message_id)+ .collect();+ assert_eq!(announced_turns[0], MessageId::first(AuthorKind::User));+ assert!(+ announced_turns[1].turn == agent_session::domain::model::TurnId(1)+ || announced_turns[1].turn == agent_session::domain::model::TurnId(2),+ "the second chip is the next prompt, or the one after a steer-stop: {announced_turns:?}");}@@ -1477,6 +1461,142 @@ async fn a_stop_cancels_the_turn_and_the_queue_keeps_draining() {);}+fn cancel_count(agent: &FakeAgent) -> usize {+ agent+ .received_notifications()+ .iter()+ .filter(|notification| matches!(notification, ClientNotification::CancelNotification(_)))+ .count()+}++#[tokio::test]+async fn a_channel_follow_up_stops_the_running_turn_announces_and_flushes() {+ let ((service, _repo, containers, announcer, _runtimes), mut turns) =+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());+ let id = AgentSessionId::new();+ let container = session_with_a_running_turn(&service, &containers, id).await;+ let agent = container.agent();+ let announcements_before = announcer.announced().len();+ let prompts_before = prompts(&agent).len();++ // Work already waiting from the session page: the follow-up jumps it.+ let waiting = service+ .control_event(+ id,+ ControlEvent {+ action: AgentAction::prompt("queued earlier from the session page"),+ actor: Some(staff_sender()),+ },+ )+ .await+ .expect("a mid-turn session-page prompt queues");+ assert_eq!(+ waiting.disposition,+ agent_session::domain::ports::ControlDisposition::Queued+ );++ let follow_up = forward_message("steer from the channel");+ let follow_up_id = follow_up.id;+ let outcome = service+ .execute(id, HarnessCommand::Deliver(follow_up))+ .await+ .expect("a channel follow-up is accepted");+ assert_eq!(outcome, CommandOutcome::Queued);+ assert_eq!(+ cancel_count(&agent),+ 1,+ "the running turn is cancelled so the follow-up can flush: {:#?}",+ agent.received_notifications()+ );+ assert_eq!(+ prompts(&agent).len(),+ prompts_before,+ "the follow-up waits for the cancelled turn to end"+ );+ let queued = service.queued_controls(id).await.expect("queue lists");+ assert_eq!(+ queued+ .iter()+ .map(|entry| entry.action_id)+ .collect::<Vec<_>>(),+ [follow_up_id, waiting.action_id],+ "the follow-up is at the front, ahead of the earlier prompt"+ );++ let announced = announcer.announced();+ assert_eq!(+ announced.len(),+ announcements_before + 1,+ "the chip is posted on the follow-up before the cancelled turn ends"+ );+ let chip = announced.last().expect("the follow-up announced a chip");+ assert_eq!(chip.prompted_content, "steer from the channel");+ assert_eq!(chip.origin_message_id, Uuid::from_u128(0xf2));+ assert_eq!(+ chip.prompted_message_id,+ MessageId {+ // Stop is its own fold turn, so the follow-up opens the next one.+ turn: agent_session::domain::model::TurnId(2),+ author: AuthorKind::User,+ }+ );++ agent.completes_prompt().await;+ agent.wait_for_requests(4).await;++ assert_eq!(+ prompts(&agent)[1],+ vec![ContentBlock::from(context_prompt("steer from the channel"))],+ "the follow-up flushes first"+ );+ assert_eq!(+ announcer.announced().len(),+ announcements_before + 1,+ "dispatch does not post a second chip for the same follow-up"+ );++ agent.completes_prompt().await;+ agent.wait_for_requests(5).await;+ turns.settled(id).await;+ // No channel origin, so no composed context: the raw text goes out.+ assert_eq!(+ prompts(&agent)[2],+ vec![ContentBlock::from("queued earlier from the session page")],+ "the displaced prompt runs after the follow-up"+ );+}++#[tokio::test]+async fn an_idle_channel_follow_up_does_not_stop() {+ let ((service, _repo, containers, announcer, _runtimes), mut turns) =+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());+ let id = AgentSessionId::new();+ let container = live_session(&service, &containers, id).await;+ turns.settled(id).await;+ let agent = container.agent();+ let cancels_before = cancel_count(&agent);++ service+ .execute(+ id,+ HarnessCommand::Deliver(forward_message("next, while idle")),+ )+ .await+ .expect("an idle follow-up dispatches");+ agent.wait_for_requests(4).await;++ assert_eq!(+ cancel_count(&agent),+ cancels_before,+ "nothing is running, so there is no turn to cancel"+ );+ assert_eq!(announcer.announced().len(), 2);+ assert_eq!(+ prompts(&agent)[1],+ vec![ContentBlock::from(context_prompt("next, while idle"))]+ );+}+#[tokio::test]async fn queued_prompts_are_editable_and_removable_until_dispatch() {let ((service, _repo, containers, _announcer, _runtimes), _turns) =@@ -2652,16 +2772,25 @@ mod lifecycle_events {let ((service, _, _, _, _), turns, id, container) = settled_session().await;let agent = container.agent();- // The first forward dispatches at once; the second waits behind it.+ // Session-page prompts queue without steering; a channel follow-up+ // would stop the running turn instead. See+ // `a_channel_follow_up_stops_the_running_turn_announces_and_flushes`.+ let prompt = |text: &str| ControlEvent {+ action: AgentAction::prompt(text),+ actor: Some(staff_sender()),+ };service- .execute(id, HarnessCommand::Deliver(forward_message("first")))+ .control_event(id, prompt("first")).await- .expect("first forward dispatches");+ .expect("first prompt dispatches");let queued = service- .execute(id, HarnessCommand::Deliver(forward_message("second")))+ .control_event(id, prompt("second")).await- .expect("second forward is accepted");- assert_eq!(queued, CommandOutcome::Queued);+ .expect("second prompt is accepted");+ assert_eq!(+ queued.disposition,+ agent_session::domain::ports::ControlDisposition::Queued+ );turns.lifecycle_published(5).await;agent.completes_prompt().await;diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 9e67f34e26..9f5c85f0ff 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -88,6 +88,10 @@ own time zone (their primary calendar's), so it resolves relative times ("tomorrbot asks before scheduling a specific clock time. `@macro-new` / `@coder` / `@cursor` / `@codex` openan agent session; follow-up`@` mentions of that bot in the same thread route to it.+A follow-up sent while that session is still working stops the current turn,+posts a new Magic Chip on the follow-up message, and steers the agent with+that text — the chip appears at the follow-up, not after the cancelled turn+finishes.The reply renders a Magic Chip: a rounded card of constant height that is presentfrom the moment the session boots. Its header names the persona (`Macro Agent`,`Cursor Agent`), the model, and what the turn is doing (`Booting agent`, `Running