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): stream cursor.com runs into an idle session live (#7229)
Wolf Mermelsteine1fe3b098dbb
diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rsindex 4082fc5e8f..9662bd21ce 100644--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs@@ -1195,53 +1195,53 @@ async fn resume_delivered_session(}/// A run driven from cursor.com while the Macro session sits idle: the mirror-/// captures it silently and asks the host to reload. The host's standard-/// `initialize` + `session/load` then shows both runs, a repeated load shows-/// exactly the same, and the mirror asks for nothing more.+/// streams it to the host as it happens, the way a turn streams, and+/// checkpoints it without asking for a reload. Every frame is traffic on the+/// pipe, so the idle reaper sees the run as the activity it is. A later+/// load shows both runs, and the mirror finds nothing more.#[tokio::test]-async fn an_idle_foreign_run_is_recovered_through_a_client_load() {+async fn an_idle_foreign_run_streams_live_to_the_host() {let (base_url, _, _) = fake_cursor_api().await;let (sender, mut receiver, before) = resume_delivered_session(base_url, "bc-idle").await;assert_eq!(count(&before, "/method", "_session/turn_complete"), 1);- let idle = collect_until(&mut receiver, |message| message == "reload_required").await;+ let live = collect_until(&mut receiver, |message| {+ message.pointer("/params/_meta/macroCursorRunCheckpoint")+ == Some(&serde_json::json!("run-foreign"))+ })+ .await;+ assert!(+ !live.iter().any(|message| message == "reload_required"),+ "a streamed run needs no reload: {live:?}"+ );assert_eq!(- idle.len(),+ count(&live, "/params/update/sessionUpdate", "user_message_chunk"),1,- "an idle mirror asks for a reload and publishes no frames: {idle:?}"+ "the cursor.com prompt streams with its run: {live:?}");+ assert_eq!(count(&live, "/method", "_session/turn_complete"), 1);- let recovered = reload(&sender, &mut receiver, 3).await;+ let loaded = reload(&sender, &mut receiver, 3).await;assert_eq!(- count(&recovered, "/method", "_session/turn_complete"),+ count(&loaded, "/method", "_session/turn_complete"),2,- "both runs are history: {recovered:?}"+ "both runs are history: {loaded:?}");assert_eq!(count(- &recovered,+ &loaded,"/params/update/sessionUpdate","user_message_chunk"),2);- assert!(- recovered.len() > before.len(),- "history grows, it is not replaced"- );-- let again = reload(&sender, &mut receiver, 5).await;- assert_eq!(- again, recovered,- "a repeated load replays the same history once"- );- // Two further mirror ticks pass without another reload: what was loaded- // is checkpointed, not rediscovered.+ // Two further mirror ticks pass quietly: the streamed run is+ // checkpointed, not rediscovered.let quiet = tokio::time::timeout(std::time::Duration::from_millis(2500), receiver.recv()).await;assert!(quiet.is_err(),- "nothing more may arrive after recovery, got {quiet:?}"+ "nothing more may arrive after the run, got {quiet:?}");}diff --git a/crates/cursor_cloud_agents/src/domain/service.rs b/crates/cursor_cloud_agents/src/domain/service.rsindex 8a08d70274..f647a676bb 100644--- a/crates/cursor_cloud_agents/src/domain/service.rs+++ b/crates/cursor_cloud_agents/src/domain/service.rs@@ -163,6 +163,16 @@ const STREAM_RECONNECT_ATTEMPTS: usize = 5;/// agent is drivable from cursor.com) before giving up, in poll intervals.const BUSY_ATTEMPTS: usize = 450;+/// How soon after the mirror's last live frame a prompt is taken to have been+/// sent while that frame was still on its way.+///+/// The client opens a prompt's turn when it sends the prompt; the request+/// reaches this service a pipe hop later, in milliseconds. Mirror frames sent+/// in between land inside that turn, and nothing here can tell which, so such+/// a prompt asks for a reload that puts the mirrored run back in its place.+/// Generous on purpose: a false positive costs one reload.+const MIRROR_PROMPT_OVERLAP: std::time::Duration = std::time::Duration::from_secs(2);+/// How long a prompt waits for the turn gate while a background mirror is/// following a run started elsewhere, before giving up.///@@ -193,20 +203,35 @@ const ARTIFACT_LISTING_RETRY_DELAY: std::time::Duration = std::time::Duration::f/// file, loudly, rather than the process losing its memory.const MAX_ARTIFACT_BYTES: u64 = 64 * 1024 * 1024;+/// Whether a captured frame reaches the client as it is journaled.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Emit {+ /// Published as captured: the frames of this session's own turn.+ Live,+ /// Journaled only, for a load to show.+ Silent,+ /// A run started on cursor.com, mirrored into an idle session: published+ /// as captured, exactly like a turn, unless a prompt is waiting behind+ /// the mirror. That prompt's turn is already open on the client, and the+ /// run's frames would render inside it, so they are withheld instead and+ /// the sweep asks for a reload.+ Mirror,+}+#[derive(Clone, Copy)]struct IngestMode {- emit: bool,+ emit: Emit,strict: bool,attempt: usize,}impl IngestMode {const LIVE: Self = Self {- emit: true,+ emit: Emit::Live,strict: false,attempt: 0,};const HYDRATE: Self = Self {- emit: false,+ emit: Emit::Silent,strict: true,attempt: 0,};@@ -404,6 +429,18 @@ struct SessionState {/// Pause background capture while the host loads, without refusing prompts/// it already dispatched before observing the recovery requirement.reload_pending: bool,+ /// Prompts parked behind a mirror's hold on the turn gate. Each one's+ /// turn is already open on the client, so the mirror stops publishing+ /// once one arrives.+ prompts_waiting: usize,+ /// Something journaled since the last load projected updates the client+ /// was never sent. Until a load shows them, the mirror cannot deliver a+ /// run by streaming it: the client would be missing whatever came+ /// before, so the sweep captures silently and asks for a reload instead.+ unshown: bool,+ /// When the mirror last published a frame live; see+ /// [`MIRROR_PROMPT_OVERLAP`].+ mirror_published_at: Option<tokio::time::Instant>,/// Set by cancel; read by the turn when its stream ends.////// The *verdict*, not the mechanism: a cancel that raced the stream's own@@ -447,6 +484,33 @@ struct SessionState {capture_failed: bool,}+/// Counts a prompt as parked behind the mirror for as long as it is held.+struct WaitingPrompt<'session>(&'session Session);++impl<'session> WaitingPrompt<'session> {+ /// The client opened this prompt's turn when it sent the prompt, before+ /// it got here, so whatever the mirror streamed in between may already+ /// sit inside that turn. Nothing can tell those frames apart, so the+ /// mirror's run is left for a reload to put in its place.+ fn new(session: &'session Session) -> Self {+ let mut state = session.state.lock().expect("session state poisoned");+ state.prompts_waiting += 1;+ state.unshown = true;+ drop(state);+ Self(session)+ }+}++impl Drop for WaitingPrompt<'_> {+ fn drop(&mut self) {+ self.0+ .state+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .prompts_waiting -= 1;+ }+}+/// A session shared between a streaming turn and a concurrent cancel.#[derive(Debug)]struct Session {@@ -846,6 +910,7 @@ where// is the one place a turn's time goes that no Cursor call// accounts for, and a trace of a slow turn has to show it.let waiting_since = std::time::Instant::now();+ let _waiting = WaitingPrompt::new(&session);let span = tracing::Span::current();tracing::info!("waiting for the turn gate behind a mirror of a run started elsewhere"@@ -882,6 +947,18 @@ where}}};+ // A mirror that finished streaming just before this prompt arrived+ // may have streamed its last frames into this prompt's turn.+ let overlapped = session+ .state+ .lock()+ .expect("session state poisoned")+ .mirror_published_at+ .is_some_and(|at| at.elapsed() < MIRROR_PROMPT_OVERLAP);+ if overlapped {+ tracing::info!("prompt arrived as a mirrored run finished streaming; reloading");+ self.require_reload(session_id, &session).await?;+ }if !session.state@@ -904,7 +981,7 @@ where.agent.clone();if let Some(agent) = &prior_agent {- self.backfill_foreign_runs(session_id, &session, agent, None, &cancel)+ self.backfill_foreign_runs(session_id, &session, agent, None, &cancel, Emit::Silent).await?;}// Preserve original content before the provider creates remote work.@@ -913,7 +990,7 @@ where&session,None,JournalInput::Prompt(blocks.clone()),- false,+ Emit::Silent,).await?;@@ -932,7 +1009,7 @@ where&session,None,JournalInput::PromptAborted(prompt_sequence),- false,+ Emit::Silent,).await?;return Ok(StopReason::Cancelled);@@ -1020,7 +1097,7 @@ where&session,None,JournalInput::PromptAborted(prompt_sequence),- false,+ Emit::Silent,).await?;if cancel.is_cancelled() {@@ -1053,7 +1130,7 @@ where&session,Some(&run),JournalInput::PromptAccepted(prompt_sequence),- false,+ Emit::Silent,).await?;{@@ -1063,8 +1140,15 @@ where}// Acceptance is durable even if recovery of an older run fails. Do// not observe/project the new run until every older run is reconciled.- self.backfill_foreign_runs(session_id, &session, &agent, Some(&run), &cancel)- .await?;+ self.backfill_foreign_runs(+ session_id,+ &session,+ &agent,+ Some(&run),+ &cancel,+ Emit::Silent,+ )+ .await?;// The turn span is the only place all three identities meet, and it// is what makes a Macro session joinable to the cursor.com run that// served it.@@ -1116,7 +1200,7 @@ where&session,Some(&run),JournalInput::Interrupted(interrupted),- true,+ Emit::Live,).await?;}@@ -1126,7 +1210,7 @@ where&session,Some(&run),JournalInput::Interrupted("user cancelled the turn".into()),- true,+ Emit::Live,).await?;}@@ -1361,7 +1445,7 @@ whereagent.acp.session_id = ?session_id,cursor.agent.id = %agent,cursor.run.id = %run,- cursor.ingest.emit = mode.emit,+ cursor.ingest.emit = ?mode.emit,cursor.ingest.strict = mode.strict,cursor.ingest.attempt = mode.attempt,cursor.stream.reconnects = tracing::field::Empty,@@ -1410,7 +1494,7 @@ wheresession,Some(run),JournalInput::Reconciled,- false,+ Emit::Silent,).await?;return match status {@@ -1842,7 +1926,7 @@ whereagent: &CursorAgentId,run: &CursorRunId,cancel: &tokio_util::sync::CancellationToken,- emit: bool,+ emit: Emit,) -> Result<crate::domain::model::RunOutcome, SessionError> {let mut raw = None;for attempt in 0..=POLL_ERROR_TOLERANCE {@@ -2005,6 +2089,11 @@ where/// following of a run that has not ended. That run is left as a turn/// leaves one it gave up on: interrupted, to be mirrored in once it does/// end, and never blocking the prompt behind it again.+ ///+ /// `emit` is [`Emit::Mirror`] for the host's sweep, which publishes the+ /// runs as they happen and checkpoints them like a turn, and+ /// [`Emit::Silent`] for a prompt catching up, whose own turn is already+ /// open on the client; silent recovery is shown by a reload.async fn backfill_foreign_runs(&self,session_id: &SessionId,@@ -2012,6 +2101,7 @@ whereagent: &CursorAgentId,current_run: Option<&CursorRunId>,cancel: &tokio_util::sync::CancellationToken,+ emit: Emit,) -> Result<bool, SessionError> {self.ensure_journal(session_id, session).await?;let last = session@@ -2081,6 +2171,7 @@ where}runs.retain(|run| !unfinished.contains(run));let mirrored = !runs.is_empty();+ let mut delivered = None;for run in &runs {if !reconciled.contains(run) {// Before the ingestion, not after: a run still going is@@ -2107,7 +2198,7 @@ whererun,cancel,IngestMode {- emit: false,+ emit,..IngestMode::LIVE},)@@ -2139,34 +2230,78 @@ where}return Err(rootcause::report!("Cursor run {run} remains unreconciled").into());}+ delivered = Some(run);}if mirrored {- let notify = {- let mut state = session.state.lock().expect("session state poisoned");- if let Err(error) =- history_projection(&state.journal_entries, HistoryGap::DeclinesReplacement)+ // Everything the client has not seen went out live, so the runs+ // are delivered the way a turn's is: checkpointed, no reload.+ let unshown = session+ .state+ .lock()+ .expect("session state poisoned")+ .unshown;+ if emit == Emit::Mirror && !unshown {+ if let Some(run) = delivered {+ self.notifier+ .checkpoint(session_id, run)+ .await+ .map_err(SessionError::Cursor)?;+ session+ .state+ .lock()+ .expect("session state poisoned")+ .last_run = Some(run.clone());+ }+ // A prompt that parked while the checkpoint was on its way+ // may hold the run's last frames in its turn.+ if !session+ .state+ .lock()+ .expect("session state poisoned")+ .unshown{- tracing::warn!(error = ?error, %session_id, "captured recovery cannot replace history yet");return Ok(mirrored);}- !std::mem::replace(&mut state.reload_pending, true)- };- if notify {- self.notifier- .require_reload(session_id)- .await- .inspect_err(|_| {- session- .state- .lock()- .expect("session state poisoned")- .reload_pending = false;- })?;}+ self.require_reload(session_id, session).await?;}Ok(mirrored)}+ /// Ask the host to reload, once, so a load shows what was captured.+ ///+ /// Declined while the journal cannot yet replace the visible history:+ /// a load then would show less than the client already has.+ async fn require_reload(+ &self,+ session_id: &SessionId,+ session: &Session,+ ) -> Result<(), SessionError> {+ let notify = {+ let mut state = session.state.lock().expect("session state poisoned");+ if let Err(error) =+ history_projection(&state.journal_entries, HistoryGap::DeclinesReplacement)+ {+ tracing::warn!(error = ?error, %session_id, "captured recovery cannot replace history yet");+ return Ok(());+ }+ !std::mem::replace(&mut state.reload_pending, true)+ };+ if notify {+ self.notifier+ .require_reload(session_id)+ .await+ .inspect_err(|_| {+ session+ .state+ .lock()+ .expect("session state poisoned")+ .reload_pending = false;+ })?;+ }+ Ok(())+ }+/// Re-host the walkthrough files this run produced and say so in the/// turn's own text.///@@ -2296,7 +2431,7 @@ wheresession,Some(run),JournalInput::ArtifactsCollected(collected),- true,+ Emit::Live,).await}@@ -2359,8 +2494,14 @@ wherestate.fresh};if fresh {- self.capture(id, session, None, JournalInput::HistoryComplete, false)- .await?;+ self.capture(+ id,+ session,+ None,+ JournalInput::HistoryComplete,+ Emit::Silent,+ )+ .await?;session.state.lock().expect("session state poisoned").fresh = false;}Ok(())@@ -2374,7 +2515,7 @@ wheresession: &Session,run: Option<&CursorRunId>,input: JournalInput,- emit: bool,+ emit: Emit,) -> Result<(), SessionError> {let (expected, duplicate) = {let state = session.state.lock().expect("session state poisoned");@@ -2446,6 +2587,29 @@ where.collect();(updates, completion, pull_request, working_branches)};+ let emit = {+ let emit_mode = emit;+ let mut state = session.state.lock().expect("session state poisoned");+ let emit = match emit {+ Emit::Live => true,+ Emit::Silent => false,+ // Once anything is held back, the rest of the run is too:+ // later frames make no sense to a client missing earlier ones.+ Emit::Mirror => state.prompts_waiting == 0 && !state.unshown,+ };+ if emit && emit_mode == Emit::Mirror {+ state.mirror_published_at = Some(tokio::time::Instant::now());+ }+ // A prompt's own blocks are on the client already: it sent them.+ let visible = !updates.is_empty()+ || completion.is_some()+ || pull_request.is_some()+ || !working_branches.is_empty();+ if !emit && visible && !matches!(input, JournalInput::Prompt(_)) {+ state.unshown = true;+ }+ emit+ };if emit {for (repository, branch) in working_branches {self.notifier@@ -2556,7 +2720,13 @@ where};let blocks = vec![ContentBlock::Text(TextContent::new(prompt))];if let Err(error) = self- .capture(id, session, None, JournalInput::Prompt(blocks), false)+ .capture(+ id,+ session,+ None,+ JournalInput::Prompt(blocks),+ Emit::Silent,+ ).await{tracing::warn!(%error, %run, "could not journal a recovered Cursor prompt");@@ -2576,7 +2746,7 @@ wheresession,Some(&run),JournalInput::PromptAccepted(sequence),- false,+ Emit::Silent,).await{@@ -2652,8 +2822,14 @@ where.await?;}}- self.capture(id, &session, None, JournalInput::HistoryComplete, false)- .await?;+ self.capture(+ id,+ &session,+ None,+ JournalInput::HistoryComplete,+ Emit::Silent,+ )+ .await?;}// Before projecting, not after: a prompt recovered here closes the gap// rather than merely surviving it, and lands in the transcript this@@ -2744,8 +2920,20 @@ wherestate.mirror_cancel = tokio_util::sync::CancellationToken::new();state.mirror_cancel.clone()};+ // Streaming a run is only whole if the client has everything+ // before it; otherwise capture silently and let a load show it.+ let emit = if session+ .state+ .lock()+ .expect("session state poisoned")+ .unshown+ {+ Emit::Silent+ } else {+ Emit::Mirror+ };if let Err(error) = self- .backfill_foreign_runs(&session_id, &session, &agent, None, &cancel)+ .backfill_foreign_runs(&session_id, &session, &agent, None, &cancel, emit).await{tracing::warn!(%session_id, %agent, %error, "could not mirror cursor.com runs");@@ -2787,6 +2975,8 @@ impl ReplayGuard {let mut state = self.session.state.lock().expect("session state poisoned");state.ready_for_sync = true;state.reload_pending = false;+ state.unshown = false;+ state.mirror_published_at = None;}}diff --git a/crates/cursor_cloud_agents/src/domain/service/test.rs b/crates/cursor_cloud_agents/src/domain/service/test.rsindex 04cd61b77b..fa0bcdf4fc 100644--- a/crates/cursor_cloud_agents/src/domain/service/test.rs+++ b/crates/cursor_cloud_agents/src/domain/service/test.rs@@ -1184,20 +1184,24 @@ async fn foreign_runs_are_captured_before_the_next_prompt_and_shown_by_its_reloalater.send(CursorEvent::Done).unwrap();service.sync_foreign_runs().await;assert_eq!(- notifier.reloads().len(),- 2,- "successful load re-arms recovery"+ user_texts(¬ifier.updates()[shown..]),+ vec!["later question"],+ "a successful load re-arms the mirror, which streams the run live"+ );+ assert_eq!(notifier.reloads().len(), 1);+ assert_eq!(+ last_run(&service, &session),+ Some(CursorRunId::new("later")));- assert_eq!(notifier.updates().len(), shown);let reloaded = load(&service, &session, ¬ifier).await;assert_eq!(user_texts(&reloaded).last().unwrap(), "later question");}-/// The host's poll: cursor.com activity is captured into a session within a-/// tick, without any Macro prompt — exactly once, and only ever shown through-/// the standard load the capture requires.+/// The host's poll: cursor.com activity reaches a session as it happens,+/// without any Macro prompt — exactly once, checkpointed like a turn, and+/// with no reload to wait for.#[tokio::test]-async fn sync_captures_foreign_runs_once_and_requires_one_load_to_show_them() {+async fn sync_streams_foreign_runs_live_once_and_checkpoints_them() {let (service, cursor, notifier) = service(None);let session = service.new_session(Path::new(""), Vec::new());let events = cursor.script_stream();@@ -1233,33 +1237,33 @@ async fn sync_captures_foreign_runs_once_and_requires_one_load_to_show_them() {foreign.send(CursorEvent::Done).expect("stream open");service.sync_foreign_runs().await;+ let live = ¬ifier.updates()[before..];+ assert_eq!(user_texts(live), vec!["asked over there"]);+ assert_eq!(agent_texts(live), vec!["from over there"]);+ assert!(+ notifier.reloads().is_empty(),+ "nothing is left for a load to show"+ );assert_eq!(- notifier.updates().len(),- before,- "recovered history never streams live"+ notifier.checkpoints().last(),+ Some(&CursorRunId::new("run-foreign-1")));- assert_eq!(notifier.reloads(), vec![session.clone()]);- assert!(- ready_for_sync(&service, &session),- "the host owns the dispatch barrier; recovery does not close the session"+ assert_eq!(+ last_run(&service, &session),+ Some(CursorRunId::new("run-foreign-1")));- // While the requirement is pending, background ticks skip the session- // rather than signalling again.++ // The checkpoint moved the watermark: the same listing delivers nothing+ // more.+ let shown = notifier.updates().len();service.sync_foreign_runs().await;- assert_eq!(notifier.reloads().len(), 1);- assert_eq!(notifier.updates().len(), before);+ assert_eq!(notifier.updates().len(), shown);+ assert!(notifier.reloads().is_empty());+ // A later load shows the same conversation the client already has.let loaded = load(&service, &session, ¬ifier).await;assert_eq!(user_texts(&loaded), vec!["first", "asked over there"]);assert_eq!(agent_texts(&loaded), vec!["from over there"]);-- // The load moved the watermark: the same listing recovers nothing more- // and requires no further reload.- let shown = notifier.updates().len();- service.sync_foreign_runs().await;- assert_eq!(notifier.updates().len(), shown);- assert_eq!(notifier.reloads().len(), 1);- assert!(ready_for_sync(&service, &session));}#[tokio::test]@@ -1272,8 +1276,8 @@ async fn standalone_recovery_does_not_require_a_host_channel() {/// Restore seeds the durable watermark. The client's initial load hydrates the/// legacy run the watermark covers; only a run Cursor finished after it is-/// recovered by sync — captured once, never streamed, then shown in provider-/// order by the load the recovery requires, after which the tick is idempotent.+/// recovered by sync — captured once and streamed live, after which the tick+/// is idempotent and a load shows both runs in provider order.#[tokio::test]async fn restore_recovers_runs_after_the_durable_watermark_once() {let cursor = FakeCursor::new();@@ -1346,12 +1350,15 @@ async fn restore_recovers_runs_after_the_durable_watermark_once() {missed.send(finished("run-missed")).expect("stream open");missed.send(CursorEvent::Done).expect("stream open");service.sync_foreign_runs().await;+ let live = ¬ifier.updates()[initial.len()..];+ assert_eq!(user_texts(live), ["missed question"]);+ assert_eq!(agent_texts(live), ["recovered answer"]);+ assert!(notifier.reloads().is_empty());assert_eq!(- notifier.updates().len(),- initial.len(),- "recovered history never streams live"+ last_run(&service, &session),+ Some(CursorRunId::new("run-missed")),+ "the live delivery checkpoints the run");- assert_eq!(notifier.reloads(), vec![session.clone()]);let captured = |run: &str| {service.session(&session)@@ -1375,15 +1382,10 @@ async fn restore_recovers_runs_after_the_durable_watermark_once() {let loaded = load(&service, &session, ¬ifier).await;assert_eq!(user_texts(&loaded), ["earlier question", "missed question"]);assert_eq!(agent_texts(&loaded), ["earlier answer", "recovered answer"]);- assert_eq!(- last_run(&service, &session),- Some(CursorRunId::new("run-missed")),- "the load checkpoints the newest reconciled run"- );let shown = notifier.updates().len();service.sync_foreign_runs().await;assert_eq!(notifier.updates().len(), shown);- assert_eq!(notifier.reloads().len(), 1);+ assert!(notifier.reloads().is_empty());}/// Sessions created before run checkpoints existed have no durable watermark.@@ -1493,9 +1495,10 @@ async fn restore_waits_for_session_load_before_recovering_runs() {}/// A foreign run whose stream is gone (retention expired) is captured from-/// its run record, so the recorded answer is durable. The record carries no-/// original prompt, so recovery must not ask the client to reload a history-/// it cannot project.+/// its run record, so the recorded answer is durable and reaches the client+/// live, without the line that asked for it. The record carries no original+/// prompt, so recovery must not ask the client to reload a history it cannot+/// project.////// An explicit load still succeeds. It is the only way back to a session/// whose runtime has gone: the harness reattaches by loading, so a load that@@ -1530,11 +1533,15 @@ async fn an_expired_foreign_stream_falls_back_to_the_run_record() {let before = notifier.updates().len();service.sync_foreign_runs().await;- assert_eq!(notifier.updates().len(), before);+ assert_eq!(+ agent_texts(¬ifier.updates()[before..]),+ ["the old answer"]+ );assert!(notifier.reloads().is_empty(),"an unprojectable recovery requires no reload");+ let before = notifier.updates().len();assert!(ready_for_sync(&service, &session));let foreign = CursorRunId::new("run-foreign-1");let continuation = cursor.script_stream();@@ -1953,7 +1960,7 @@ async fn partial_capture_reconnect_matches_the_prefix_without_duplicate_content(text: "asked elsewhere".into(),},))),- false,+ Emit::Silent,).await.unwrap();@@ -1965,7 +1972,7 @@ async fn partial_capture_reconnect_matches_the_prefix_without_duplicate_content(JournalInput::Sse(crate::testing::raw_record(CursorEvent::Assistant {text: "hel".into(),})),- false,+ Emit::Silent,).await.unwrap();@@ -1988,7 +1995,7 @@ async fn partial_capture_reconnect_matches_the_prefix_without_duplicate_content(&run,&tokio_util::sync::CancellationToken::new(),IngestMode {- emit: true,+ emit: Emit::Live,..IngestMode::HYDRATE},)@@ -2105,12 +2112,18 @@ async fn aborted_prompt_is_retained_in_load_history_without_remote_execution() {JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new("stopped before execution",))]),- false,+ Emit::Silent,).await.unwrap();service- .capture(&id, &session, None, JournalInput::PromptAborted(2), false)+ .capture(+ &id,+ &session,+ None,+ JournalInput::PromptAborted(2),+ Emit::Silent,+ ).await.unwrap();}@@ -2136,7 +2149,7 @@ async fn terminal_poll_crash_is_reconciled_without_reopening_or_duplicating_tool&session,Some(&run),JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new("go"))]),- false,+ Emit::Silent,).await.unwrap();@@ -2148,7 +2161,7 @@ async fn terminal_poll_crash_is_reconciled_without_reopening_or_duplicating_toolJournalInput::Sse(crate::testing::raw_record(CursorEvent::Assistant {text: "hel".into(),})),- false,+ Emit::Silent,).await.unwrap();@@ -2167,7 +2180,7 @@ async fn terminal_poll_crash_is_reconciled_without_reopening_or_duplicating_tooltruncated: Truncation::default(),},))),- false,+ Emit::Silent,).await.unwrap();@@ -2177,7 +2190,7 @@ async fn terminal_poll_crash_is_reconciled_without_reopening_or_duplicating_tool&session,Some(&run),JournalInput::Poll(r#"{"status":"FINISHED","result":"hello"}"#.into()),- false,+ Emit::Silent,).await.unwrap();@@ -2234,7 +2247,7 @@ async fn capture_backlog_includes_the_run_at_the_delivered_watermark_after_resta&session,Some(&run),JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new("go"))]),- false,+ Emit::Silent,).await.unwrap();@@ -2246,7 +2259,7 @@ async fn capture_backlog_includes_the_run_at_the_delivered_watermark_after_restaJournalInput::Sse(crate::testing::raw_record(CursorEvent::Assistant {text: "hel".into(),})),- false,+ Emit::Silent,).await.unwrap();@@ -2256,7 +2269,7 @@ async fn capture_backlog_includes_the_run_at_the_delivered_watermark_after_resta&session,Some(&run),JournalInput::Interrupted("disconnected cancellation".into()),- false,+ Emit::Silent,).await.unwrap();@@ -2282,11 +2295,11 @@ async fn capture_backlog_includes_the_run_at_the_delivered_watermark_after_restatx.send(CursorEvent::Done).unwrap();service.sync_foreign_runs().await;assert_eq!(- output.updates().len(),- before,- "the backlog is captured, not streamed"+ agent_texts(&output.updates()[before..]),+ ["lo"],+ "the load showed the captured prefix; only the rest streams");- assert_eq!(output.reloads(), vec![id.clone()]);+ assert!(output.reloads().is_empty());assert!(service.journal@@ -2593,7 +2606,7 @@ async fn actual_load_frames_restore_terminal_outcomes_and_leave_partial_tail_ope&session,Some(&run),JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new("question"))]),- false,+ Emit::Silent,).await.unwrap();@@ -2605,7 +2618,7 @@ async fn actual_load_frames_restore_terminal_outcomes_and_leave_partial_tail_opeJournalInput::Sse(crate::testing::raw_record(CursorEvent::Assistant {text: "answer".into(),})),- false,+ Emit::Silent,).await.unwrap();@@ -2618,7 +2631,7 @@ async fn actual_load_frames_restore_terminal_outcomes_and_leave_partial_tail_opeJournalInput::Poll(serde_json::json!({"status":status,"result":"answer"}).to_string(),),- false,+ Emit::Silent,).await.unwrap();@@ -3681,7 +3694,7 @@ async fn a_resumed_stream_continues_the_captured_prefix_without_duplicating_it()&session,Some(&run),JournalInput::Sse(record.clone()),- false,+ Emit::Silent,).await.expect("capture");@@ -3837,6 +3850,137 @@ async fn a_stop_ends_a_prompt_waiting_behind_a_mirror() {assert!(!service.has_active_turn());}+/// A prompt parked behind the mirror already has its turn open on the+/// client, so the rest of the cursor.com run must not stream into it. The+/// mirror holds those frames back and asks for a reload, which shows the run+/// in its own place, instead of checkpointing a delivery that never happened.+#[tokio::test]+async fn a_prompt_waiting_behind_a_mirror_holds_the_rest_of_the_run_for_a_reload() {+ let (service, cursor, notifier) = service(None);+ let id = service.new_session(Path::new(""), vec![]);+ let (mirror, foreign) = mirror_following_a_live_run(&service, &cursor, &id).await;+ notifier.wait_for_updates(1).await;+ assert_eq!(user_texts(¬ifier.updates()), ["asked over there"]);++ let session = service.session(&id).unwrap();+ let waiting = WaitingPrompt::new(&session);+ foreign+ .send(CursorEvent::Assistant {+ text: "answered over there".into(),+ })+ .unwrap();+ foreign.send(finished("R1")).unwrap();+ foreign.send(CursorEvent::Done).unwrap();+ tokio::time::timeout(std::time::Duration::from_secs(5), mirror)+ .await+ .expect("the mirror ends with the run")+ .unwrap();+ drop(waiting);++ assert!(+ agent_texts(¬ifier.updates()).is_empty(),+ "nothing lands in the waiting prompt's turn"+ );+ assert_eq!(notifier.reloads(), vec![id.clone()]);+ assert!(notifier.checkpoints().is_empty());+ let loaded = load(&service, &id, ¬ifier).await;+ assert_eq!(user_texts(&loaded), ["asked over there"]);+ assert_eq!(agent_texts(&loaded), ["answered over there"]);+}++/// A prompt that stops waiting (a stop, or the gate budget running out) does+/// not let the mirror resume streaming: the client is already missing what+/// was held back, and the rest of the run would render without it.+#[tokio::test]+async fn a_mirror_that_held_frames_back_keeps_the_rest_of_the_run_for_the_reload() {+ let (service, cursor, notifier) = service(None);+ let id = service.new_session(Path::new(""), vec![]);+ let (mirror, foreign) = mirror_following_a_live_run(&service, &cursor, &id).await;+ notifier.wait_for_updates(1).await;++ let session = service.session(&id).unwrap();+ drop(WaitingPrompt::new(&session));+ foreign+ .send(CursorEvent::Assistant {+ text: "answered over there".into(),+ })+ .unwrap();+ foreign.send(finished("R1")).unwrap();+ foreign.send(CursorEvent::Done).unwrap();+ tokio::time::timeout(std::time::Duration::from_secs(5), mirror)+ .await+ .expect("the mirror ends with the run")+ .unwrap();++ assert!(+ agent_texts(¬ifier.updates()).is_empty(),+ "the rest of the run waits for the reload"+ );+ assert_eq!(notifier.reloads(), vec![id.clone()]);+ let loaded = load(&service, &id, ¬ifier).await;+ assert_eq!(agent_texts(&loaded), ["answered over there"]);+}++/// A prompt sent while the mirror's last frames were on their way reaches the+/// service only after the mirror let go of the gate, with those frames+/// already inside its turn on the client. Arriving that soon after the+/// mirror streamed, it asks for a reload; a prompt well after does not.+#[tokio::test(start_paused = true)]+async fn a_prompt_right_after_a_mirror_streamed_asks_for_a_reload() {+ let (service, cursor, notifier) = service(None);+ let id = service.new_session(Path::new(""), vec![]);+ let events = cursor.script_stream();+ events.send(finished("run-fake-1")).unwrap();+ events.send(CursorEvent::Done).unwrap();+ service.prompt(&id, "first").await.unwrap();++ let mirror_one = |run: &'static str, previous: &'static str| {+ cursor.script_run_listings(vec![+ RunListing {+ id: CursorRunId::new(run),+ status: RunStatus::Finished,+ },+ RunListing {+ id: CursorRunId::new(previous),+ status: RunStatus::Finished,+ },+ ]);+ let foreign = cursor.script_stream();+ foreign+ .send(CursorEvent::Interaction(InteractionUpdate::UserMessage {+ text: format!("{run} question"),+ }))+ .unwrap();+ foreign+ .send(CursorEvent::Assistant {+ text: format!("{run} answer"),+ })+ .unwrap();+ foreign.send(finished(run)).unwrap();+ foreign.send(CursorEvent::Done).unwrap();+ };+ let own = |run: &'static str| {+ let events = cursor.script_stream();+ events.send(finished(run)).unwrap();+ events.send(CursorEvent::Done).unwrap();+ };++ mirror_one("run-foreign-1", "run-fake-1");+ service.sync_foreign_runs().await;+ assert!(notifier.reloads().is_empty());+ own("run-fake-2");+ service.prompt(&id, "right after").await.unwrap();+ assert_eq!(notifier.reloads(), vec![id.clone()]);+ load(&service, &id, ¬ifier).await;++ mirror_one("run-foreign-2", "run-fake-2");+ service.sync_foreign_runs().await;+ tokio::time::advance(MIRROR_PROMPT_OVERLAP * 2).await;+ own("run-fake-3");+ service.prompt(&id, "much later").await.unwrap();+ assert_eq!(notifier.reloads().len(), 1, "no overlap, no reload");+}+/// A stop reaches the mirror itself, not only the prompt behind it.////// Cursor was observed to keep a run at `RUNNING` after a cancel, with a@@ -3882,10 +4026,11 @@ async fn a_stop_ends_a_mirror_following_a_run_cursor_never_ends() {"an interrupted following is not reconciliation");assert_eq!(- notifier.reloads(),- vec![id.clone()],- "what the mirror captured before the stop is still shown"+ user_texts(¬ifier.updates()),+ ["asked over there"],+ "what the mirror streamed before the stop stays shown");+ assert!(notifier.reloads().is_empty());// The next prompt does not wait behind the run Cursor never ended: it is// skipped as abandoned, and the prompt runs.diff --git a/crates/cursor_cloud_agents/src/domain/service/test/fold.rs b/crates/cursor_cloud_agents/src/domain/service/test/fold.rsindex c9e90df20a..55cf35a72c 100644--- a/crates/cursor_cloud_agents/src/domain/service/test/fold.rs+++ b/crates/cursor_cloud_agents/src/domain/service/test/fold.rs@@ -74,12 +74,19 @@ pub(super) async fn replay_with_runs(drop(events);}service.sync_foreign_runs().await;- // Recovery is host-local: one reload requirement for this session and- // no frame on the wire until the client's own standard load.- assert_eq!(reload_rx.try_recv().ok(), Some(id.clone()));+ // The mirror streams the runs to the client as they happen, with no+ // reload to wait for.assert!(reload_rx.try_recv().is_err());- assert_no_frame(&mut client).await;+ drain_live_frames(&mut client, &mut log).await;+ assert_incremental_matches_batch(&log);+ let live = serde_json::to_value(agent_fold::domain::fold::fold(log.clone())).unwrap();+ // A later load replaces that with the same conversation.load(&mut client, &mut log, &id, 93).await;+ assert_eq!(+ live,+ serde_json::to_value(agent_fold::domain::fold::fold(log.clone())).unwrap(),+ "the live mirror and a load show one conversation"+ );}task.abort();assert_incremental_matches_batch(&log);@@ -154,7 +161,24 @@ async fn drain_available_commands_update(client: &mut agent_client_protocol::Cha);}-/// The served transport stays silent: recovered history never streams live.+/// Record every frame the agent sends unprompted until it goes quiet.+async fn drain_live_frames(+ client: &mut agent_client_protocol::Channel,+ log: &mut Vec<AgentSessionLog>,+) {+ while let Ok(frame) =+ tokio::time::timeout(std::time::Duration::from_millis(100), client.rx.next()).await+ {+ let TransportFrame::Single(frame) = frame.expect("the connection stayed open") else {+ panic!("single frame")+ };+ log.push(entry(Message::ToServer(ToServerMessage::Acp(AcpMessage(+ frame,+ )))));+ }+}++/// The served transport stays silent: nothing leaves the agent unprompted.async fn assert_no_frame(client: &mut agent_client_protocol::Channel) {assert!(tokio::time::timeout(std::time::Duration::from_millis(100), client.rx.next())@@ -421,7 +445,7 @@ async fn accepted_newer_run_survives_partial_crash_load_then_actual_sync_without&session,None,JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new("R2"))]),- false,+ Emit::Silent,).await.unwrap();@@ -433,7 +457,7 @@ async fn accepted_newer_run_survives_partial_crash_load_then_actual_sync_without&session,Some(&r2),JournalInput::PromptAccepted(2),- false,+ Emit::Silent,).await.unwrap();@@ -457,7 +481,7 @@ async fn accepted_newer_run_survives_partial_crash_load_then_actual_sync_without&session,Some(&r1),JournalInput::Sse(crate::testing::raw_record(event.clone())),- false,+ Emit::Silent,).await.unwrap();@@ -594,9 +618,12 @@ async fn load_waiting_for_an_active_backfill_replays_one_copy_through_fold() {reload_rx.try_recv().is_err(),"no reload is required before the recovered run is reconciled");- // The load arrives mid-backfill and waits behind the gate; the run's- // completion is captured before the load reads the journal.+ // What the mirror has streamed so far is already on the client.let mut log = Vec::new();+ drain_live_frames(&mut client, &mut log).await;+ assert!(!log.is_empty(), "the mirror streams the run as it happens");+ // The load arrives mid-backfill and waits behind the gate; the run's+ // completion is captured, and streamed, before the load reads the journal.let loading = tokio::spawn(async move {load(&mut client, &mut log, &id, 91).await;(client, log, id)@@ -604,9 +631,11 @@ async fn load_waiting_for_an_active_backfill_replays_one_copy_through_fold() {older.send(finished("R1")).unwrap();older.send(CursorEvent::Done).unwrap();producer.await.unwrap();- let (mut client, log, id) = loading.await.unwrap();- assert_eq!(reload_rx.try_recv().ok(), Some(id.clone()));- assert!(reload_rx.try_recv().is_err());+ let (mut client, log, _id) = loading.await.unwrap();+ assert!(+ reload_rx.try_recv().is_err(),+ "a streamed run needs no reload"+ );assert_no_frame(&mut client).await;task.abort();assert_incremental_matches_batch(&log);diff --git a/crates/cursor_cloud_agents/src/testing.rs b/crates/cursor_cloud_agents/src/testing.rsindex 73d7380fbc..8b264de245 100644--- a/crates/cursor_cloud_agents/src/testing.rs+++ b/crates/cursor_cloud_agents/src/testing.rs@@ -792,6 +792,7 @@ pub struct RecordingNotifier {reloads: Arc<Mutex<Vec<SessionId>>>,pull_requests: Arc<Mutex<Vec<String>>>,working_branches: Arc<Mutex<Vec<(String, String)>>>,+ checkpoints: Arc<Mutex<Vec<CursorRunId>>>,delivered: Arc<tokio::sync::Notify>,}@@ -824,6 +825,11 @@ impl RecordingNotifier {.clone()}+ /// Runs checkpointed as fully delivered, in order.+ pub fn checkpoints(&self) -> Vec<CursorRunId> {+ self.checkpoints.lock().expect("notifier poisoned").clone()+ }+/// Sessions whose recovered history needs a client load.pub fn reloads(&self) -> Vec<SessionId> {self.reloads.lock().expect("notifier poisoned").clone()@@ -906,8 +912,12 @@ impl SessionNotifier for RecordingNotifier {async fn checkpoint(&self,_session: &SessionId,- _run: &CursorRunId,+ run: &CursorRunId,) -> Result<(), rootcause::Report> {+ self.checkpoints+ .lock()+ .expect("notifier poisoned")+ .push(run.clone());Ok(())}}diff --git a/docs/CURSOR_AGENT_TRANSPORT.md b/docs/CURSOR_AGENT_TRANSPORT.mdindex b6504b8fea..3eecf8b92e 100644--- a/docs/CURSOR_AGENT_TRANSPORT.md+++ b/docs/CURSOR_AGENT_TRANSPORT.md@@ -440,8 +440,17 @@ reads the selected indexed range. Generic server and browser folds stage loadupdates separately and replace visible history only on success. Failed orincomplete loads preserve the committed conversation; resume does not replace it.-Live recovery uses this same load path. Cursor captures foreign or interrupted-runs into its native journal without publishing replacement conversation frames.+A run started on cursor.com while the session is idle is not recovery: the+background mirror journals it and publishes its frames as they arrive, exactly+as a Macro turn does, then checkpoints it. The fold opens a turn for the+cursor.com prompt and closes it on `_session/turn_complete`. Streaming is only+whole when the client already has everything journaled before the run, so the+mirror falls back to recovery while a prompt waits behind it (that prompt's+turn is already open on the client) or while anything journaled since the last+load was never sent.++Recovery uses this same load path. Cursor captures foreign or interrupted runs+into its native journal without publishing replacement conversation frames.Its notifier enqueues a typed, host-local reload requirement; the pipe adapterdelivers that requirement before a queued prompt response. The session domainwaits for the current prompt response, queues subsequent commands, and initiates