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 async_graphql::{EmptyMutation, EmptySubscription, Object, Schema, futures_util::StreamExt};
use graphql_entity_mutation::GraphqlEntityMutationResult;
use tracing::{
Event, Metadata, Subscriber,
field::{Field, Visit},
span::{Attributes, Id, Record},
};
const PATCH_SELECTION: &str = r#"
__typename
... on SoupUpdated { item { __typename id displayName cacheProjection ... on GraphqlSoupChat { model } ... on GraphqlSoupForeignEntity { sourceMetadata } ... on GraphqlSoupAgentSession { pullRequestState pullRequestId } } }
... on GraphqlCacheDeletion { graphqlTypeName entityId }
"#;
type RealtimeSchema = SoupSchema<
CountingSoupService,
TestRealtimeSubscriptionService,
NoopWebSocketNotificationSubscriptionService,
graphql_activity::NoOpActivitySubscriptionService,
NoOpEmailService,
NoOpEntityAccessService,
SchemaOnlyAuthorizationService,
SchemaOnlyState,
NoOpEntityPropertyWriter,
UnavailableEntityMutationService,
NoOpFavoriteMutationService,
NoOpChannelActivityMutationService,
NoOpNotificationMutationService,
NoOpSoupNotificationEdgeReader,
NoOpEntityPropertyReader,
NoOpSoupEmailContentEdgeReader,
NoOpEntityFavoriteEdgeReader,
NoOpEntityPermissionEdgeReader,
NoOpActivityReader,
>;
type TestEdges = SoupEdges<
NoOpSoupNotificationEdgeReader,
NoOpEntityPropertyReader,
NoOpSoupEmailContentEdgeReader,
NoOpEntityFavoriteEdgeReader,
NoOpEntityPermissionEdgeReader,
NoOpActivityReader,
>;
fn entity(id: u128) -> model_entity::Entity<'static> {
ModelEntityType::Document.with_entity_string(Uuid::from_u128(id).to_string())
}
async fn subscription_responses(
soup: CountingSoupService,
patches: Vec<Patch<model_entity::Entity<'static>>>,
) -> Vec<async_graphql::Response> {
subscription_responses_from(soup.clone(), soup, patches).await
}
/// Runs `soupUpdates` with separate list (replica) and hydration (primary) readers.
async fn subscription_responses_from(
replica: CountingSoupService,
primary: CountingSoupService,
patches: Vec<Patch<model_entity::Entity<'static>>>,
) -> Vec<async_graphql::Response> {
let (sender, receiver) = tokio::sync::mpsc::channel(16);
for patch in patches {
sender.send(patch).await.unwrap();
}
drop(sender);
let list_loader = graphql_soup::soup_item_loader(
replica.clone(),
Arc::new(NoOpEmailService),
NoOpEntityAccessService,
);
let hydration_loader = graphql_soup::PrimarySoupItemLoader::new(
primary,
Arc::new(NoOpEmailService),
NoOpEntityAccessService,
);
let schema: RealtimeSchema = build_schema_with_services(
replica,
TestRealtimeSubscriptionService {
receiver: Arc::new(Mutex::new(Some(receiver))),
subscribed_user: Arc::new(Mutex::new(None)),
},
NoopWebSocketNotificationSubscriptionService,
graphql_activity::NoOpActivitySubscriptionService,
);
let request = async_graphql::Request::new(format!(
"subscription {{ soupUpdates {{ {PATCH_SELECTION} }} }}"
))
.data(MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap())
.data(list_loader)
.data(hydration_loader);
tokio::time::timeout(
std::time::Duration::from_secs(5),
schema.execute_stream(request).collect(),
)
.await
.expect("closed source terminates the subscription")
}
#[tokio::test]
async fn batch_keeps_last_operation_per_entity_and_batches_hydration() {
let soup = CountingSoupService::default();
soup.set_raw_response(vec![
soup_document(Uuid::from_u128(1)),
soup_document(Uuid::from_u128(2)),
]);
let calls = soup.raw_calls.clone();
let responses = subscription_responses(
soup,
vec![
Patch::Updated(entity(1)),
Patch::Deleted(entity(2)),
Patch::Updated(entity(1)),
Patch::Updated(entity(2)),
Patch::Updated(entity(3)),
Patch::Deleted(entity(3)),
],
)
.await;
assert_eq!(responses.len(), 1);
assert!(responses[0].errors.is_empty(), "{:?}", responses[0].errors);
let data = responses[0].data.clone().into_json().unwrap();
let patches = data["soupUpdates"].as_array().unwrap();
assert_eq!(patches.len(), 3);
for (patch, id) in patches[..2].iter().zip([1, 2]) {
assert_eq!(patch["__typename"], "SoupUpdated");
assert_eq!(patch["item"]["id"], Uuid::from_u128(id).to_string());
assert!(patch["item"]["cacheProjection"].is_string());
}
assert_eq!(patches[2]["__typename"], "GraphqlCacheDeletion");
assert_eq!(patches[2]["entityId"], Uuid::from_u128(3).to_string());
assert_eq!(
calls.load(Ordering::SeqCst),
1,
"surviving updates share a DataLoader request"
);
}
#[tokio::test]
async fn updates_hydrate_from_the_primary_before_the_replica_replays_them() {
let replica = CountingSoupService {
return_empty_raw: true,
..CountingSoupService::default()
};
let replica_calls = replica.raw_calls.clone();
let primary = CountingSoupService::default();
primary.set_raw_response(vec![soup_document(Uuid::from_u128(1))]);
let responses =
subscription_responses_from(replica, primary, vec![Patch::Updated(entity(1))]).await;
assert_eq!(responses.len(), 1);
assert!(responses[0].errors.is_empty(), "{:?}", responses[0].errors);
let data = responses[0].data.clone().into_json().unwrap();
assert_eq!(
data["soupUpdates"][0]["item"]["id"],
Uuid::from_u128(1).to_string()
);
assert_eq!(replica_calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn later_batches_can_update_the_same_entity_again() {
let soup = CountingSoupService::default();
soup.set_raw_response(vec![soup_document(Uuid::from_u128(1))]);
let calls = soup.raw_calls.clone();
// The subscription's receive buffer holds ten entries. Deduplication must
// not remember the first batch's key and swallow the following update.
let responses = subscription_responses(soup, vec![Patch::Updated(entity(1)); 11]).await;
assert_eq!(responses.len(), 2);
for response in responses {
assert!(response.errors.is_empty());
let data = response.data.into_json().unwrap();
assert_eq!(data["soupUpdates"].as_array().unwrap().len(), 1);
assert_eq!(
data["soupUpdates"][0]["item"]["id"],
Uuid::from_u128(1).to_string()
);
}
assert_eq!(calls.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn chat_updates_hydrate_the_saved_model() {
let soup = CountingSoupService::default();
let chat_id = Uuid::from_u128(91);
soup.set_raw_response(vec![soup_chat(chat_id)]);
let responses = subscription_responses(
soup,
vec![Patch::Updated(
ModelEntityType::Chat.with_entity_string(chat_id.to_string()),
)],
)
.await;
assert_eq!(responses.len(), 1);
assert!(responses[0].errors.is_empty(), "{:?}", responses[0].errors);
let data = responses[0].data.clone().into_json().unwrap();
assert_eq!(data["soupUpdates"][0]["item"]["model"], "openai/gpt-5.6");
}
#[tokio::test]
async fn dedup_uses_entity_type_and_id_and_preserves_last_occurrence_order() {
let soup = CountingSoupService::default();
let calls = soup.raw_calls.clone();
let project = ModelEntityType::Project.with_entity_string(Uuid::from_u128(1).to_string());
let responses = subscription_responses(
soup,
vec![
Patch::Updated(entity(1)),
Patch::Deleted(project),
Patch::Deleted(entity(1)),
],
)
.await;
assert_eq!(responses.len(), 1);
assert!(responses[0].errors.is_empty());
let data = responses[0].data.clone().into_json().unwrap();
let patches = data["soupUpdates"].as_array().unwrap();
assert_eq!(patches.len(), 2);
assert_eq!(patches[0]["graphqlTypeName"], "GraphqlSoupProject");
assert_eq!(patches[1]["graphqlTypeName"], "GraphqlSoupDocument");
assert_eq!(
calls.load(Ordering::SeqCst),
0,
"superseded updates never hydrate"
);
}
#[derive(Default)]
struct CapturedEvent {
fields: HashMap<String, String>,
}
impl Visit for CapturedEvent {
fn record_str(&mut self, field: &Field, value: &str) {
self.fields
.insert(field.name().to_owned(), value.to_owned());
}
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
self.fields
.insert(field.name().to_owned(), format!("{value:?}"));
}
}
struct EventCapture(Arc<Mutex<Vec<CapturedEvent>>>);
impl Subscriber for EventCapture {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
metadata.is_event() && metadata.target() == "graphql_soup::objects"
}
fn event(&self, event: &Event<'_>) {
let mut captured = CapturedEvent::default();
event.record(&mut captured);
self.0.lock().unwrap().push(captured);
}
// This probe observes structured events only, not span state or formatting.
fn new_span(&self, _attrs: &Attributes<'_>) -> Id {
Id::from_u64(1)
}
fn record(&self, _span: &Id, _values: &Record<'_>) {}
fn record_follows_from(&self, _span: &Id, _follows: &Id) {}
fn enter(&self, _span: &Id) {}
fn exit(&self, _span: &Id) {}
}
fn captured_events() -> Arc<Mutex<Vec<CapturedEvent>>> {
// The schema and DataLoader may poll work outside the test's scoped
// dispatcher. Keep one probe for this test binary and select each test's
// unique entity IDs. No production subscriber setup or formatter is needed.
static EVENTS: std::sync::OnceLock<Arc<Mutex<Vec<CapturedEvent>>>> = std::sync::OnceLock::new();
EVENTS
.get_or_init(|| {
let events = Arc::new(Mutex::new(Vec::new()));
tracing::subscriber::set_global_default(EventCapture(events.clone()))
.expect("test capture subscriber");
events
})
.clone()
}
#[tokio::test]
async fn two_missing_updates_log_identities_without_emitting_nulls_or_deletions() {
let events = captured_events();
let soup = CountingSoupService {
return_empty_raw: true,
..Default::default()
};
let responses = subscription_responses(
soup,
vec![Patch::Updated(entity(4)), Patch::Updated(entity(5))],
)
.await;
assert!(
responses.is_empty(),
"a batch of misses emits no data frame"
);
let events = events.lock().unwrap();
for id in [4, 5] {
let entity_id = Uuid::from_u128(id).to_string();
let matching = events
.iter()
.filter(|event| event.fields.get("entity_id") == Some(&entity_id))
.collect::<Vec<_>>();
assert_eq!(matching.len(), 1, "one hydration miss per entity");
let fields = &matching[0].fields;
assert!(fields["message"].contains("omitting update"));
assert_eq!(fields["user_id"], VALID_USER_ID);
assert_eq!(fields["entity_type"], "document");
}
}
#[tokio::test]
async fn missing_update_does_not_suppress_valid_sibling_or_explicit_delete() {
let soup = CountingSoupService::default();
soup.set_raw_response(vec![soup_document(Uuid::from_u128(1))]);
let responses = subscription_responses(
soup,
vec![
Patch::Updated(entity(1)),
Patch::Updated(entity(2)),
Patch::Deleted(entity(3)),
],
)
.await;
assert_eq!(responses.len(), 1);
assert!(responses[0].errors.is_empty());
let data = responses[0].data.clone().into_json().unwrap();
let patches = data["soupUpdates"].as_array().unwrap();
assert_eq!(patches.len(), 2);
assert_eq!(patches[0]["item"]["id"], Uuid::from_u128(1).to_string());
assert_eq!(patches[1]["entityId"], Uuid::from_u128(3).to_string());
}
#[tokio::test]
async fn hydration_service_failure_is_an_error_not_a_deletion() {
let events = captured_events();
let responses = subscription_responses(
CountingSoupService::default(),
vec![Patch::Updated(entity(6))],
)
.await;
assert_eq!(responses.len(), 1);
assert!(!responses[0].errors.is_empty());
assert!(
!responses[0]
.data
.to_string()
.contains("GraphqlCacheDeletion")
);
let events = events.lock().unwrap();
let entity_id = Uuid::from_u128(6).to_string();
let event = events
.iter()
.find(|event| event.fields.get("entity_id") == Some(&entity_id))
.expect("hydration failure logs its entity");
assert!(event.fields["message"].contains("failed to hydrate Soup update"));
assert!(event.fields.contains_key("error"));
assert_eq!(event.fields["user_id"], VALID_USER_ID);
}
struct MutationEffectsQuery;
#[Object]
impl MutationEffectsQuery {
async fn result(&self) -> GraphqlEntityMutationResult<TestEdges> {
GraphqlEntityMutationResult::from_updated_entity(entity(1))
}
}
#[tokio::test]
async fn mutation_effects_share_non_nullable_hydration_and_omit_misses() {
let soup = CountingSoupService::default();
soup.set_raw_response(vec![soup_document(Uuid::from_u128(1))]);
let loader = graphql_soup::soup_item_loader(
soup.clone(),
Arc::new(NoOpEmailService),
NoOpEntityAccessService,
);
let schema = Schema::build(MutationEffectsQuery, EmptyMutation, EmptySubscription)
.data(loader)
.data(entity_mutation::EntityMutationActor {
user_id: MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap(),
organization_id: None,
})
.finish();
let query = format!(
"{{ result {{ ... on GraphqlMutationSuccess {{ effects {{ {PATCH_SELECTION} }} }} }} }}"
);
let response = schema.execute(&query).await;
assert!(response.errors.is_empty(), "{:?}", response.errors);
let data = response.data.into_json().unwrap();
assert_eq!(
data["result"]["effects"][0]["item"]["id"],
Uuid::from_u128(1).to_string()
);
soup.set_raw_response(Vec::new());
let response = schema.execute(&query).await;
assert!(response.errors.is_empty(), "{:?}", response.errors);
let data = response.data.into_json().unwrap();
assert!(data["result"]["effects"].as_array().unwrap().is_empty());
}
#[tokio::test]
async fn initiative_patches_hydrate_and_delete_the_soup_record() {
let soup = CountingSoupService::default();
let id = Uuid::from_u128(42);
let removed_id = Uuid::from_u128(44);
soup.set_raw_response(vec![soup_initiative(id)]);
let responses = subscription_responses(
soup,
vec![
Patch::Updated(ModelEntityType::Initiative.with_entity_string(id.to_string())),
Patch::Deleted(ModelEntityType::Initiative.with_entity_string(removed_id.to_string())),
],
)
.await;
assert_eq!(responses.len(), 1);
assert!(responses[0].errors.is_empty(), "{:?}", responses[0].errors);
let data = responses[0].data.clone().into_json().unwrap();
let patches = data["soupUpdates"].as_array().unwrap();
assert_eq!(patches.len(), 2);
assert_eq!(patches[0]["item"]["__typename"], "GraphqlSoupInitiative");
assert_eq!(patches[0]["item"]["id"], id.to_string());
assert_eq!(patches[1]["graphqlTypeName"], "GraphqlSoupInitiative");
assert_eq!(patches[1]["entityId"], removed_id.to_string());
}
#[tokio::test]
async fn pr_and_linked_session_updates_serialize_current_metadata() {
use models_soup::{
agent_session::{AgentPullRequestState, SoupAgentSession},
foreign_entity::SoupForeignEntity,
};
let pr_id = Uuid::now_v7();
let session_id = Uuid::now_v7();
let now = chrono::Utc::now();
let soup = CountingSoupService::default();
soup.set_raw_response(vec![
SoupItem::ForeignEntity(SoupForeignEntity {
id: pr_id,
foreign_entity_id: "macro/app/pull/7".into(),
foreign_entity_source: "github_pull_request".into(),
metadata: async_graphql::value!({"title": "Updated PR", "state": "merged"})
.into_json()
.unwrap(),
stored_for_id: VALID_USER_ID.into(),
stored_for_auth_entity: "user".into(),
created_at: now,
updated_at: now,
}),
SoupItem::AgentSession(SoupAgentSession {
id: session_id,
name: "Linked session".into(),
archived_by: None,
archived_at: None,
owner_id: model_owner::Owner::from_principal_str(VALID_USER_ID).unwrap(),
bot_id: Uuid::now_v7(),
harness: "claude".into(),
repo_url: None,
repo_branch: None,
pull_request_url: Some("https://github.com/macro/app/pull/7".into()),
working_branch: None,
pull_request_state: Some(AgentPullRequestState::Merged),
pull_request_id: Some(pr_id),
turn_state: None,
thread_id: None,
status: "disconnected".into(),
created_at: now,
updated_at: now,
viewed_at: None,
extra: (),
source: models_soup::agent_session::AgentSessionSource::User,
visibility: models_soup::agent_session::AgentSessionVisibility::Listed,
}),
]);
let calls = soup.raw_calls.clone();
let responses = subscription_responses(
soup,
vec![
Patch::Updated(ModelEntityType::ForeignEntity.with_entity_string(pr_id.to_string())),
Patch::Updated(
ModelEntityType::AgentSession.with_entity_string(session_id.to_string()),
),
],
)
.await;
assert_eq!(responses.len(), 1);
assert!(responses[0].errors.is_empty(), "{:?}", responses[0].errors);
let data = responses[0].data.clone().into_json().unwrap();
let patches = data["soupUpdates"].as_array().unwrap();
let pr = patches
.iter()
.find(|p| p["item"]["id"] == pr_id.to_string())
.unwrap();
assert_eq!(pr["item"]["sourceMetadata"]["state"], "merged");
let session = patches
.iter()
.find(|p| p["item"]["id"] == session_id.to_string())
.unwrap();
assert_eq!(session["item"]["pullRequestState"], "MERGED");
assert_eq!(session["item"]["pullRequestId"], pr_id.to_string());
assert_eq!(calls.load(Ordering::SeqCst), 1);
}