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.

Stop Cursor turns by draining the stream, not by settling locally (#5986)

Wolf Mermelsteinbb64d4fa1f45
diff --git a/apps/web/src/features/block-agent/context/create-composer-controller.test.ts b/apps/web/src/features/block-agent/context/create-composer-controller.test.ts
index 3204290e84..a44de0bc4c 100644
--- a/apps/web/src/features/block-agent/context/create-composer-controller.test.ts
+++ b/apps/web/src/features/block-agent/context/create-composer-controller.test.ts
@@ -266,6 +266,35 @@ describe('stop', () => {
expect(control.calls.at(-1)?.action).toEqual({ type: 'stop' });
dispose();
});
+
+ // Each cancel the service accepts is its own Stopped line in the
+ // transcript, so a user clicking through a turn that takes a moment to
+ // settle would otherwise stack one per click.
+ it('posts one stop per turn, however many times it is clicked', async () => {
+ const { controller, setWorking, dispose } = setup({ working: true });
+ const isStop = (action: unknown) =>
+ typeof action === 'object' &&
+ action !== null &&
+ 'type' in action &&
+ action.type === 'stop';
+ const stops = () => control.calls.filter((call) => isStop(call.action));
+
+ controller.stop();
+ controller.stop();
+ controller.stop();
+ await flush();
+ expect(stops()).toHaveLength(1);
+
+ // The next turn stops on its own click: the latch tracks the turn, not
+ // the session.
+ setWorking(false);
+ await flush();
+ setWorking(true);
+ controller.stop();
+ await flush();
+ expect(stops()).toHaveLength(2);
+ dispose();
+ });
});
describe('a session that does not exist yet', () => {
diff --git a/apps/web/src/features/block-agent/context/create-composer-controller.ts b/apps/web/src/features/block-agent/context/create-composer-controller.ts
index 94da1ba8d1..275f1cb82a 100644
--- a/apps/web/src/features/block-agent/context/create-composer-controller.ts
+++ b/apps/web/src/features/block-agent/context/create-composer-controller.ts
@@ -96,11 +96,18 @@ export function createComposerController(options: {
* (nor an older refusal of the same model) can answer this request.
*/
requestedActionId: string | undefined;
+ /**
+ * A stop has been posted and the fold has not settled the turn yet.
+ * Further clicks must not stack another `session/cancel`, each of which
+ * the fold renders as its own accepted Stopped line.
+ */
+ stopping: boolean;
}>({
queue: [],
post: { type: 'idle' },
requestedModel: undefined,
requestedActionId: undefined,
+ stopping: false,
});
const postHead = async (sessionId: string, prompt: QueuedPrompt) => {
@@ -150,10 +157,11 @@ export function createComposerController(options: {
.control(sessionId, { type: 'stop' })
.catch(() => undefined);
if (result === undefined || result.isErr()) {
+ setState('stopping', false);
toast.failure('The agent could not be stopped');
}
// Success is observed through the fold: the turn settles and `working`
- // flips false, which re-runs the drain.
+ // flips false, which re-runs the drain and releases the latch.
};
// The drain: whenever any fact changes, ask the model what to do and do
@@ -224,6 +232,13 @@ export function createComposerController(options: {
onCleanup(() => clearTimeout(timer));
});
+ // The stop is done when the fold says the turn is no longer running. The
+ // release is read off `working` rather than off the POST returning, because
+ // the POST only means the cancel was accepted, not that the turn is over.
+ createEffect(() => {
+ if (!options.working()) setState('stopping', false);
+ });
+
// A session switch resets the composer: queued prompts belong to the
// session they were typed in, never the next one.
//
@@ -246,6 +261,7 @@ export function createComposerController(options: {
post: { type: 'idle' },
requestedModel: undefined,
requestedActionId: undefined,
+ stopping: false,
});
});
@@ -284,7 +300,8 @@ export function createComposerController(options: {
stop: () => {
const sessionId = options.sessionId();
if (!sessionId) return;
- if (!isBusy(state.post, options.working())) return;
+ if (!isBusy(state.post, options.working()) || state.stopping) return;
+ setState('stopping', true);
void postStop(sessionId);
},
setModel: (model) => {
diff --git a/crates/agent_fold/src/domain/fold.rs b/crates/agent_fold/src/domain/fold.rs
index d9e43b155e..2c4569c4c6 100644
--- a/crates/agent_fold/src/domain/fold.rs
+++ b/crates/agent_fold/src/domain/fold.rs
@@ -310,6 +310,14 @@ struct Turn {
/// Where this turn's plan sits in the agent message's parts, so later
/// plan updates can replace it.
plan_position: Option<usize>,
+ /// Whether closing this turn needs an agent message to record its stop
+ /// reason on, minting one if the agent never produced a part.
+ ///
+ /// True for a turn a prompt opened: the user's bubble is then the
+ /// transcript's newest turn message, and readers take one without a stop
+ /// reason to mean the agent is still working. False for a turn a control
+ /// opened (`/compact`), whose own message readers skip.
+ expects_reply: bool,
}
impl FoldState {
@@ -501,6 +509,7 @@ impl FoldState {
tool_positions: HashMap::new(),
permission_positions: HashMap::new(),
plan_position: None,
+ expects_reply: true,
});
changed
@@ -536,6 +545,7 @@ impl FoldState {
tool_positions: HashMap::new(),
permission_positions: HashMap::new(),
plan_position: None,
+ expects_reply: false,
});
Some(Changed::new(message))
}
@@ -643,34 +653,17 @@ impl FoldState {
return None;
}
- // Give the turn an agent message if the runtime never opened one, so
- // the stop reason - and with it the error - has a message to sit on.
- let agent = match self.turn.as_ref()?.agent {
- Some(agent) => agent,
- None => {
- let turn_id = self.turn.as_ref()?.id;
- let agent = self.messages.len();
- self.messages.push(FoldedMessage {
- id: turn_id,
- author: Author::Agent,
- request_id: None,
- parts: NonEmpty::one(MessagePart::Text {
- text: String::new(),
- }),
- stop: None,
- });
- if let Some(turn) = self.turn.as_mut() {
- turn.agent = Some(agent);
- }
- agent
- }
+ // An error is worth showing under any turn, control's included, so
+ // this mints unconditionally where a clean close does not.
+ let turn = self.turn.take()?;
+ let (agent, changed) = match turn.agent {
+ Some(agent) => (agent, Changed::updated(agent)),
+ None => self.mint_agent_message(turn.id),
};
-
- self.turn = None;
self.messages[agent].stop = Some(StopReason::Failed {
message: message.to_owned(),
});
- Some(Changed::new(agent))
+ Some(changed)
}
/// Handle a `session/update`.
@@ -1067,15 +1060,46 @@ impl FoldState {
/// Close the open turn, recording on its agent message how it stopped.
///
- /// Unlike the batch fold this replaces, closing does not emit the agent
- /// message - it has been in [`State::messages`] since the agent's first
- /// part. All that is left is the stop reason, so a turn that stopped for
- /// no stated reason, or that the agent never answered, changes nothing.
+ /// Usually the agent message has been in [`State::messages`] since the
+ /// agent's first part, and all that is left is the stop reason. When the
+ /// agent produced nothing at all, one is minted to carry it: readers ask
+ /// whether a turn is running by looking for a stop reason on the
+ /// transcript's tail, so recording none anywhere reads as working
+ /// forever. That is a stop pressed before the first chunk - a first
+ /// prompt spends ~10s creating the Cursor agent - which answers
+ /// `session/prompt` with `cancelled` and nothing to stamp it on.
fn close_turn(&mut self, stop: Option<StopReason>) -> Option<Changed> {
+ let Some(stop) = stop else {
+ // Nothing to record, so nothing to mint a message for.
+ self.turn = None;
+ return None;
+ };
let turn = self.turn.take()?;
- let message = turn.agent?;
- self.messages[message].stop = Some(stop?);
- Some(Changed::updated(message))
+ let (message, changed) = match turn.agent {
+ Some(message) => (message, Changed::updated(message)),
+ // A turn a control opened is skipped by those readers, so an
+ // empty agent bubble under its line would be noise, not a fix.
+ None if !turn.expects_reply => return None,
+ None => self.mint_agent_message(turn.id),
+ };
+ self.messages[message].stop = Some(stop);
+ Some(changed)
+ }
+
+ /// Mint the agent message a turn never opened, so a stop reason has
+ /// somewhere to sit. Reported as new: the client has not seen it.
+ fn mint_agent_message(&mut self, turn: TurnId) -> (usize, Changed) {
+ let message = self.messages.len();
+ self.messages.push(FoldedMessage {
+ id: turn,
+ author: Author::Agent,
+ request_id: None,
+ parts: NonEmpty::one(MessagePart::Text {
+ text: String::new(),
+ }),
+ stop: None,
+ });
+ (message, Changed::new(message))
}
/// Add a part to the open turn's agent message, creating that message if
@@ -1141,6 +1165,7 @@ impl FoldState {
tool_positions: HashMap::new(),
permission_positions: HashMap::new(),
plan_position: None,
+ expects_reply: true,
});
}
diff --git a/crates/agent_fold/src/domain/test/fold.rs b/crates/agent_fold/src/domain/test/fold.rs
index a3157cccb9..9211d0f38d 100644
--- a/crates/agent_fold/src/domain/test/fold.rs
+++ b/crates/agent_fold/src/domain/test/fold.rs
@@ -216,6 +216,69 @@ fn folds_session_controls_as_typed_parts() {
assert_eq!(messages[2].id, TurnId(2));
}
+/// A stop pressed before the agent's first chunk - a window over ten seconds
+/// wide, since a session's first prompt spends that creating the Cursor agent.
+///
+/// The turn has no agent message to stamp, so the close has to mint one. Left
+/// unstamped, the newest turn message is the user's prompt, which every reader
+/// takes to mean the agent is still working: the composer keeps its stop
+/// affordance, and each further click stacks another Stopped line onto a
+/// session that can never settle.
+#[test]
+fn a_stop_before_the_agent_speaks_still_settles_the_turn() {
+ let log = parse_log(concat!(
+ r#"{"direction":"to_runtime","user_id":"macro|[email protected]","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"do a big job"}]}}}"#,
+ "\n",
+ r#"{"direction":"to_runtime","user_id":"macro|[email protected]","content":{"type":"acp","jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"s"}}}"#,
+ "\n",
+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","result":{"stopReason":"cancelled"}}}"#,
+ ));
+
+ let messages = fold(log);
+ assert_eq!(messages.len(), 3, "prompt, stop control, minted reply");
+ let reply = &messages[2];
+ assert!(matches!(reply.author, Author::Agent));
+ assert_eq!(
+ reply.id,
+ TurnId(0),
+ "the reply belongs to the prompt's turn"
+ );
+ assert_eq!(reply.stop, Some(StopReason::Cancelled));
+ assert_eq!(
+ reply.parts.as_slice(),
+ &[MessagePart::Text {
+ text: String::new()
+ }],
+ "nothing was said, so there is nothing to render but the stop"
+ );
+}
+
+/// The same stop once the agent has managed a single thought: the message
+/// already exists, so nothing is minted and the thought is kept.
+#[test]
+fn a_stop_after_the_agent_speaks_stamps_the_message_it_has() {
+ let log = parse_log(concat!(
+ r#"{"direction":"to_runtime","user_id":"macro|[email protected]","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"do a big job"}]}}}"#,
+ "\n",
+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"hmm"}}}}}"#,
+ "\n",
+ r#"{"direction":"to_runtime","user_id":"macro|[email protected]","content":{"type":"acp","jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"s"}}}"#,
+ "\n",
+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","result":{"stopReason":"cancelled"}}}"#,
+ ));
+
+ let messages = fold(log);
+ assert_eq!(messages.len(), 3, "prompt, reply, stop control");
+ let reply = &messages[1];
+ assert_eq!(reply.stop, Some(StopReason::Cancelled));
+ assert_eq!(
+ reply.parts.as_slice(),
+ &[MessagePart::Thought {
+ text: "hmm".to_owned()
+ }]
+ );
+}
+
#[test]
fn a_rejected_control_reports_the_runtime_error() {
let log = parse_log(concat!(
diff --git a/crates/cursor_cloud_agents/src/domain/service.rs b/crates/cursor_cloud_agents/src/domain/service.rs
index bf8fba149a..dec1a95db1 100644
--- a/crates/cursor_cloud_agents/src/domain/service.rs
+++ b/crates/cursor_cloud_agents/src/domain/service.rs
@@ -13,18 +13,27 @@
//! a turn is streaming, so cancellation state lives behind a lock the
//! streaming loop never holds across an await.
//!
-//! Cancelling is local. A turn ends on its own cancellation token, not on
-//! Cursor's answer to `POST /runs/{run}/cancel` — that call is best-effort and
-//! only decides whether the run stops burning credits server-side. The
-//! 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.
+//! `session/cancel` is a notification we pump into Cursor: `POST
+//! /v1/agents/{id}/runs/{runId}/cancel`. The turn itself keeps reading the
+//! run's stream until Cursor's terminal `result` frame (then `done`) — the
+//! same way a finished run ends. Cancellation is terminal on Cursor's side;
+//! that `result` is what closes the ACP prompt.
+//!
+//! The cancellation token never cuts a live stream short — that is the whole
+//! point of the paragraph above. It ends the waits where there is nothing to
+//! read: a prompt queued behind `agent_busy`, and the fallback poll, which
+//! only runs because the stream is gone. Reading `GET …/runs/{run}` once more
+//! after the user has stopped buys nothing a stopped turn reports anyway, so
+//! the poll's wait is where a stop lands.
//!
//! 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.
+//! skipping the remote call. A stop that beats the run into existence has
+//! nothing to fall back to, so [`CursorSessionService::prompt`] re-sends it
+//! the moment the run has an id; otherwise the stop would be swallowed and
+//! the turn would run to the agent's own natural end.
#[cfg(test)]
mod test;
@@ -439,9 +448,16 @@ where
Some(agent) => {
// Queue behind any run still going (the same agent advances
// from cursor.com too) instead of failing the prompt.
- let run = self
+ let run = match self
.create_run_when_free(&agent, prompt, model.as_ref(), &cancel)
- .await?;
+ .await
+ {
+ Ok(run) => run,
+ // The wait ended because the client asked to stop, which
+ // ACP answers with a stop reason rather than an error.
+ Err(_) if cancel.is_cancelled() => return Ok(StopReason::Cancelled),
+ Err(error) => return Err(error),
+ };
// Catch the session's view up on whatever it missed while it
// was not looking. After the create on purpose: creating
// proved the agent free, so every missed run is terminal and
@@ -471,10 +487,25 @@ where
}
};
tracing::info!(%agent, %run, "cursor run started");
- {
+ let cancelled_before_the_run = {
let mut state = session.state.lock().expect("session state poisoned");
state.agent = Some(agent.clone());
state.active_run = Some(run.clone());
+ state.cancelled
+ };
+ // A stop this run did not exist to receive. `cancel` had no run id to
+ // POST — a first prompt spends ten seconds creating the agent, and a
+ // session with no agent yet cannot name one — so the remote work was
+ // left going and the stream below would have read it to the agent's
+ // own natural end. Ask now, and the same stream ends on Cursor's
+ // cancelled `result` a second or two later.
+ if cancelled_before_the_run {
+ tracing::info!(%agent, %run, "stop arrived before this run existed; cancelling it now");
+ if let Err(error) = self.cursor.cancel_run(&agent, &run).await {
+ // Best-effort, exactly as in `cancel`: the turn still ends on
+ // whatever the stream reports.
+ tracing::warn!(%agent, %run, %error, "could not cancel a run stopped before it existed");
+ }
}
let outcome = self
@@ -512,14 +543,16 @@ where
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:
- // whether Cursor honours the cancel decides only whether the run
- // keeps burning credits server-side, never whether this client
- // gets its turn back. A cancel Cursor refuses used to leave the
- // turn streaming to natural completion.
+ // Unblocks a prompt still queued behind `agent_busy`. The live
+ // stream is not abandoned — Cursor's `result` frame is what ends
+ // the turn. The POST below is the notification that asks for that
+ // frame.
state.cancel.cancel();
(state.agent.clone(), state.active_run.clone())
};
+ // No agent yet: the session's first prompt is still creating one, so
+ // there is nothing to name in a remote cancel. `cancelled` is set,
+ // and `prompt` sends it as soon as the run has an id.
let Some(agent) = agent else {
return Ok(());
};
@@ -670,27 +703,11 @@ where
// not to repeat it from the run's final result.
let mut streamed_text = false;
loop {
- // The client's cancel outranks anything still on the wire. Without
- // this the turn ran to the stream's natural end and only *then*
- // reported `Cancelled` — the stop button stayed lit for as long as
- // the agent felt like working.
- let next = match tokio::time::timeout(STREAM_QUIET_TIMEOUT, async {
- tokio::select! {
- biased;
- // Outer `None` means cancelled; outer `Some` carries the
- // stream's own `Option`, whose `None` means it ended.
- () = cancel.cancelled() => None,
- next = stream.next() => Some(next),
- }
- })
- .await
- {
- 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,
+ // A client cancel is a notification already POSTed; it does not
+ // outrank the stream. Cursor's `result` frame is what ends the
+ // turn, including a cancelled one.
+ let next = match tokio::time::timeout(STREAM_QUIET_TIMEOUT, stream.next()).await {
+ Ok(next) => next,
// The stream has gone quiet. If the run is already over, the
// stream's terminal event is the only thing anyone is waiting
// for — take the answer from the record instead of holding
@@ -706,7 +723,16 @@ where
.poll_turn(session_id, session, agent, run, streamed_text, cancel)
.await;
}
- Ok(_) => continue, // still running; keep listening
+ // Still running: keep listening. Unless the client
+ // stopped, in which case a silent stream and a run
+ // the record says is still going is nothing left to
+ // wait for.
+ Ok(_) if cancel.is_cancelled() => {
+ tracing::info!(%agent, %run, "stopped run's stream went quiet");
+ self.close_open_tool_calls(session_id, session).await;
+ return Ok(StopReason::Cancelled);
+ }
+ Ok(_) => continue,
Err(error) => {
tracing::warn!(%agent, %run, %error, "quiet-stream status check failed");
continue;
@@ -763,7 +789,10 @@ where
match outcome {
Some(RunStatus::Finished) => Ok(StopReason::EndTurn),
- Some(RunStatus::Cancelled) => Ok(StopReason::Cancelled),
+ Some(RunStatus::Cancelled) => {
+ self.close_open_tool_calls(session_id, session).await;
+ Ok(StopReason::Cancelled)
+ }
// A run that ended in any other state did not succeed, and ACP
// answers a prompt with a stop reason or an error — there is no
// stop reason for "it failed", so this is an error.
@@ -786,12 +815,32 @@ where
}
}
- /// Close out every tool call left open when a turn ends on the client's
- /// cancel rather than Cursor's own terminal event.
+ /// Wait out one poll interval, unless the client has stopped the turn.
+ /// `true` means it has, and the turn is over.
+ ///
+ /// The only cancel check in the fallback poll. Ending here is not the
+ /// local settle this service refuses elsewhere: the poll runs precisely
+ /// because the stream is gone, so there are no frames left to abandon —
+ /// only a record to stop re-reading on the user's behalf.
+ async fn wait_unless_stopped(
+ &self,
+ session_id: &SessionId,
+ session: &Session,
+ cancel: &tokio_util::sync::CancellationToken,
+ ) -> bool {
+ if !sleep_unless_cancelled(cancel, POLL_INTERVAL).await {
+ return false;
+ }
+ tracing::info!("turn stopped while polling for its run's record");
+ self.close_open_tool_calls(session_id, session).await;
+ true
+ }
+
+ /// Close out every tool call still open when a turn ends cancelled.
///
- /// 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.
+ /// Cursor's `result` with `CANCELLED` is the terminal frame; it does not
+ /// always include a completed `tool_call` for work that was mid-flight,
+ /// so without this the client would render that call running forever.
async fn close_open_tool_calls(&self, session_id: &SessionId, session: &Session) {
let updates = session
.state
@@ -1033,14 +1082,8 @@ where
) -> Result<StopReason, SessionError> {
let mut consecutive_errors = 0;
for _ in 0..POLL_ATTEMPTS {
- // A client cancel ends the wait, not just the run: the server
- // often closes a cancelled run's stream without a result, and
- // polling an outcome nobody wants any more would hold the turn
- // open for minutes. Read from the token rather than the flag so
- // the exit is immediate instead of up to one interval late.
- if cancel.is_cancelled() {
- return Ok(StopReason::Cancelled);
- }
+ // Both waits below go through `wait_unless_stopped`, the one
+ // place a stop ends this poll.
let outcome = match self.cursor.run_result(agent, run).await {
Ok(outcome) => outcome,
// A blip mid-poll is survivable; the same failure over and
@@ -1048,7 +1091,7 @@ where
Err(error) if consecutive_errors < POLL_ERROR_TOLERANCE => {
consecutive_errors += 1;
tracing::warn!(%agent, %run, %error, consecutive_errors, "run poll failed");
- if sleep_unless_cancelled(cancel, POLL_INTERVAL).await {
+ if self.wait_unless_stopped(session_id, session, cancel).await {
return Ok(StopReason::Cancelled);
}
continue;
@@ -1057,7 +1100,7 @@ where
};
consecutive_errors = 0;
if !outcome.is_terminal() {
- if sleep_unless_cancelled(cancel, POLL_INTERVAL).await {
+ if self.wait_unless_stopped(session_id, session, cancel).await {
return Ok(StopReason::Cancelled);
}
continue;
@@ -1085,7 +1128,10 @@ where
}
return match outcome.status {
RunStatus::Finished => Ok(StopReason::EndTurn),
- RunStatus::Cancelled => Ok(StopReason::Cancelled),
+ RunStatus::Cancelled => {
+ self.close_open_tool_calls(session_id, session).await;
+ Ok(StopReason::Cancelled)
+ }
status => Err(SessionError::Cursor(rootcause::report!(
"cursor run {run} ended in {status:?}"
))),
diff --git a/crates/cursor_cloud_agents/src/domain/service/test.rs b/crates/cursor_cloud_agents/src/domain/service/test.rs
index 9ada151fa2..97afd53486 100644
--- a/crates/cursor_cloud_agents/src/domain/service/test.rs
+++ b/crates/cursor_cloud_agents/src/domain/service/test.rs
@@ -30,6 +30,15 @@ fn finished(run: &str) -> CursorEvent {
}
}
+fn cancelled(run: &str) -> CursorEvent {
+ CursorEvent::Result {
+ run_id: CursorRunId::new(run),
+ status: RunStatus::Cancelled,
+ text: None,
+ duration_ms: Some(1),
+ }
+}
+
#[tokio::test]
async fn first_prompt_creates_the_agent_with_the_session_repo() {
let repo = RepoUrl::parse("https://github.com/macro-inc/macro").expect("valid repo");
@@ -121,15 +130,63 @@ async fn cancel_mid_turn_cancels_the_run_and_reports_cancelled() {
);
}
-/// The turn ends on the client's cancel alone, with the run's stream still
-/// wide open and still delivering.
+/// A stop must not lose an answer the run had already produced.
+///
+/// The race: the run finishes, its stream is truncated before the `result`
+/// frame, and the stop lands. Get A Run is the only place that answer exists,
+/// so the poll reads it and delivers its text — a stopped turn ends on the
+/// record it can reach, not on the token alone.
+#[tokio::test(start_paused = true)]
+async fn a_stop_still_delivers_a_finished_run_the_stream_never_reported() {
+ 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::Thinking {
+ text: "hmm".to_owned(),
+ })
+ .expect("stream open");
+ notifier.wait_for_updates(1).await;
+
+ cursor.script_run_result(RunOutcome {
+ status: RunStatus::Finished,
+ text: Some("here is the answer".to_owned()),
+ });
+ service.cancel(&session).await.expect("cancel works");
+ drop(events);
+
+ let stop = turn.await.expect("task joins").expect("prompt resolves");
+ assert_eq!(stop, StopReason::Cancelled);
+ let texts: Vec<String> = notifier
+ .updates()
+ .iter()
+ .filter_map(|(_, update)| match update {
+ SessionUpdate::AgentMessageChunk(chunk) => match &chunk.content {
+ agent_client_protocol::schema::v1::ContentBlock::Text(text) => {
+ Some(text.text.clone())
+ }
+ _ => None,
+ },
+ _ => None,
+ })
+ .collect();
+ assert_eq!(texts, vec!["here is the answer".to_owned()]);
+}
+
+/// Cancel is a notification: POST it, keep reading until Cursor's `result`.
///
-/// This is the shape seen live: Cursor accepts the cancel and keeps streaming
-/// anyway, so a turn that waits for the stream to end waits for the agent to
-/// finish of its own accord — which is the whole bug. Note what this test does
-/// *not* do: drop `events`.
+/// Chunks that land after the POST are still the run — the Cloud Agents stream
+/// is scoped to that run through `result` then `done`. Dropping the stream at
+/// the POST used to resolve the ACP prompt while Cursor was still emitting.
#[tokio::test]
-async fn cancel_ends_the_turn_while_the_stream_stays_open() {
+async fn cancel_keeps_reading_until_the_result_frame() {
let (service, cursor, notifier) = service(None);
let session = service.new_session(Path::new(""), Vec::new());
@@ -147,22 +204,33 @@ async fn cancel_ends_the_turn_while_the_stream_stays_open() {
.expect("stream open");
notifier.wait_for_updates(1).await;
- // The stream is live and mid-turn at the moment the cancel lands: no
- // terminal event has been sent, and none ever will be.
assert!(!events.is_closed());
service.cancel(&session).await.expect("cancel works");
+ assert!(
+ cursor
+ .calls()
+ .iter()
+ .any(|call| matches!(call, CursorCall::CancelRun(..)))
+ );
+
+ events
+ .send(CursorEvent::Assistant {
+ text: " winding down".to_owned(),
+ })
+ .expect("stream still open after cancel");
+ notifier.wait_for_updates(2).await;
+
+ events.send(cancelled("run-fake-1")).expect("stream open");
+ events.send(CursorEvent::Done).expect("stream open");
let stop = turn.await.expect("task joins").expect("prompt resolves");
assert_eq!(stop, StopReason::Cancelled);
- // Only the one chunk from before the cancel: nothing arrived to end the
- // turn, so the turn ended itself. The sender reads as closed from here on
- // precisely because the turn dropped the stream rather than draining it.
- assert_eq!(notifier.updates().len(), 1);
+ assert_eq!(notifier.updates().len(), 2);
}
-/// 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.
+/// A cancelled `result` does not always complete in-flight tool calls, so the
+/// turn must fail them locally when that frame arrives — otherwise they stay
+/// "running" in the transcript forever.
#[tokio::test]
async fn cancel_mid_tool_call_closes_it_as_failed() {
let (service, cursor, notifier) = service(None);
@@ -188,6 +256,8 @@ async fn cancel_mid_tool_call_closes_it_as_failed() {
notifier.wait_for_updates(1).await;
service.cancel(&session).await.expect("cancel works");
+ events.send(cancelled("run-fake-1")).expect("stream open");
+ events.send(CursorEvent::Done).expect("stream open");
let stop = turn.await.expect("task joins").expect("prompt resolves");
assert_eq!(stop, StopReason::Cancelled);
@@ -195,6 +265,7 @@ async fn cancel_mid_tool_call_closes_it_as_failed() {
let closing = notifier
.updates()
.into_iter()
+ .rev()
.find_map(|(_, update)| match update {
SessionUpdate::ToolCallUpdate(update) if &*update.tool_call_id.0 == "call-1" => {
Some(update)
@@ -205,8 +276,12 @@ async fn cancel_mid_tool_call_closes_it_as_failed() {
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.
+/// A cancel while the prompt is still queued behind someone else's run ends
+/// the wait, rather than sitting out the full busy timeout — and reports it as
+/// the stop it is. The wait itself fails, but a failure the client asked for
+/// is a stop reason: an ACP error would surface in the transcript as a red
+/// "the prompt was cancelled while waiting for the agent to be free" instead
+/// of a stopped turn.
#[tokio::test]
async fn cancel_ends_a_prompt_waiting_on_a_busy_agent() {
let (service, cursor, _notifier) = service(None);
@@ -231,13 +306,107 @@ async fn cancel_ends_a_prompt_waiting_on_a_busy_agent() {
service.cancel(&session).await.expect("cancel works");
- let outcome = turn.await.expect("task joins");
+ let stop = turn.await.expect("task joins").expect("prompt resolves");
+ assert_eq!(stop, StopReason::Cancelled);
+ // Nothing was ever created, so there is no run to have cancelled.
assert!(
- outcome.is_err(),
- "a cancelled wait is an error, not a silent success: {outcome:?}"
+ !cursor
+ .calls()
+ .iter()
+ .any(|call| matches!(call, CursorCall::CancelRun(..)))
);
}
+/// A stop while the fallback poll is running.
+///
+/// The poll only exists because the stream is gone, so a stop ends it at the
+/// first wait rather than re-reading a record nobody is waiting on: one read,
+/// then the turn is over.
+#[tokio::test(start_paused = true)]
+async fn a_stop_ends_the_fallback_poll_at_its_first_wait() {
+ let (service, cursor, notifier) = service(None);
+ let session = service.new_session(Path::new(""), Vec::new());
+
+ // Plenty scripted, so what ends the poll is the stop and not the script.
+ for _ in 0..10 {
+ cursor.script_run_result(RunOutcome {
+ status: RunStatus::Running,
+ text: None,
+ });
+ }
+
+ 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::Thinking {
+ text: "hmm".to_owned(),
+ })
+ .expect("stream open");
+ notifier.wait_for_updates(1).await;
+
+ service.cancel(&session).await.expect("cancel works");
+ drop(events); // no result frame, so the turn falls back to polling
+
+ let stop = turn.await.expect("task joins").expect("prompt resolves");
+ assert_eq!(stop, StopReason::Cancelled);
+ let polls = cursor
+ .calls()
+ .iter()
+ .filter(|call| matches!(call, CursorCall::RunResult(..)))
+ .count();
+ assert_eq!(polls, 1, "one read of the record, then the stop ends it");
+}
+
+/// A stop that beats the run into existence.
+///
+/// `cancel` has no run id to POST while the first prompt is still creating the
+/// agent — ten seconds, live — so the stop is sent the moment the run has one.
+/// Left unsent, Cursor keeps working and this turn reads the stream to the
+/// agent's own natural end, which is the stop button doing nothing at all.
+#[tokio::test]
+async fn a_stop_before_the_run_exists_is_sent_once_it_does() {
+ let (service, cursor, _notifier) = service(None);
+ let session = service.new_session(Path::new(""), Vec::new());
+
+ let finish_creating = cursor.script_create_gate();
+ 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 }
+ });
+
+ // Mid-create: the turn has neither agent nor run for a cancel to name.
+ cursor
+ .wait_for_calls(1, |call| matches!(call, CursorCall::CreateAgent(..)))
+ .await;
+ service.cancel(&session).await.expect("cancel works");
+ assert!(
+ !cursor
+ .calls()
+ .iter()
+ .any(|call| matches!(call, CursorCall::CancelRun(..))),
+ "there was no run to cancel yet"
+ );
+
+ finish_creating.send(()).expect("the create is waiting");
+
+ // The run exists now, so the stop it missed is sent for it, and the turn
+ // ends on Cursor's cancelled result like any other cancelled run.
+ cursor
+ .wait_for_calls(1, |call| matches!(call, CursorCall::CancelRun(..)))
+ .await;
+ events.send(cancelled("run-fake-1")).expect("stream open");
+ events.send(CursorEvent::Done).expect("stream open");
+
+ let stop = turn.await.expect("task joins").expect("prompt resolves");
+ assert_eq!(stop, StopReason::Cancelled);
+}
+
#[tokio::test]
async fn concurrent_prompt_on_an_active_turn_is_rejected() {
let (service, cursor, notifier) = service(None);
diff --git a/crates/cursor_cloud_agents/src/domain/translate.rs b/crates/cursor_cloud_agents/src/domain/translate.rs
index 806b85bc15..308d94e762 100644
--- a/crates/cursor_cloud_agents/src/domain/translate.rs
+++ b/crates/cursor_cloud_agents/src/domain/translate.rs
@@ -150,14 +150,14 @@ 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.
+ /// A cancelled run's `result` frame is the turn's terminal signal; it
+ /// does not always carry a completed `tool_call` for work that was
+ /// mid-flight. 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()
diff --git a/crates/cursor_cloud_agents/src/testing.rs b/crates/cursor_cloud_agents/src/testing.rs
index a7d54a494b..2f9c8746a0 100644
--- a/crates/cursor_cloud_agents/src/testing.rs
+++ b/crates/cursor_cloud_agents/src/testing.rs
@@ -72,6 +72,8 @@ struct FakeCursorState {
run_listings: Vec<RunListing>,
/// Errors the next `create_run` calls answer with, consumed in order.
create_run_errors: Vec<String>,
+ /// Held by the next create call until the test lets it finish.
+ create_gate: Option<tokio::sync::oneshot::Receiver<()>>,
/// The answer every `list_models` call gets.
models: Vec<CursorModel>,
}
@@ -117,6 +119,18 @@ impl FakeCursor {
}
}
+ /// Hold the next create call open until the returned sender fires.
+ ///
+ /// How a test acts inside the window where a turn has started but has no
+ /// run id yet — the ten seconds a real first prompt spends creating the
+ /// Cursor agent, and the only window in which a stop has nothing to name.
+ #[must_use]
+ pub fn script_create_gate(&self) -> tokio::sync::oneshot::Sender<()> {
+ let (sender, receiver) = tokio::sync::oneshot::channel();
+ self.inner.lock().expect("fake cursor poisoned").create_gate = Some(receiver);
+ sender
+ }
+
/// Set the models `list_models` answers with.
pub fn script_models(&self, models: Vec<CursorModel>) {
self.inner.lock().expect("fake cursor poisoned").models = models;
@@ -158,6 +172,20 @@ impl FakeCursor {
}
}
+ /// Wait out the scripted create gate, if a test set one. Taken out of the
+ /// lock first: the mutex is never held across an await.
+ async fn await_create_gate(&self) {
+ let gate = self
+ .inner
+ .lock()
+ .expect("fake cursor poisoned")
+ .create_gate
+ .take();
+ if let Some(gate) = gate {
+ let _ = gate.await;
+ }
+ }
+
/// Record a call and wake anything waiting on one.
fn record(&self, call: CursorCall) {
self.inner
@@ -183,6 +211,7 @@ impl CursorAgents for FakeCursor {
mcp_servers.to_vec(),
model.cloned(),
));
+ self.await_create_gate().await;
let mut state = self.inner.lock().expect("fake cursor poisoned");
state.next_run += 1;
Ok((