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.

16.4 KB
Raw Blame
use super::*;
use crate::domain::sandbox::SandboxResizeEffect;
use crate::testing::helpers::egress::test_egress;
use agent_runtime_protocol::domain::schema::v0::{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 macro_user_id::user_id::MacroUserIdStr;
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc;

/// A transport that only exists to be told apart from the other provider's.
struct TaggedTransport;

impl Transport<ToRuntimeMessage, ToServerMessage> for TaggedTransport {
    type Sender = mpsc::UnboundedSender<ToRuntimeMessage>;
    type Receiver = mpsc::UnboundedReceiver<ToServerMessage>;

    fn split(self) -> (Self::Sender, Self::Receiver) {
        let (sender, _) = mpsc::unbounded_channel();
        let (_, receiver) = mpsc::unbounded_channel();
        (sender, receiver)
    }
}

/// Records which provider each call landed on.
#[derive(Clone)]
struct TaggedManager {
    tag: &'static str,
    calls: Arc<Mutex<Vec<String>>>,
}

impl TaggedManager {
    fn new(tag: &'static str) -> Self {
        Self {
            tag,
            calls: Arc::new(Mutex::new(Vec::new())),
        }
    }

    fn calls(&self) -> Vec<String> {
        self.calls.lock().expect("calls poisoned").clone()
    }

    fn record(&self, operation: &str) {
        self.calls
            .lock()
            .expect("calls poisoned")
            .push(format!("{}:{operation}", self.tag));
    }
}

impl ContainerManager for TaggedManager {
    type Transport = TaggedTransport;

    async fn preflight(
        &self,
        _kind: AgentKind,
        _owner: &MacroUserIdStr<'_>,
    ) -> Result<Option<SessionBlocker>> {
        self.record("preflight");
        Ok(None)
    }

    async fn spawn(
        &self,
        _command: SpawnContainer,
    ) -> Result<agent_session::domain::connection::RuntimeAttachment<TaggedTransport>> {
        self.record("spawn");
        Ok(agent_session::domain::connection::RuntimeAttachment::solo(
            TaggedTransport,
        ))
    }

    async fn resume(
        &self,
        _session: AgentSessionId,
    ) -> Result<agent_session::domain::connection::RuntimeAttachment<TaggedTransport>> {
        self.record("resume");
        Ok(agent_session::domain::connection::RuntimeAttachment::solo(
            TaggedTransport,
        ))
    }

    async fn session_token(&self, _session: AgentSessionId) -> Result<Option<String>> {
        self.record("session_token");
        Ok(None)
    }

    async fn teardown(&self, _session: AgentSessionId) -> Result<()> {
        self.record("teardown");
        Ok(())
    }

    fn resize_effect(&self, _from: SandboxSize, _to: SandboxSize) -> SandboxResizeEffect {
        unimplemented!("these tests never resize")
    }

    async fn resize(&self, _session: AgentSessionId, _size: SandboxSize) -> Result<()> {
        unimplemented!("these tests never resize")
    }
}

/// Answers every session lookup with a fixed bot and harness slug.
#[derive(Clone)]
struct FixedBotSessions(BotId, &'static str);

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

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

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

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

    async fn get(&self, id: AgentSessionId) -> SessionResult<AgentSession> {
        Ok(AgentSession {
            origin: Default::default(),
            repo_branch: None,
            pull_request_url: None,
            task_id: None,
            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: self.0,
            model: "auto".to_owned(),
            harness: self.1.to_owned(),
            repo_url: 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: None,
            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 router never routes channel events")
    }

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

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

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

    async fn set_acp_session_id(
        &self,
        _id: AgentSessionId,
        _acp_session_id: agent_client_protocol::schema::v1::SessionId,
    ) -> SessionResult<()> {
        unimplemented!("the router never persists acp ids")
    }

    async fn set_model(&self, _id: AgentSessionId, _model: &str) -> SessionResult<()> {
        unimplemented!("the router 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 router 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: &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<()> {
        unimplemented!("the router never sets repositories")
    }

    async fn delete(&self, _id: AgentSessionId) -> SessionResult<()> {
        unimplemented!("the router never deletes sessions")
    }

    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 router never reads the queue")
    }

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

fn spawn_for(kind: AgentKind) -> SpawnContainer {
    SpawnContainer {
        session_id: AgentSessionId::new(),
        kind,
        size: SandboxSize::Default,
        egress: test_egress(),
    }
}

#[tokio::test]
async fn the_cursor_bot_routes_to_cursor_and_everything_else_to_the_sandbox() {
    let sandbox = TaggedManager::new("sandbox");
    let cursor = TaggedManager::new("cursor");
    let router = RoutedContainerManager::new(
        sandbox.clone(),
        cursor.clone(),
        TaggedManager::new("codex"),
        FixedBotSessions(bot_id::CURSOR_BOT_ID, "cursor"),
    );

    let spawned = router
        .spawn(spawn_for(AgentKind::Cursor))
        .await
        .expect("spawn");
    spawned.map_transport(|transport| assert!(matches!(transport, RoutedTransport::Cursor(_))));
    let spawned = router
        .spawn(spawn_for(AgentKind::SandboxedCoder))
        .await
        .expect("spawn");
    spawned.map_transport(|transport| assert!(matches!(transport, RoutedTransport::Sandbox(_))));
    assert_eq!(cursor.calls(), ["cursor:spawn"]);
    assert_eq!(sandbox.calls(), ["sandbox:spawn"]);
}

/// Preflight has no session row yet, so it routes on the kind the trigger
/// resolved, like spawn.
#[tokio::test]
async fn preflight_routes_by_kind_before_any_session_exists() {
    let sandbox = TaggedManager::new("sandbox");
    let cursor = TaggedManager::new("cursor");
    let codex = TaggedManager::new("codex");
    let router = RoutedContainerManager::new(
        sandbox.clone(),
        cursor.clone(),
        codex.clone(),
        FixedBotSessions(bot_id::CURSOR_BOT_ID, "cursor"),
    );
    let owner = MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id");

    assert_eq!(
        router.preflight(AgentKind::Cursor, &owner).await.unwrap(),
        None
    );
    assert_eq!(
        router.preflight(AgentKind::InMemory, &owner).await.unwrap(),
        None
    );
    assert_eq!(
        router
            .preflight(AgentKind::CodexCloud, &owner)
            .await
            .unwrap(),
        None
    );
    assert!(router.preflight(AgentKind::External, &owner).await.is_err());
    assert_eq!(cursor.calls(), ["cursor:preflight"]);
    assert_eq!(sandbox.calls(), ["sandbox:preflight"]);
    assert_eq!(codex.calls(), ["codex:preflight"]);
}

/// Resume and teardown route by the session row's bot — the repo says cursor
/// here, so the sandbox provider must never hear about the session.
#[tokio::test]
async fn resume_and_teardown_route_by_the_stored_bot() {
    let sandbox = TaggedManager::new("sandbox");
    let cursor = TaggedManager::new("cursor");
    let router = RoutedContainerManager::new(
        sandbox.clone(),
        cursor.clone(),
        TaggedManager::new("codex"),
        FixedBotSessions(bot_id::CURSOR_BOT_ID, "cursor"),
    );

    let session = AgentSessionId::new();
    router.resume(session).await.expect("resume");
    router.teardown(session).await.expect("teardown");
    assert_eq!(cursor.calls(), ["cursor:resume", "cursor:teardown"]);
    assert!(sandbox.calls().is_empty());
}

#[tokio::test]
async fn a_database_backed_cursor_agent_routes_by_its_stored_harness() {
    let sandbox = TaggedManager::new("sandbox");
    let cursor = TaggedManager::new("cursor");
    let router = RoutedContainerManager::new(
        sandbox.clone(),
        cursor.clone(),
        TaggedManager::new("codex"),
        FixedBotSessions(BotId::TEST_A, "cursor"),
    );

    let session = AgentSessionId::new();
    router.resume(session).await.expect("resume");
    router.session_token(session).await.expect("session token");
    router.teardown(session).await.expect("teardown");
    assert_eq!(
        cursor.calls(),
        ["cursor:resume", "cursor:session_token", "cursor:teardown"]
    );
    assert!(sandbox.calls().is_empty());
}

#[tokio::test]
async fn codex_routes_all_lifecycle_operations_and_rejects_resize() {
    let sandbox = TaggedManager::new("sandbox");
    let cursor = TaggedManager::new("cursor");
    let codex = TaggedManager::new("codex");
    let router = RoutedContainerManager::new(
        sandbox.clone(),
        cursor.clone(),
        codex.clone(),
        FixedBotSessions(bot_id::CODEX_BOT_ID, "cursor"),
    );
    router
        .spawn(spawn_for(AgentKind::CodexCloud))
        .await
        .unwrap()
        .map_transport(|transport| assert!(matches!(transport, RoutedTransport::Codex(_))));
    let session = AgentSessionId::new();
    router.resume(session).await.unwrap();
    router.session_token(session).await.unwrap();
    router.teardown(session).await.unwrap();
    assert!(router.resize(session, SandboxSize::Default).await.is_err());
    assert_eq!(
        codex.calls(),
        [
            "codex:spawn",
            "codex:resume",
            "codex:session_token",
            "codex:teardown"
        ]
    );
    assert!(sandbox.calls().is_empty());
    assert!(cursor.calls().is_empty());
    assert_eq!(
        AgentKind::from_harness("codex-cloud"),
        AgentKind::CodexCloud
    );
}

/// An external session's runtime is its operator's, so deleting it has no
/// provider to release: teardown succeeds without reaching one, while
/// operations that would need a provider still refuse.
#[tokio::test]
async fn external_teardown_is_a_no_op_and_resume_still_refuses() {
    let sandbox = TaggedManager::new("sandbox");
    let cursor = TaggedManager::new("cursor");
    let codex = TaggedManager::new("codex");
    let router = RoutedContainerManager::new(
        sandbox.clone(),
        cursor.clone(),
        codex.clone(),
        FixedBotSessions(BotId::TEST_A, harness_id::MACROD_HARNESS_SLUG),
    );

    let session = AgentSessionId::new();
    router.teardown(session).await.expect("teardown");
    assert!(router.resume(session).await.is_err());
    assert!(sandbox.calls().is_empty());
    assert!(cursor.calls().is_empty());
    assert!(codex.calls().is_empty());
}