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): survive a branch Cursor could not verify without losing the conversation (#6584)
Wolf Mermelstein65083c6d66d1
diff --git a/crates/cursor_cloud_agents/src/api.rs b/crates/cursor_cloud_agents/src/api.rsindex 3ea87dd03d..523ad4732b 100644--- a/crates/cursor_cloud_agents/src/api.rs+++ b/crates/cursor_cloud_agents/src/api.rs@@ -176,22 +176,58 @@ pub enum CursorClientError {/// remedy is the same connect flow, which is why both map to one error.////// Deliberately excluded: `repository_required` (the request sent no repo, a-/// bug here, not the user's), `validation_error` (a malformed url is ours to-/// fix), and `unauthorized`/`plan_required` (about the key, not the repo).+/// bug here, not the user's), `validation_error` in general (a malformed url+/// is ours to fix; the one branch-verification wording is matched separately+/// by [`classify_repository_rejection`]), and `unauthorized`/`plan_required`+/// (about the key, not the repo).const REPOSITORY_ACCESS_CODES: [&str; 2] = ["repository_access", "integration_not_connected"];-/// Whether a create-agent failure means Cursor cannot reach the repository.+/// The wording Cursor uses when its GitHub-side check could not confirm the+/// starting ref. Filed under the generic `validation_error` code, so the+/// message is the only handle. Seen in production for a `main` that existed,+/// and reported on Cursor's forum as intermittent for unchanged inputs.+const BRANCH_UNVERIFIABLE_MESSAGE: &str = "Failed to verify existence of branch";++/// How long to wait before each retry of a create that Cursor answered with+/// [`BRANCH_UNVERIFIABLE_MESSAGE`]; its length is the retry budget.+///+/// Retrying is safe here and nowhere else in create: the 400 proves no agent+/// was minted, so a second POST cannot duplicate work on cursor.com. Two+/// retries and ~7s is enough to ride out a flake without holding a chat+/// turn open for long when the repository genuinely is not visible.+const BRANCH_UNVERIFIABLE_RETRY_BACKOFF: [std::time::Duration; 2] = [+ std::time::Duration::from_secs(2),+ std::time::Duration::from_secs(5),+];++/// Which repository refusal, if any, a create-agent failure is.///-/// Matches only the documented envelope, `{"error": {"code": "…"}}`, and only-/// on a 4xx: an unrecognized body — a different code, a proxy's HTML, a 5xx —-/// is left to the generic path so a new failure mode is never mislabelled as-/// a repository the user must go connect.-fn repository_is_inaccessible(status: reqwest::StatusCode, body: &str) -> bool {+/// Matches only the documented envelope, `{"error": {"code", "message"}}`,+/// and only on a 4xx: an unrecognized body — a different code, a proxy's+/// HTML, a 5xx — is left to the generic path so a new failure mode is never+/// mislabelled as a repository the user must go connect.+fn classify_repository_rejection(+ status: reqwest::StatusCode,+ body: &str,+ starting_ref: &str,+) -> Option<crate::domain::error::RepositoryRejection> {+ use crate::domain::error::RepositoryRejection;+if !status.is_client_error() || status == reqwest::StatusCode::REQUEST_TIMEOUT {- return false;+ return None;}- serde_json::from_str::<crate::api::wire::ApiErrorEnvelope>(body)- .is_ok_and(|envelope| REPOSITORY_ACCESS_CODES.contains(&envelope.error.code.as_str()))+ let envelope = serde_json::from_str::<crate::api::wire::ApiErrorEnvelope>(body).ok()?;+ if REPOSITORY_ACCESS_CODES.contains(&envelope.error.code.as_str()) {+ return Some(RepositoryRejection::Inaccessible);+ }+ if envelope.error.code == "validation_error"+ && envelope.error.message.contains(BRANCH_UNVERIFIABLE_MESSAGE)+ {+ return Some(RepositoryRejection::BranchUnverifiable {+ starting_ref: starting_ref.to_owned(),+ });+ }+ None}/// The Cursor cloud API client.@@ -199,6 +235,10 @@ fn repository_is_inaccessible(status: reqwest::StatusCode, body: &str) -> bool {pub struct CursorClient {http: reqwest::Client,config: CursorConfig,+ /// Delays before each retry of a branch-unverifiable create; see+ /// [`BRANCH_UNVERIFIABLE_RETRY_BACKOFF`]. Overridable so a test can+ /// exercise the retry without sleeping through the production schedule.+ branch_retry_backoff: Vec<std::time::Duration>,}impl CursorClient {@@ -222,7 +262,19 @@ impl CursorClient {let http = reqwest::Client::builder().connect_timeout(std::time::Duration::from_secs(10)).build()?;- Ok(Self { http, config })+ Ok(Self {+ http,+ config,+ branch_retry_backoff: BRANCH_UNVERIFIABLE_RETRY_BACKOFF.to_vec(),+ })+ }++ /// Replace the retry schedule for branch-unverifiable creates. An empty+ /// schedule disables the retry.+ #[must_use]+ pub fn with_branch_retry_backoff(mut self, backoff: Vec<std::time::Duration>) -> Self {+ self.branch_retry_backoff = backoff;+ self}fn url(&self, path: &str) -> String {@@ -492,18 +544,41 @@ impl CursorAgents for CursorClient {// whatever the caller asked for.auto_create_pr: open_pull_request && repo.is_some(),};- let (status, text) = self.post_for_text("/v1/agents", &request).await?;- if let Some(repo) = repo- && repository_is_inaccessible(status, &text)- {+ let mut retries = self.branch_retry_backoff.iter();+ let (status, text) = loop {+ let (status, text) = self.post_for_text("/v1/agents", &request).await?;+ let Some(repo) = repo else {+ break (status, text);+ };+ let Some(reason) =+ classify_repository_rejection(status, &text, &self.config.starting_ref)+ else {+ break (status, text);+ };+ if matches!(+ reason,+ crate::domain::error::RepositoryRejection::BranchUnverifiable { .. }+ ) && let Some(delay) = retries.next()+ {+ tracing::warn!(+ repo = %repo,+ starting_ref = %self.config.starting_ref,+ retry_in_ms = delay.as_millis() as u64,+ detail = %text,+ "cursor could not verify the starting ref; retrying the create"+ );+ tokio::time::sleep(*delay).await;+ continue;+ }return Err(rootcause::report!(crate::domain::error::RepositoryUnavailable {repo: repo.clone(),+ reason,detail: text,}).into_dynamic(),);- }+ };let reply: CreateAgentResponse = Self::decode_post("/v1/agents", status, &text)?;tracing::info!(agent = %reply.agent.id, url = %reply.agent.url, "cursor agent created");Ok((diff --git a/crates/cursor_cloud_agents/src/api/test.rs b/crates/cursor_cloud_agents/src/api/test.rsindex 23e99cc391..ec2e6a5cbb 100644--- a/crates/cursor_cloud_agents/src/api/test.rs+++ b/crates/cursor_cloud_agents/src/api/test.rs@@ -80,52 +80,74 @@ fn stand_in_server(status_line: &str, body: &'static str) -> String {fn stand_in_server_capturing(status_line: &str,body: &'static str,+) -> (String, std::sync::mpsc::Receiver<String>) {+ stand_in_server_sequence(vec![(status_line.to_owned(), body)])+}++/// A stand-in that answers one request per scripted response, in order, then+/// stops listening. Each connection is closed after its answer, so a client+/// that retries has to reconnect — the same as it would against Cursor.+fn stand_in_server_sequence(+ responses: Vec<(String, &'static str)>,) -> (String, std::sync::mpsc::Receiver<String>) {let (sender, receiver) = std::sync::mpsc::channel();let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a loopback port");let base_url = format!("http://{}", listener.local_addr().expect("a bound address"));- let response = format!(- "HTTP/1.1 {status_line}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",- body.len()- );std::thread::spawn(move || {use std::io::{Read as _, Write as _};- let (mut socket, _) = listener.accept().expect("the client connects");- // Drain the request before answering: a peer that never reads the- // body can leave the client seeing a reset instead of the response.- let mut request = Vec::new();- let mut chunk = [0_u8; 4096];- while !request.windows(4).any(|window| window == b"\r\n\r\n") {- match socket.read(&mut chunk) {- Ok(0) | Err(_) => break,- Ok(read) => request.extend_from_slice(&chunk[..read]),+ for (status_line, body) in responses {+ let response = format!(+ "HTTP/1.1 {status_line}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",+ body.len()+ );+ let (mut socket, _) = listener.accept().expect("the client connects");+ // Drain the request before answering: a peer that never reads the+ // body can leave the client seeing a reset instead of the response.+ let mut request = Vec::new();+ let mut chunk = [0_u8; 4096];+ while !request.windows(4).any(|window| window == b"\r\n\r\n") {+ match socket.read(&mut chunk) {+ Ok(0) | Err(_) => break,+ Ok(read) => request.extend_from_slice(&chunk[..read]),+ }}- }- let headers = String::from_utf8_lossy(&request).to_lowercase();- let content_length = headers- .split("content-length:")- .nth(1)- .and_then(|rest| rest.split("\r\n").next())- .and_then(|value| value.trim().parse::<usize>().ok())- .unwrap_or(0);- let already_read = request- .windows(4)- .position(|window| window == b"\r\n\r\n")- .map_or(0, |end| request.len() - (end + 4));- let mut remaining = content_length.saturating_sub(already_read);- while remaining > 0 {- match socket.read(&mut chunk) {- Ok(0) | Err(_) => break,- Ok(read) => remaining = remaining.saturating_sub(read),+ let headers = String::from_utf8_lossy(&request).to_lowercase();+ let content_length = headers+ .split("content-length:")+ .nth(1)+ .and_then(|rest| rest.split("\r\n").next())+ .and_then(|value| value.trim().parse::<usize>().ok())+ .unwrap_or(0);+ let already_read = request+ .windows(4)+ .position(|window| window == b"\r\n\r\n")+ .map_or(0, |end| request.len() - (end + 4));+ let mut remaining = content_length.saturating_sub(already_read);+ while remaining > 0 {+ match socket.read(&mut chunk) {+ Ok(0) | Err(_) => break,+ Ok(read) => remaining = remaining.saturating_sub(read),+ }}+ let _ = sender.send(String::from_utf8_lossy(&request).into_owned());+ let _ = socket.write_all(response.as_bytes());+ let _ = socket.flush();}- let _ = sender.send(String::from_utf8_lossy(&request).into_owned());- let _ = socket.write_all(response.as_bytes());- let _ = socket.flush();});(base_url, receiver)}+/// The body Cursor answered a real create with, for a `main` that existed.+const BRANCH_UNVERIFIABLE_BODY: &str = r#"{"error":{"code":"validation_error","message":"Failed to verify existence of branch 'main' in repository macro-inc/macro. Please ensure the branch name is correct."}}"#;++const CREATED_BODY: &str = r#"{"agent":{"id":"bc-00000000-0000-0000-0000-000000000001","url":"https://cursor.com/agents/bc-00000000-0000-0000-0000-000000000001"},"run":{"id":"run-00000000-0000-0000-0000-000000000001"}}"#;++/// A client whose retry schedule does not sleep, so the retry path runs in+/// test time rather than the production seven seconds.+fn client_with_instant_retries(base_url: String, retries: usize) -> CursorClient {+ client_against(base_url).with_branch_retry_backoff(vec![std::time::Duration::ZERO; retries])+}+fn client_against(base_url: String) -> CursorClient {CursorClient::new(CursorConfig {base_url,@@ -154,11 +176,106 @@ async fn a_repository_rejection_is_typed_with_the_repository() {.downcast_current_context::<crate::domain::error::RepositoryUnavailable>().expect("a repository rejection is typed as one");assert_eq!(unavailable.repo, repo());+ assert_eq!(+ unavailable.reason,+ crate::domain::error::RepositoryRejection::Inaccessible+ );assert!(unavailable.detail.contains("repository_access"),"cursor's own body is kept for the logs: {}",unavailable.detail);+ assert!(+ unavailable+ .user_message()+ .contains("Connect the repository"),+ "got {}",+ unavailable.user_message()+ );+}++/// Cursor's branch check flakes for refs that exist, and a 400 proves no+/// agent was minted, so the create is simply asked again — and the caller+/// sees only the eventual success.+#[tokio::test]+async fn a_branch_cursor_could_not_verify_is_retried() {+ let (base_url, requests) = stand_in_server_sequence(vec![+ ("400 Bad Request".to_owned(), BRANCH_UNVERIFIABLE_BODY),+ ("400 Bad Request".to_owned(), BRANCH_UNVERIFIABLE_BODY),+ ("200 OK".to_owned(), CREATED_BODY),+ ]);+ let (agent, run) = client_with_instant_retries(base_url, 2)+ .create_agent("prompt", Some(&repo()), true, &[], None)+ .await+ .expect("the third answer is a created agent");+ assert_eq!(agent.as_str(), "bc-00000000-0000-0000-0000-000000000001");+ assert_eq!(run.as_str(), "run-00000000-0000-0000-0000-000000000001");++ let sent: Vec<String> = requests.try_iter().collect();+ assert_eq!(sent.len(), 3, "one request per scripted answer");+ for request in &sent {+ assert!(+ request.contains(r#""startingRef":"main""#),+ "every attempt asks for the same ref: {request}"+ );+ }+}++/// Once the budget is spent the rejection is still typed as a repository+/// problem — and names the branch, so the message does not read like a+/// generic internal error — rather than the raw report.+#[tokio::test]+async fn a_branch_still_unverifiable_after_retrying_is_typed_with_the_branch() {+ let (base_url, requests) = stand_in_server_sequence(vec![+ ("400 Bad Request".to_owned(), BRANCH_UNVERIFIABLE_BODY),+ ("400 Bad Request".to_owned(), BRANCH_UNVERIFIABLE_BODY),+ ]);+ let error = client_with_instant_retries(base_url, 1)+ .create_agent("prompt", Some(&repo()), true, &[], None)+ .await+ .expect_err("the stand-in never relents");+ let unavailable = error+ .downcast_current_context::<crate::domain::error::RepositoryUnavailable>()+ .expect("an exhausted branch retry is a repository rejection");+ assert_eq!(unavailable.repo, repo());+ assert_eq!(+ unavailable.reason,+ crate::domain::error::RepositoryRejection::BranchUnverifiable {+ starting_ref: "main".to_owned(),+ }+ );+ let message = unavailable.user_message();+ assert!(message.contains("'main'"), "names the ref: {message}");+ assert!(+ message.contains("macro-inc/macro"),+ "names the repo: {message}"+ );+ assert!(+ !message.contains("Bad Request") && !message.contains("api.rs"),+ "no transport or source decorations reach the user: {message}"+ );+ assert_eq!(requests.try_iter().count(), 2, "one retry, then give up");+}++/// The retry exists for one wording only. A `validation_error` about anything+/// else is not asked again — a malformed model id will not fix itself.+#[tokio::test]+async fn other_validation_errors_are_not_retried() {+ let (base_url, requests) = stand_in_server_sequence(vec![(+ "400 Bad Request".to_owned(),+ r#"{"error":{"code":"validation_error","message":"Model 'nope' does not match a known variant"}}"#,+ )]);+ let error = client_with_instant_retries(base_url, 2)+ .create_agent("prompt", Some(&repo()), true, &[], None)+ .await+ .expect_err("the stand-in rejects the create");+ assert!(+ error+ .downcast_current_context::<crate::domain::error::PromptRejected>()+ .is_some(),+ "still a plain rejection"+ );+ assert_eq!(requests.try_iter().count(), 1, "asked exactly once");}/// Every other 4xx must keep behaving exactly as it did — a genericdiff --git a/crates/cursor_cloud_agents/src/api/wire.rs b/crates/cursor_cloud_agents/src/api/wire.rsindex 263125827d..624eb41dd0 100644--- a/crates/cursor_cloud_agents/src/api/wire.rs+++ b/crates/cursor_cloud_agents/src/api/wire.rs@@ -338,22 +338,28 @@ impl CreateRunResponse {}}-/// The envelope Cursor wraps an error status in: `{"error": {"code", …}}`.+/// The envelope Cursor wraps an error status in: `{"error": {"code", "message"}}`.///-/// Only `code` is modelled. The human half of the body is Cursor's wording of-/// the same fact, and this crate has its own wording for the one case it acts-/// on; everything else keeps the raw body instead.+/// `message` is read as well as `code` because Cursor files more than one+/// distinct failure under `validation_error`, and the wording is the only+/// thing that tells a branch it could not verify apart from a malformed+/// model id. This crate still has its own wording for the cases it acts on;+/// everything else keeps the raw body instead.#[derive(Debug, Deserialize)]pub struct ApiErrorEnvelope {/// The error itself.pub error: ApiErrorCode,}-/// The machine-readable half of an error body.+/// The two halves of an error body.#[derive(Debug, Deserialize)]pub struct ApiErrorCode {/// Cursor's error code, e.g. `repository_access`.pub code: String,+ /// Cursor's human-readable wording. Defaulted so a body with only a code+ /// still classifies by it.+ #[serde(default)]+ pub message: String,}/// `GET /v1/agents/{id}/artifacts` response.diff --git a/crates/cursor_cloud_agents/src/domain/error.rs b/crates/cursor_cloud_agents/src/domain/error.rsindex 2df7d679c0..ddd93aa0b5 100644--- a/crates/cursor_cloud_agents/src/domain/error.rs+++ b/crates/cursor_cloud_agents/src/domain/error.rs@@ -40,21 +40,55 @@ impl From<rootcause::Report> for SessionError {#[error("{0}")]pub struct PromptRejected(pub String);-/// A prompt rejected specifically because Cursor cannot reach the session's-/// repository — the account has not connected it to Cursor's GitHub app.+/// A prompt rejected specifically because Cursor could not use the session's+/// repository.////// A distinct context because it is the one rejection the user can act on,/// and acting on it happens outside Macro. `detail` keeps Cursor's own body/// for the logs; [`Self::user_message`] is what a person should read.#[derive(Debug, Error)]-#[error("cursor cannot access {repo}: {detail}")]+#[error("cursor cannot use {repo} ({reason}): {detail}")]pub struct RepositoryUnavailable {/// The repository the session asked Cursor to work in.pub repo: RepoUrl,+ /// Which of Cursor's refusals this was.+ pub reason: RepositoryRejection,/// Cursor's own error body, verbatim.pub detail: String,}+/// The ways Cursor has refused a repository, as seen in production.+///+/// Each maps to a different sentence for the user: an inaccessible repository+/// wants the GitHub app connected, while a branch Cursor could not verify is+/// usually Cursor's own verification flaking — the ref exists — so the+/// message must not send the user off to rename a branch that is fine.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum RepositoryRejection {+ /// `repository_access` / `integration_not_connected`: the account cannot+ /// reach the repository at all.+ Inaccessible,+ /// `validation_error` "Failed to verify existence of branch …": Cursor's+ /// GitHub-side check could not confirm the starting ref. Observed to be+ /// intermittent for refs that exist, so the client retries it before+ /// surfacing it.+ BranchUnverifiable {+ /// The ref the request asked to start from.+ starting_ref: String,+ },+}++impl std::fmt::Display for RepositoryRejection {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Inaccessible => formatter.write_str("inaccessible"),+ Self::BranchUnverifiable { starting_ref } => {+ write!(formatter, "could not verify branch {starting_ref}")+ }+ }+ }+}+impl RepositoryUnavailable {/// What to show the person who sent the prompt.#[must_use]@@ -63,8 +97,15 @@ impl RepositoryUnavailable {.repo.github_owner_and_name().unwrap_or_else(|| self.repo.as_str());- format!(- "Cursor can't access {repo}. Connect the repository to Cursor's GitHub app, then prompt again."- )+ match &self.reason {+ RepositoryRejection::Inaccessible => format!(+ "Cursor can't access {repo}. Connect the repository to Cursor's GitHub app, then prompt again."+ ),+ RepositoryRejection::BranchUnverifiable { starting_ref } => format!(+ "Cursor couldn't verify that branch '{starting_ref}' exists in {repo}, even after retrying. \+ This is usually transient on Cursor's side; prompt again in a moment. \+ If it keeps happening, check that {repo} is connected to Cursor's GitHub app."+ ),+ }}}diff --git a/crates/cursor_cloud_agents/src/domain/service.rs b/crates/cursor_cloud_agents/src/domain/service.rsindex 465afd08d2..e2a83772e9 100644--- a/crates/cursor_cloud_agents/src/domain/service.rs+++ b/crates/cursor_cloud_agents/src/domain/service.rs@@ -47,8 +47,8 @@ use crate::domain::model::{ModelChoice, RepoUrl, RunStatus,};use crate::domain::ports::{- ArtifactStore, CursorAgents, CursorArtifacts, RepositoryChooser, RunStream, SessionNotifier,- StreamConnectError,+ ArtifactStore, CursorAgents, CursorArtifacts, RepositoryChooser, RunStream, SessionIntent,+ SessionNotifier, StreamConnectError,};use agent_client_protocol::schema::v1::{ContentBlock, SessionId, SessionUpdate, StopReason, TextContent,@@ -199,8 +199,9 @@ fn explain_repository_rejection(error: SessionError) -> SessionError {};tracing::warn!(repo = %unavailable.repo,+ reason = %unavailable.reason,detail = %unavailable.detail,- "cursor rejected the prompt: the repository is not connected to this cursor account"+ "cursor rejected the prompt: it could not use the session's repository");SessionError::Rejected(unavailable.user_message())}@@ -217,6 +218,45 @@ fn is_prompt_rejection(error: &SessionError) -> bool {}}+/// A prompt Cursor refused before the session had an agent, and why.+#[derive(Debug, Clone, PartialEq, Eq)]+struct RejectedPrompt {+ /// What the person asked, as it would have gone to Cursor.+ text: String,+ /// The refusal as it was shown to them, when there was a readable one.+ reason: Option<String>,+}++/// The prompt that finally mints an agent, carrying the ones Cursor refused+/// before it so the agent reads the whole conversation the person had.+///+/// Plain text rather than structure because that is all `create_agent`+/// takes; the framing tells the agent which message is current and that the+/// earlier ones were never acted on, so it neither re-does nor ignores them.+fn prompt_with_rejected(rejected: &[RejectedPrompt], prompt: &str) -> String {+ if rejected.is_empty() {+ return prompt.to_owned();+ }+ let mut text = String::from(+ "The following earlier message(s) in this conversation never reached an agent: \+ each attempt to start one was refused by Cursor. They are included so nothing the \+ person asked is lost. The message under \"Latest message\" is the one to respond to.\n",+ );+ for earlier in rejected {+ text.push_str("\n--- Earlier message ---\n");+ text.push_str(&earlier.text);+ if let Some(reason) = &earlier.reason {+ text.push_str("\n(Refused with: ");+ text.push_str(reason);+ text.push(')');+ }+ text.push('\n');+ }+ text.push_str("\n--- Latest message ---\n");+ text.push_str(prompt);+ text+}+/// One session's mutable state. Guarded by a std mutex: every critical/// section is a handful of field reads/writes, never an await.#[derive(Debug, Default)]@@ -228,6 +268,23 @@ struct SessionState {/// prompt chose. Still needed after the agent exists - Cursor fixed the/// repository at creation, and a restore has to hand the same one back.repo: Option<RepoUrl>,+ /// The first prompt's repository decision, kept until an agent exists.+ ///+ /// Cursor can reject the create that follows the decision — a branch it+ /// could not verify, a repository the account has not connected — and the+ /// next prompt is then usually "what happened?", which is no evidence of+ /// where the work belongs. So the decision is made once, on the prompt+ /// that carried the evidence, and reused by every create attempt until+ /// one succeeds. Cleared with the process: a restored session re-decides.+ intent: Option<SessionIntent>,+ /// Prompts Cursor refused before any agent existed, oldest first.+ ///+ /// A refused prompt is journaled as aborted and never reaches Cursor; if+ /// the next one alone minted the agent, the agent would answer a question+ /// about a message it never saw. So they ride along with the prompt that+ /// finally creates it. Cancelled prompts are deliberately not here — the+ /// person withdrew those. Cleared once a prompt is accepted.+ rejected_prompts: Vec<RejectedPrompt>,/// The Cursor agent, once the first prompt has minted it.agent: Option<CursorAgentId>,/// The run currently streaming, so cancel knows what to cancel.@@ -706,6 +763,7 @@ wherereturn Ok(StopReason::Cancelled);}+ let creating_agent = prior_agent.is_none();let created = match prior_agent {Some(agent) => {// Queue behind any run still going (the same agent advances@@ -717,20 +775,38 @@ whereNone => {// Snapshotted out of the lock: `create_agent` is a network// call, and the state mutex must never be held across an await.- let mcp_servers = session- .state- .lock()- .expect("session state poisoned")- .mcp_servers- .clone();+ let (mcp_servers, decided, rejected) = {+ let state = session.state.lock().expect("session state poisoned");+ (+ state.mcp_servers.clone(),+ state.intent.clone(),+ state.rejected_prompts.clone(),+ )+ };// The first prompt is the only evidence there is for which// repository this session belongs to, and Cursor fixes an// agent's repository at creation - so the decision is made- // here, before the agent exists, and never revisited.- match self.chooser.choose(prompt, &session.cwd).await {+ // here, before the agent exists, and never revisited: a+ // create Cursor refused leaves the decision standing for the+ // next attempt rather than re-reading a prompt that is now+ // about the refusal.+ let intent = match decided {+ Some(intent) => {+ tracing::info!(+ repo = ?intent.repository.as_ref().map(RepoUrl::as_str),+ "reusing the repository decided by this session's first prompt"+ );+ Ok(intent)+ }+ None => self.chooser.choose(prompt, &session.cwd).await,+ };+ match intent {Ok(intent) => {- session.state.lock().expect("session state poisoned").repo =- intent.repository.clone();+ {+ let mut state = session.state.lock().expect("session state poisoned");+ state.repo = intent.repository.clone();+ state.intent = Some(intent.clone());+ }if intent.repository.is_none() {tracing::warn!("no repository chosen - this session will not appear in the Cursor sessions list"@@ -738,7 +814,7 @@ where}self.cursor.create_agent(- prompt,+ &prompt_with_rejected(&rejected, prompt),intent.repository.as_ref(),intent.open_pull_request,&mcp_servers,@@ -776,6 +852,24 @@ whereif cancel.is_cancelled() {return Ok(StopReason::Cancelled);}+ // Only a create's refusal is carried: a follow-up run+ // refused on an existing agent is already in a conversation+ // the agent can see.+ if creating_agent {+ let reason = match &error {+ SessionError::Rejected(message) => Some(message.clone()),+ _ => None,+ };+ session+ .state+ .lock()+ .expect("session state poisoned")+ .rejected_prompts+ .push(RejectedPrompt {+ text: prompt.to_owned(),+ reason,+ });+ }}return Err(error);}@@ -788,7 +882,11 @@ wherefalse,).await?;- session.state.lock().expect("session state poisoned").agent = Some(agent.clone());+ {+ let mut state = session.state.lock().expect("session state poisoned");+ state.agent = Some(agent.clone());+ state.rejected_prompts.clear();+ }// 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))diff --git a/crates/cursor_cloud_agents/src/domain/service/test.rs b/crates/cursor_cloud_agents/src/domain/service/test.rsindex 8cc08614f7..7d5ced20f9 100644--- a/crates/cursor_cloud_agents/src/domain/service/test.rs+++ b/crates/cursor_cloud_agents/src/domain/service/test.rs@@ -2700,6 +2700,110 @@ async fn an_unconnected_repository_reaches_the_client_as_an_instruction() {);}+/// After Cursor refuses the first create, the next prompt is almost always+/// about the refusal ("what's the error?"), which is no evidence of where+/// the work belongs. The repository decided from the first prompt has to+/// stand, and the agent that finally starts has to see the message that+/// was refused, or it is asked about a conversation it never had.+#[tokio::test]+async fn a_refused_create_keeps_its_repository_and_carries_the_prompt_forward() {+ struct CountingChooser(RepoUrl, Arc<std::sync::atomic::AtomicUsize>);+ impl RepositoryChooser for CountingChooser {+ async fn choose(+ &self,+ _: &str,+ _: &std::path::Path,+ ) -> Result<SessionIntent, rootcause::Report> {+ self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ Ok(SessionIntent {+ repository: Some(self.0.clone()),+ open_pull_request: true,+ })+ }+ }++ let repo = RepoUrl::parse("https://github.com/macro-inc/macro").expect("an https remote");+ let cursor = FakeCursor::new();+ let choices = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let service = Arc::new(CursorSessionService::new(+ cursor.clone(),+ RecordingNotifier::new(),+ CountingChooser(repo.clone(), choices.clone()),+ Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),+ NoArtifactStore,+ ));+ let id = service.new_session(Path::new(""), vec![]);++ cursor.script_repository_rejection();+ let refusal = service+ .prompt(&id, "fix the notification grouping bug")+ .await+ .expect_err("the first create is refused");++ let events = cursor.script_stream();+ events.send(finished("run-fake-1")).expect("stream open");+ events.send(CursorEvent::Done).expect("stream open");+ service+ .prompt(&id, "what's the error?")+ .await+ .expect("the second create succeeds");++ assert_eq!(+ choices.load(std::sync::atomic::Ordering::SeqCst),+ 1,+ "the repository is decided once, on the prompt that carried the evidence"+ );+ let creates: Vec<_> = cursor+ .calls()+ .into_iter()+ .filter_map(|call| match call {+ CursorCall::CreateAgent(prompt, repo, ..) => Some((prompt, repo)),+ _ => None,+ })+ .collect();+ assert_eq!(creates.len(), 2, "one refused create, one accepted");+ assert_eq!(creates[0].1.as_ref(), Some(&repo));+ assert_eq!(+ creates[1].1.as_ref(),+ Some(&repo),+ "the follow-up is created against the same repository"+ );+ assert_eq!(creates[0].0, "fix the notification grouping bug");+ let carried = &creates[1].0;+ assert!(+ carried.contains("fix the notification grouping bug"),+ "the refused prompt rides along: {carried}"+ );+ assert!(+ carried.contains(&refusal.to_string()),+ "and so does what the person was told: {carried}"+ );+ assert!(+ carried.ends_with("what's the error?"),+ "the current prompt is last, marked as the one to answer: {carried}"+ );++ // Once an agent exists nothing is carried any more: the conversation is+ // on cursor.com, and the next prompt is an ordinary follow-up run.+ let events = cursor.script_stream();+ events.send(finished("run-fake-2")).expect("stream open");+ events.send(CursorEvent::Done).expect("stream open");+ service+ .prompt(&id, "thanks")+ .await+ .expect("a follow-up run");+ let follow_up = cursor+ .calls()+ .into_iter()+ .rev()+ .find_map(|call| match call {+ CursorCall::CreateRun(_, prompt, ..) => Some(prompt),+ _ => None,+ })+ .expect("a run was created");+ assert_eq!(follow_up, "thanks");+}+#[tokio::test]async fn repository_setup_failure_is_retryable_and_not_reported_as_prompt_ambiguity() {struct UnavailableChooser;diff --git a/crates/cursor_cloud_agents/src/testing.rs b/crates/cursor_cloud_agents/src/testing.rsindex 58e7aea392..76ead55b6d 100644--- a/crates/cursor_cloud_agents/src/testing.rs+++ b/crates/cursor_cloud_agents/src/testing.rs@@ -473,6 +473,7 @@ impl CursorAgents for FakeCursor {return Err(rootcause::report!(crate::domain::error::RepositoryUnavailable {repo: repo.clone(),+ reason: crate::domain::error::RepositoryRejection::Inaccessible,detail: r#"{"error":{"code":"repository_access","message":"Repository not accessible"}}"#.into(),}