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
use super::*;
use agent_session::domain::routines::{
PrepareRoutineSession, PreparedRoutineSession, PromptRoutineSession, RoutineActionStatus,
RoutinePromptAccepted, RoutineSessionAction, RoutineSessionError, ValidatedRoutineSession,
};
use serde_json::json;
use std::sync::Mutex;
pub(crate) const BOT: &str = "01960000-0000-7000-8000-000000000001";
pub(crate) const OWNER: &str = "macro|[email protected]";
#[derive(Default)]
pub(crate) struct Sessions {
pub(crate) validations: Mutex<Vec<ValidateRoutineSession>>,
pub(crate) preparations: Mutex<Vec<PrepareRoutineSession>>,
pub(crate) error: Mutex<Option<RoutineSessionError>>,
}
impl RoutineSessions for Sessions {
async fn validate(
&self,
command: ValidateRoutineSession,
) -> Result<ValidatedRoutineSession, RoutineSessionError> {
self.validations.lock().unwrap().push(command.clone());
if command.owner.as_ref() != OWNER {
return Err(RoutineSessionError::Forbidden);
}
if command.bot_id.to_string() != BOT && command.bot_id != bot_id::MACRO_NEW_BOT_ID {
return Err(RoutineSessionError::PersonaUnavailable);
}
if let Some(error) = *self.error.lock().unwrap() {
return Err(error);
}
// External runtime need not be online for its authorized selection to be saved.
Ok(ValidatedRoutineSession { managed: false })
}
async fn prepare(
&self,
command: PrepareRoutineSession,
) -> Result<PreparedRoutineSession, RoutineSessionError> {
self.preparations.lock().unwrap().push(command.clone());
self.validate(command.selection).await?;
Ok(PreparedRoutineSession {
session_id: command.session_id,
})
}
async fn prompt(
&self,
_: PromptRoutineSession,
) -> Result<RoutinePromptAccepted, RoutineSessionError> {
panic!("configuration validation and denied preparation must never prompt")
}
async fn status(
&self,
_: RoutineSessionAction,
) -> Result<RoutineActionStatus, RoutineSessionError> {
panic!("configuration validation and denied preparation must never poll")
}
async fn cancel(&self, _: RoutineSessionAction) -> Result<(), RoutineSessionError> {
panic!("configuration validation must never cancel")
}
}
pub(crate) fn agent_task() -> Value {
json!({"agent":{"bot_id":BOT}, "prompt":"instructions", "user_prompt":"task"})
}
#[tokio::test]
async fn local_validation_precedes_remote_authorization() {
let sessions = Arc::new(Sessions::default());
let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();
let validator = TargetValidation::new(sessions.clone());
for task in [
json!({}),
json!({"prompt":"instructions", "user_prompt":"task"}),
json!({"model":" ", "prompt":"instructions", "user_prompt":"task"}),
json!({"agent":{"bot_id":"bad-id"}, "prompt":"instructions", "user_prompt":"task"}),
json!({"agent":{"bot_id":BOT}, "model":"", "prompt":"instructions", "user_prompt":"task"}),
] {
let error = validator.validate_task(&task, &owner).await.unwrap_err();
assert!(matches!(
error.downcast_ref(),
Some(TargetValidationError::InvalidTask | TargetValidationError::InvalidProgram(_))
));
}
assert!(sessions.validations.lock().unwrap().is_empty());
}
#[tokio::test]
async fn model_selection_validates_a_macro_session() {
let sessions = Arc::new(Sessions::default());
let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();
TargetValidation::new(sessions.clone())
.validate_task(
&json!({"model":"runtime/model", "prompt":"instructions", "user_prompt":"task"}),
&owner,
)
.await
.unwrap();
let validations = sessions.validations.lock().unwrap();
assert_eq!(validations.len(), 1);
assert_eq!(validations[0].bot_id, bot_id::MACRO_NEW_BOT_ID);
assert_eq!(validations[0].model.as_deref(), Some("runtime/model"));
assert_eq!(validations[0].owner, owner);
assert!(sessions.preparations.lock().unwrap().is_empty());
}
#[tokio::test]
async fn a_validator_without_sessions_rejects_agents() {
let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();
let error = ModelOnlyTargets
.validate_task(&agent_task(), &owner)
.await
.unwrap_err();
assert_eq!(
error.downcast_ref(),
Some(&TargetValidationError::SessionsUnavailable)
);
}
/// A user's own agent, built in or on a self-hosted runtime, is checked by
/// the session domain rather than refused by the scheduler.
#[tokio::test]
async fn hands_an_owned_agent_to_the_session_check() {
let sessions = Arc::new(Sessions::default());
let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();
TargetValidation::new(sessions.clone())
.validate_task(&agent_task(), &owner)
.await
.unwrap();
let validations = sessions.validations.lock().unwrap();
assert_eq!(validations.len(), 1);
assert_eq!(validations[0].bot_id.to_string(), BOT);
assert_eq!(validations[0].owner, owner);
}
#[tokio::test]
async fn rejects_a_deleted_agent() {
let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();
let error = TargetValidation::new(Arc::new(Sessions::default()))
.validate_task(
&json!({"agent":{"bot_id":"01960000-0000-7000-8000-0000000000ff"}, "prompt":"instructions", "user_prompt":"task"}),
&owner,
)
.await
.unwrap_err();
assert_eq!(
error.downcast_ref(),
Some(&RoutineSessionError::PersonaUnavailable)
);
}
#[tokio::test]
async fn authorizes_owner_and_override_without_starting_external_runtime() {
let sessions = Arc::new(Sessions::default());
let validator = TargetValidation::new(sessions.clone());
let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();
for model in [None, Some("external/model")] {
let mut task = agent_task();
if let Some(model) = model {
task["model"] = json!(model);
}
validator.validate_task(&task, &owner).await.unwrap();
let calls = sessions.validations.lock().unwrap();
let call = calls.last().unwrap();
assert_eq!(call.owner, owner);
assert_eq!(call.bot_id.to_string(), BOT);
assert_eq!(call.model.as_deref(), model);
}
let foreign = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let error = validator
.validate_task(&agent_task(), &foreign)
.await
.unwrap_err();
assert_eq!(error.downcast_ref(), Some(&RoutineSessionError::Forbidden));
assert!(sessions.preparations.lock().unwrap().is_empty());
}
#[test]
fn requires_explicit_null_to_remove_even_an_unparseable_historical_selection() {
for previous in [
agent_task(),
json!({"agent":{"bot_id":"deleted-legacy-id"}}),
] {
let error = require_explicit_selection(&previous, &json!({"model":"model"})).unwrap_err();
assert_eq!(
error.downcast_ref(),
Some(&TargetValidationError::ExplicitAgentRequired)
);
require_explicit_selection(&previous, &json!({"agent":null,"model":"model"})).unwrap();
require_explicit_selection(&previous, &agent_task()).unwrap();
}
require_explicit_selection(&json!({"model":"old"}), &json!({"model":"new"})).unwrap();
}
#[tokio::test]
async fn hands_the_routine_apps_to_the_session_check() {
let sessions = Arc::new(Sessions::default());
let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();
TargetValidation::new(sessions.clone())
.validate_task(
&json!({
"agent": {"bot_id": BOT},
"mcp_servers": [{"app_slug": "linear", "server_name": "Linear"}],
"prompt": "instructions",
"user_prompt": "task",
}),
&owner,
)
.await
.unwrap();
assert_eq!(
sessions.validations.lock().unwrap()[0].mcp_servers,
vec![bots::domain::models::AgentMcpServer {
app_slug: "linear".into(),
server_name: "Linear".into(),
}]
);
*sessions.error.lock().unwrap() = Some(RoutineSessionError::AppNotConnected);
let error = TargetValidation::new(sessions.clone())
.validate_task(
&json!({
"model": "runtime/model",
"mcp_servers": [{"app_slug": "linear", "server_name": "Linear"}],
"prompt": "instructions",
"user_prompt": "task",
}),
&owner,
)
.await
.unwrap_err();
assert_eq!(
error.downcast_ref(),
Some(&RoutineSessionError::AppNotConnected)
);
}
#[tokio::test]
async fn a_validator_that_cannot_check_connections_rejects_routine_apps() {
let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();
let error = ModelOnlyTargets
.validate_task(
&json!({
"model": "runtime/model",
"mcp_servers": [{"app_slug": "linear", "server_name": "Linear"}],
"prompt": "instructions",
"user_prompt": "task",
}),
&owner,
)
.await
.unwrap_err();
assert_eq!(
error.downcast_ref(),
Some(&TargetValidationError::SessionsUnavailable)
);
}
#[test]
fn an_update_must_restate_the_routine_apps_to_keep_or_clear_them() {
let previous = json!({
"model": "model",
"mcp_servers": [{"app_slug": "linear", "server_name": "Linear"}],
});
let error = require_explicit_selection(&previous, &json!({"model":"model"})).unwrap_err();
assert_eq!(
error.downcast_ref(),
Some(&TargetValidationError::ExplicitAppsRequired)
);
require_explicit_selection(&previous, &json!({"model":"model","mcp_servers":[]})).unwrap();
require_explicit_selection(&json!({"model":"old"}), &json!({"model":"new"})).unwrap();
}
#[tokio::test]
async fn every_agent_step_is_authorized_and_structural_errors_name_the_rule() {
let sessions = Arc::new(Sessions::default());
let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();
let program = json!({ "steps": [
{ "type": "code", "title": "Label it", "source": "export async function main() {}" },
{ "type": "agent", "agent": { "bot_id": BOT }, "instructions": "Escalate" }
] });
TargetValidation::new(sessions.clone())
.validate_task(&program, &owner)
.await
.unwrap();
{
let validations = sessions.validations.lock().unwrap();
assert_eq!(validations.len(), 1);
assert_eq!(validations[0].bot_id.to_string(), BOT);
}
let error = ModelOnlyTargets
.validate_task(&program, &owner)
.await
.unwrap_err();
assert_eq!(
error.downcast_ref(),
Some(&TargetValidationError::SessionsUnavailable)
);
let sequential = json!({ "steps": [
{ "type": "agent", "model": "m", "instructions": "One" },
{ "type": "agent", "model": "m", "instructions": "Two" }
] });
let error = TargetValidation::new(sessions.clone())
.validate_task(&sequential, &owner)
.await
.unwrap_err();
assert_eq!(
error.to_string(),
"a routine can hand off to at most one agent"
);
// Structural errors stop it before any agent is authorized.
assert_eq!(sessions.validations.lock().unwrap().len(), 1);
}
#[test]
fn programs_never_trip_the_old_client_agent_guard() {
let previous = agent_task();
let program =
json!({ "steps": [{ "type": "agent", "agent": { "bot_id": BOT }, "instructions": "x" }] });
require_explicit_selection(&previous, &program).unwrap();
assert!(
require_explicit_selection(
&previous,
&json!({ "model": "m", "prompt": "", "user_prompt": "x" })
)
.is_err()
);
}
#[test]
fn an_update_from_before_steps_cannot_replace_them() {
let program = json!({ "steps": [{ "type": "code", "title": "Comment", "source": "export async function main() {}" }] });
let error = require_explicit_selection(
&program,
&json!({ "model": "m", "prompt": "", "user_prompt": "x" }),
)
.unwrap_err();
assert_eq!(
error.downcast_ref::<TargetValidationError>(),
Some(&TargetValidationError::ExplicitStepsRequired)
);
// A program may still be replaced by another program.
require_explicit_selection(&program, &json!({ "steps": [] })).unwrap();
}
#[tokio::test]
async fn a_program_hands_its_apps_to_its_agent_and_an_update_must_restate_them() {
let sessions = Arc::new(Sessions::default());
let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();
let program = json!({
"steps": [{ "type": "agent", "agent": { "bot_id": BOT }, "instructions": "File it" }],
"mcp_servers": [{ "app_slug": "linear", "server_name": "Linear" }],
});
TargetValidation::new(sessions.clone())
.validate_task(&program, &owner)
.await
.unwrap();
assert_eq!(
sessions.validations.lock().unwrap()[0].mcp_servers,
vec![bots::domain::models::AgentMcpServer {
app_slug: "linear".into(),
server_name: "Linear".into(),
}]
);
let without_apps =
json!({ "steps": [{ "type": "agent", "agent": { "bot_id": BOT }, "instructions": "x" }] });
let error = require_explicit_selection(&program, &without_apps).unwrap_err();
assert_eq!(
error.downcast_ref(),
Some(&TargetValidationError::ExplicitAppsRequired)
);
}