Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(cursor): a resumed session must not be stranded by a gap in its history (#6491)

Wolf Mermelstein65bdd746b6d5
diff --git a/crates/agent_harness/src/outbound/cursor/manager.rs b/crates/agent_harness/src/outbound/cursor/manager.rs
index 2de5a33844..633b9bc997 100644
--- a/crates/agent_harness/src/outbound/cursor/manager.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager.rs
@@ -692,6 +692,16 @@ where
{
self.client.list_runs(agent, through).await
}
+
+ async fn conversation(
+ &self,
+ agent: &CursorAgentId,
+ ) -> std::result::Result<
+ Vec<cursor_cloud_agents::domain::model::ConversationLine>,
+ rootcause::Report,
+ > {
+ self.client.conversation(agent).await
+ }
}
impl<Sessions> RunStream for RecordingCursor<Sessions>
diff --git a/crates/cursor_cloud_agents/src/api.rs b/crates/cursor_cloud_agents/src/api.rs
index 0ff440d3c3..33c82dfecd 100644
--- a/crates/cursor_cloud_agents/src/api.rs
+++ b/crates/cursor_cloud_agents/src/api.rs
@@ -22,13 +22,14 @@ pub mod wire;
use crate::api::record::SseRecording;
use crate::api::wire::{
- AgentSummary, ArchiveAgentResponse, CreateAgentRequest, CreateAgentResponse, CreateRunRequest,
- CreateRunResponse, ListAgentsResponse, ListModelsResponse, ListRunsResponse,
- McpServerSelection, MeResponse, ModelSelection, PromptBody, RepoSelection,
+ AgentSummary, ArchiveAgentResponse, ConversationResponse, CreateAgentRequest,
+ CreateAgentResponse, CreateRunRequest, CreateRunResponse, ListAgentsResponse,
+ ListModelsResponse, ListRunsResponse, McpServerSelection, MeResponse, ModelSelection,
+ PromptBody, RepoSelection,
};
use crate::domain::model::{
- CursorAgentId, CursorModel, CursorRunId, McpServer, ModelChoice, ModelParam, ModelVariant,
- RepoUrl, RunListing,
+ ConversationLine, ConversationSpeaker, CursorAgentId, CursorModel, CursorRunId, McpServer,
+ ModelChoice, ModelParam, ModelVariant, RepoUrl, RunListing,
};
use crate::domain::ports::{ConnectedStream, CursorAgents, RunStream, StreamConnectError};
use futures::{Stream, StreamExt as _};
@@ -539,6 +540,33 @@ impl CursorAgents for CursorClient {
}
Ok(listings)
}
+
+ /// Version zero on purpose: v1 exposes no conversation endpoint, and this
+ /// one answers for the agents v1 created.
+ #[tracing::instrument(skip(self), err)]
+ async fn conversation(
+ &self,
+ agent: &CursorAgentId,
+ ) -> Result<Vec<ConversationLine>, rootcause::Report> {
+ let reply: ConversationResponse = self
+ .get_json(&format!("/v0/agents/{agent}/conversation"))
+ .await?;
+ Ok(reply
+ .messages
+ .into_iter()
+ .filter_map(|message| {
+ let speaker = match message.kind.as_str() {
+ "user_message" => ConversationSpeaker::User,
+ "assistant_message" => ConversationSpeaker::Agent,
+ _ => return None,
+ };
+ Some(ConversationLine {
+ speaker,
+ text: message.text?,
+ })
+ })
+ .collect())
+ }
}
/// How many times a run's stream is connected before an unavailable stream
diff --git a/crates/cursor_cloud_agents/src/api/wire.rs b/crates/cursor_cloud_agents/src/api/wire.rs
index b5004b29cf..9ce7f477ee 100644
--- a/crates/cursor_cloud_agents/src/api/wire.rs
+++ b/crates/cursor_cloud_agents/src/api/wire.rs
@@ -224,6 +224,28 @@ pub struct ListRunsResponse {
pub next_cursor: Option<String>,
}
+/// `GET /v0/agents/{id}/conversation` response.
+///
+/// Deliberately the older API version: v1 has no conversation endpoint, and
+/// this one answers for agents v1 created.
+#[derive(Debug, Deserialize)]
+pub struct ConversationResponse {
+ /// The agent's prompts and replies, oldest first.
+ pub messages: Vec<ConversationMessage>,
+}
+
+/// One message in a `GET /v0/agents/{id}/conversation` response.
+#[derive(Debug, Deserialize)]
+pub struct ConversationMessage {
+ /// `user_message` or `assistant_message`. Anything else is skipped rather
+ /// than guessed at, so a kind Cursor adds cannot be read as a prompt.
+ #[serde(rename = "type")]
+ pub kind: String,
+ /// The message text. Absent on a kind that carries none.
+ #[serde(default)]
+ pub text: Option<String>,
+}
+
/// One run in a `GET /v1/agents/{id}/runs` page.
#[derive(Debug, Deserialize)]
pub struct RunListItem {
diff --git a/crates/cursor_cloud_agents/src/domain/journal.rs b/crates/cursor_cloud_agents/src/domain/journal.rs
index 6e5433aa2d..41d5a4a14b 100644
--- a/crates/cursor_cloud_agents/src/domain/journal.rs
+++ b/crates/cursor_cloud_agents/src/domain/journal.rs
@@ -132,6 +132,14 @@ impl ReplayMachine {
.get(run)
.is_some_and(|s| s.prompt && s.terminal.is_some())
}
+ /// The run's answer as this journal captured it, empty string and all.
+ ///
+ /// Only the final step's text: a new step clears what came before, the
+ /// same way Cursor's own final text keeps only the last step. That is
+ /// what makes it comparable with a line of the agent's conversation.
+ pub fn answer(&self, run: &CursorRunId) -> Option<&str> {
+ self.runs.get(run).map(|state| state.text.as_str())
+ }
/// Durable provider terminal status, independent of the reconciliation marker.
pub fn terminal_status(&self, run: &CursorRunId) -> Option<RunStatus> {
self.runs.get(run).and_then(|s| s.terminal.clone())
diff --git a/crates/cursor_cloud_agents/src/domain/model.rs b/crates/cursor_cloud_agents/src/domain/model.rs
index 203b31bb61..d530564bad 100644
--- a/crates/cursor_cloud_agents/src/domain/model.rs
+++ b/crates/cursor_cloud_agents/src/domain/model.rs
@@ -175,6 +175,29 @@ pub struct RunListing {
pub status: RunStatus,
}
+/// Who said one line of an agent's conversation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ConversationSpeaker {
+ /// A prompt, whether typed here or on cursor.com.
+ User,
+ /// One of the agent's replies. A turn has several, one per step.
+ Agent,
+}
+
+/// One line of an agent's conversation, as Cursor still holds it.
+///
+/// Prompts and replies only: no tool calls, no reasoning, no run ids and no
+/// timestamps. Enough to find a prompt that was lost, not enough to rebuild
+/// a turn - which is why this supplements captured history rather than
+/// replacing it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ConversationLine {
+ /// Who said it.
+ pub speaker: ConversationSpeaker,
+ /// What was said.
+ pub text: String,
+}
+
/// An MCP server a session should make available to its Cursor agent.
///
/// Only the transports a *cloud* agent can honour. ACP's third transport,
diff --git a/crates/cursor_cloud_agents/src/domain/ports.rs b/crates/cursor_cloud_agents/src/domain/ports.rs
index e51033933b..e5dc71a509 100644
--- a/crates/cursor_cloud_agents/src/domain/ports.rs
+++ b/crates/cursor_cloud_agents/src/domain/ports.rs
@@ -10,7 +10,8 @@
//! subprocesses remain outside the service.
use crate::domain::model::{
- CursorAgentId, CursorModel, CursorRunId, McpServer, ModelChoice, RepoUrl, RunListing,
+ ConversationLine, CursorAgentId, CursorModel, CursorRunId, McpServer, ModelChoice, RepoUrl,
+ RunListing,
};
use agent_client_protocol::schema::v1::{SessionId, SessionUpdate};
use futures::Stream;
@@ -90,6 +91,23 @@ pub trait CursorAgents: Sync {
agent: &CursorAgentId,
through: Option<&CursorRunId>,
) -> impl Future<Output = Result<Vec<RunListing>, rootcause::Report>> + Send;
+
+ /// The agent's prompts and replies in order, as Cursor still holds them.
+ ///
+ /// The longest-lived record Cursor keeps, and the reason this exists: a
+ /// run's stream expires within hours and its record drops its final text
+ /// within weeks, while this still answers for agents whose every other
+ /// trace is gone. It is where a prompt that was never captured here -
+ /// a run driven from cursor.com, mirrored after its stream aged out -
+ /// can still be found.
+ ///
+ /// Carries no run ids, so a line is tied to a run by matching text the
+ /// journal already holds, never by position. See
+ /// [`CursorSessionService::recover_lost_prompts`](crate::domain::service::CursorSessionService).
+ fn conversation(
+ &self,
+ agent: &CursorAgentId,
+ ) -> impl Future<Output = Result<Vec<ConversationLine>, rootcause::Report>> + Send;
}
/// One connected run stream, with what the provider said about resuming it.
diff --git a/crates/cursor_cloud_agents/src/domain/service.rs b/crates/cursor_cloud_agents/src/domain/service.rs
index 475ef99134..9dc8661630 100644
--- a/crates/cursor_cloud_agents/src/domain/service.rs
+++ b/crates/cursor_cloud_agents/src/domain/service.rs
@@ -42,7 +42,8 @@ use crate::domain::error::SessionError;
use crate::domain::event::CursorEvent;
use crate::domain::journal::{CursorJournal, JournalEntry, JournalInput, ReplayMachine};
use crate::domain::model::{
- CursorAgentId, CursorModel, CursorRunId, McpServer, ModelChoice, RepoUrl, RunStatus,
+ ConversationLine, ConversationSpeaker, CursorAgentId, CursorModel, CursorRunId, McpServer,
+ ModelChoice, RepoUrl, RunStatus,
};
use crate::domain::ports::{
CursorAgents, RepositoryChooser, RunStream, SessionNotifier, StreamConnectError,
@@ -1760,7 +1761,9 @@ where
if mirrored {
let notify = {
let mut state = session.state.lock().expect("session state poisoned");
- if let Err(error) = history_projection(&state.journal_entries) {
+ 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(mirrored);
}
@@ -1794,7 +1797,17 @@ where
let entries = self.journal.read(id).await?;
let mut machine = ReplayMachine::default();
for entry in &entries {
- project_entry(&mut machine, entry, &entries)?;
+ // An entry that will not project is skipped rather than failed.
+ // It is already durable, so failing here fails identically every
+ // time this session is read, and a session whose journal cannot
+ // be read cannot be loaded or prompted ever again.
+ if let Err(error) = project_entry(&mut machine, entry, &entries) {
+ tracing::warn!(
+ %error,
+ sequence = entry.sequence,
+ "skipping a Cursor journal entry that will not project"
+ );
+ }
}
let fresh = {
let mut state = session.state.lock().expect("session state poisoned");
@@ -1931,6 +1944,88 @@ where
Ok(())
}
+ /// Fill in prompts the journal never captured, from Cursor's own record.
+ ///
+ /// A run driven from cursor.com and mirrored here after its stream aged
+ /// out has an answer and no question: the stream is the only thing that
+ /// carries the opening message, and the run record left behind does not.
+ /// The conversation endpoint outlives both, so it is asked once per load
+ /// that has a gap, and what it recovers is journaled - a prompt written
+ /// exactly as a live one is, so it projects into place rather than onto
+ /// the end of the transcript, and so the next load needs no lookup.
+ ///
+ /// Best effort throughout. Every failure here leaves the gap exactly as
+ /// it was, which the load already serves.
+ async fn recover_lost_prompts(
+ &self,
+ id: &SessionId,
+ session: &Session,
+ agent: Option<&CursorAgentId>,
+ ) {
+ let Some(agent) = agent else {
+ return;
+ };
+ let lost = {
+ let state = session.state.lock().expect("session state poisoned");
+ runs_without_prompts(&state.journal_entries, &state.machine)
+ .into_iter()
+ .filter_map(|run| {
+ state
+ .machine
+ .answer(run)
+ .filter(|answer| !answer.is_empty())
+ .map(|answer| (run.clone(), answer.to_owned()))
+ })
+ .collect::<Vec<_>>()
+ };
+ if lost.is_empty() {
+ return;
+ }
+ let conversation = match self.cursor.conversation(agent).await {
+ Ok(conversation) => conversation,
+ Err(error) => {
+ tracing::warn!(%error, %agent, "could not read the Cursor conversation");
+ return;
+ }
+ };
+ for (run, answer) in lost {
+ let Some(prompt) = prompt_for_answer(&conversation, &answer) else {
+ tracing::warn!(%run, "no Cursor conversation line names this run's prompt");
+ continue;
+ };
+ let blocks = vec![ContentBlock::Text(TextContent::new(prompt))];
+ if let Err(error) = self
+ .capture(id, session, None, JournalInput::Prompt(blocks), false)
+ .await
+ {
+ tracing::warn!(%error, %run, "could not journal a recovered Cursor prompt");
+ return;
+ }
+ let sequence = session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .journal_entries
+ .last()
+ .expect("captured prompt")
+ .sequence;
+ if let Err(error) = self
+ .capture(
+ id,
+ session,
+ Some(&run),
+ JournalInput::PromptAccepted(sequence),
+ false,
+ )
+ .await
+ {
+ tracing::warn!(%error, %run, "could not link a recovered Cursor prompt");
+ return;
+ }
+ tracing::info!(%run, "recovered a lost Cursor prompt from the conversation");
+ }
+ }
+
/// Reconstruct the entire session before allowing a successful load reply.
/// The returned guard serializes the reply itself with every live writer.
///
@@ -1999,13 +2094,21 @@ where
self.capture(id, &session, None, JournalInput::HistoryComplete, false)
.await?;
}
+ // Before projecting, not after: a prompt recovered here closes the gap
+ // rather than merely surviving it, and lands in the transcript this
+ // load is about to publish.
+ self.recover_lost_prompts(id, &session, agent.as_ref())
+ .await;
let entries = session
.state
.lock()
.expect("session state poisoned")
.journal_entries
.clone();
- let (machine, updates) = history_projection(&entries)?;
+ // A gap here cannot be allowed to fail the load. The runtime reattaches
+ // to a disconnected session by loading it, so a load that refuses is
+ // also every future prompt refused as disconnected, with no way back.
+ let (machine, updates) = history_projection(&entries, HistoryGap::IsServedAnyway)?;
if let Some(url) = machine.pull_request_url() {
self.notifier.set_pull_request(id, url).await?;
}
@@ -2173,8 +2276,74 @@ type HistoryUpdates = Vec<(
Option<agent_runtime_protocol::domain::turn::TurnOutcome>,
)>;
+/// Runs the journal holds frames for but no opening prompt.
+///
+/// The same condition [`history_projection`] reports a gap on, named once so
+/// recovery looks for exactly what the projection would complain about.
+fn runs_without_prompts<'a>(
+ entries: &'a [JournalEntry],
+ machine: &ReplayMachine,
+) -> Vec<&'a CursorRunId> {
+ let mut missing: Vec<&CursorRunId> = Vec::new();
+ for run in entries.iter().filter_map(|e| e.run.as_ref()) {
+ if missing.contains(&run) || machine.has_prompt(run) {
+ continue;
+ }
+ let accepted_only = entries
+ .iter()
+ .filter(|e| e.run.as_ref() == Some(run))
+ .all(|e| matches!(e.input, JournalInput::PromptAccepted(_)));
+ if !accepted_only {
+ missing.push(run);
+ }
+ }
+ missing
+}
+
+/// The prompt that produced `answer`, if the conversation says so plainly.
+///
+/// Anchored on the answer the journal already holds rather than on position:
+/// Cursor's conversation carries no run ids, and its turn numbering does not
+/// track the run list once runs are cancelled or fail. An answer that appears
+/// more than once names no single turn - an agent that replied the same thing
+/// twice is ordinary - so an ambiguous match yields nothing rather than a
+/// guess. Attaching the wrong question to an answer is worse than leaving the
+/// question blank, which is all a gap costs now.
+fn prompt_for_answer<'a>(conversation: &'a [ConversationLine], answer: &str) -> Option<&'a str> {
+ let mut spoken = conversation
+ .iter()
+ .enumerate()
+ .filter(|(_, line)| line.speaker == ConversationSpeaker::Agent && line.text == answer);
+ let (at, _) = spoken.next()?;
+ if spoken.next().is_some() {
+ return None;
+ }
+ conversation[..at]
+ .iter()
+ .rev()
+ .find(|line| line.speaker == ConversationSpeaker::User)
+ .map(|line| line.text.as_str())
+}
+
+/// What a gap in the recovered history costs the caller asking for it.
+///
+/// Replacing a session's conversation is a choice, and a candidate missing a
+/// turn's opening is worse than the history already on screen, so a gap
+/// declines the replacement and what is there stands.
+///
+/// Loading is not a choice. The journal is the only history there is, and a
+/// load that refuses leaves a session that cannot be opened and cannot be
+/// prompted - the runtime reattaches by loading, so every later prompt is
+/// refused as disconnected too. A gap is reported and the rest is served.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum HistoryGap {
+ DeclinesReplacement,
+ IsServedAnyway,
+}
+
fn history_projection(
entries: &[JournalEntry],
+ gap: HistoryGap,
) -> Result<(ReplayMachine, HistoryUpdates), SessionError> {
for entry in entries {
if entry.run.is_none()
@@ -2183,6 +2352,13 @@ fn history_projection(
matches!(e.input, JournalInput::PromptAccepted(n) | JournalInput::PromptAborted(n) if n == entry.sequence)
})
{
+ if gap == HistoryGap::IsServedAnyway {
+ tracing::warn!(
+ sequence = entry.sequence,
+ "serving Cursor history whose prompt was never resolved"
+ );
+ break;
+ }
return Err(rootcause::report!("Cursor prompt acceptance is unknown; refusing incomplete replacement history").into());
}
}
@@ -2235,6 +2411,13 @@ fn history_projection(
.filter(|e| e.run.as_ref() == Some(run))
.all(|e| matches!(e.input, JournalInput::PromptAccepted(_)));
if !machine.has_prompt(run) && !accepted_only {
+ if gap == HistoryGap::IsServedAnyway {
+ // The run's own frames are already projected; only the line
+ // that opened it is missing. Serving the turn without it
+ // beats serving nothing, forever.
+ tracing::warn!(%run, "serving Cursor history without a run's original prompt");
+ continue;
+ }
return Err(rootcause::report!(
"Cursor original prompt unavailable for {run}; preserving existing history"
)
diff --git a/crates/cursor_cloud_agents/src/domain/service/test.rs b/crates/cursor_cloud_agents/src/domain/service/test.rs
index 9f310c4571..912595488d 100644
--- a/crates/cursor_cloud_agents/src/domain/service/test.rs
+++ b/crates/cursor_cloud_agents/src/domain/service/test.rs
@@ -3,7 +3,8 @@ use crate::domain::error::SessionError;
use crate::domain::event::{CursorEvent, InteractionUpdate, ToolCallEvent, Truncation};
use crate::domain::journal::NativeRecord;
use crate::domain::model::{
- McpHeader, McpServer, McpTransport, RepoUrl, RunListing, RunOutcome, RunStatus,
+ ConversationLine, ConversationSpeaker, McpHeader, McpServer, McpTransport, RepoUrl, RunListing,
+ RunOutcome, RunStatus,
};
use crate::domain::ports::StreamConnectError;
use crate::testing::{CursorCall, FakeCursor, FixedChooser, RecordingNotifier};
@@ -90,6 +91,13 @@ async fn load(
notifier.updates()[before..].to_vec()
}
+fn line(speaker: ConversationSpeaker, text: &str) -> ConversationLine {
+ ConversationLine {
+ speaker,
+ text: text.to_owned(),
+ }
+}
+
fn finished(run: &str) -> CursorEvent {
CursorEvent::Result {
run_id: CursorRunId::new(run),
@@ -1489,10 +1497,15 @@ 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. But the record carries
-/// no original prompt: recovery must not ask the client to reload a history
-/// it cannot project, and an explicit load must fail rather than invent one —
-/// the client's prior view stays in place until a load succeeds.
+/// 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.
+///
+/// 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
+/// refuses is every later prompt refused as disconnected, with nothing the
+/// user can do about it. The answer is served without the line that asked
+/// for it, and the gap is reported.
#[tokio::test(start_paused = true)]
async fn an_expired_foreign_stream_falls_back_to_the_run_record() {
let (service, cursor, notifier) = service(None);
@@ -1548,29 +1561,143 @@ async fn an_expired_foreign_stream_falls_back_to_the_run_record() {
.any(|e| e.run.as_ref() == Some(&foreign) && e.input == JournalInput::Reconciled)
);
- let error = service
+ service
.replay_session(&session)
.await
- .err()
- .expect("a run without its original prompt cannot replace history");
+ .expect("a run without its original prompt still loads")
+ .complete();
assert!(
- error.to_string().contains("original prompt unavailable"),
- "{error}"
- );
- assert_eq!(
- notifier.updates().len(),
- before,
- "a failed load publishes nothing: the prior view is retained"
+ notifier.updates().len() > before,
+ "the load serves the history it does have"
);
assert!(
- !ready_for_sync(&service, &session),
- "nothing syncs or prompts until a load succeeds"
+ ready_for_sync(&service, &session),
+ "a loaded session is promptable again"
);
assert_eq!(
service.journal.read(&session).await.expect("journal"),
entries,
- "the failed load discards nothing captured"
+ "the load discards nothing captured"
+ );
+ service
+ .prompt(&session, "still reachable after the gap")
+ .await
+ .expect_err("no stream is scripted, but the prompt is not refused as unloaded");
+}
+
+/// The gap the load survives is closed when Cursor's conversation names the
+/// prompt. The mirrored run's answer is matched against the conversation and
+/// the line before it is journaled as that run's prompt, so it projects into
+/// place and the next load needs no lookup.
+#[tokio::test(start_paused = true)]
+async fn a_lost_prompt_is_recovered_from_the_cursor_conversation() {
+ let (service, cursor, notifier) = service(None);
+ let session = service.new_session(Path::new(""), Vec::new());
+ let events = cursor.script_stream();
+ events.send(finished("run-fake-1")).expect("stream open");
+ events.send(CursorEvent::Done).expect("stream open");
+ service.prompt(&session, "first").await.expect("first turn");
+
+ cursor.script_run_listings(vec![
+ RunListing {
+ id: CursorRunId::new("run-foreign-1"),
+ status: RunStatus::Finished,
+ },
+ RunListing {
+ id: CursorRunId::new("run-fake-1"),
+ status: RunStatus::Finished,
+ },
+ ]);
+ cursor.script_run_result(RunOutcome {
+ status: RunStatus::Finished,
+ text: Some("the old answer".to_owned()),
+ });
+ service.sync_foreign_runs().await;
+
+ cursor.script_conversation(vec![
+ line(ConversationSpeaker::User, "what was asked on cursor.com"),
+ line(ConversationSpeaker::Agent, "the old answer"),
+ ]);
+ service
+ .replay_session(&session)
+ .await
+ .expect("load")
+ .complete();
+
+ let entries = service.journal.read(&session).await.expect("journal");
+ let foreign = CursorRunId::new("run-foreign-1");
+ let recovered = entries
+ .iter()
+ .find_map(|e| match &e.input {
+ JournalInput::Prompt(blocks) if e.run.is_none() => blocks.iter().find_map(|b| {
+ matches!(b, ContentBlock::Text(t) if t.text == "what was asked on cursor.com")
+ .then_some(e.sequence)
+ }),
+ _ => None,
+ })
+ .expect("the recovered prompt is journaled");
+ assert!(
+ entries.iter().any(|e| e.run.as_ref() == Some(&foreign)
+ && e.input == JournalInput::PromptAccepted(recovered)),
+ "and is linked to the run it opened"
+ );
+ assert!(
+ notifier.updates().iter().any(|(_, update)| matches!(
+ update,
+ SessionUpdate::UserMessageChunk(c)
+ if matches!(&c.content, ContentBlock::Text(t) if t.text == "what was asked on cursor.com")
+ )),
+ "the load publishes it as part of the transcript"
);
+ assert!(ready_for_sync(&service, &session));
+}
+
+/// An answer the agent gave more than once names no single turn, so nothing
+/// is attached. A wrong question against a real answer is worse than none.
+#[tokio::test(start_paused = true)]
+async fn an_ambiguous_conversation_match_recovers_nothing() {
+ let (service, cursor, _notifier) = service(None);
+ let session = service.new_session(Path::new(""), Vec::new());
+ let events = cursor.script_stream();
+ events.send(finished("run-fake-1")).expect("stream open");
+ events.send(CursorEvent::Done).expect("stream open");
+ service.prompt(&session, "first").await.expect("first turn");
+
+ cursor.script_run_listings(vec![
+ RunListing {
+ id: CursorRunId::new("run-foreign-1"),
+ status: RunStatus::Finished,
+ },
+ RunListing {
+ id: CursorRunId::new("run-fake-1"),
+ status: RunStatus::Finished,
+ },
+ ]);
+ cursor.script_run_result(RunOutcome {
+ status: RunStatus::Finished,
+ text: Some("done".to_owned()),
+ });
+ service.sync_foreign_runs().await;
+
+ cursor.script_conversation(vec![
+ line(ConversationSpeaker::User, "first way of asking"),
+ line(ConversationSpeaker::Agent, "done"),
+ line(ConversationSpeaker::User, "second way of asking"),
+ line(ConversationSpeaker::Agent, "done"),
+ ]);
+ service
+ .replay_session(&session)
+ .await
+ .expect("the load still succeeds without the prompt")
+ .complete();
+
+ let entries = service.journal.read(&session).await.expect("journal");
+ assert!(
+ !entries.iter().any(|e| matches!(&e.input, JournalInput::Prompt(blocks)
+ if blocks.iter().any(|b| matches!(b, ContentBlock::Text(t) if t.text.contains("way of asking"))))),
+ "neither candidate is guessed at"
+ );
+ assert!(ready_for_sync(&service, &session));
}
/// A run that is still executing cannot become the watermark when its stream
diff --git a/crates/cursor_cloud_agents/src/testing.rs b/crates/cursor_cloud_agents/src/testing.rs
index f349dc8214..08d6c9c39e 100644
--- a/crates/cursor_cloud_agents/src/testing.rs
+++ b/crates/cursor_cloud_agents/src/testing.rs
@@ -3,8 +3,8 @@
use crate::domain::event::CursorEvent;
use crate::domain::journal::NativeRecord;
use crate::domain::model::{
- CursorAgentId, CursorModel, CursorRunId, McpServer, ModelChoice, RepoUrl, RunListing,
- RunOutcome,
+ ConversationLine, CursorAgentId, CursorModel, CursorRunId, McpServer, ModelChoice, RepoUrl,
+ RunListing, RunOutcome,
};
use crate::domain::ports::{
ConnectedStream, CursorAgents, RepositoryChooser, RunStream, SessionIntent, SessionNotifier,
@@ -156,6 +156,8 @@ pub enum CursorCall {
CancelRun(CursorAgentId, CursorRunId),
/// `run_result(agent, run)`.
RunResult(CursorAgentId, CursorRunId),
+ /// `conversation(agent)`.
+ Conversation(CursorAgentId),
}
/// A scripted Cursor: hands out ids, records calls, and streams whatever the
@@ -180,6 +182,7 @@ struct FakeCursorState {
run_results: Vec<RunOutcome>,
/// The answer every `list_runs` call gets.
run_listings: Vec<RunListing>,
+ conversation: Vec<ConversationLine>,
/// 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.
@@ -308,6 +311,15 @@ impl FakeCursor {
self.inner.lock().expect("fake cursor poisoned").models = models;
}
+ /// Set the agent's run history, newest first, for `list_runs`.
+ /// What `conversation()` answers with.
+ pub fn script_conversation(&self, lines: Vec<ConversationLine>) {
+ self.inner
+ .lock()
+ .expect("fake cursor poisoned")
+ .conversation = lines;
+ }
+
/// Set the agent's run history, newest first, for `list_runs`.
pub fn script_run_listings(&self, listings: Vec<RunListing>) {
self.inner
@@ -490,6 +502,19 @@ impl CursorAgents for FakeCursor {
.run_listings
.clone())
}
+
+ async fn conversation(
+ &self,
+ agent: &CursorAgentId,
+ ) -> Result<Vec<ConversationLine>, rootcause::Report> {
+ self.record(CursorCall::Conversation(agent.clone()));
+ Ok(self
+ .inner
+ .lock()
+ .expect("fake cursor poisoned")
+ .conversation
+ .clone())
+ }
}
/// What one scripted `raw_stream()` call answers with.