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 item_filters::ast::EntityFilterAst;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Arc;
const OWNER: &str = "macro|[email protected]";
const MEMBER: &str = "macro|[email protected]";
const STRANGER: &str = "macro|[email protected]";
const BOT_ID: Uuid = Uuid::from_u128(0xa9e7);
const CHANNEL_ID: Uuid = Uuid::from_u128(0xc05);
#[test]
fn persisted_row_metadata_survives_property_enrichment() {
let created_at = "2026-01-01T00:00:00Z".parse().unwrap();
let item = row_to_item(AgentSessionRow {
id: Uuid::now_v7(),
name: "Fix agent rows".to_owned(),
owner_id: OWNER.to_owned(),
bot_id: BOT_ID,
harness: "cursor".to_owned(),
repo_url: Some("https://github.com/macro/macro".to_owned()),
repo_branch: Some("main".to_owned()),
working_branch: Some("cursor/fix-rows".to_owned()),
pull_request_url: Some("https://github.com/macro/macro/pull/6712".to_owned()),
turn_state: Some("running".to_owned()),
thread_id: None,
source: "user".to_owned(),
visibility: "listed".to_owned(),
archived_by: None,
archived_at: None,
status: "event".to_owned(),
status_event_name: Some("acp_ready".to_owned()),
created_at,
modified_at: created_at,
viewed_at: None,
})
.expect("valid persisted session")
.map_extra(|()| "properties");
let SoupItem::AgentSession(session) = item else {
panic!("expected an agent session");
};
assert_eq!(session.harness, "cursor");
assert_eq!(
session.repo_url.as_deref(),
Some("https://github.com/macro/macro")
);
assert_eq!(session.repo_branch.as_deref(), Some("main"));
assert_eq!(
session.pull_request_url.as_deref(),
Some("https://github.com/macro/macro/pull/6712")
);
assert_eq!(session.turn_state.as_deref(), Some("running"));
assert_eq!(session.status, "acp_ready");
assert_eq!(
session.working_branch.as_deref(),
Some("cursor/fix-rows"),
"runtime working branch survives list mapping"
);
assert_eq!(
session.pull_request_state, None,
"unknown PR state stays unknown"
);
assert_eq!(session.extra, "properties");
}
struct Fixture {
/// Owned by `OWNER`, granted to `CHANNEL_ID` (where `MEMBER` participates).
shared: Uuid,
/// Owned by `OWNER` only.
private: Uuid,
}
async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
for user in [OWNER, MEMBER, STRANGER] {
let macro_user_id = Uuid::now_v7();
sqlx::query!(
"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $2, $2)",
macro_user_id,
user,
)
.execute(pool)
.await?;
sqlx::query!(
r#"INSERT INTO "User" ("id", "email", "macro_user_id") VALUES ($1, $1, $2)"#,
user,
macro_user_id,
)
.execute(pool)
.await?;
}
sqlx::query!(
r#"
INSERT INTO comms_channels (id, name, channel_type, owner_id)
VALUES ($1, 'agents', 'public', $2)
"#,
CHANNEL_ID,
OWNER,
)
.execute(pool)
.await?;
sqlx::query!(
r#"
INSERT INTO comms_channel_participants (channel_id, user_id, role)
VALUES ($1, $2, 'owner'), ($1, $3, 'member')
"#,
CHANNEL_ID,
OWNER,
MEMBER,
)
.execute(pool)
.await?;
let shared = Uuid::now_v7();
let private = Uuid::now_v7();
for (id, name, modified) in [
(shared, "Shared session", "2026-01-02T00:00:00Z"),
(private, "Private session", "2026-01-03T00:00:00Z"),
] {
let modified: chrono::DateTime<chrono::Utc> = modified.parse()?;
sqlx::query!(
r#"
INSERT INTO agent_session (
id, owner_id, bot_id, model, harness, repo_url, workspace, name,
status, status_event_name, created_at, modified_at
)
VALUES ($1, $2, $3, 'model', 'harness', NULL, '/workspace', $4,
'event', 'session/end', '2026-01-01 00:00:00+00', $5)
"#,
id,
OWNER,
BOT_ID,
name,
modified,
)
.execute(pool)
.await?;
sqlx::query!(
r#"
INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
VALUES ($1, 'agent_session', $2, 'user', 'owner')
"#,
id,
OWNER,
)
.execute(pool)
.await?;
}
sqlx::query!(
r#"
INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
VALUES ($1, 'agent_session', $2, 'channel', 'edit')
"#,
shared,
CHANNEL_ID.to_string(),
)
.execute(pool)
.await?;
Ok(Fixture { shared, private })
}
fn request(
user: &'static str,
filter: Option<Expr<AgentSessionLiteral>>,
) -> SimpleSortRequest<'static> {
let cursor = match filter {
Some(filter) => SimpleSortQuery::ItemsFilter(Query::Sort(
SimpleSortMethod::UpdatedAt,
EntityFilterAst {
agent_session_filter: Some(Arc::new(filter)),
..EntityFilterAst::default()
},
)),
None => SimpleSortQuery::NoFilter(Query::Sort(SimpleSortMethod::UpdatedAt, ())),
};
SimpleSortRequest {
limit: 10,
cursor,
user_id: MacroUserIdStr::parse_from_str(user).expect("valid user id"),
}
}
fn ids(items: &[SoupItem<()>]) -> Vec<Uuid> {
items
.iter()
.map(|item| match item {
SoupItem::AgentSession(session) => session.id,
other => panic!("unexpected soup item {other:?}"),
})
.collect()
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn runtime_branch_without_a_pr_is_listed_only_for_authorized_viewers(
pool: PgPool,
) -> anyhow::Result<()> {
let fixture = seed(&pool).await?;
sqlx::query!(
"UPDATE agent_session SET working_branch = 'cursor/no-pr', repo_url = 'https://github.com/example/example' WHERE id = $1",
fixture.shared,
).execute(&pool).await?;
let items = cursor_soup(
&pool,
request(MEMBER, Some(Expr::val(AgentSessionLiteral::Include))),
)
.await?;
let SoupItem::AgentSession(session) = &items[0] else {
unreachable!()
};
assert_eq!(session.id, fixture.shared);
assert_eq!(session.working_branch.as_deref(), Some("cursor/no-pr"));
assert_eq!(session.pull_request_url, None);
assert!(
cursor_soup(
&pool,
request(STRANGER, Some(Expr::val(AgentSessionLiteral::Include)))
)
.await?
.is_empty()
);
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn sessions_are_opt_in(pool: PgPool) -> anyhow::Result<()> {
seed(&pool).await?;
let no_filter = cursor_soup(&pool, request(OWNER, None)).await?;
assert!(no_filter.is_empty(), "no AST must not surface sessions");
let ast_without_sessions = SimpleSortRequest {
limit: 10,
cursor: SimpleSortQuery::ItemsFilter(Query::Sort(
SimpleSortMethod::UpdatedAt,
EntityFilterAst::default(),
)),
user_id: MacroUserIdStr::parse_from_str(OWNER)?,
};
assert!(
cursor_soup(&pool, ast_without_sessions).await?.is_empty(),
"an AST that never mentions sessions must not surface them"
);
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn include_lists_accessible_sessions_newest_first(pool: PgPool) -> anyhow::Result<()> {
let fixture = seed(&pool).await?;
let owner_items = cursor_soup(
&pool,
request(OWNER, Some(Expr::val(AgentSessionLiteral::Include))),
)
.await?;
assert_eq!(ids(&owner_items), vec![fixture.private, fixture.shared]);
let SoupItem::AgentSession(private) = &owner_items[0] else {
unreachable!()
};
assert_eq!(private.name, "Private session");
assert_eq!(private.status, "session/end");
assert_eq!(private.owner_id.principal_id(), OWNER);
assert_eq!(private.bot_id, BOT_ID);
let member_items = cursor_soup(
&pool,
request(MEMBER, Some(Expr::val(AgentSessionLiteral::Include))),
)
.await?;
assert_eq!(
ids(&member_items),
vec![fixture.shared],
"channel members see only the session shared into their channel"
);
let stranger_items = cursor_soup(
&pool,
request(STRANGER, Some(Expr::val(AgentSessionLiteral::Include))),
)
.await?;
assert!(stranger_items.is_empty());
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn id_and_owner_literals_constrain_the_page(pool: PgPool) -> anyhow::Result<()> {
let fixture = seed(&pool).await?;
let by_id = cursor_soup(
&pool,
request(
OWNER,
Some(Expr::val(AgentSessionLiteral::Id(fixture.shared))),
),
)
.await?;
assert_eq!(ids(&by_id), vec![fixture.shared]);
let by_owner = cursor_soup(
&pool,
request(
MEMBER,
Some(Expr::val(AgentSessionLiteral::Owner(
Owner::from_principal_str(OWNER)?,
))),
),
)
.await?;
assert_eq!(ids(&by_owner), vec![fixture.shared]);
let other_owner = cursor_soup(
&pool,
request(
OWNER,
Some(Expr::val(AgentSessionLiteral::Owner(
Owner::from_principal_str(MEMBER)?,
))),
),
)
.await?;
assert!(other_owner.is_empty());
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn cursor_pages_past_the_first_row(pool: PgPool) -> anyhow::Result<()> {
let fixture = seed(&pool).await?;
let first = cursor_soup(
&pool,
SimpleSortRequest {
limit: 1,
cursor: SimpleSortQuery::ItemsFilter(Query::Sort(
SimpleSortMethod::UpdatedAt,
EntityFilterAst {
agent_session_filter: Some(Arc::new(Expr::val(AgentSessionLiteral::Include))),
..EntityFilterAst::default()
},
)),
user_id: MacroUserIdStr::parse_from_str(OWNER)?,
},
)
.await?;
assert_eq!(ids(&first), vec![fixture.private]);
let SoupItem::AgentSession(private) = &first[0] else {
unreachable!()
};
let second = cursor_soup(
&pool,
SimpleSortRequest {
limit: 1,
cursor: SimpleSortQuery::ItemsFilter(Query::Cursor(
models_pagination::CursorWithValAndFilter {
id: private.id,
limit: 1,
val: models_pagination::CursorVal {
sort_type: SimpleSortMethod::UpdatedAt,
last_val: private.updated_at,
},
filter: EntityFilterAst {
agent_session_filter: Some(Arc::new(Expr::val(
AgentSessionLiteral::Include,
))),
..EntityFilterAst::default()
},
},
)),
user_id: MacroUserIdStr::parse_from_str(OWNER)?,
},
)
.await?;
assert_eq!(ids(&second), vec![fixture.shared]);
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn by_ids_respects_access(pool: PgPool) -> anyhow::Result<()> {
let fixture = seed(&pool).await?;
let entities = [
EntityType::AgentSession.with_entity_string(fixture.shared.to_string()),
EntityType::AgentSession.with_entity_string(fixture.private.to_string()),
EntityType::Chat.with_entity_string(fixture.private.to_string()),
];
let owner_items = by_ids(
&pool,
AdvancedSortParams {
entities: &entities,
user_id: MacroUserIdStr::parse_from_str(OWNER)?,
},
)
.await?;
assert_eq!(ids(&owner_items), vec![fixture.private, fixture.shared]);
let member_items = by_ids(
&pool,
AdvancedSortParams {
entities: &entities,
user_id: MacroUserIdStr::parse_from_str(MEMBER)?,
},
)
.await?;
assert_eq!(ids(&member_items), vec![fixture.shared]);
Ok(())
}
/// A hidden session (one started from a thread) is missing from broad lists for
/// everyone, but a named id still finds it and hydrating by id still works.
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn hidden_sessions_stay_out_of_broad_lists(pool: PgPool) -> anyhow::Result<()> {
let fixture = seed(&pool).await?;
sqlx::query!(
"UPDATE agent_session SET visibility = 'hidden' WHERE id = $1",
fixture.shared,
)
.execute(&pool)
.await?;
let owner_before = cursor_soup(
&pool,
request(OWNER, Some(Expr::val(AgentSessionLiteral::Include))),
)
.await?;
assert_eq!(
ids(&owner_before),
vec![fixture.private],
"the owner's list omits the unopened inline session"
);
let member_before = cursor_soup(
&pool,
request(MEMBER, Some(Expr::val(AgentSessionLiteral::Include))),
)
.await?;
assert!(
member_before.is_empty(),
"a channel member does not inherit the owner's list"
);
let named = cursor_soup(
&pool,
request(
OWNER,
Some(Expr::val(AgentSessionLiteral::Id(fixture.shared))),
),
)
.await?;
assert_eq!(ids(&named), vec![fixture.shared]);
let entities = [EntityType::AgentSession.with_entity_string(fixture.shared.to_string())];
let hydrated = by_ids(
&pool,
AdvancedSortParams {
entities: &entities,
user_id: MacroUserIdStr::parse_from_str(MEMBER)?,
},
)
.await?;
assert_eq!(ids(&hydrated), vec![fixture.shared]);
Ok(())
}
/// Hidden unthreaded DM contexts use the same broad-list visibility boundary
/// as inline mentions, without losing owner access by ID.
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn hidden_dm_contexts_are_omitted_from_home_and_agents_but_open_by_id(
pool: PgPool,
) -> anyhow::Result<()> {
let fixture = seed(&pool).await?;
let dm = Uuid::now_v7();
sqlx::query!(
"INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'direct_message', $2)",
dm,
OWNER
)
.execute(&pool)
.await?;
sqlx::query!("INSERT INTO comms_channel_participants (channel_id, user_id, role) VALUES ($1, $2, 'owner')", dm, OWNER)
.execute(&pool).await?;
sqlx::query!("INSERT INTO comms_channel_agents (channel_id, bot_id, kind, user_id) VALUES ($1, $2, 'direct', $3)", dm, BOT_ID, OWNER)
.execute(&pool).await?;
sqlx::query!("INSERT INTO agent_conversation_sessions (session_id, channel_id, bot_id) VALUES ($1, $2, $3)", fixture.shared, dm, BOT_ID)
.execute(&pool).await?;
// The session domain's enabled policy persists these two flags.
sqlx::query!(
"UPDATE agent_session SET visibility = 'hidden', for_warming = FALSE WHERE id = $1",
fixture.shared
)
.execute(&pool)
.await?;
for literal in [
AgentSessionLiteral::Include,
AgentSessionLiteral::Owner(Owner::from_principal_str(OWNER)?),
] {
let listed = cursor_soup(&pool, request(OWNER, Some(Expr::val(literal)))).await?;
assert_eq!(ids(&listed), vec![fixture.private]);
}
let named = cursor_soup(
&pool,
request(
OWNER,
Some(Expr::val(AgentSessionLiteral::Id(fixture.shared))),
),
)
.await?;
assert_eq!(ids(&named), vec![fixture.shared]);
let entities = [EntityType::AgentSession.with_entity_string(fixture.shared.to_string())];
let opened = by_ids(
&pool,
AdvancedSortParams {
entities: &entities,
user_id: MacroUserIdStr::parse_from_str(OWNER)?,
},
)
.await?;
assert_eq!(ids(&opened), vec![fixture.shared]);
let channel = sqlx::query_scalar!("SELECT id FROM comms_channels WHERE id = $1", dm)
.fetch_one(&pool)
.await?;
assert_eq!(channel, dm);
Ok(())
}
/// A routine's unlisted runs stay reachable for whoever asks for them, say a
/// routine started them, and are what a list asks for by source or
/// visibility: alone, or left out.
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn unlisted_runs_leave_lists_that_exclude_them(pool: PgPool) -> anyhow::Result<()> {
let fixture = seed(&pool).await?;
sqlx::query!(
"UPDATE agent_session SET source = 'routine', visibility = 'unlisted' WHERE id = $1",
fixture.private,
)
.execute(&pool)
.await?;
let routine = || Expr::val(AgentSessionLiteral::Source(AgentSessionSource::Routine));
let unlisted = || {
Expr::val(AgentSessionLiteral::Visibility(
AgentSessionVisibility::Unlisted,
))
};
let all = cursor_soup(
&pool,
request(OWNER, Some(Expr::val(AgentSessionLiteral::Include))),
)
.await?;
assert_eq!(ids(&all), vec![fixture.private, fixture.shared]);
let SoupItem::AgentSession(run) = &all[0] else {
panic!("expected an agent session");
};
assert_eq!(run.source, AgentSessionSource::Routine);
assert_eq!(run.visibility, AgentSessionVisibility::Unlisted);
let only_runs = cursor_soup(
&pool,
request(
OWNER,
Some(Expr::and(
Expr::val(AgentSessionLiteral::Include),
routine(),
)),
),
)
.await?;
assert_eq!(ids(&only_runs), vec![fixture.private]);
let without_runs = cursor_soup(
&pool,
request(
OWNER,
Some(Expr::and(
Expr::val(AgentSessionLiteral::Include),
Expr::is_not(routine()),
)),
),
)
.await?;
assert_eq!(ids(&without_runs), vec![fixture.shared]);
let listed = cursor_soup(
&pool,
request(
OWNER,
Some(Expr::and(
Expr::val(AgentSessionLiteral::Include),
Expr::is_not(unlisted()),
)),
),
)
.await?;
assert_eq!(ids(&listed), vec![fixture.shared]);
Ok(())
}
/// A session started from a document or call thread inherits the parent's
/// viewers, as the session's REST read and its inline chip already do, so
/// opening it by id works for someone who prompted it or saw it in the thread.
/// Broad lists stay limited to grants on the session itself.
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn by_ids_inherits_the_parent_thread_access(pool: PgPool) -> anyhow::Result<()> {
let fixture = seed(&pool).await?;
let entities = [EntityType::AgentSession.with_entity_string(fixture.private.to_string())];
for kind in ["document", "call"] {
let root = Uuid::now_v7();
// A call's thread root carries the call's own id.
let parent = if kind == "call" { root } else { Uuid::now_v7() };
sqlx::query!(
r#"INSERT INTO comms_messages (id, parent_entity_type, parent_entity_id, sender_id, content)
VALUES ($1, $2, $3, $4, '@macro look')"#,
root,
kind,
parent.to_string(),
OWNER,
)
.execute(&pool)
.await?;
sqlx::query!(
"UPDATE agent_session SET thread_id = $1 WHERE id = $2",
root,
fixture.private,
)
.execute(&pool)
.await?;
let stranger_items = by_ids(
&pool,
AdvancedSortParams {
entities: &entities,
user_id: MacroUserIdStr::parse_from_str(STRANGER)?,
},
)
.await?;
assert!(
stranger_items.is_empty(),
"no access to the {kind} means no access to its session"
);
sqlx::query!(
r#"
INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
VALUES ($1, $2, $3, 'user', 'view')
"#,
parent,
kind,
STRANGER,
)
.execute(&pool)
.await?;
let viewer_items = by_ids(
&pool,
AdvancedSortParams {
entities: &entities,
user_id: MacroUserIdStr::parse_from_str(STRANGER)?,
},
)
.await?;
assert_eq!(ids(&viewer_items), vec![fixture.private], "{kind} viewer");
// GraphQL `agentSession` loads through a cursor query naming the id.
let named = cursor_soup(
&pool,
request(
STRANGER,
Some(Expr::val(AgentSessionLiteral::Id(fixture.private))),
),
)
.await?;
assert_eq!(ids(&named), vec![fixture.private], "{kind} viewer by id");
let listed = cursor_soup(
&pool,
request(STRANGER, Some(Expr::val(AgentSessionLiteral::Include))),
)
.await?;
assert!(listed.is_empty(), "{kind} access does not list the session");
sqlx::query!(
"UPDATE comms_message_threads SET deleted_at = NOW() WHERE root_id = $1",
root,
)
.execute(&pool)
.await?;
let after_delete = by_ids(
&pool,
AdvancedSortParams {
entities: &entities,
user_id: MacroUserIdStr::parse_from_str(STRANGER)?,
},
)
.await?;
assert!(
after_delete.is_empty(),
"a deleted {kind} thread no longer shares its session"
);
}
Ok(())
}
/// A session started from a document thread is hidden, so mentioning the
/// agent there lists it for nobody, owner included. Prompting it from the
/// session itself follows it: it then lists for that one person while they
/// can still read it, through a session grant or the thread's parent.
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn a_hidden_thread_session_lists_only_for_its_followers(pool: PgPool) -> anyhow::Result<()> {
let fixture = seed(&pool).await?;
let document = Uuid::now_v7();
let root = Uuid::now_v7();
sqlx::query!(
r#"INSERT INTO comms_messages (id, parent_entity_type, parent_entity_id, sender_id, content)
VALUES ($1, 'document', $2, $3, '@agent look')"#,
root,
document.to_string(),
OWNER,
)
.execute(&pool)
.await?;
sqlx::query!(
"UPDATE agent_session SET thread_id = $1, visibility = 'hidden' WHERE id = $2",
root,
fixture.private,
)
.execute(&pool)
.await?;
sqlx::query!(
r#"
INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
VALUES ($1, 'document', $2, 'user', 'edit')
"#,
document,
STRANGER,
)
.execute(&pool)
.await?;
let include = || Some(Expr::val(AgentSessionLiteral::Include));
assert_eq!(
ids(&cursor_soup(&pool, request(OWNER, include())).await?),
vec![fixture.shared],
"the owner's mention lists nothing"
);
assert!(
cursor_soup(&pool, request(STRANGER, include()))
.await?
.is_empty(),
"a document editor who never prompted it directly sees nothing"
);
sqlx::query!(
"INSERT INTO agent_session_follower (agent_session_id, user_id) VALUES ($1, $2)",
fixture.private,
STRANGER,
)
.execute(&pool)
.await?;
assert_eq!(
ids(&cursor_soup(&pool, request(STRANGER, include())).await?),
vec![fixture.private],
"the follower reads it through the document and lists it"
);
assert_eq!(
ids(&cursor_soup(&pool, request(OWNER, include())).await?),
vec![fixture.shared],
"another person's follow changes nothing for the owner"
);
sqlx::query!(
"INSERT INTO agent_session_follower (agent_session_id, user_id) VALUES ($1, $2)",
fixture.private,
OWNER,
)
.execute(&pool)
.await?;
assert_eq!(
ids(&cursor_soup(&pool, request(OWNER, include())).await?),
vec![fixture.private, fixture.shared],
"the owner follows it once they prompt it directly"
);
sqlx::query!(
"DELETE FROM entity_access WHERE entity_id = $1 AND source_id = $2",
document,
STRANGER,
)
.execute(&pool)
.await?;
assert!(
cursor_soup(&pool, request(STRANGER, include()))
.await?
.is_empty(),
"following never outlives access"
);
Ok(())
}