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
fix(cursor): accept a terminal status frame, and stop a stuck run killing the session (#6434)
Wolf Mermelsteina14772e001e6
diff --git a/crates/cursor_cloud_agents/src/domain/journal.rs b/crates/cursor_cloud_agents/src/domain/journal.rsindex a4fb09e8c4..c64a807f0d 100644--- a/crates/cursor_cloud_agents/src/domain/journal.rs+++ b/crates/cursor_cloud_agents/src/domain/journal.rs@@ -202,6 +202,17 @@ impl ReplayMachine {) -> Result<Vec<SessionUpdate>, rootcause::Report> {let state = self.runs.entry(run.clone()).or_default();match event {+ // A terminal lifecycle frame is a terminal fact here for the same+ // reason it is one in the session service: a run whose `result`+ // never arrives still ended, and a projection that only learns+ // outcomes from `result` leaves such a turn open forever on every+ // replay — no `turn_complete`, and tool calls still rendering as+ // in progress. Ordinarily `result` follows a frame later and does+ // the rest; this is what happens when it does not.+ CursorEvent::Status { status, .. } if status.is_terminal() => {+ state.terminal = Some(status);+ Ok(self.translator.close_open_calls())+ }CursorEvent::Interaction(InteractionUpdate::Other { kind })if kind == "step-started" =>{diff --git a/crates/cursor_cloud_agents/src/domain/model.rs b/crates/cursor_cloud_agents/src/domain/model.rsindex b197d97eb3..203b31bb61 100644--- a/crates/cursor_cloud_agents/src/domain/model.rs+++ b/crates/cursor_cloud_agents/src/domain/model.rs@@ -149,12 +149,20 @@ pub struct RunOutcome {pub text: Option<String>,}-impl RunOutcome {+impl RunStatus {/// Whether the run has ended, in any way. `Unknown` counts as terminal:/// a status this crate cannot read is not one worth polling forever on.#[must_use]pub fn is_terminal(&self) -> bool {- !matches!(self.status, RunStatus::Creating | RunStatus::Running)+ !matches!(self, Self::Creating | Self::Running)+ }+}++impl RunOutcome {+ /// Whether the run has ended, in any way. See [`RunStatus::is_terminal`].+ #[must_use]+ pub fn is_terminal(&self) -> bool {+ self.status.is_terminal()}}diff --git a/crates/cursor_cloud_agents/src/domain/service.rs b/crates/cursor_cloud_agents/src/domain/service.rsindex 407ae9b3c8..ce239e3377 100644--- a/crates/cursor_cloud_agents/src/domain/service.rs+++ b/crates/cursor_cloud_agents/src/domain/service.rs@@ -636,7 +636,7 @@ whereSome(agent) => {// Queue behind any run still going (the same agent advances// from cursor.com too) instead of failing the prompt.- self.create_run_when_free(&agent, prompt, model.as_ref(), &cancel)+ self.create_run_when_free(&session, &agent, prompt, model.as_ref(), &cancel).await.map(|run| (agent, run))}@@ -756,12 +756,20 @@ wherestate.active_run = None;state.cancelled};- if let Err(SessionError::Cursor(error)) = &outcome {+ // Both variants are a turn that stopped without a terminal fact, and+ // both have to leave that record: a `Rejected` here is the turn giving+ // up on a run still going, not a prompt refused before it ran.+ let interrupted = match &outcome {+ Err(SessionError::Cursor(error)) => Some(error.to_string()),+ Err(SessionError::Rejected(message)) => Some(message.clone()),+ _ => None,+ };+ if let Some(interrupted) = interrupted {self.capture(session_id,&session,Some(&run),- JournalInput::Interrupted(error.to_string()),+ JournalInput::Interrupted(interrupted),true,).await?;@@ -796,8 +804,14 @@ where}// A cancel that raced the stream's own ending still reports// Cancelled: ACP requires it once the client sent `session/cancel`.+ // `Rejected` included, because giving up on a run still going takes+ // that variant now — a stop landing near the end of the poll budget+ // must still answer Cancelled, not "Cursor is still working". Journal+ // failures stay unmasked by cancellation, as ever.match outcome {- Ok(_) | Err(SessionError::Cursor(_)) if cancelled => Ok(StopReason::Cancelled),+ Ok(_) | Err(SessionError::Cursor(_) | SessionError::Rejected(_)) if cancelled => {+ Ok(StopReason::Cancelled)+ }Ok(stop_reason) => Ok(stop_reason),Err(error) => Err(error),}@@ -1156,6 +1170,20 @@ wherebreak;}CursorEvent::Result { status, .. } => terminal = Some(status),+ // The stream's own account of the run's lifecycle, and a+ // terminal one is a terminal fact even with no `result`+ // frame behind it. Observed live: a run whose record+ // stayed `RUNNING` with a frozen `updatedAt` announced+ // `FINISHED` here and sent no `result` at all, so a turn+ // that accepted only `result` waited out its whole poll+ // budget against a record that was never going to move.+ //+ // Not a break: trailing content can still be in flight,+ // and `done`, the stream's end, or a quiet gap closes the+ // turn now that there is an outcome to close it with.+ CursorEvent::Status { status, .. } if status.is_terminal() => {+ terminal = Some(status);+ }CursorEvent::Error { .. } => break,CursorEvent::Done => break,_ => {}@@ -1205,8 +1233,22 @@ wheresleep_unless_cancelled(cancel, POLL_INTERVAL).await;}}- let status = terminal- .ok_or_else(|| rootcause::report!("Cursor run {run} did not reach a terminal state"))?;+ let Some(status) = terminal else {+ // Not a failure to describe in provider terms: the run is still+ // going as far as Cursor is concerned, and this turn has simply+ // run out of patience. The person who prompted gets told that in+ // their own words; the diagnostics stay in the span.+ tracing::warn!(+ %run,+ attempts = POLL_ATTEMPTS,+ "gave up waiting; Cursor still reports a non-terminal status"+ );+ return Err(SessionError::Rejected(+ "Cursor has not reported a result for this run, and has stopped saying \+ anything about it. Prompting again starts fresh and abandons this run."+ .into(),+ ));+ };if strict&& !session.state@@ -1317,11 +1359,13 @@ where/// wait behind, not an error. A client cancel abandons the wait.async fn create_run_when_free(&self,+ session: &Session,agent: &CursorAgentId,prompt: &str,model: Option<&ModelChoice>,cancel: &tokio_util::sync::CancellationToken,) -> Result<CursorRunId, SessionError> {+ let mut released = false;for _ in 0..BUSY_ATTEMPTS {if cancel.is_cancelled() {return Err(SessionError::Cursor(@@ -1334,6 +1378,18 @@ wherematch self.cursor.create_run(agent, prompt, model).await {Ok(run) => return Ok(run),Err(error) if error.to_string().contains("agent_busy") => {+ // A run this session already gave up on still holds the+ // agent's single run slot, and it is not going to release+ // it by itself — waiting out the full budget would only+ // fail the prompt slower. Cancelling is terminal on+ // Cursor's side, so it frees the agent and gives the+ // abandoned run the terminal fact it needs to reconcile.+ // Done once: a run that is merely slow, or one driven from+ // cursor.com, is still something to wait behind.+ if !std::mem::replace(&mut released, true) {+ self.release_abandoned_runs(session, agent).await;+ continue;+ }tracing::info!(%agent, "agent busy (a run is active, possibly from cursor.com); waiting");if sleep_unless_cancelled(cancel, POLL_INTERVAL).await {return Err(SessionError::Cursor(@@ -1357,6 +1413,56 @@ where))}+ /// The runs a turn in this session already stopped waiting for.+ ///+ /// A journal fact, not a guess: a run recorded as+ /// [`JournalInput::Interrupted`] and never reconciled is one a turn gave+ /// up on. That is the only class of run this service may cancel or+ /// decline to recover — a run merely still going, including one driven+ /// from cursor.com, is someone's live conversation.+ fn abandoned_runs(session: &Session) -> Vec<CursorRunId> {+ let state = session.state.lock().expect("session state poisoned");+ let reconciled: std::collections::HashSet<_> = state+ .journal_entries+ .iter()+ .filter(|e| e.input == JournalInput::Reconciled)+ .filter_map(|e| e.run.clone())+ .collect();+ let mut abandoned = Vec::new();+ for run in state+ .journal_entries+ .iter()+ .filter(|e| matches!(e.input, JournalInput::Interrupted(_)))+ .filter_map(|e| e.run.as_ref())+ {+ if !reconciled.contains(run) && !abandoned.contains(run) {+ abandoned.push(run.clone());+ }+ }+ abandoned+ }++ /// Cancel the runs this session abandoned, freeing the agent's run slot.+ ///+ /// Cancellation is terminal on Cursor's side, so this both returns the+ /// agent's single run slot and gives the abandoned run the terminal fact+ /// it needs before it can ever reconcile.+ ///+ /// Best effort. A cancel that fails leaves the caller exactly where it+ /// was, waiting out the busy agent, so there is nothing here to fail on.+ async fn release_abandoned_runs(&self, session: &Session, agent: &CursorAgentId) {+ for run in Self::abandoned_runs(session) {+ match self.cursor.cancel_run(agent, &run).await {+ Ok(()) => {+ tracing::info!(%agent, %run, "cancelled an abandoned run holding the agent");+ }+ Err(error) => {+ tracing::warn!(%agent, %run, %error, "could not cancel an abandoned run");+ }+ }+ }+ }+/// Catch up foreign runs through the same journal path as local prompts.async fn backfill_foreign_runs(&self,@@ -1397,6 +1503,22 @@ where.take_while(|r| Some(&r.id) != last.as_ref()).map(|r| r.id.clone()).collect();+ // A run a turn already gave up on, which Cursor still has not ended,+ // is not recoverable history: there is no terminal fact to reconcile+ // against, and re-reading it cannot manufacture one. Retrying it here+ // would fail every later prompt for as long as the run stays+ // unfinished — which, when the provider wedges a run at `RUNNING`, is+ // forever. Left pending instead, to be mirrored in once it does end.+ //+ // Deliberately not every unfinished run: one still going that no turn+ // has abandoned — a prompt sent from cursor.com — is exactly what this+ // backfill exists to stream in, and must still be followed.+ let abandoned = Self::abandoned_runs(session);+ let unfinished: std::collections::HashSet<_> = listings+ .iter()+ .filter(|r| !r.status.is_terminal() && abandoned.contains(&r.id))+ .map(|r| r.id.clone())+ .collect();let mut runs = Vec::new();// A pending run omitted by the provider listing still has to recover.for run in &pending {@@ -1411,6 +1533,7 @@ whereruns.push(listing.id);}}+ runs.retain(|run| !unfinished.contains(run));let mirrored = !runs.is_empty();for run in &runs {if !reconciled.contains(run) {diff --git a/crates/cursor_cloud_agents/src/domain/service/test.rs b/crates/cursor_cloud_agents/src/domain/service/test.rsindex 70e5f45bd9..bab270ac0a 100644--- a/crates/cursor_cloud_agents/src/domain/service/test.rs+++ b/crates/cursor_cloud_agents/src/domain/service/test.rs@@ -2664,3 +2664,303 @@ async fn repository_choice_receives_each_sessions_working_directory() {]);}++/// Drive a turn whose run Cursor never finishes: the stream dies, and every+/// poll after it answers `RUNNING`, exactly as the provider behaved when it+/// wedged a run's record at `RUNNING` with a frozen `updatedAt`.+/// Answers with the wedged run's id, which Cursor keeps listing as `RUNNING`.+async fn wedge_a_run(+ service: &Arc<Service>,+ cursor: &FakeCursor,+ session: &SessionId,+) -> CursorRunId {+ let events = cursor.script_stream();+ events+ .send(CursorEvent::Assistant {+ text: "partial work".to_owned(),+ })+ .expect("stream open");+ drop(events);+ for _ in 0..=POLL_ATTEMPTS {+ cursor.script_run_result(RunOutcome {+ status: RunStatus::Running,+ text: None,+ });+ }+ service+ .prompt(session, "do the thing")+ .await+ .expect_err("a run that never ends cannot close its turn");+ let Some(run) = cursor.calls().into_iter().find_map(|call| match call {+ CursorCall::RunResult(_, run) => Some(run),+ _ => None,+ }) else {+ panic!("the wedged turn should have polled its run");+ };+ cursor.script_run_listings(vec![RunListing {+ id: run.clone(),+ status: RunStatus::Running,+ }]);+ run+}++/// Giving up on a run still going is not a provider failure, and must not+/// reach the person who prompted as one: an `AcpError` renders the whole+/// report, source location and all, which is what shipped to a user.+#[tokio::test(start_paused = true)]+async fn a_run_that_never_ends_is_reported_in_words_the_prompter_can_act_on() {+ let (service, cursor, _notifier) = service(None);+ let session = service.new_session(Path::new(""), Vec::new());++ let events = cursor.script_stream();+ events+ .send(CursorEvent::Assistant {+ text: "partial work".to_owned(),+ })+ .expect("stream open");+ drop(events);+ for _ in 0..=POLL_ATTEMPTS {+ cursor.script_run_result(RunOutcome {+ status: RunStatus::Running,+ text: None,+ });+ }++ let error = service+ .prompt(&session, "do the thing")+ .await+ .expect_err("the turn cannot close on a run that never ends");+ let SessionError::Rejected(message) = &error else {+ panic!("a run still going is not a Cursor failure: {error:?}");+ };+ // The decorations a report carries would be read as part of the sentence.+ assert!(+ !message.contains("├"),+ "leaked report decoration: {message}"+ );+ assert!(+ !message.contains(".rs:"),+ "leaked source location: {message}"+ );+ assert!(+ message.contains("has not reported a result"),+ "must say what actually happened: {message}"+ );+}++/// The turn gave up, but the journal still has to record that it did - the+/// projection reads `Interrupted` to tell an abandoned run from a live one,+/// and the busy-agent release reads it to know which run it may cancel.+#[tokio::test(start_paused = true)]+async fn giving_up_on_an_unfinished_run_is_still_journalled_as_interrupted() {+ use crate::outbound::memory_journal::MemoryJournal;+ let journal = Arc::new(MemoryJournal::default());+ let cursor = FakeCursor::new();+ let service = Arc::new(CursorSessionService::new(+ cursor.clone(),+ RecordingNotifier::new(),+ FixedChooser(None, false),+ journal.clone(),+ ));+ let session = service.new_session(Path::new(""), Vec::new());++ wedge_a_run(&service, &cursor, &session).await;++ let entries = journal.read(&session).await.expect("journal readable");+ assert!(+ entries+ .iter()+ .any(|e| matches!(e.input, JournalInput::Interrupted(_))),+ "an abandoned turn must leave its record"+ );+ assert!(+ !entries.iter().any(|e| e.input == JournalInput::Reconciled),+ "nothing terminal was observed, so nothing may be reconciled"+ );+}++/// The regression that killed sessions: one run Cursor never finished made+/// every later prompt fail, because recovery insisted on reconciling it+/// first and a run still going has no terminal fact to reconcile against.+#[tokio::test(start_paused = true)]+async fn an_unfinished_run_does_not_block_the_next_prompt() {+ let (service, cursor, _notifier) = service(None);+ let session = service.new_session(Path::new(""), Vec::new());++ // Cursor goes on listing that run as RUNNING, which is the whole problem.+ let stuck = wedge_a_run(&service, &cursor, &session).await;+ let before = cursor.calls().len();++ // The next prompt answers normally instead of dying on recovery.+ let events = cursor.script_stream();+ events+ .send(CursorEvent::Assistant {+ text: "the next answer".to_owned(),+ })+ .expect("stream open");+ events+ .send(CursorEvent::Result {+ run_id: CursorRunId::new("run-2"),+ status: RunStatus::Finished,+ text: None,+ duration_ms: None,+ git: None,+ })+ .expect("stream open");+ events.send(CursorEvent::Done).expect("stream open");+ drop(events);++ let stop = service+ .prompt(&session, "try again")+ .await+ .expect("an unfinished earlier run must not fail a new prompt");+ assert_eq!(stop, StopReason::EndTurn);+ // And it was left alone rather than recovered slowly: nothing this prompt+ // did touched the wedged run.+ assert!(+ !cursor.calls()[before..].iter().any(|call| matches!(+ call,+ CursorCall::RunResult(_, run) if run == &stuck+ )),+ "the wedged run should not have been re-read by the next prompt"+ );+}++/// A wedged run holds the agent's single run slot forever, so waiting out+/// `agent_busy` only fails the prompt slower. The run this session already+/// abandoned is cancelled to get the slot back.+#[tokio::test(start_paused = true)]+async fn a_busy_agent_is_freed_by_cancelling_the_run_this_session_abandoned() {+ let (service, cursor, _notifier) = service(None);+ let session = service.new_session(Path::new(""), Vec::new());++ let abandoned = wedge_a_run(&service, &cursor, &session).await;++ // The wedged run still holds the slot; one release frees it.+ cursor.script_create_run_errors(1, "agent_busy");+ let events = cursor.script_stream();+ events+ .send(CursorEvent::Result {+ run_id: CursorRunId::new("run-3"),+ status: RunStatus::Finished,+ text: None,+ duration_ms: None,+ git: None,+ })+ .expect("stream open");+ events.send(CursorEvent::Done).expect("stream open");+ drop(events);++ service+ .prompt(&session, "try again")+ .await+ .expect("the prompt proceeds once the abandoned run lets go");+ assert!(+ cursor+ .calls()+ .iter()+ .any(|call| matches!(call, CursorCall::CancelRun(_, run) if run == &abandoned)),+ "the abandoned run should have been cancelled to free the agent"+ );+}++/// The root cause of the reported incident. Cursor announced `FINISHED` on+/// the stream's `status` channel and sent no `result` frame at all, while its+/// run record stayed `RUNNING` with an `updatedAt` frozen seconds after the+/// run began. A turn that accepts only `result` waits out its entire poll+/// budget against a record that is never going to move, and then fails a run+/// that had in fact finished.+#[tokio::test(start_paused = true)]+async fn a_terminal_status_frame_closes_the_turn_without_a_result_frame() {+ let (service, cursor, notifier) = service(None);+ let session = service.new_session(Path::new(""), Vec::new());++ let events = cursor.script_stream();+ events+ .send(CursorEvent::Assistant {+ text: "the whole answer".to_owned(),+ })+ .expect("stream open");+ events+ .send(CursorEvent::Status {+ run_id: CursorRunId::new("run-fake-1"),+ status: RunStatus::Finished,+ })+ .expect("stream open");+ drop(events); // no `result` frame ever comes, exactly as observed+ // No poll result is scripted: `raw_result` errors when asked, so a turn+ // that closes here proves it closed on the status frame alone and never+ // consulted the run record — which in production was frozen at RUNNING.+ let stop = service+ .prompt(&session, "hi")+ .await+ .expect("a terminal status frame is a terminal fact");+ assert_eq!(stop, StopReason::EndTurn);+ assert_eq!(agent_texts(¬ifier.updates()), vec!["the whole answer"]);+}++/// A non-terminal `status` is framing, not an outcome - Cursor re-sends one+/// at the top of every reconnect - so it must not close anything.+#[tokio::test(start_paused = true)]+async fn a_running_status_frame_does_not_close_the_turn() {+ let (service, cursor, _notifier) = service(None);+ let session = service.new_session(Path::new(""), Vec::new());++ let events = cursor.script_stream();+ events+ .send(CursorEvent::Status {+ run_id: CursorRunId::new("run-fake-1"),+ status: RunStatus::Running,+ })+ .expect("stream open");+ drop(events);+ // With no outcome from the stream, the record is still what decides.+ cursor.script_run_result(RunOutcome {+ status: RunStatus::Finished,+ text: Some("from the record".to_owned()),+ });++ let stop = service+ .prompt(&session, "hi")+ .await+ .expect("the record closes a turn the stream did not");+ assert_eq!(stop, StopReason::EndTurn);+}++/// A stop landing while the poll budget runs out still answers Cancelled:+/// ACP requires it once the client sent `session/cancel`, and giving up on an+/// unfinished run takes the `Rejected` variant now.+#[tokio::test(start_paused = true)]+async fn a_cancel_near_poll_exhaustion_still_reports_cancelled() {+ let (service, cursor, _notifier) = service(None);+ let session = service.new_session(Path::new(""), Vec::new());++ let events = cursor.script_stream();+ events+ .send(CursorEvent::Assistant {+ text: "partial work".to_owned(),+ })+ .expect("stream open");+ drop(events);+ for _ in 0..=POLL_ATTEMPTS {+ cursor.script_run_result(RunOutcome {+ status: RunStatus::Running,+ text: None,+ });+ }++ let turn = {+ let service = Arc::clone(&service);+ let session = session.clone();+ tokio::spawn(async move { service.prompt(&session, "hi").await })+ };+ // Let the turn reach the poll loop, then stop it.+ tokio::time::sleep(std::time::Duration::from_secs(5)).await;+ service.cancel(&session).await.expect("cancel lands");++ let stop = turn+ .await+ .expect("the turn task completes")+ .expect("a cancelled turn reports a stop reason, not an error");+ assert_eq!(stop, StopReason::Cancelled);+}