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
fix(databases): share agent-created databases with the channel they were made in (#9568)
Wolf Mermelstein38be4f4d709b
diff --git a/crates/databases/AGENTS.md b/crates/databases/AGENTS.mdindex 9edf00f24e..fe2e573feb 100644--- a/crates/databases/AGENTS.md+++ b/crates/databases/AGENTS.md@@ -53,6 +53,10 @@ service with Axum, agent-tool and Postgres adapters.## Gotchas+- `POST /databases` and `POST /databases/{id}/duplicate` attribute the+ creation to the SDK token's `agent_id` (code mode, `agent_attribution`), like+ the native tool, so channel delivery shares a database an agent makes; access+ checks still run as the plain user (`viewer_of`).- Hosts authorize the database through their own entity before calling`storage_view_positions`; the operation also checks database, table and viewmembership.diff --git a/crates/databases/src/domain/duplicate.rs b/crates/databases/src/domain/duplicate.rsindex 6ee65e3657..bb90e87d5e 100644--- a/crates/databases/src/domain/duplicate.rs+++ b/crates/databases/src/domain/duplicate.rs@@ -27,11 +27,14 @@ pub trait DatabaseDuplicateRepo: Send + Sync + 'static {/// Duplicate use case; view access to the source is enough.pub trait DatabaseDuplicateService: Send + Sync + 'static {/// Copy the receipt's database for `owner`, named `name`, or "<name>- /// copy" without one.+ /// copy" without one. `acting_bot` is the agent duplicating it for the+ /// owner, `None` when the owner acts; only the creation's attribution+ /// reads it.fn duplicate_database(&self,receipt: EntityAccessReceipt<ViewAccessLevel>,owner: macro_user_id::user_id::MacroUserIdStr<'static>,+ acting_bot: Option<bot_id::BotId>,name: Option<String>,) -> impl Future<Output = Result<Database, DatabaseError>> + Send;}diff --git a/crates/databases/src/domain/entity_mutation.rs b/crates/databases/src/domain/entity_mutation.rsindex 0e0e88f44f..2dfe4a7cbf 100644--- a/crates/databases/src/domain/entity_mutation.rs+++ b/crates/databases/src/domain/entity_mutation.rs@@ -120,9 +120,14 @@ whereuser_id: MacroUserIdStr<'static>,display_name: Option<String>,) -> Result<Vec<EntityMutationEffect>, EntityMutationErrorCode> {- let copy =- DatabaseDuplicateService::duplicate_database(self, receipt, user_id, display_name)- .await?;+ let copy = DatabaseDuplicateService::duplicate_database(+ self,+ receipt,+ user_id,+ None,+ display_name,+ )+ .await?;Ok(vec![EntityMutationEffect::updated(EntityType::Database.with_entity_string(copy.id.to_string()),)])diff --git a/crates/databases/src/domain/service/duplicate.rs b/crates/databases/src/domain/service/duplicate.rsindex 5702069546..baadca3119 100644--- a/crates/databases/src/domain/service/duplicate.rs+++ b/crates/databases/src/domain/service/duplicate.rs@@ -614,11 +614,12 @@ whereAccess: AccessDirectory,Broker: MacroEventBroker,{- #[tracing::instrument(skip(self, receipt, owner, name), fields(database_id = %receipt.entity().entity_id, copy_id = tracing::field::Empty, tables = tracing::field::Empty, rows = tracing::field::Empty), err)]+ #[tracing::instrument(skip(self, receipt, owner, acting_bot, name), fields(database_id = %receipt.entity().entity_id, copy_id = tracing::field::Empty, tables = tracing::field::Empty, rows = tracing::field::Empty), err)]async fn duplicate_database(&self,receipt: EntityAccessReceipt<ViewAccessLevel>,owner: MacroUserIdStr<'static>,+ acting_bot: Option<bot_id::BotId>,name: Option<String>,) -> Result<Database, DatabaseError> {let database_id = receipt_database_id(&receipt)?;@@ -671,7 +672,7 @@ whereowner: owner.clone(),name: copy.name.clone(),created_at: copy.created_at,- attribution: events::Attribution::acting(owner, None),+ attribution: events::Attribution::acting(owner, acting_bot),}));let mut changes: Vec<(DatabaseId, TableId, TableVersion)> = table_versions.into_iter()diff --git a/crates/databases/src/domain/service/test/duplicate.rs b/crates/databases/src/domain/service/test/duplicate.rsindex 507aae53a9..af523542c3 100644--- a/crates/databases/src/domain/service/test/duplicate.rs+++ b/crates/databases/src/domain/service/test/duplicate.rs@@ -212,7 +212,12 @@ async fn a_viewer_duplicates_every_table_column_view_and_row_into_a_database_thelet copy = seeded.service- .duplicate_database(view_receipt(seeded.database_id, VIEWER), user(VIEWER), None)+ .duplicate_database(+ view_receipt(seeded.database_id, VIEWER),+ user(VIEWER),+ None,+ None,+ ).await.unwrap();@@ -416,6 +421,7 @@ async fn a_named_duplicate_takes_the_name_given() {.duplicate_database(view_receipt(seeded.database_id, VIEWER),user(VIEWER),+ None,Some(" Offsite 2027 ".into()),).await@@ -440,7 +446,12 @@ async fn the_source_is_left_as_it_was() {seeded.service- .duplicate_database(view_receipt(seeded.database_id, VIEWER), user(VIEWER), None)+ .duplicate_database(+ view_receipt(seeded.database_id, VIEWER),+ user(VIEWER),+ None,+ None,+ ).await.unwrap();@@ -494,7 +505,12 @@ async fn a_trashed_database_is_not_duplicated() {let error = seeded.service- .duplicate_database(view_receipt(seeded.database_id, VIEWER), user(VIEWER), None)+ .duplicate_database(+ view_receipt(seeded.database_id, VIEWER),+ user(VIEWER),+ None,+ None,+ ).await.unwrap_err();@@ -509,7 +525,12 @@ async fn a_refused_write_leaves_no_copy_behind() {let error = seeded.service- .duplicate_database(view_receipt(seeded.database_id, VIEWER), user(VIEWER), None)+ .duplicate_database(+ view_receipt(seeded.database_id, VIEWER),+ user(VIEWER),+ None,+ None,+ ).await.unwrap_err();@@ -591,7 +612,12 @@ async fn relations_into_other_databases_follow_what_the_duplicator_can_see() {// VIEWER cannot see Venues.let hidden = seeded.service- .duplicate_database(view_receipt(seeded.database_id, VIEWER), user(VIEWER), None)+ .duplicate_database(+ view_receipt(seeded.database_id, VIEWER),+ user(VIEWER),+ None,+ None,+ ).await.unwrap();assert_eq!(copied_names(&hidden), vec![]);@@ -606,7 +632,12 @@ async fn relations_into_other_databases_follow_what_the_duplicator_can_see() {.push((other.id, AccessLevel::View));let seen = seeded.service- .duplicate_database(view_receipt(seeded.database_id, VIEWER), user(VIEWER), None)+ .duplicate_database(+ view_receipt(seeded.database_id, VIEWER),+ user(VIEWER),+ None,+ None,+ ).await.unwrap();assert_eq!(@@ -626,7 +657,12 @@ async fn a_name_at_the_limit_is_cut_short_to_fit_its_copy_suffix() {let copy = seeded.service- .duplicate_database(view_receipt(seeded.database_id, VIEWER), user(VIEWER), None)+ .duplicate_database(+ view_receipt(seeded.database_id, VIEWER),+ user(VIEWER),+ None,+ None,+ ).await.unwrap();@@ -655,7 +691,12 @@ async fn a_relation_naming_a_removed_row_is_copied_without_it() {let copy = seeded.service- .duplicate_database(view_receipt(seeded.database_id, VIEWER), user(VIEWER), None)+ .duplicate_database(+ view_receipt(seeded.database_id, VIEWER),+ user(VIEWER),+ None,+ None,+ ).await.unwrap();@@ -770,7 +811,12 @@ async fn a_shared_property_the_duplicator_cannot_bind_is_copied_into_one_the_coplet bound = seeded.service- .duplicate_database(view_receipt(seeded.database_id, VIEWER), user(VIEWER), None)+ .duplicate_database(+ view_receipt(seeded.database_id, VIEWER),+ user(VIEWER),+ None,+ None,+ ).await.unwrap();let (definition, value) = priority(&bound);@@ -780,7 +826,12 @@ async fn a_shared_property_the_duplicator_cannot_bind_is_copied_into_one_the_copseeded.world.lock().unwrap().unbindable.push(shared_id);let owned = seeded.service- .duplicate_database(view_receipt(seeded.database_id, VIEWER), user(VIEWER), None)+ .duplicate_database(+ view_receipt(seeded.database_id, VIEWER),+ user(VIEWER),+ None,+ None,+ ).await.unwrap();let (definition, value) = priority(&owned);@@ -831,7 +882,12 @@ async fn a_formula_column_is_copied_with_its_values_computed_in_the_copy() {let copy = seeded.service- .duplicate_database(view_receipt(seeded.database_id, VIEWER), user(VIEWER), None)+ .duplicate_database(+ view_receipt(seeded.database_id, VIEWER),+ user(VIEWER),+ None,+ None,+ ).await.unwrap();@@ -858,3 +914,34 @@ async fn a_formula_column_is_copied_with_its_values_computed_in_the_copy() {Some(&PropertyValue::Num(4.0)));}++#[tokio::test]+async fn a_copy_an_agent_makes_is_announced_as_the_agents_creation() {+ let seeded = seeded().await;+ seeded.world.lock().unwrap().broker_events.clear();+ let agent = bot_id::MACRO_AI_BOT_ID;++ seeded+ .service+ .duplicate_database(+ view_receipt(seeded.database_id, VIEWER),+ user(VIEWER),+ Some(agent),+ None,+ )+ .await+ .unwrap();++ let events = seeded.world.lock().unwrap().broker_events.clone();+ let created = events+ .iter()+ .find(|event| event["event_type"] == "database.created")+ .expect("the copy is announced");+ assert_eq!(+ created["metadata"]["attribution"],+ serde_json::json!({+ "actor": "bot|00000000-0000-0000-0000-00000000a1a1",+ "on_behalf_of": VIEWER,+ })+ );+}diff --git a/crates/databases/src/inbound/axum_router.rs b/crates/databases/src/inbound/axum_router.rsindex c887476745..f27bd42909 100644--- a/crates/databases/src/inbound/axum_router.rs+++ b/crates/databases/src/inbound/axum_router.rs@@ -212,6 +212,23 @@ pub(crate) fn viewer_of<Authorization>(}}+/// The agent an SDK token (code mode) carries, recorded on the current span.+/// A creation made with it is attributed to the agent, like the native tool's,+/// so channel delivery can share what the agent made for the request; access+/// checks still run as the plain user ([`viewer_of`]).+pub(crate) fn agent_attribution<Authorization>(+ user: &MacroAuthorizationExtractor<Authorization, UserOrInternal>,+) -> Option<bot_id::BotId> {+ let acting_bot = user.authorization.user.agent_id;+ tracing::Span::current().record(+ "acting_bot",+ tracing::field::display(+ acting_bot.map_or_else(|| "none".to_owned(), |bot| bot.to_string()),+ ),+ );+ acting_bot+}+/// Request body for creating a database.#[derive(Debug, Deserialize, utoipa::ToSchema)]#[serde(rename_all = "camelCase")]@@ -272,7 +289,7 @@ where(status = 500, body = ErrorResponse),))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err, skip_all, fields(acting_bot = tracing::field::Empty))]pub async fn create_database_handler<Service, EntityAccess, Authorization>(State(state): State<DatabasesRouterState<Service, EntityAccess, Authorization>>,user: MacroAuthorizationExtractor<Authorization, UserOrInternal>,@@ -283,12 +300,13 @@ whereEntityAccess: EntityAccessService,Authorization: MacroAuthorizationService,{+ let acting_bot = agent_attribution(&user);let database = state.service.create_database(CreateDatabase {name: request.name,owner_id: viewer_of(&user).user_id,- acting_bot: None,+ acting_bot,}).await?;Ok((StatusCode::CREATED, Json(database)))diff --git a/crates/databases/src/inbound/axum_router/duplicate.rs b/crates/databases/src/inbound/axum_router/duplicate.rsindex 270e7515a1..804d7a0d8c 100644--- a/crates/databases/src/inbound/axum_router/duplicate.rs+++ b/crates/databases/src/inbound/axum_router/duplicate.rs@@ -20,7 +20,7 @@ pub struct DuplicateDatabaseRequest {responses((status = 201, body = Database), (status = 400, body = ErrorResponse),(status = 401, body = ErrorResponse), (status = 403, body = ErrorResponse),(status = 404, body = ErrorResponse), (status = 500, body = ErrorResponse)))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err, skip_all, fields(acting_bot = tracing::field::Empty))]pub async fn duplicate_database_handler<Service, EntityAccess, Authorization>(access: DatabaseAccessLevelExtractor<ViewAccessLevel, EntityAccess, Authorization>,State(state): State<DatabasesRouterState<Service, EntityAccess, Authorization>>,@@ -32,11 +32,13 @@ whereEntityAccess: EntityAccessService,Authorization: MacroAuthorizationService,{+ let acting_bot = agent_attribution(&user);let copy = state.service.duplicate_database(access.entity_access_receipt,viewer_of(&user).user_id,+ acting_bot,request.name,).await?;diff --git a/crates/databases/src/inbound/axum_router/test.rs b/crates/databases/src/inbound/axum_router/test.rsindex 491c871af3..6167c5d3a3 100644--- a/crates/databases/src/inbound/axum_router/test.rs+++ b/crates/databases/src/inbound/axum_router/test.rs@@ -1023,6 +1023,7 @@ async fn view_access_duplicates_a_database_for_the_caller() {vec![(database.to_string(),fakes::USER.to_string(),+ None,Some("Plans 2027".to_string()))]);@@ -1050,5 +1051,62 @@ async fn a_duplicate_without_a_body_name_reaches_the_service_unnamed() {.unwrap();assert_eq!(response.status(), StatusCode::CREATED);- assert_eq!(service.duplicates.lock().unwrap()[0].2, None);+ assert_eq!(service.duplicates.lock().unwrap()[0].3, None);+}++#[tokio::test]+async fn a_database_an_agent_creates_with_its_sdk_token_is_attributed_to_the_agent() {+ use axum::body::Body;+ use axum::http::{Request, header};+ use tower::ServiceExt;++ for (token, bot) in [("agent", Some(fakes::AGENT)), ("valid", None)] {+ let (router, service) = fakes::create_router();+ let response = router+ .oneshot(+ Request::post("/")+ .header(header::AUTHORIZATION, format!("Bearer {token}"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(Body::from(r#"{"name": "Standup notes"}"#))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::CREATED, "{token}");+ let creates = service.creates.lock().unwrap();+ assert_eq!(creates.len(), 1, "{token}");+ assert_eq!(creates[0].owner_id.as_ref(), fakes::USER, "{token}");+ assert_eq!(creates[0].acting_bot, bot, "{token}");+ }+}++#[tokio::test]+async fn a_database_an_agent_duplicates_with_its_sdk_token_is_attributed_to_the_agent() {+ use axum::body::Body;+ use axum::http::{Request, header};+ use entity_access::domain::models::AccessLevel;+ use tower::ServiceExt;++ let database = Uuid::from_u128(0x0dbb);+ for (token, bot) in [("agent", Some(fakes::AGENT)), ("valid", None)] {+ let (router, service) = fakes::duplicate_router(AccessLevel::View);+ let response = router+ .oneshot(+ Request::post(format!("/{database}/duplicate"))+ .header(header::AUTHORIZATION, format!("Bearer {token}"))+ .header(header::CONTENT_TYPE, "application/json")+ .body(Body::from("{}"))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::CREATED, "{token}");+ assert_eq!(+ *service.duplicates.lock().unwrap(),+ vec![(database.to_string(), fakes::USER.to_string(), bot, None)],+ "{token}"+ );+ }}diff --git a/crates/databases/src/inbound/axum_router/test/fakes.rs b/crates/databases/src/inbound/axum_router/test/fakes.rsindex ebb58d8441..aafbab3ad9 100644--- a/crates/databases/src/inbound/axum_router/test/fakes.rs+++ b/crates/databases/src/inbound/axum_router/test/fakes.rs@@ -36,8 +36,10 @@ use crate::inbound::axum_router::ops::apply_ops_handler;use crate::inbound::axum_router::{DatabasesRouterState, databases_router};pub(super) const USER: &str = "macro|[email protected]";+pub(super) const AGENT: BotId = bot_id::MACRO_AI_BOT_ID;-/// Accepts the bearer token `valid` as [`USER`].+/// Accepts the bearer token `valid` as [`USER`], and `agent`: [`USER`]'s SDK+/// token carrying [`AGENT`]'s attribution, as code mode mints.#[derive(Clone, Copy)]struct ValidToken;@@ -46,20 +48,25 @@ impl JwtValidator for ValidToken {&self,jwt: &str,) -> Result<macro_authorization::ValidatedCredential, Report<MacroAuthorizationError>> {- match jwt {- "valid" => Ok(macro_authorization::ValidatedCredential {- origin: macro_authorization::CredentialOrigin::Session,- identity: ValidatedIdentity {- agent_id: None,- agent_via: None,- user_id: USER.to_string(),- fusion_user_id: "fusion-ops-router".to_string(),- organization_id: None,- permissions: None,- },- }),- _ => Err(Report::new(MacroAuthorizationError::InvalidCredentials)),- }+ let (origin, agent_id) = match jwt {+ "valid" => (macro_authorization::CredentialOrigin::Session, None),+ "agent" => (+ macro_authorization::CredentialOrigin::MacroApiJwt,+ Some(AGENT),+ ),+ _ => return Err(Report::new(MacroAuthorizationError::InvalidCredentials)),+ };+ Ok(macro_authorization::ValidatedCredential {+ origin,+ identity: ValidatedIdentity {+ agent_id,+ agent_via: None,+ user_id: USER.to_string(),+ fusion_user_id: "fusion-ops-router".to_string(),+ organization_id: None,+ permissions: None,+ },+ })}}@@ -137,6 +144,29 @@ pub(super) fn duplicate_router(level: AccessLevel) -> (Router, Arc<RecordingServ(router, service)}+/// The create route alone, and the service behind it.+pub(super) fn create_router() -> (Router, Arc<RecordingService>) {+ let service = Arc::new(RecordingService::default());+ let state = DatabasesRouterState::new(+ service.clone(),+ Arc::new(GrantingAccess(AccessLevel::Owner)),+ authorization_state(),+ );+ let router = Router::new()+ .route(+ "/",+ post(+ super::super::create_database_handler::<+ RecordingService,+ GrantingAccess,+ Authorization,+ >,+ ),+ )+ .with_state(state);+ (router, service)+}+/// Every databases route, for a caller holding `level` on every database.pub(super) fn full_router(level: AccessLevel) -> Router {databases_router::<RecordingService, GrantingAccess, Authorization, ()>(@@ -252,6 +282,10 @@ impl EntityAccessService for GrantingAccess {}}+/// A duplicate asked for: the source, the owner, the acting agent and the+/// name.+pub(super) type Duplicate = (String, String, Option<BotId>, Option<String>);+/// Records the batches that reached it, and answers each with no results,/// or with `refusal` when one is set; records the conversions asked for and/// answers each with `conversion`. The routes under test call nothing else.@@ -261,8 +295,10 @@ pub(super) struct RecordingService {pub(super) refusal: Mutex<Option<DatabaseError>>,pub(super) conversions: Mutex<Vec<(TableId, ColumnId, ColumnKind)>>,pub(super) conversion: Mutex<Option<ColumnConversion>>,- /// Every duplicate asked for: the source, the owner and the name.- pub(super) duplicates: Mutex<Vec<(String, String, Option<String>)>>,+ /// Every duplicate asked for.+ pub(super) duplicates: Mutex<Vec<Duplicate>>,+ /// Every create asked for.+ pub(super) creates: Mutex<Vec<CreateDatabase>>,}const ONLY_OPS: &str = "the routes under test call only apply_ops and column_conversion";@@ -329,8 +365,16 @@ impl DatabasesService for RecordingService {unimplemented!("{ONLY_OPS}")}- async fn create_database(&self, _: CreateDatabase) -> Result<Database, DatabaseError> {- unimplemented!("{ONLY_OPS}")+ async fn create_database(&self, command: CreateDatabase) -> Result<Database, DatabaseError> {+ self.creates.lock().unwrap().push(command.clone());+ Ok(Database {+ id: DatabaseId::from_uuid(Uuid::from_u128(0xc4ea)),+ name: command.name,+ owner_id: command.owner_id.to_string(),+ created_at: chrono::DateTime::UNIX_EPOCH,+ trashed_at: None,+ project_id: None,+ })}async fn list_databases(&self, _: Viewer) -> Result<Vec<ListedDatabase>, DatabaseError> {unimplemented!("{ONLY_OPS}")@@ -444,11 +488,13 @@ impl crate::domain::duplicate::DatabaseDuplicateService for RecordingService {&self,receipt: EntityAccessReceipt<ViewAccessLevel>,owner: MacroUserIdStr<'static>,+ acting_bot: Option<BotId>,name: Option<String>,) -> Result<Database, DatabaseError> {self.duplicates.lock().unwrap().push((receipt.entity().entity_id.to_string(),owner.to_string(),+ acting_bot,name.clone(),));Ok(Database {diff --git a/crates/databases/src/outbound/pg_databases_repo/test/duplicate.rs b/crates/databases/src/outbound/pg_databases_repo/test/duplicate.rsindex abfe53b656..a93e1cca52 100644--- a/crates/databases/src/outbound/pg_databases_repo/test/duplicate.rs+++ b/crates/databases/src/outbound/pg_databases_repo/test/duplicate.rs@@ -210,7 +210,7 @@ async fn a_duplicate_copies_tables_columns_rows_relations_and_boards(pool: PgPoo.unwrap();let copy = service- .duplicate_database(view(guests.database_id), duplicator(), None)+ .duplicate_database(view(guests.database_id), duplicator(), None, None).await.unwrap();diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex d738060bf1..7d5d18ed1a 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -547,8 +547,8 @@ email at all. A bot or agent reply posted for a person shares, as that person, t(chips or attachments) that the replying bot created for them while answering: those with a`created` activity row by that bot on the person's behalf since the person's latest message inthe thread before the reply, or, for a bot message that starts its own thread (a poll card-posted top-level), their latest message in the channel. Forms an agent creates through code-mode (its SDK token) are attributed to its bot like native tool creations. Activity arrives asynchronously, so missing rows are re-checked+posted top-level), their latest message in the channel. Forms and databases an agent creates+through code mode (its SDK token) are attributed to its bot like native tool creations. Activity arrives asynchronously, so missing rows are re-checkedafter 5 and 30 seconds. Existing items it links, plain URLs, and bot posts with no personbehind them share nothing. The bot never asks whether to share; it calls `ShareWithChannel` when asked toshare an existing item. Private and confidential calendar events stay unshared, and a