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(cursor): make session/cancel actually stop the remote run (#5960)

Wolf Mermelstein29d22f9f29ab
diff --git a/crates/cursor_cloud_agents/src/domain/service.rs b/crates/cursor_cloud_agents/src/domain/service.rs
index 6690faf1e9..bf8fba149a 100644
--- a/crates/cursor_cloud_agents/src/domain/service.rs
+++ b/crates/cursor_cloud_agents/src/domain/service.rs
@@ -19,6 +19,12 @@
//! distinction matters because Cursor keeps a cancelled run's stream open often
//! enough that waiting for it meant the client's stop button did nothing until
//! the agent finished of its own accord.
+//!
+//! The remote cancel still needs a run id, and this process only remembers
+//! one for a turn it is itself streaming. A session restored after a restart,
+//! or one whose run started from cursor.com, has no such memory — cancelling
+//! it falls back to asking Cursor which run is current rather than silently
+//! skipping the remote call.
#[cfg(test)]
mod test;
@@ -493,10 +499,17 @@ where
/// Cancel the session's active turn, if any. Idempotent; a session with
/// no active turn is a no-op rather than an error, because the turn may
/// have ended while the cancel was in flight.
+ ///
+ /// `active_run` is this process's own memory of what it started, so it is
+ /// empty for a session restored after a restart — or one whose run this
+ /// process never drove at all (started from cursor.com). Either way the
+ /// agent may still have a run going, so a miss falls back to asking
+ /// Cursor which run, if any, is current before giving up on the remote
+ /// cancel.
#[tracing::instrument(skip(self), err)]
pub async fn cancel(&self, session_id: &SessionId) -> Result<(), SessionError> {
let session = self.session(session_id)?;
- let target = {
+ let (agent, active_run) = {
let mut state = session.state.lock().expect("session state poisoned");
state.cancelled = true;
// Fired before the network call, and the turn ends on it alone:
@@ -505,14 +518,59 @@ where
// gets its turn back. A cancel Cursor refuses used to leave the
// turn streaming to natural completion.
state.cancel.cancel();
- state.agent.clone().zip(state.active_run.clone())
+ (state.agent.clone(), state.active_run.clone())
+ };
+ let Some(agent) = agent else {
+ return Ok(());
};
- if let Some((agent, run)) = target {
- self.cursor.cancel_run(&agent, &run).await?;
+ let runs = match active_run {
+ Some(run) => vec![run],
+ None => self.current_runs(&agent).await,
+ };
+ // Concurrent rather than sequential so one failing cancel does not
+ // skip the rest — every run found gets its own attempt regardless of
+ // how the others land.
+ let results =
+ futures::future::join_all(runs.iter().map(|run| self.cursor.cancel_run(&agent, run)))
+ .await;
+ for result in results {
+ result?;
}
Ok(())
}
+ /// The agent's runs still in progress, per Cursor's own record.
+ ///
+ /// The fallback [`Self::cancel`] takes when this process has no memory of
+ /// one: best-effort, like the remote cancel itself, so a lookup failure
+ /// costs the remote cancel, never the local one that already fired.
+ /// Cursor documents one active run per agent (see
+ /// [`Self::create_run_when_free`]), but that is a server-side invariant
+ /// this client does not enforce, so every match is cancelled rather than
+ /// just the first — cheap insurance against it ever slipping.
+ async fn current_runs(&self, agent: &CursorAgentId) -> Vec<CursorRunId> {
+ let listings = match self.cursor.list_runs(agent).await {
+ Ok(listings) => listings,
+ Err(error) => {
+ tracing::warn!(%agent, %error, "could not list runs to find one to cancel");
+ return Vec::new();
+ }
+ };
+ let runs: Vec<CursorRunId> = listings
+ .into_iter()
+ .filter(|listing| matches!(listing.status, RunStatus::Creating | RunStatus::Running))
+ .map(|listing| listing.id)
+ .collect();
+ if runs.len() > 1 {
+ tracing::warn!(
+ %agent,
+ count = runs.len(),
+ "more than one run in progress for an agent; Cursor documents one active run per agent"
+ );
+ }
+ runs
+ }
+
/// Drop a session, reporting whether it existed. Any active run keeps
/// running server-side; closing the ACP session does not imply
/// cancelling the work.
@@ -629,6 +687,7 @@ where
{
Ok(None) => {
tracing::info!(%agent, %run, "turn cancelled by the client; abandoning the stream");
+ self.close_open_tool_calls(session_id, session).await;
return Ok(StopReason::Cancelled);
}
Ok(Some(next)) => next,
@@ -727,6 +786,26 @@ where
}
}
+ /// Close out every tool call left open when a turn ends on the client's
+ /// cancel rather than Cursor's own terminal event.
+ ///
+ /// The abandoned stream (see the `Ok(None)` arm above) means Cursor may
+ /// still be mid-call and will never get the chance to say how it ended,
+ /// so without this the client renders that call running forever.
+ async fn close_open_tool_calls(&self, session_id: &SessionId, session: &Session) {
+ let updates = session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .translator
+ .close_open_calls();
+ for update in updates {
+ if let Err(error) = self.notifier.notify(session_id, update).await {
+ tracing::warn!(%error, "could not close an open tool call after cancel");
+ }
+ }
+ }
+
/// Create a follow-up run, waiting out whatever run is already going.
///
/// Cursor allows one active run per agent and answers `agent_busy`
diff --git a/crates/cursor_cloud_agents/src/domain/service/test.rs b/crates/cursor_cloud_agents/src/domain/service/test.rs
index b47e61cdfd..9ada151fa2 100644
--- a/crates/cursor_cloud_agents/src/domain/service/test.rs
+++ b/crates/cursor_cloud_agents/src/domain/service/test.rs
@@ -1,11 +1,11 @@
use super::*;
use crate::domain::error::SessionError;
-use crate::domain::event::{CursorEvent, InteractionUpdate};
+use crate::domain::event::{CursorEvent, InteractionUpdate, ToolCallEvent, Truncation};
use crate::domain::model::{
McpHeader, McpServer, McpTransport, RepoUrl, RunListing, RunOutcome, RunStatus,
};
use crate::testing::{CursorCall, FakeCursor, FixedRepos, RecordingNotifier};
-use agent_client_protocol::schema::v1::{SessionUpdate, StopReason};
+use agent_client_protocol::schema::v1::{SessionUpdate, StopReason, ToolCallStatus};
use std::path::Path;
type Service = CursorSessionService<FakeCursor, RecordingNotifier, FixedRepos>;
@@ -160,6 +160,51 @@ async fn cancel_ends_the_turn_while_the_stream_stays_open() {
assert_eq!(notifier.updates().len(), 1);
}
+/// A tool call still running when the client cancels never gets Cursor's own
+/// terminal event — the stream is abandoned, not drained — so it must be
+/// closed out locally rather than left rendering "in progress" forever.
+#[tokio::test]
+async fn cancel_mid_tool_call_closes_it_as_failed() {
+ let (service, cursor, notifier) = service(None);
+ let session = service.new_session(Path::new(""), Vec::new());
+
+ let events = cursor.script_stream();
+ let turn = tokio::spawn({
+ let service = Arc::clone(&service);
+ let session = session.clone();
+ async move { service.prompt(&session, "long job").await }
+ });
+
+ events
+ .send(CursorEvent::ToolCall(ToolCallEvent {
+ call_id: "call-1".to_owned(),
+ name: "run_terminal_cmd".to_owned(),
+ status: Some("running".to_owned()),
+ args: None,
+ result: None,
+ truncated: Truncation::default(),
+ }))
+ .expect("stream open");
+ notifier.wait_for_updates(1).await;
+
+ service.cancel(&session).await.expect("cancel works");
+
+ let stop = turn.await.expect("task joins").expect("prompt resolves");
+ assert_eq!(stop, StopReason::Cancelled);
+
+ let closing = notifier
+ .updates()
+ .into_iter()
+ .find_map(|(_, update)| match update {
+ SessionUpdate::ToolCallUpdate(update) if &*update.tool_call_id.0 == "call-1" => {
+ Some(update)
+ }
+ _ => None,
+ })
+ .expect("the open call was closed out");
+ assert_eq!(closing.fields.status, Some(ToolCallStatus::Failed));
+}
+
/// A cancel while the prompt is still queued behind someone else's run ends the
/// wait, rather than sitting out the full busy timeout.
#[tokio::test]
@@ -547,6 +592,118 @@ async fn a_restored_session_prompts_its_existing_agent() {
);
}
+/// A restored session has no in-memory `active_run` — this process never
+/// drove the run itself — so cancelling it must fall back to asking Cursor
+/// which run is current instead of silently skipping the remote cancel.
+#[tokio::test]
+async fn cancel_on_a_restored_session_finds_the_run_from_cursor() {
+ let (service, cursor, _notifier) = service(None);
+ service.restore_session(
+ SessionId::new("cursor-acp-7"),
+ Some(CursorAgentId::new("bc-restored")),
+ None,
+ None,
+ );
+
+ cursor.script_run_listings(vec![
+ RunListing {
+ id: CursorRunId::new("run-in-flight"),
+ status: RunStatus::Running,
+ },
+ RunListing {
+ id: CursorRunId::new("run-old"),
+ status: RunStatus::Finished,
+ },
+ ]);
+
+ service
+ .cancel(&SessionId::new("cursor-acp-7"))
+ .await
+ .expect("cancel works");
+
+ assert_eq!(
+ cursor.calls(),
+ vec![CursorCall::CancelRun(
+ CursorAgentId::new("bc-restored"),
+ CursorRunId::new("run-in-flight"),
+ )]
+ );
+}
+
+/// The fallback lookup cancels every run it finds in progress, not just the
+/// first — Cursor documents one active run per agent, but that invariant is
+/// not enforced client-side, and cancelling one leaked run is cheaper than
+/// missing it.
+#[tokio::test]
+async fn cancel_on_a_restored_session_cancels_every_run_in_progress() {
+ let (service, cursor, _notifier) = service(None);
+ service.restore_session(
+ SessionId::new("cursor-acp-10"),
+ Some(CursorAgentId::new("bc-restored")),
+ None,
+ None,
+ );
+
+ cursor.script_run_listings(vec![
+ RunListing {
+ id: CursorRunId::new("run-creating"),
+ status: RunStatus::Creating,
+ },
+ RunListing {
+ id: CursorRunId::new("run-running"),
+ status: RunStatus::Running,
+ },
+ RunListing {
+ id: CursorRunId::new("run-old"),
+ status: RunStatus::Finished,
+ },
+ ]);
+
+ service
+ .cancel(&SessionId::new("cursor-acp-10"))
+ .await
+ .expect("cancel works");
+
+ assert_eq!(
+ cursor.calls(),
+ vec![
+ CursorCall::CancelRun(
+ CursorAgentId::new("bc-restored"),
+ CursorRunId::new("run-creating"),
+ ),
+ CursorCall::CancelRun(
+ CursorAgentId::new("bc-restored"),
+ CursorRunId::new("run-running"),
+ ),
+ ]
+ );
+}
+
+/// A restored session with no run currently going is a no-op, not an error —
+/// the fallback lookup found nothing to cancel.
+#[tokio::test]
+async fn cancel_on_a_restored_session_with_no_run_going_is_a_no_op() {
+ let (service, cursor, _notifier) = service(None);
+ service.restore_session(
+ SessionId::new("cursor-acp-8"),
+ Some(CursorAgentId::new("bc-restored")),
+ None,
+ None,
+ );
+
+ cursor.script_run_listings(vec![RunListing {
+ id: CursorRunId::new("run-old"),
+ status: RunStatus::Finished,
+ }]);
+
+ service
+ .cancel(&SessionId::new("cursor-acp-8"))
+ .await
+ .expect("cancel works");
+
+ assert!(cursor.calls().is_empty());
+}
+
/// Fresh ids skip over restored ones instead of replacing a live session.
#[tokio::test]
async fn new_sessions_never_collide_with_restored_ids() {
diff --git a/crates/cursor_cloud_agents/src/domain/translate.rs b/crates/cursor_cloud_agents/src/domain/translate.rs
index d6817c255b..806b85bc15 100644
--- a/crates/cursor_cloud_agents/src/domain/translate.rs
+++ b/crates/cursor_cloud_agents/src/domain/translate.rs
@@ -24,6 +24,9 @@
//! of a sized window. Inventing a size would misrender in any client that
//! shows a percentage, so usage is deliberately not translated.
+#[cfg(test)]
+mod test;
+
use crate::domain::event::{CursorEvent, InteractionUpdate, ToolCallEvent};
use agent_client_protocol::schema::v1::{
ContentBlock, ContentChunk, Diff, SessionUpdate, TextContent, ToolCall, ToolCallContent,
@@ -35,8 +38,12 @@ use std::collections::{HashMap, HashSet};
/// time.
#[derive(Debug, Default)]
pub struct TranslateMachine {
- /// Call ids already announced, so repeats become `tool_call_update`.
- announced: HashSet<String>,
+ /// Call ids announced and not yet terminal, so repeats become
+ /// `tool_call_update` and a turn that ends early knows what it left
+ /// open. A call id leaves this set the moment it reports `Completed` or
+ /// `Failed` — it re-entering would mean Cursor reused a finished id,
+ /// which has never been observed.
+ open: HashSet<String>,
/// Kinds learned from Cursor's typed tool descriptor, keyed by call id.
learned_kinds: HashMap<String, ToolKind>,
}
@@ -100,7 +107,15 @@ impl TranslateMachine {
// new file would claim everything else was deleted.
let diff = call.result.as_ref().and_then(edit_diff);
- if self.announced.insert(call_id.clone()) {
+ // Captured before the status below can remove it: a call id is only
+ // ever a fresh announcement the first time it is seen, even when
+ // that first frame already reports it terminal.
+ let is_new = self.open.insert(call_id.clone());
+ if matches!(status, ToolCallStatus::Completed | ToolCallStatus::Failed) {
+ self.open.remove(&call_id);
+ }
+
+ if is_new {
let mut announcement = ToolCall::new(call_id, call.name)
.kind(kind)
.status(status)
@@ -132,6 +147,29 @@ impl TranslateMachine {
}
}
+ /// Force every call still open to a terminal status, for a turn that
+ /// ended without Cursor ever reporting one.
+ ///
+ /// A cancelled turn abandons the stream (see
+ /// [`crate::domain::service::CursorSessionService::cancel`]) rather than
+ /// waiting for Cursor's own terminal `tool_call` frame, so a call still
+ /// running at that moment would otherwise never receive one — the
+ /// client is left rendering it in progress forever. `Failed` is the
+ /// honest status to close it with: ACP v1 has no `cancelled` tool-call
+ /// status, and Cursor never actually reported an outcome for these, so
+ /// `Completed` would claim a success nobody witnessed.
+ pub fn close_open_calls(&mut self) -> Vec<SessionUpdate> {
+ self.open
+ .drain()
+ .map(|call_id| {
+ SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
+ call_id,
+ ToolCallUpdateFields::new().status(ToolCallStatus::Failed),
+ ))
+ })
+ .collect()
+ }
+
/// Record what the envelope teaches; it never emits an update itself.
fn interaction(&mut self, update: &InteractionUpdate) {
match update {
diff --git a/crates/cursor_cloud_agents/src/domain/translate/test.rs b/crates/cursor_cloud_agents/src/domain/translate/test.rs
new file mode 100644
index 0000000000..41d05d0117
--- /dev/null
+++ b/crates/cursor_cloud_agents/src/domain/translate/test.rs
@@ -0,0 +1,60 @@
+use super::*;
+use crate::domain::event::Truncation;
+
+fn tool_call(call_id: &str, status: &str) -> CursorEvent {
+ CursorEvent::ToolCall(ToolCallEvent {
+ call_id: call_id.to_owned(),
+ name: "run_terminal_cmd".to_owned(),
+ status: Some(status.to_owned()),
+ args: None,
+ result: None,
+ truncated: Truncation::default(),
+ })
+}
+
+#[test]
+fn a_call_left_running_is_closed_as_failed() {
+ let mut machine = TranslateMachine::new();
+ machine.push(tool_call("call-1", "running"));
+
+ let updates = machine.close_open_calls();
+ assert_eq!(updates.len(), 1);
+ let SessionUpdate::ToolCallUpdate(update) = &updates[0] else {
+ panic!("expected a tool_call_update, got {updates:?}");
+ };
+ assert_eq!(&*update.tool_call_id.0, "call-1");
+ assert_eq!(update.fields.status, Some(ToolCallStatus::Failed));
+}
+
+#[test]
+fn a_call_already_completed_is_not_closed_again() {
+ let mut machine = TranslateMachine::new();
+ machine.push(tool_call("call-1", "running"));
+ machine.push(tool_call("call-1", "completed"));
+
+ assert!(machine.close_open_calls().is_empty());
+}
+
+#[test]
+fn only_calls_still_open_are_closed() {
+ let mut machine = TranslateMachine::new();
+ machine.push(tool_call("call-1", "running"));
+ machine.push(tool_call("call-2", "running"));
+ machine.push(tool_call("call-1", "completed"));
+
+ let updates = machine.close_open_calls();
+ assert_eq!(updates.len(), 1);
+ let SessionUpdate::ToolCallUpdate(update) = &updates[0] else {
+ panic!("expected a tool_call_update, got {updates:?}");
+ };
+ assert_eq!(&*update.tool_call_id.0, "call-2");
+}
+
+#[test]
+fn closing_drains_so_a_second_call_finds_nothing_left() {
+ let mut machine = TranslateMachine::new();
+ machine.push(tool_call("call-1", "running"));
+
+ assert_eq!(machine.close_open_calls().len(), 1);
+ assert!(machine.close_open_calls().is_empty());
+}