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.

49.0 KB
Raw Blame
use super::super::keys::ResolvedCursorConfig;
use super::*;
use crate::domain::model::AgentKind;
use crate::testing::helpers::egress::test_egress;
use agent_client_protocol::schema::v1::SessionId;
use agent_runtime_protocol::domain::ports::{Transport as _, TransportSender as _};
use agent_runtime_protocol::domain::schema::v0::{
    AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage,
};
use agent_session::domain::coding_preferences::CodingPreferences;
use agent_session::domain::error::Result as SessionResult;
use agent_session::domain::model::{
    AgentSession, CreateAgentSessionParams, DEFAULT_AGENT_SESSION_NAME, SandboxSize, SessionBot,
    SessionStatus, ThreadSession,
};
use bot_id::BotId;
use cursor_api_key::cipher::CursorApiKey;
use cursor_cloud_agents::domain::ports::NoArtifactStore;
use macro_user_id::user_id::MacroUserIdStr;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use std::sync::{Arc, Mutex};

/// In-memory sessions double: a real map for the external rows, a canned row
/// for the one session the test asks about, and loud failure for everything
/// the manager has no business calling.
#[derive(Clone, Default)]
struct StubSessions {
    repo_branch: Option<agent_session::domain::repository_branch::RepositoryBranch>,
    external: Arc<Mutex<HashMap<AgentSessionId, ExternalSession>>>,
    acp_session_id: Arc<Mutex<Option<String>>>,
    /// What the repository chooser wrote back, per session.
    repo_url: Arc<Mutex<HashMap<AgentSessionId, Option<String>>>>,
}

impl ExternalSessionRepo for StubSessions {
    async fn upsert(&self, id: AgentSessionId, external: ExternalSession) -> SessionResult<()> {
        self.external
            .lock()
            .expect("stub poisoned")
            .insert(id, external);
        Ok(())
    }

    async fn get(&self, id: AgentSessionId) -> SessionResult<Option<ExternalSession>> {
        Ok(self
            .external
            .lock()
            .expect("stub poisoned")
            .get(&id)
            .cloned())
    }

    async fn delete(&self, id: AgentSessionId) -> SessionResult<()> {
        self.external.lock().expect("stub poisoned").remove(&id);
        Ok(())
    }
}

impl AgentSessionRepo for StubSessions {
    async fn create(&self, _params: CreateAgentSessionParams) -> SessionResult<AgentSession> {
        unimplemented!("the manager never creates sessions")
    }

    async fn find_by_egress_token_hash(
        &self,
        _egress_token_hash: &str,
    ) -> SessionResult<Option<AgentSession>> {
        unimplemented!("the manager never looks sessions up by egress token")
    }

    async fn find(&self, _id: AgentSessionId) -> SessionResult<Option<AgentSession>> {
        unimplemented!("the manager never probes for a missing session")
    }

    async fn preview(
        &self,
        _viewer: &MacroUserIdStr<'static>,
        _ids: &[AgentSessionId],
    ) -> SessionResult<Vec<agent_session::domain::model::SessionPreviewCandidate>> {
        unimplemented!("the manager never previews sessions")
    }

    async fn get(&self, id: AgentSessionId) -> SessionResult<AgentSession> {
        Ok(AgentSession {
            origin: Default::default(),
            repo_branch: self.repo_branch.clone(),
            id,
            owner_id: model_owner::Owner::User(
                MacroUserIdStr::try_from("macro|[email protected]".to_owned())
                    .expect("valid user id"),
            ),
            thread_id: None,
            thread_parent: None,
            originating_message_id: None,
            bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),
            model: "auto".to_owned(),
            harness: "cursor".to_owned(),
            repo_url: self
                .repo_branch
                .as_ref()
                .map(|_| "https://github.com/macro-inc/macro".into()),
            pull_request_url: None,
            task_id: None,
            workspace: "/workspace".to_owned(),
            name: DEFAULT_AGENT_SESSION_NAME.to_owned(),
            archived: None,
            sandbox_size: SandboxSize::Default,
            instructions: None,
            mcp_servers: Default::default(),
            acp_session_id: self
                .acp_session_id
                .lock()
                .expect("stub poisoned")
                .clone()
                .map(SessionId::new),
            external: None,
            status: SessionStatus::NoMessages,
            created_at: chrono::Utc::now(),
            modified_at: chrono::Utc::now(),
            source: agent_session::domain::model::SessionSource::User,
            visibility: agent_session::domain::model::SessionVisibility::Listed,
        })
    }

    async fn find_for_thread(
        &self,
        _thread_id: Option<macro_uuid::Uuid>,
        _bot_id: Option<BotId>,
    ) -> SessionResult<ThreadSession> {
        unimplemented!("the manager never routes channel events")
    }

    async fn find_all_for_thread(
        &self,
        _thread_id: macro_uuid::Uuid,
    ) -> SessionResult<Vec<AgentSession>> {
        unimplemented!("the manager never lists thread sessions")
    }

    async fn recent_for_owner(
        &self,
        _owner: &MacroUserIdStr<'_>,
        _limit: std::num::NonZeroUsize,
    ) -> SessionResult<Vec<agent_session::domain::model::AgentSession>> {
        unimplemented!("the manager never summarizes an owner's recent sessions")
    }

    async fn session_bot(&self, _id: BotId) -> SessionResult<SessionBot> {
        unimplemented!("the manager never renders bots")
    }

    async fn set_acp_session_id(
        &self,
        _id: AgentSessionId,
        _acp_session_id: SessionId,
    ) -> SessionResult<()> {
        unimplemented!("persisting the acp session id is the session actor's job")
    }

    async fn set_model(&self, _id: AgentSessionId, _model: &str) -> SessionResult<()> {
        unimplemented!("the manager never sets models")
    }

    async fn set_origin(
        &self,
        _id: AgentSessionId,
        _source: agent_session::domain::model::SessionSource,
        _visibility: agent_session::domain::model::SessionVisibility,
    ) -> SessionResult<()> {
        unimplemented!("the manager never records origins")
    }

    async fn set_egress_token_hash(&self, _id: AgentSessionId, _hash: &str) -> SessionResult<()> {
        unimplemented!("this adapter does not rotate credentials")
    }

    async fn set_turn_prompter(
        &self,
        _id: AgentSessionId,
        _prompter: &agent_session::domain::model::TurnPrompter,
    ) -> SessionResult<()> {
        unimplemented!("this adapter does not dispatch turns")
    }

    async fn add_follower(
        &self,
        _id: AgentSessionId,
        _user: &macro_user_id::user_id::MacroUserIdStr<'static>,
    ) -> SessionResult<()> {
        unimplemented!("this adapter does not dispatch turns")
    }

    async fn turn_prompter(
        &self,
        _id: AgentSessionId,
    ) -> SessionResult<Option<agent_session::domain::model::TurnPrompter>> {
        unimplemented!("this adapter does not dispatch turns")
    }

    async fn set_repo_url(
        &self,
        id: AgentSessionId,
        repo_url: Option<String>,
    ) -> SessionResult<()> {
        self.repo_url
            .lock()
            .expect("stub poisoned")
            .insert(id, repo_url);
        Ok(())
    }

    async fn delete(&self, _id: AgentSessionId) -> SessionResult<()> {
        unimplemented!("deleting sessions is the harness service's job")
    }

    async fn set_name(&self, _id: AgentSessionId, _name: &str) -> SessionResult<()> {
        unimplemented!("naming sessions is the session actor's job")
    }

    async fn set_archived(&self, _id: AgentSessionId, _archived: bool) -> SessionResult<()> {
        unimplemented!("archiving sessions is the harness service's job")
    }

    async fn is_current_conversation_session(&self, _id: AgentSessionId) -> SessionResult<bool> {
        unimplemented!("archiving sessions is the harness service's job")
    }

    async fn set_name_if_default(&self, _id: AgentSessionId, _name: &str) -> SessionResult<bool> {
        unimplemented!("naming sessions is the session actor's job")
    }

    async fn generated_name(&self, _id: AgentSessionId) -> SessionResult<Option<String>> {
        unimplemented!("naming sessions is the session actor's job")
    }

    async fn replace_generated_name(
        &self,
        _id: AgentSessionId,
        _current: &str,
        _name: &str,
    ) -> SessionResult<bool> {
        unimplemented!("naming sessions is the session actor's job")
    }

    async fn set_sandbox_size(&self, _id: AgentSessionId, _size: SandboxSize) -> SessionResult<()> {
        unimplemented!("resizing is the harness service's job")
    }

    async fn user_sandbox_size(
        &self,
        _owner: &MacroUserIdStr<'static>,
    ) -> SessionResult<SandboxSize> {
        unimplemented!("resizing is the harness service's job")
    }

    async fn set_user_sandbox_size(
        &self,
        _owner: &MacroUserIdStr<'static>,
        _size: SandboxSize,
    ) -> SessionResult<()> {
        unimplemented!("resizing is the harness service's job")
    }

    async fn user_coding_preferences(
        &self,
        _owner: &MacroUserIdStr<'static>,
    ) -> SessionResult<CodingPreferences> {
        unimplemented!("coding preferences are read when a session opens")
    }

    async fn set_user_coding_preferences(
        &self,
        _owner: &MacroUserIdStr<'static>,
        _preferences: CodingPreferences,
    ) -> SessionResult<()> {
        unimplemented!("coding preferences are read when a session opens")
    }

    async fn list_queued_actions(
        &self,
        _id: AgentSessionId,
    ) -> SessionResult<Vec<agent_session::domain::model::StoredQueuedAction>> {
        unimplemented!("the manager never reads the queue")
    }

    async fn replace_queued_actions(
        &self,
        _id: AgentSessionId,
        _entries: &[agent_session::domain::model::StoredQueuedAction],
    ) -> SessionResult<()> {
        unimplemented!("the manager never writes the queue")
    }
}

/// A fake Cursor API: create/get/archive/stream, canned. Returns its base url,
/// the archive-call log, and the bodies of every `create_agent` POST — the
/// last being how a test sees which model a spawn asked for.
async fn fake_cursor_api() -> (
    String,
    Arc<Mutex<Vec<String>>>,
    Arc<Mutex<Vec<serde_json::Value>>>,
) {
    let archived = Arc::new(Mutex::new(Vec::<String>::new()));
    let archive_log = archived.clone();
    let created = Arc::new(Mutex::new(Vec::<serde_json::Value>::new()));
    let create_log = created.clone();
    let app = axum::Router::new()
        .route(
            "/v1/agents",
            axum::routing::post(move |axum::Json(body): axum::Json<serde_json::Value>| {
                let created = created.clone();
                async move {
                    created.lock().expect("create log poisoned").push(body);
                    axum::Json(serde_json::json!({
                        "agent": {
                            "id": "bc-test-agent",
                            "name": "Add a health check",
                            "status": "ACTIVE",
                            "url": "https://cursor.com/agents/bc-test-agent",
                        },
                        "run": { "id": "run-test-1" },
                    }))
                }
            }),
        )
        .route(
            "/v1/agents/{id}",
            axum::routing::get(|| async {
                axum::Json(serde_json::json!({
                    "id": "bc-test-agent",
                    "name": "Add a health check",
                    "url": "https://cursor.com/agents/bc-test-agent",
                }))
            }),
        )
        .route(
            "/v1/models",
            axum::routing::get(|| async {
                // Enough of the real shape for the wrapper to resolve an id to
                // its default variant: grok-4.6's default is high + fast.
                axum::Json(serde_json::json!({
                    "items": [{
                        "id": "grok-4.6",
                        "displayName": "Cursor Grok 4.6",
                        "variants": [
                            {"params": [{"id":"effort","value":"low"}], "isDefault": false},
                            {"params": [{"id":"effort","value":"high"},{"id":"fast","value":"true"}], "isDefault": true},
                        ],
                    }],
                }))
            }),
        )
        .route("/v1/agents/{id}/runs", {
            // `bc-idle` grows a foreign run after the listing `session/load`
            // hydrates from; `bc-busy` grows one only once a follow-up run is
            // created, so its discovery is the prompt's own backfill and not a
            // mirror tick racing it.
            let listings = Arc::new(AtomicUsize::new(0));
            let follow_ups = Arc::new(AtomicUsize::new(0));
            axum::routing::get({
                let (listings, follow_ups) = (listings.clone(), follow_ups.clone());
                move |axum::extract::Path(id): axum::extract::Path<String>| {
                    let first_listing = listings.fetch_add(1, SeqCst) == 0;
                    let prompted = follow_ups.load(SeqCst) > 0;
                    let runs = match id.as_str() {
                        "bc-restored" => vec!["run-delivered"],
                        "bc-idle" if first_listing => vec!["run-delivered"],
                        "bc-idle" => vec!["run-foreign", "run-delivered"],
                        "bc-busy" if prompted => vec!["run-test-2", "run-foreign", "run-delivered"],
                        "bc-busy" => vec!["run-delivered"],
                        _ => Vec::new(),
                    };
                    let items: Vec<_> = runs
                        .into_iter()
                        .map(|run| serde_json::json!({"id": run, "status": "FINISHED"}))
                        .collect();
                    async move { axum::Json(serde_json::json!({"items": items})) }
                }
            })
            .post(move || {
                follow_ups.fetch_add(1, SeqCst);
                async { axum::Json(serde_json::json!({"id":"run-test-2"})) }
            })
        })
        .route(
            "/v1/agents/{id}/archive",
            axum::routing::post(move |axum::extract::Path(id): axum::extract::Path<String>| {
                let archived = archived.clone();
                async move {
                    archived.lock().expect("log poisoned").push(id.clone());
                    axum::Json(serde_json::json!({ "id": id }))
                }
            }),
        )
        .route(
            "/v1/agents/{id}/runs/{run}/stream",
            axum::routing::get({
                let connects = Arc::new(Mutex::new(0usize));
                move || {
                    let connects = connects.clone();
                    async move {
                        // The first connects land in the window before Cursor
                        // has provisioned the run's stream, in both refusal
                        // shapes seen live: an outright 409, then a 200 whose
                        // only event is an error. The client must reconnect
                        // through both rather than fail the turn.
                        let attempt = {
                            let mut connects = connects.lock().expect("counter poisoned");
                            *connects += 1;
                            *connects
                        };
                        if attempt == 1 {
                            return (
                                axum::http::StatusCode::CONFLICT,
                                [(axum::http::header::CONTENT_TYPE, "application/json")],
                                r#"{"error":{"code":"stream_unavailable","message":"Run stream is no longer available"}}"#,
                            );
                        }
                        let body: &'static str = if attempt == 2 {
                            concat!(
                                "event: error\n",
                                "data: {\"code\":\"stream_unavailable\",\"message\":\"Run stream is no longer available\"}\n",
                                "\n",
                            )
                        } else {
                            concat!(
                                "event: status\n",
                                "data: {\"runId\":\"run-test-1\",\"status\":\"RUNNING\"}\n",
                                "\n",
                                "event: interaction_update\n",
                                "data: {\"type\":\"user-message-appended\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"original\"}]}}\n\n",
                                "event: assistant\n",
                                "data: {\"text\":\"done\"}\n",
                                "\n",
                                "event: result\n",
                                "data: {\"runId\":\"run-test-1\",\"status\":\"FINISHED\",\"text\":\"done\"}\n",
                                "\n",
                                "event: done\n",
                                "data: {}\n",
                                "\n",
                            )
                        };
                        (
                            axum::http::StatusCode::OK,
                            [(axum::http::header::CONTENT_TYPE, "text/event-stream")],
                            body,
                        )
                    }
                }
            }),
        );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind");
    let base_url = format!("http://{}", listener.local_addr().expect("addr"));
    tokio::spawn(async move {
        axum::serve(listener, app).await.expect("serve");
    });
    (base_url, archive_log, create_log)
}

/// A config source: `key` is `Some` for an owner who has connected Cursor,
/// `None` for one who has not — the state every user starts in. `model` is the
/// default model that owner chose, if any.
#[derive(Clone, Copy)]
struct StubKeys {
    key: Option<&'static str>,
    model: Option<&'static str>,
}

impl StubKeys {
    /// A connected owner with a well-formed key and no model preference.
    const fn connected() -> Self {
        Self {
            key: Some("crsr_test"),
            model: None,
        }
    }

    /// An owner who has not connected Cursor.
    const fn absent() -> Self {
        Self {
            key: None,
            model: None,
        }
    }
}

impl CursorApiKeys for StubKeys {
    async fn resolve(&self, _owner: &MacroUserIdStr<'_>) -> Result<ResolvedCursorConfig> {
        let key = self
            .key
            .map(|key| CursorApiKey::parse(key).expect("a well-formed stub key"))
            .ok_or(HarnessError::CursorNotConnected)?;
        Ok(ResolvedCursorConfig {
            key,
            default_model_id: self.model.map(str::to_owned),
        })
    }
}

struct UnavailableKeys;

impl CursorApiKeys for UnavailableKeys {
    async fn resolve(&self, _owner: &MacroUserIdStr<'_>) -> Result<ResolvedCursorConfig> {
        Err(HarnessError::Container("key decryption failed".to_owned()))
    }
}

/// A user who reaches one repository through the GitHub App: the chooser
/// short-circuits on a single candidate, so these tests drive the whole spawn
/// path without a model call.
struct OneRepository;

#[async_trait::async_trait]
impl ReachableRepositories for OneRepository {
    async fn for_user(
        &self,
        _user: &MacroUserIdStr<'_>,
    ) -> Result<Vec<crate::domain::model::ReachableRepository>> {
        Ok(vec![crate::domain::model::ReachableRepository {
            url: "https://github.com/macro-inc/macro".into(),
            default_branch: Some("main".into()),
        }])
    }
}

fn manager(
    base_url: String,
    sessions: StubSessions,
) -> CursorContainerManager<StubSessions, StubKeys, OneRepository, NoArtifactStore> {
    manager_with_keys(base_url, sessions, StubKeys::connected())
}

fn manager_with_keys<Keys: CursorApiKeys>(
    base_url: String,
    sessions: StubSessions,
    keys: Keys,
) -> CursorContainerManager<StubSessions, Keys, OneRepository, NoArtifactStore> {
    CursorContainerManager::with_memory_journal(
        keys,
        base_url,
        sessions,
        Arc::new(OneRepository),
        NoArtifactStore,
    )
}

async fn next_acp(
    receiver: &mut tokio::sync::mpsc::UnboundedReceiver<ToServerMessage>,
) -> serde_json::Value {
    loop {
        match receiver.recv().await.expect("a message") {
            ToServerMessage::Acp(AcpMessage(frame)) => {
                return serde_json::to_value(frame).expect("serializable");
            }
            _ => continue,
        }
    }
}

async fn send_acp(sender: &super::super::pipe::PipeSender, frame: serde_json::Value) {
    sender
        .send(ToRuntimeMessage::Acp(AcpMessage(
            serde_json::from_value(frame).expect("valid frame"),
        )))
        .await
        .expect("send");
}

/// The whole spawn path: initialize, open a session, prompt — and the minted
/// agent's identity lands in the external-session repo before the prompt
/// answers.
#[tokio::test]
async fn spawning_and_prompting_records_the_minted_agent() {
    let (base_url, _, _) = fake_cursor_api().await;
    let sessions = StubSessions::default();
    let session_id = AgentSessionId::new();
    let manager = manager(base_url, sessions.clone());

    let transport = manager
        .spawn(SpawnContainer {
            session_id,
            kind: AgentKind::Cursor,
            size: SandboxSize::Default,
            egress: test_egress(),
        })
        .await
        .expect("spawn");
    let mut halves = None;
    transport.map_transport(|pipe| halves = Some(pipe.split()));
    let (sender, mut receiver) = halves.unwrap();

    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}),
    )
    .await;
    let initialize = next_acp(&mut receiver).await;
    assert_eq!(
        initialize["result"]["agentCapabilities"]["loadSession"],
        true
    );

    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":2,"method":"session/new","params":{"cwd":"/workspace","mcpServers":[]}}),
    )
    .await;
    let opened = next_acp(&mut receiver).await;
    let acp_session = opened["result"]["sessionId"]
        .as_str()
        .expect("a session id");

    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{
            "sessionId": acp_session,
            "prompt": [{"type":"text","text":"add a health check"}],
        }}),
    )
    .await;
    // Updates stream first; the prompt's response ends the turn.
    let response = loop {
        let frame = next_acp(&mut receiver).await;
        if frame["id"] == 3 {
            break frame;
        }
    };
    assert_eq!(response["result"]["stopReason"], "end_turn");

    let recorded = ExternalSessionRepo::get(&sessions, session_id)
        .await
        .expect("get")
        .expect("row written");
    assert_eq!(recorded.provider, CURSOR_PROVIDER);
    assert_eq!(recorded.external_id, "bc-test-agent");
    assert_eq!(
        recorded.external_url.as_deref(),
        Some("https://cursor.com/agents/bc-test-agent")
    );
}

/// A fresh session starts on the owner's configured default model, resolved
/// to its variant against the live model table — the per-user setting reaching
/// all the way to the agent Cursor mints.
#[tokio::test]
async fn spawn_uses_the_owners_default_model() {
    let (base_url, _, created) = fake_cursor_api().await;
    let sessions = StubSessions::default();
    let session_id = AgentSessionId::new();
    let manager = manager_with_keys(
        base_url,
        sessions,
        StubKeys {
            key: Some("crsr_test"),
            model: Some("grok-4.6"),
        },
    );

    let transport = manager
        .spawn(SpawnContainer {
            session_id,
            kind: AgentKind::Cursor,
            size: SandboxSize::Default,
            egress: crate::testing::helpers::egress::test_egress(),
        })
        .await
        .expect("spawn");
    let mut halves = None;
    transport.map_transport(|pipe| halves = Some(pipe.split()));
    let (sender, mut receiver) = halves.unwrap();

    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}),
    )
    .await;
    next_acp(&mut receiver).await;
    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":2,"method":"session/new","params":{"cwd":"/workspace","mcpServers":[]}}),
    )
    .await;
    let acp_session = next_acp(&mut receiver).await["result"]["sessionId"]
        .as_str()
        .expect("a session id")
        .to_owned();
    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{
            "sessionId": acp_session,
            "prompt": [{"type":"text","text":"go"}],
        }}),
    )
    .await;
    loop {
        if next_acp(&mut receiver).await["id"] == 3 {
            break;
        }
    }

    let body = created.lock().expect("create log poisoned")[0].clone();
    assert_eq!(body["model"]["id"], "grok-4.6");
    // The default variant's params travel with the id — a bare id is not a
    // selection Cursor accepts.
    assert_eq!(
        body["model"]["params"],
        serde_json::json!([{"id":"effort","value":"high"},{"id":"fast","value":"true"}])
    );
}

/// MCP servers ride the ACP protocol itself: whatever the client names in
/// `session/new` reaches the agent Cursor mints - which is how the harness's
/// egress-proxied servers arrive, on the same rail as every other transport.
#[tokio::test]
async fn session_new_mcp_servers_reach_the_created_agent() {
    let (base_url, _, created) = fake_cursor_api().await;
    let sessions = StubSessions {
        repo_branch: Some(
            agent_session::domain::repository_branch::RepositoryBranch::parse(
                "feature/home".into(),
            )
            .unwrap(),
        ),
        ..StubSessions::default()
    };
    let session_id = AgentSessionId::new();
    let manager = manager(base_url, sessions);

    let transport = manager
        .spawn(SpawnContainer {
            session_id,
            kind: AgentKind::Cursor,
            size: SandboxSize::Default,
            egress: test_egress(),
        })
        .await
        .expect("spawn");
    let mut halves = None;
    transport.map_transport(|pipe| halves = Some(pipe.split()));
    let (sender, mut receiver) = halves.unwrap();

    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}),
    )
    .await;
    next_acp(&mut receiver).await;
    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":2,"method":"session/new","params":{
            "cwd":"/workspace",
            "mcpServers":[
                {
                    "type": "http",
                    "name": "macro",
                    "url": "https://egress.test/mcp-macro",
                    "headers": [{"name": "Authorization", "value": "Bearer test-session-token"}],
                },
                {
                    "type": "http",
                    "name": "macro_internal",
                    "url": "https://egress.test/mcp/internal",
                    "headers": [{"name": "Authorization", "value": "Bearer test-session-token"}],
                },
            ],
        }}),
    )
    .await;
    let acp_session = next_acp(&mut receiver).await["result"]["sessionId"]
        .as_str()
        .expect("a session id")
        .to_owned();
    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{
            "sessionId": acp_session,
            "prompt": [{"type":"text","text":"go"}],
        }}),
    )
    .await;
    loop {
        if next_acp(&mut receiver).await["id"] == 3 {
            break;
        }
    }

    let body = created.lock().expect("create log poisoned")[0].clone();
    assert_eq!(body["repos"][0]["startingRef"], "feature/home");
    assert_eq!(
        body["mcpServers"],
        serde_json::json!([
            {
                "name": "macro",
                "type": "http",
                "url": "https://egress.test/mcp-macro",
                "headers": { "Authorization": "Bearer test-session-token" },
            },
            {
                "name": "macro_internal",
                "type": "http",
                "url": "https://egress.test/mcp/internal",
                "headers": { "Authorization": "Bearer test-session-token" },
            },
        ])
    );
}

/// Resume restores the persisted identity: the harness's `session/load` is
/// answered, and the next prompt is a follow-up run on the restored agent —
/// not a fresh agent.
#[tokio::test]
async fn resume_restores_the_persisted_identity() {
    let (base_url, _, _) = fake_cursor_api().await;
    let (_, _, history) = resume_delivered_session(base_url, "bc-restored").await;
    assert_eq!(count(&history, "/method", "_session/turn_complete"), 1);
}

/// A session that died between `session/new` and its first prompt has an
/// acp id but no external row. Resume must still answer its `session/load` —
/// refusing left a session every follow-up crashed against (seen live).
#[tokio::test]
async fn resume_answers_session_load_even_before_an_agent_was_minted() {
    let (base_url, _, _) = fake_cursor_api().await;
    let sessions = StubSessions::default();
    let session_id = AgentSessionId::new();
    *sessions.acp_session_id.lock().expect("stub poisoned") = Some("cursor-acp-1".to_owned());
    let manager = manager(base_url, sessions.clone());

    let transport = manager.resume(session_id).await.expect("resume");
    let mut halves = None;
    transport.map_transport(|pipe| halves = Some(pipe.split()));
    let (sender, mut receiver) = halves.unwrap();

    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}),
    )
    .await;
    next_acp(&mut receiver).await;
    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":2,"method":"session/load","params":{
            "sessionId":"cursor-acp-1","cwd":"/workspace","mcpServers":[]}}),
    )
    .await;
    let loaded = next_acp(&mut receiver).await;
    assert!(loaded.get("error").is_none(), "got {loaded}");

    // The next prompt mints the agent and records it, like any first prompt.
    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{
            "sessionId": "cursor-acp-1",
            "prompt": [{"type":"text","text":"still there?"}],
        }}),
    )
    .await;
    loop {
        let frame = next_acp(&mut receiver).await;
        if frame["id"] == 3 {
            assert_eq!(frame["result"]["stopReason"], "end_turn", "got {frame}");
            break;
        }
    }
    assert!(
        ExternalSessionRepo::get(&sessions, session_id)
            .await
            .expect("get")
            .is_some(),
        "the newly minted agent must be recorded"
    );
}

/// A pipe nothing has moved through for the idle timeout is shut down —
/// Daytona's reaper made local. The harness side observes a clean end of
/// stream, which is what parks the session until its next prompt resumes it.
#[tokio::test(start_paused = true)]
async fn an_idle_pipe_is_shut_down() {
    // No fake API: nothing is called before the first prompt, and a live
    // TCP listener's pending io would hold tokio's paused clock back to
    // real time — five real minutes for one idle timeout.
    let manager = manager("http://127.0.0.1:1".to_owned(), StubSessions::default());

    let transport = manager
        .spawn(SpawnContainer {
            session_id: AgentSessionId::new(),
            kind: AgentKind::Cursor,
            size: SandboxSize::Default,
            egress: test_egress(),
        })
        .await
        .expect("spawn");
    let mut halves = None;
    transport.map_transport(|pipe| halves = Some(pipe.split()));
    let (_sender, mut receiver) = halves.unwrap();

    // The ready marker arrives; then nothing ever does, and after the idle
    // timeout (paused clock, so instantly) the stream ends instead of
    // holding its tasks and its cursor.com poll forever.
    assert!(receiver.recv().await.is_some(), "acp ready arrives");
    assert!(
        receiver.recv().await.is_none(),
        "an idle pipe must close, not hang"
    );
}

#[test]
fn a_pipe_is_not_idle_while_cursor_is_running_a_turn() {
    assert!(!should_reap_cursor_pipe(CURSOR_IDLE_TIMEOUT, true, false));
    assert!(should_reap_cursor_pipe(CURSOR_IDLE_TIMEOUT, false, false));
}

#[test]
fn a_pipe_is_not_idle_while_a_command_is_pending() {
    // Same idle duration, no active turn yet - the case a command admitted
    // just before the reap tick looks like, before the runtime has had a
    // chance to mark a turn active.
    assert!(!should_reap_cursor_pipe(CURSOR_IDLE_TIMEOUT, false, true));
}

/// The warning for a pipe kept open past its deadline: silent for the first
/// half hour a turn holds it, then once per half hour after, and re-armed
/// as soon as the pipe is either free or active again.
#[test]
fn a_pipe_held_open_past_its_deadline_warns_once_per_interval() {
    let minute = std::time::Duration::from_secs(60);
    let armed = HELD_OPEN_WARNING_INTERVAL;

    // Idle but not yet past the deadline, or past it and free: nothing to say.
    assert_eq!(held_open_warning(minute, true, armed), (false, armed));
    assert_eq!(
        held_open_warning(CURSOR_IDLE_TIMEOUT, false, armed),
        (false, armed)
    );

    // Held past the deadline, but for less than the interval: not yet.
    assert_eq!(
        held_open_warning(CURSOR_IDLE_TIMEOUT, true, armed),
        (false, armed)
    );
    assert_eq!(
        held_open_warning(armed - minute, true, armed),
        (false, armed)
    );

    // The interval reached: warn, and wait a whole interval for the next.
    let (warn, next) = held_open_warning(armed, true, armed);
    assert!(warn);
    assert_eq!(next, armed * 2);
    assert_eq!(
        held_open_warning(armed + minute, true, next),
        (false, next),
        "the same stretch does not warn on every tick"
    );
    let (warn, next) = held_open_warning(armed * 2, true, next);
    assert!(warn);
    assert_eq!(next, armed * 3);

    // Activity resumed: the threshold is re-armed for the next stretch.
    assert_eq!(held_open_warning(minute, true, next), (false, armed));
}

/// Teardown archives the agent on cursor.com and forgets the mapping; a
/// session that never minted an agent tears down without any API call.
#[tokio::test]
async fn teardown_archives_and_forgets() {
    let (base_url, archived, _) = fake_cursor_api().await;
    let sessions = StubSessions::default();
    let session_id = AgentSessionId::new();
    let manager = manager(base_url, sessions.clone());

    // Nothing minted: no API call, still Ok.
    manager.teardown(session_id).await.expect("no-op teardown");
    assert!(archived.lock().expect("log poisoned").is_empty());

    ExternalSessionRepo::upsert(
        &sessions,
        session_id,
        ExternalSession {
            provider: CURSOR_PROVIDER.to_owned(),
            external_id: "bc-doomed".to_owned(),
            external_name: None,
            external_url: None,
            last_run_id: None,
        },
    )
    .await
    .expect("seed row");
    manager.teardown(session_id).await.expect("teardown");
    assert_eq!(
        archived.lock().expect("log poisoned").as_slice(),
        ["bc-doomed"]
    );
    assert_eq!(
        ExternalSessionRepo::get(&sessions, session_id)
            .await
            .expect("get"),
        None
    );
}

#[tokio::test]
async fn preflight_only_requests_a_connection_when_no_key_is_saved() {
    let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();
    for (keys, expected) in [
        (StubKeys::connected(), None),
        (StubKeys::absent(), Some(SessionBlocker::CursorNotConnected)),
    ] {
        let manager = manager_with_keys(
            "http://127.0.0.1:1".to_owned(),
            StubSessions::default(),
            keys,
        );
        assert_eq!(
            manager.preflight(AgentKind::Cursor, &owner).await.unwrap(),
            expected
        );
    }
}

#[tokio::test]
async fn preflight_propagates_key_errors_instead_of_requesting_a_connection() {
    let manager = manager_with_keys(
        "http://127.0.0.1:1".to_owned(),
        StubSessions::default(),
        UnavailableKeys,
    );
    let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();

    let error = manager
        .preflight(AgentKind::Cursor, &owner)
        .await
        .unwrap_err();

    assert!(
        matches!(error, HarnessError::Container(message) if message == "key decryption failed")
    );
}

/// An owner who has not connected Cursor gets a sentence they can act on, not
/// a generic provisioning failure — this is the first run of `@cursor` for
/// everyone, so it is the error most users will ever see.
#[tokio::test]
async fn spawning_without_a_registered_key_says_so() {
    let (base_url, _, _) = fake_cursor_api().await;
    let sessions = StubSessions::default();
    let manager = manager_with_keys(base_url, sessions, StubKeys::absent());

    let refused = manager
        .spawn(SpawnContainer {
            session_id: AgentSessionId::new(),
            kind: AgentKind::Cursor,
            size: SandboxSize::Default,
            egress: test_egress(),
        })
        .await
        // `err()` rather than `expect_err`: the success type is a live
        // transport, which has no `Debug` to print.
        .err()
        .expect("a session with no key must not open");

    assert!(
        matches!(refused, HarnessError::CursorNotConnected),
        "expected a connect-your-account error, got {refused:?}"
    );
}

/// Disconnecting Cursor and then tearing down a session it owns: the agent
/// cannot be archived without the key, but the session must still clean up.
/// The alternative is a Macro session nothing can ever remove.
#[tokio::test]
async fn teardown_forgets_the_session_even_when_the_key_is_gone() {
    let (base_url, archived, _) = fake_cursor_api().await;
    let sessions = StubSessions::default();
    let session_id = AgentSessionId::new();
    let manager = manager_with_keys(base_url, sessions.clone(), StubKeys::absent());

    ExternalSessionRepo::upsert(
        &sessions,
        session_id,
        ExternalSession {
            provider: CURSOR_PROVIDER.to_owned(),
            external_id: "bc-orphaned".to_owned(),
            external_name: None,
            external_url: None,
            last_run_id: None,
        },
    )
    .await
    .expect("seed row");

    manager.teardown(session_id).await.expect("teardown");

    assert!(
        archived.lock().expect("log poisoned").is_empty(),
        "archiving is impossible without the owner's key"
    );
    assert_eq!(
        ExternalSessionRepo::get(&sessions, session_id)
            .await
            .expect("get"),
        None,
        "the row is ours to forget even when the agent is not ours to archive"
    );
}

/// Every message up to and including the first one `stop` accepts, in arrival
/// order: ACP frames as JSON, `ReloadRequired` as `"reload_required"`, other
/// runtime events dropped. Recovery has no history replacement protocol, so a
/// `_session/history*` frame anywhere fails the test.
async fn collect_until(
    receiver: &mut tokio::sync::mpsc::UnboundedReceiver<ToServerMessage>,
    stop: impl Fn(&serde_json::Value) -> bool,
) -> Vec<serde_json::Value> {
    let mut seen = Vec::new();
    loop {
        let message = tokio::time::timeout(std::time::Duration::from_secs(30), receiver.recv())
            .await
            .expect("a message before the timeout")
            .expect("the pipe stays open");
        let value = match message {
            ToServerMessage::Acp(AcpMessage(frame)) => {
                serde_json::to_value(frame).expect("serializable")
            }
            ToServerMessage::Event {
                event: SystemEvent::ReloadRequired,
            } => serde_json::json!("reload_required"),
            ToServerMessage::Event { .. } => continue,
            other => panic!("unexpected runtime message {other:?}"),
        };
        assert!(
            !value["method"]
                .as_str()
                .unwrap_or_default()
                .starts_with("_session/history"),
            "recovery must not push a history replacement, got {value}"
        );
        let done = stop(&value);
        seen.push(value);
        if done {
            return seen;
        }
    }
}

/// Frames whose JSON `pointer` holds the string `value`.
fn count(frames: &[serde_json::Value], pointer: &str, value: &str) -> usize {
    frames
        .iter()
        .filter(|frame| frame.pointer(pointer).and_then(|found| found.as_str()) == Some(value))
        .count()
}

/// Whether this frame is the slash-command catalog, not conversation history.
fn is_available_commands_update(frame: &serde_json::Value) -> bool {
    frame
        .pointer("/params/update/sessionUpdate")
        .and_then(|found| found.as_str())
        == Some("available_commands_update")
}

/// Consume the `available_commands_update` that follows a successful load so
/// leftover catalog frames do not precede the next initialize or look like
/// unsolicited history.
async fn drain_available_commands_update(
    receiver: &mut tokio::sync::mpsc::UnboundedReceiver<ToServerMessage>,
) {
    let frames = collect_until(receiver, is_available_commands_update).await;
    assert_eq!(
        frames.len(),
        1,
        "session/load is followed by the slash-command catalog and nothing else: {frames:?}"
    );
}

/// The recovery handshake as the session actor performs it: `initialize`,
/// then `session/load`. Returns the history replayed before the load's
/// response after asserting the load succeeded and only history preceded it.
///
/// The catalog notification that follows a successful load is drained, the
/// same way the Cursor fold helpers do, so a leftover metadata frame cannot
/// poison the next handshake.
async fn reload(
    sender: &super::super::pipe::PipeSender,
    receiver: &mut tokio::sync::mpsc::UnboundedReceiver<ToServerMessage>,
    first_id: u64,
) -> Vec<serde_json::Value> {
    send_acp(
        sender,
        serde_json::json!({"jsonrpc":"2.0","id":first_id,"method":"initialize","params":{"protocolVersion":1}}),
    )
    .await;
    let initialized = collect_until(receiver, |message| message["id"] == first_id).await;
    assert_eq!(
        initialized.len(),
        1,
        "nothing precedes initialize's answer: {initialized:?}"
    );
    let load_id = first_id + 1;
    send_acp(
        sender,
        serde_json::json!({"jsonrpc":"2.0","id":load_id,"method":"session/load","params":{
            "sessionId":"cursor-acp-1","cwd":"/workspace","mcpServers":[]}}),
    )
    .await;
    let mut replayed = collect_until(receiver, |message| message["id"] == load_id).await;
    let loaded = replayed.pop().expect("the load response");
    assert!(
        loaded.get("error").is_none(),
        "load must succeed, got {loaded}"
    );
    for frame in &replayed {
        assert!(
            matches!(
                frame["method"].as_str(),
                Some("session/update" | "_session/turn_complete")
            ),
            "only history travels before a load's response, got {frame}"
        );
        assert!(
            !is_available_commands_update(frame),
            "the catalog is advertised after the load result, not as history: {frame}"
        );
    }
    drain_available_commands_update(receiver).await;
    replayed
}

/// Resume a session whose Cursor agent is `agent` with `run-delivered` already
/// in Macro's log, then `initialize` + `session/load` it; the third element is
/// what that first load replayed.
async fn resume_delivered_session(
    base_url: String,
    agent: &str,
) -> (
    super::super::pipe::PipeSender,
    tokio::sync::mpsc::UnboundedReceiver<ToServerMessage>,
    Vec<serde_json::Value>,
) {
    let sessions = StubSessions::default();
    let session_id = AgentSessionId::new();
    ExternalSessionRepo::upsert(
        &sessions,
        session_id,
        ExternalSession {
            provider: CURSOR_PROVIDER.to_owned(),
            external_id: agent.to_owned(),
            external_name: None,
            external_url: None,
            last_run_id: Some("run-delivered".to_owned()),
        },
    )
    .await
    .expect("seed row");
    *sessions.acp_session_id.lock().expect("stub poisoned") = Some("cursor-acp-1".to_owned());
    let transport = manager(base_url, sessions)
        .resume(session_id)
        .await
        .expect("resume");
    let mut halves = None;
    transport.map_transport(|pipe| halves = Some(pipe.split()));
    let (sender, mut receiver) = halves.unwrap();
    let history = reload(&sender, &mut receiver, 1).await;
    (sender, receiver, history)
}

/// A run driven from cursor.com while the Macro session sits idle: the mirror
/// 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_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 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!(
        count(&live, "/params/update/sessionUpdate", "user_message_chunk"),
        1,
        "the cursor.com prompt streams with its run: {live:?}"
    );
    assert_eq!(count(&live, "/method", "_session/turn_complete"), 1);

    let loaded = reload(&sender, &mut receiver, 3).await;
    assert_eq!(
        count(&loaded, "/method", "_session/turn_complete"),
        2,
        "both runs are history: {loaded:?}"
    );
    assert_eq!(
        count(
            &loaded,
            "/params/update/sessionUpdate",
            "user_message_chunk"
        ),
        2
    );

    // 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 the run, got {quiet:?}"
    );
}

/// A run driven from cursor.com discovered by a prompt's own backfill: the
/// reload requirement reaches the host before the prompt's response, the live
/// turn streams only its own frames, and the load that follows shows the
/// delivered run, the foreign run and the prompt just answered.
#[tokio::test]
async fn a_foreign_run_found_by_a_prompt_is_recovered_after_its_response() {
    let (base_url, _, _) = fake_cursor_api().await;
    let (sender, mut receiver, before) = resume_delivered_session(base_url, "bc-busy").await;
    assert_eq!(count(&before, "/method", "_session/turn_complete"), 1);

    send_acp(
        &sender,
        serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{
            "sessionId": "cursor-acp-1",
            "prompt": [{"type":"text","text":"follow up"}],
        }}),
    )
    .await;
    let turn = collect_until(&mut receiver, |message| message["id"] == 3).await;
    let response = turn.last().expect("the prompt response");
    assert_eq!(
        response["result"]["stopReason"], "end_turn",
        "got {response}"
    );
    let reload_at = turn
        .iter()
        .position(|message| message == "reload_required")
        .expect("the prompt's backfill requires a reload");
    assert!(
        reload_at < turn.len() - 1,
        "the requirement precedes the response"
    );
    assert_eq!(
        count(&turn, "/params/update/sessionUpdate", "user_message_chunk"),
        0,
        "neither the foreign run's prompt nor our own is echoed live: {turn:?}"
    );
    assert_eq!(
        count(&turn, "/params/update/content/text", "done"),
        1,
        "only the live run's text streams; the foreign run waits for load: {turn:?}"
    );

    let recovered = reload(&sender, &mut receiver, 4).await;
    assert_eq!(
        count(&recovered, "/method", "_session/turn_complete"),
        3,
        "delivered, foreign, and ours: {recovered:?}"
    );
    assert_eq!(
        count(
            &recovered,
            "/params/update/sessionUpdate",
            "user_message_chunk"
        ),
        3
    );
    assert_eq!(
        count(&recovered, "/params/update/content/text", "follow up"),
        1,
        "the prompt just answered is part of the loaded history: {recovered:?}"
    );

    let again = reload(&sender, &mut receiver, 6).await;
    assert_eq!(
        again, recovered,
        "a repeated load replays the same history once"
    );
}