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(activity): attribute signup defaults and support channel to system (#6049)
teob9f77f920299
diff --git a/Cargo.lock b/Cargo.lockindex 29457dcb7e..ff12f7a957 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6962,6 +6962,7 @@ dependencies = [name = "github"version = "0.1.0"dependencies = [+ "activity","anyhow","axum","axum-extra",diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex dcabeb7d37..9fe7d858e8 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -15259,6 +15259,17 @@"$ref": "#/components/schemas/ChannelType","description": "Type of channel that was created."},+ "on_behalf_of": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "User the actor created the channel for, when the actor is a bot."+ }+ ]+ },"participant_user_ids": {"type": "array","items": {diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex 398fa4c959..9d51102138 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -28,7 +28,10 @@ use connection::domain::ports::ConnectionService;use connection_gateway_client::ConnectionGatewayClient;use contacts::{domain::service::SqsContactsIngress, outbound::ingress::SqsContactsQueue};use crm::inbound::toolset::CrmToolContext;-use documents::{domain::ports::TaskPropertiesPort, inbound::toolset::DocumentToolContext};+use documents::{+ domain::ports::{TaskPropertiesPort, task_property_edit_receipt},+ inbound::toolset::DocumentToolContext,+};use email::{domain::service::EmailServiceImpl, inbound::toolset::EmailToolContext, outbound::EmailPgRepo,};@@ -393,6 +396,7 @@ impl TaskPropertiesPort for NoOpTaskProperties {_entity_id: &str,_property_definition_id: uuid::Uuid,_value: Option<models_properties::api::requests::SetPropertyValue>,+ _attribution: &activity::Attribution,) -> anyhow::Result<()> {Ok(())}@@ -440,19 +444,18 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {entity_id: &str,property_definition_id: uuid::Uuid,value: Option<models_properties::api::requests::SetPropertyValue>,+ attribution: &activity::Attribution,) -> anyhow::Result<()> {use properties::PropertiesService as _;let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)?;- let entity_access_receipt = self- .entity_access_service- .generate_entity_access_receipt::<EditAccessLevel>(- &user_id,- None,- entity_id,- model_entity::EntityType::Document,- )- .await?;+ let entity_access_receipt = task_property_edit_receipt(+ self.entity_access_service.as_ref(),+ &user_id,+ attribution,+ entity_id,+ )+ .await?;self.properties.set_entity_property(&entity_access_receipt, property_definition_id, value).await@@ -1020,6 +1023,9 @@ impl ToolEntityCreator {use models_properties::api::requests::SetPropertyValue;use system_properties::SystemPropertyKey;+ let attribution =+ activity::Attribution::direct(activity::Actor::new_from_user(user.clone()));+if let Some(status) = properties.status.as_deref()&& let Err(e) = self.task_properties@@ -1048,6 +1054,7 @@ impl ToolEntityCreator {Some(SetPropertyValue::SelectOption {option_id: option.uuid(),}),+ &attribution,).await{@@ -1069,6 +1076,7 @@ impl ToolEntityCreator {task_id,SystemPropertyKey::DueDate.uuid(),Some(SetPropertyValue::Date { value }),+ &attribution,).await{@@ -1103,6 +1111,7 @@ impl ToolEntityCreator {Some(SetPropertyValue::MultiEntityReference {references: vec![reference],}),+ &attribution,).await{diff --git a/crates/channels/src/domain/activity.rs b/crates/channels/src/domain/activity.rsindex 543ff8a02f..80fedbd969 100644--- a/crates/channels/src/domain/activity.rs+++ b/crates/channels/src/domain/activity.rs@@ -137,9 +137,16 @@ impl ActivitySource for ChannelTopicEvent {};match self {- ChannelTopicEvent::Created(m) => {- common(m.actor.clone(), CommonAction::Created, m.channel_id, now())- }+ ChannelTopicEvent::Created(m) => Ingest::Insert(vec![Activity::common(+ event_id,+ 0,+ m.actor.clone(),+ m.on_behalf_of.clone(),+ EntityType::Channel,+ m.channel_id.to_string(),+ CommonAction::Created,+ now(),+ )]),ChannelTopicEvent::Updated(m) => common(Actor::new_from_user(m.actor.clone()),CommonAction::Edited,diff --git a/crates/channels/src/domain/activity/test.rs b/crates/channels/src/domain/activity/test.rsindex c621018d5a..e869c5bd6a 100644--- a/crates/channels/src/domain/activity/test.rs+++ b/crates/channels/src/domain/activity/test.rs@@ -1,4 +1,5 @@use ::activity::Action;+use ::activity::Actor;use ::activity::EntityType;use chrono::Utc;use macro_user_id::user_id::MacroUserIdStr;@@ -94,6 +95,7 @@ fn created_maps_to_created_by_the_actor() {let event = envelope(ChannelTopicEvent::Created(ChannelCreatedMetadata {channel_id: CHANNEL_ID,actor: Actor::new_from_user(user("macro|[email protected]")),+ on_behalf_of: None,channel_type: ChannelType::Public,channel_name: Some("general".to_string()),participant_user_ids: vec![user("macro|[email protected]")],@@ -103,5 +105,28 @@ fn created_maps_to_created_by_the_actor() {panic!("expected activities");};assert_eq!(activities[0].action, Action::Created);+ assert_eq!(activities[0].actor.as_ref(), "macro|[email protected]");+ assert_eq!(activities[0].subject_id, "macro|[email protected]");+}++#[test]+fn created_by_system_stays_on_the_owner_feed() {+ let event = envelope(ChannelTopicEvent::Created(ChannelCreatedMetadata {+ channel_id: CHANNEL_ID,+ actor: Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID),+ on_behalf_of: Some(user("macro|[email protected]")),+ channel_type: ChannelType::Private,+ channel_name: Some("Macro Support x owner".to_string()),+ participant_user_ids: vec![user("macro|[email protected]")],+ }));++ let Ingest::Insert(activities) = event.event.ingest(event.event_id) else {+ panic!("expected activities");+ };+ assert_eq!(activities[0].action, Action::Created);+ assert_eq!(+ activities[0].actor.as_ref(),+ Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID).as_ref()+ );assert_eq!(activities[0].subject_id, "macro|[email protected]");}diff --git a/crates/channels/src/domain/broker_events.rs b/crates/channels/src/domain/broker_events.rsindex 24551ad93b..8dba8f0cd4 100644--- a/crates/channels/src/domain/broker_events.rs+++ b/crates/channels/src/domain/broker_events.rs@@ -50,6 +50,9 @@ pub struct ChannelCreatedMetadata {pub channel_id: Uuid,/// Actor that created the channel (channel owner).pub actor: ChannelSender<'static>,+ /// User the actor created the channel for, when the actor is a bot.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub on_behalf_of: Option<MacroUserIdStr<'static>>,/// Type of channel that was created.pub channel_type: ChannelType,/// Stored channel name; `None` for direct message / unnamed channels.diff --git a/crates/channels/src/domain/broker_events/test.rs b/crates/channels/src/domain/broker_events/test.rsindex 23403e8bb6..8c27dde8b2 100644--- a/crates/channels/src/domain/broker_events/test.rs+++ b/crates/channels/src/domain/broker_events/test.rs@@ -27,6 +27,7 @@ fn created_event_wire_shape() {ChannelTopicEvent::Created(ChannelCreatedMetadata {channel_id,actor: user("macro|[email protected]"),+ on_behalf_of: None,channel_type: ChannelType::Private,channel_name: Some("general".to_string()),participant_user_ids: vec![@@ -57,6 +58,43 @@ fn created_event_wire_shape() {);}+#[test]+fn created_event_wire_shape_includes_on_behalf_of() {+ let channel_id = Uuid::nil();+ let actor = ChannelSender::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID);+ let event = Event::with_event_id(+ Uuid::nil(),+ ChannelTopicEvent::Created(ChannelCreatedMetadata {+ channel_id,+ actor: actor.clone(),+ on_behalf_of: Some(user_id("macro|[email protected]")),+ channel_type: ChannelType::Private,+ channel_name: Some("Macro Support x owner".to_string()),+ participant_user_ids: vec![user_id("macro|[email protected]")],+ }),+ );++ let value = serde_json::to_value(&event).expect("serializable");+ assert_eq!(+ value,+ json!({+ "event_id": "00000000-0000-0000-0000-000000000000",+ "schema_version": 1,+ "event_type": "channel.created",+ "metadata": {+ "channel_id": "00000000-0000-0000-0000-000000000000",+ "actor": actor.as_ref(),+ "on_behalf_of": "macro|[email protected]",+ "channel_type": "private",+ "channel_name": "Macro Support x owner",+ "participant_user_ids": [+ "macro|[email protected]",+ ],+ },+ })+ );+}+#[test]fn message_posted_wire_shape_with_bot_sender() {let channel_id = Uuid::nil();diff --git a/crates/channels/src/domain/events.rs b/crates/channels/src/domain/events.rsindex 500fda4543..784601fa11 100644--- a/crates/channels/src/domain/events.rs+++ b/crates/channels/src/domain/events.rs@@ -31,6 +31,8 @@ pub enum ChannelEvent {channel_id: Uuid,/// Actor that created the channel.actor: ChannelSender<'static>,+ /// User the actor created the channel for, when the actor is a bot.+ on_behalf_of: Option<MacroUserIdStr<'static>>,/// Type of channel that was created.channel_type: ChannelType,/// Stored channel name; `None` for direct message / unnamed channels.diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rsindex 26057802ca..8b2388a061 100644--- a/crates/channels/src/domain/ports.rs+++ b/crates/channels/src/domain/ports.rs@@ -667,6 +667,21 @@ pub trait ChannelService: Send + Sync + 'static {}}+ /// Create a channel owned by `owner` on the platform's initiative (e.g.+ /// signup). The activity is attributed to the system bot acting for+ /// `owner`; ownership and permissions are unchanged.+ fn create_system_channel(+ &self,+ _owner: MacroUserIdStr<'static>,+ _req: CreateChannelRequest,+ ) -> impl Future<Output = Result<CreateChannelResponse, ChannelMutationErr>> + Send {+ async move {+ Err(ChannelMutationErr::NotFound(+ "channel mutations are not configured".to_string(),+ ))+ }+ }+/// Add or reactivate a user in every auto-join channel for a team.fn auto_join_by_team_id(&self,diff --git a/crates/channels/src/domain/service.rs b/crates/channels/src/domain/service.rsindex b6e8d4bb12..031bac5a21 100644--- a/crates/channels/src/domain/service.rs+++ b/crates/channels/src/domain/service.rs@@ -333,7 +333,33 @@ where_actor_org_id: Option<i64>,req: crate::domain::models::CreateChannelRequest,) -> Result<crate::domain::models::CreateChannelResponse, ChannelMutationErr> {- let actor = require_user_actor(&actor)?;+ let owner = require_user_actor(&actor)?;+ self.create_owned_channel(owner.clone(), Sender::new_from_user(owner), None, req)+ .await+ }++ #[tracing::instrument(err, skip(self, req))]+ async fn create_system_channel(+ &self,+ owner: MacroUserIdStr<'static>,+ req: crate::domain::models::CreateChannelRequest,+ ) -> Result<crate::domain::models::CreateChannelResponse, ChannelMutationErr> {+ self.create_owned_channel(+ owner.clone(),+ Sender::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID),+ Some(owner),+ req,+ )+ .await+ }++ async fn create_owned_channel(+ &self,+ owner: MacroUserIdStr<'static>,+ activity_actor: Sender,+ on_behalf_of: Option<MacroUserIdStr<'static>>,+ req: crate::domain::models::CreateChannelRequest,+ ) -> Result<crate::domain::models::CreateChannelResponse, ChannelMutationErr> {if req.auto_join_team && req.channel_type != ChannelType::Team {return Err(ChannelMutationErr::BadRequest("auto-join is only available for team channels".to_string(),@@ -345,7 +371,7 @@ where})?;let has_team = self.repo- .user_has_team(actor.as_ref().to_string(), team_id)+ .user_has_team(owner.as_ref().to_string(), team_id).await.map_err(|e| ChannelMutationErr::Repo(e.into()))?;if !has_team {@@ -372,12 +398,13 @@ wherelet channel_name = req.name.clone();let created_channel = self- .create_channel_record(actor.copied(), org_id, req)+ .create_channel_record(owner.copied(), org_id, req).await?;self.events.dispatch(ChannelEvent::ChannelCreated {channel_id: created_channel.id,- actor: Sender::new_from_user(actor),+ actor: activity_actor,+ on_behalf_of,channel_type,channel_name,participant_user_ids: created_channel.participant_user_ids,@@ -1342,6 +1369,7 @@ whereself.events.dispatch(ChannelEvent::ChannelCreated {channel_id: created_channel.id,actor: owner_sender,+ on_behalf_of: None,channel_type,channel_name,participant_user_ids: created_channel.participant_user_ids,@@ -1847,6 +1875,14 @@ whereChannelServiceImpl::create_channel(self, actor, None, req).await}+ async fn create_system_channel(+ &self,+ owner: MacroUserIdStr<'static>,+ req: crate::domain::models::CreateChannelRequest,+ ) -> Result<crate::domain::models::CreateChannelResponse, ChannelMutationErr> {+ ChannelServiceImpl::create_system_channel(self, owner, req).await+ }+#[tracing::instrument(err, skip(self, user_id))]async fn auto_join_by_team_id(&self,diff --git a/crates/channels/src/domain/service/test.rs b/crates/channels/src/domain/service/test.rsindex fa8f1568aa..31bc62c5b3 100644--- a/crates/channels/src/domain/service/test.rs+++ b/crates/channels/src/domain/service/test.rs@@ -2269,6 +2269,72 @@ async fn remove_participants_allows_removing_non_owner() {assert!(state.touched_channel_ids.is_empty());}+#[tokio::test]+async fn create_system_channel_event_uses_system_actor() {+ let channel_id = Uuid::new_v4();+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");+ let events = FakeEvents::default();+ let svc = mutation_service(repo, events.clone(), FakeReferenceSharing::default());++ svc.create_system_channel(+ macro_id("macro|[email protected]"),+ crate::domain::models::CreateChannelRequest {+ name: Some("Macro Support x owner".to_string()),+ channel_type: ChannelType::Private,+ team_id: None,+ auto_join_team: false,+ participants: HashSet::from([macro_id("macro|[email protected]")]),+ },+ )+ .await+ .unwrap();++ let events = events.events.lock().unwrap();+ assert!(matches!(+ events.as_slice(),+ [ChannelEvent::ChannelCreated {+ actor,+ on_behalf_of: Some(owner),+ channel_name: Some(name),+ ..+ }] if actor == &Sender::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID)+ && owner.as_ref() == "macro|[email protected]"+ && name == "Macro Support x owner"+ ));+}++/// Signup on main called `create_channel(Sender::new_from_user(owner))`.+/// That is the path that made "Created # Macro Support x …" render as You.+#[tokio::test]+async fn signup_support_channel_via_user_create_channel_attributes_created_to_owner() {+ let channel_id = Uuid::new_v4();+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");+ let events = FakeEvents::default();+ let svc = mutation_service(repo, events.clone(), FakeReferenceSharing::default());++ svc.create_channel(+ sender("macro|[email protected]"),+ None,+ crate::domain::models::CreateChannelRequest {+ name: Some("Macro Support x owner".to_string()),+ channel_type: ChannelType::Private,+ team_id: None,+ auto_join_team: false,+ participants: HashSet::from([macro_id("macro|[email protected]")]),+ },+ )+ .await+ .unwrap();++ let events = events.events.lock().unwrap();+ assert!(matches!(+ events.as_slice(),+ [ChannelEvent::ChannelCreated { actor, channel_name: Some(name), .. }]+ if actor == &sender("macro|[email protected]")+ && name == "Macro Support x owner"+ ));+}+#[tokio::test]async fn create_channel_event_carries_channel_name() {let channel_id = Uuid::new_v4();@@ -2328,6 +2394,7 @@ async fn ensure_dms_dispatches_created_channel_once() {[ChannelEvent::ChannelCreated {channel_id: actual_channel_id,actor,+ on_behalf_of: None,channel_type: ChannelType::DirectMessage,channel_name: None,participant_user_ids,diff --git a/crates/channels/src/domain/side_effects.rs b/crates/channels/src/domain/side_effects.rsindex a7781e89ec..1d71609312 100644--- a/crates/channels/src/domain/side_effects.rs+++ b/crates/channels/src/domain/side_effects.rs@@ -1220,9 +1220,12 @@ fn contact_sync_users_for_event(event: &ChannelEvent) -> Option<HashSet<MacroUseChannelEvent::ChannelCreated {channel_type: ChannelType::Private | ChannelType::DirectMessage,actor,+ on_behalf_of,participant_user_ids,..- } if actor.as_user().is_some() => Some(participant_user_ids.iter().cloned().collect()),+ } if actor.as_user().is_some() || on_behalf_of.is_some() => {+ Some(participant_user_ids.iter().cloned().collect())+ }ChannelEvent::ParticipantsAdded {channel_type: ChannelType::Private | ChannelType::Team,invited_by,@@ -1252,12 +1255,14 @@ fn broker_events_for_event(event: &ChannelEvent) -> Vec<ChannelMacroEvent> {ChannelEvent::ChannelCreated {channel_id,actor,+ on_behalf_of,channel_type,channel_name,participant_user_ids,} => vec![ChannelMacroEvent::created(ChannelCreatedMetadata {channel_id: *channel_id,actor: actor.clone(),+ on_behalf_of: on_behalf_of.clone(),channel_type: *channel_type,channel_name: channel_name.clone(),participant_user_ids: participant_user_ids.clone(),diff --git a/crates/channels/src/domain/side_effects/test.rs b/crates/channels/src/domain/side_effects/test.rsindex a2150f509a..2859da90ad 100644--- a/crates/channels/src/domain/side_effects/test.rs+++ b/crates/channels/src/domain/side_effects/test.rs@@ -1007,6 +1007,7 @@ fn contact_sync_is_derived_from_private_channel_created() {let event = ChannelEvent::ChannelCreated {channel_id: Uuid::nil(),actor: Sender::new_from_user(user("[email protected]")),+ on_behalf_of: None,channel_type: ChannelType::Private,channel_name: None,participant_user_ids: users(&["[email protected]", "[email protected]"]),@@ -1019,11 +1020,44 @@ fn contact_sync_is_derived_from_private_channel_created() {assert!(contact_users.contains(&user("[email protected]")));}+#[test]+fn contact_sync_system_channel_created_with_subject() {+ let event = ChannelEvent::ChannelCreated {+ channel_id: Uuid::nil(),+ actor: Sender::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID),+ on_behalf_of: Some(user("[email protected]")),+ channel_type: ChannelType::Private,+ channel_name: Some("Macro Support x owner".to_string()),+ participant_user_ids: users(&["[email protected]", "[email protected]"]),+ };++ let contact_users = contact_sync_users_for_event(&event).unwrap();++ assert_eq!(contact_users.len(), 2);+ assert!(contact_users.contains(&user("[email protected]")));+ assert!(contact_users.contains(&user("[email protected]")));+}++#[test]+fn contact_sync_ignores_bot_channel_created_without_subject() {+ let event = ChannelEvent::ChannelCreated {+ channel_id: Uuid::nil(),+ actor: Sender::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID),+ on_behalf_of: None,+ channel_type: ChannelType::Private,+ channel_name: None,+ participant_user_ids: users(&["[email protected]", "[email protected]"]),+ };++ assert!(contact_sync_users_for_event(&event).is_none());+}+#[test]fn contact_sync_ignores_public_channel_created() {let event = ChannelEvent::ChannelCreated {channel_id: Uuid::nil(),actor: Sender::new_from_user(user("[email protected]")),+ on_behalf_of: None,channel_type: ChannelType::Public,channel_name: None,participant_user_ids: users(&["[email protected]", "[email protected]"]),@@ -1247,6 +1281,7 @@ async fn handle_publishes_channel_created_event() {.handle(ChannelEvent::ChannelCreated {channel_id,actor: Sender::new_from_user(user("[email protected]")),+ on_behalf_of: None,channel_type: ChannelType::Private,channel_name: Some("general".to_string()),participant_user_ids: users(&["[email protected]", "[email protected]"]),diff --git a/crates/documents/src/domain/create.rs b/crates/documents/src/domain/create.rsindex 29b5d55743..17856cdf55 100644--- a/crates/documents/src/domain/create.rs+++ b/crates/documents/src/domain/create.rs@@ -569,6 +569,7 @@ whereteam_id,},);+ let attribution = args.resolved_attribution();let mut response = self.document_service@@ -596,6 +597,7 @@ whereproperty_values,share_with_team,},+ &attribution,).await?;}diff --git a/crates/documents/src/domain/ports.rs b/crates/documents/src/domain/ports.rsindex 0819648a51..30b5ce9858 100644--- a/crates/documents/src/domain/ports.rs+++ b/crates/documents/src/domain/ports.rs@@ -10,8 +10,10 @@ pub mod markdown;use std::future::Future;use entity_access::domain::models::{- EditAccessLevel, EntityAccessReceipt, MemberTeamRole, OwnerAccessLevel, ViewAccessLevel,+ AccessError, BotAccessScope, EditAccessLevel, EntityAccessReceipt, EntityType, MemberTeamRole,+ OwnerAccessLevel, ViewAccessLevel,};+use entity_access::domain::ports::EntityAccessService;use macro_user_id::user_id::MacroUserIdStr;use model::document::{ContentType, DocumentBasic, DocumentMetadata, FileType};use models_permissions::share_permission::{SharePermissionV2, TeamLinkShareDefault};@@ -26,6 +28,8 @@ use model::sync_service::SyncServiceVersionID;use model_entity::Entity;+use activity::Attribution;+use super::models::{BranchNameContext, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs,CreateTaskRequest, DocumentError, DocumentTeamShare, DocumentTeamShareResponse,@@ -350,6 +354,7 @@ pub trait TaskPropertiesPort: Send + Sync + 'static {entity_id: &str,property_definition_id: uuid::Uuid,value: Option<models_properties::api::requests::SetPropertyValue>,+ attribution: &Attribution,) -> impl Future<Output = anyhow::Result<()>> + Send;/// Copy all task property values from one task to another.@@ -360,6 +365,35 @@ pub trait TaskPropertiesPort: Send + Sync + 'static {) -> impl Future<Output = anyhow::Result<()>> + Send;}+/// Mint the edit receipt a [`TaskPropertiesPort`] adapter writes task+/// properties with.+///+/// A bot creating the task for a user gets a bot receipt scoped to that user,+/// so the property write publishes the same delegated attribution as the+/// document itself. Every other attribution writes as `user_id`.+pub async fn task_property_edit_receipt<A: EntityAccessService>(+ entity_access: &A,+ user_id: &MacroUserIdStr<'_>,+ attribution: &Attribution,+ task_id: &str,+) -> Result<EntityAccessReceipt<EditAccessLevel>, AccessError> {+ if let Attribution::Delegated { actor, subject } = attribution+ && let Some(bot) = actor.as_bot()+ {+ return entity_access+ .generate_bot_entity_access_receipt(+ bot.bot_id(),+ BotAccessScope::user(subject.clone()),+ task_id,+ EntityType::Document,+ )+ .await;+ }+ entity_access+ .generate_entity_access_receipt(user_id, None, task_id, EntityType::Document)+ .await+}+/// Use case for relaying document content-upload events.pub trait DocumentContentEventService: Send + Sync + 'static {/// Load the document owner and publish a content-uploaded event.@@ -513,6 +547,7 @@ pub trait DocumentService: Send + Sync + 'static {user_id: MacroUserIdStr<'static>,document_id: &str,request: &CreateTaskRequest,+ attribution: &Attribution,) -> impl Future<Output = Result<(), DocumentError>> + Send;/// Returns the raw bytes of the cached Loro snapshot, or `None` if no snapshot exists.diff --git a/crates/documents/src/domain/ports/create.rs b/crates/documents/src/domain/ports/create.rsindex ed22c3fe29..86a924730b 100644--- a/crates/documents/src/domain/ports/create.rs+++ b/crates/documents/src/domain/ports/create.rs@@ -3,6 +3,7 @@use std::future::Future;use std::sync::Arc;+use activity::Attribution;use macro_user_id::user_id::MacroUserIdStr;use crate::domain::content::DocumentContent;@@ -46,6 +47,7 @@ pub trait DocumentCreationService: Send + Sync {user_id: MacroUserIdStr<'static>,document_id: &str,request: &CreateTaskRequest,+ attribution: &Attribution,) -> impl Future<Output = Result<(), DocumentError>> + Send;/// Mark a created document's upload/finalization lifecycle as complete.@@ -83,9 +85,10 @@ whereuser_id: MacroUserIdStr<'static>,document_id: &str,request: &CreateTaskRequest,+ attribution: &Attribution,) -> Result<(), DocumentError> {(**self)- .handle_task_properties(user_id, document_id, request)+ .handle_task_properties(user_id, document_id, request, attribution).await}diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rsindex 44a6a75ea3..5c8b51dae7 100644--- a/crates/documents/src/domain/service.rs+++ b/crates/documents/src/domain/service.rs@@ -771,8 +771,16 @@ impl<user_id: MacroUserIdStr<'static>,document_id: &str,request: &CreateTaskRequest,+ attribution: &Attribution,) -> Result<(), DocumentError> {- <Self as DocumentService>::handle_task_properties(self, user_id, document_id, request).await+ <Self as DocumentService>::handle_task_properties(+ self,+ user_id,+ document_id,+ request,+ attribution,+ )+ .await}#[tracing::instrument(err, skip(self))]@@ -1831,12 +1839,13 @@ impl<}/// Assigns the task properties to a document- #[tracing::instrument(skip(self, request), err)]+ #[tracing::instrument(skip(self, request, attribution), err)]async fn handle_task_properties(&self,user_id: MacroUserIdStr<'static>,document_id: &str,request: &CreateTaskRequest,+ attribution: &Attribution,) -> Result<(), DocumentError> {if request.share_with_team&& let Some(team_id) = request.team_id@@ -1887,6 +1896,7 @@ impl<document_id,property_uuid,Some(property_input.value.clone()),+ attribution,).await.inspect_err(|e| {diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rsindex f1cd328b9f..e5b75301d2 100644--- a/crates/documents/src/domain/service/tests.rs+++ b/crates/documents/src/domain/service/tests.rs@@ -14,6 +14,7 @@ use crate::domain::models::{use crate::domain::ports::{DocumentContentEventService, MockDocumentRepo};use super::*;+use activity::{Actor, Attribution};fn make_test_metadata() -> DocumentMetadata {DocumentMetadata {@@ -166,6 +167,7 @@ impl TaskPropertiesPort for TestTaskPropertiesPort {_entity_id: &str,_property_definition_id: uuid::Uuid,_value: Option<models_properties::api::requests::SetPropertyValue>,+ _attribution: &activity::Attribution,) -> anyhow::Result<()> {Ok(())}@@ -2044,6 +2046,106 @@ async fn create_document_publishes_resolved_attribution() {);}+#[derive(Default, Clone)]+struct RecordingTaskPropertiesPort {+ writes: Arc<Mutex<Vec<(String, uuid::Uuid, Attribution)>>>,+}++impl TaskPropertiesPort for RecordingTaskPropertiesPort {+ async fn attach_task_properties(&self, _entity_ids: Vec<String>) -> anyhow::Result<()> {+ Ok(())+ }++ async fn update_task_status(&self, _entity_id: &str, _status: &str) -> anyhow::Result<()> {+ Ok(())+ }++ async fn set_entity_property(+ &self,+ user_id: &str,+ _entity_id: &str,+ property_definition_id: uuid::Uuid,+ _value: Option<models_properties::api::requests::SetPropertyValue>,+ attribution: &Attribution,+ ) -> anyhow::Result<()> {+ self.writes.lock().unwrap().push((+ user_id.to_string(),+ property_definition_id,+ attribution.clone(),+ ));+ Ok(())+ }++ async fn copy_task_properties(+ &self,+ _from_task_id: &str,+ _to_task_id: &str,+ ) -> anyhow::Result<()> {+ Ok(())+ }+}++#[tokio::test]+async fn handle_task_properties_forwards_create_attribution() {+ use crate::domain::models::{ASSIGNEES_PROPERTY_ID, CreateTaskRequest, STATUS_PROPERTY_ID};++ let task_properties = RecordingTaskPropertiesPort::default();+ let service = DocumentServiceImpl::new(+ make_mock_repo(),+ test_cloudfront_config(),+ sync_service_client::SyncServiceClient::new(+ "test-sync-key".to_string(),+ "http://sync-service.test".to_string(),+ ),+ TestUploadUrlPort,+ task_properties.clone(),+ TestConnectionService,+ TestEntityAccessManagementService::default(),+ TestForeignEntityService::default(),+ TestEventBroker::default(),+ );+ let user = macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ let attribution = Attribution::delegated(+ Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID),+ user.clone(),+ );++ crate::domain::ports::DocumentService::handle_task_properties(+ &service,+ user.clone(),+ "task-1",+ &CreateTaskRequest {+ task_name: "Intro to tasks".to_string(),+ markdown: None,+ project_id: None,+ team_id: None,+ property_values: None,+ share_with_team: false,+ },+ &attribution,+ )+ .await+ .unwrap();++ let writes = task_properties.writes.lock().unwrap().clone();+ assert_eq!(writes.len(), 2);+ assert_eq!(+ writes[0].1,+ uuid::Uuid::parse_str(ASSIGNEES_PROPERTY_ID).unwrap()+ );+ assert_eq!(+ writes[1].1,+ uuid::Uuid::parse_str(STATUS_PROPERTY_ID).unwrap()+ );+ assert!(+ writes+ .iter()+ .all(|(user_id, _, recorded)| user_id == user.as_ref() && recorded == &attribution)+ );+}+#[tokio::test]async fn create_document_reuse_skips_content_url_and_created_event() {let mut repo = make_mock_repo();diff --git a/crates/documents/src/inbound/axum_router/tests.rs b/crates/documents/src/inbound/axum_router/tests.rsindex 210328de9d..585099359d 100644--- a/crates/documents/src/inbound/axum_router/tests.rs+++ b/crates/documents/src/inbound/axum_router/tests.rs@@ -394,6 +394,7 @@ impl DocumentService for FakeDocumentService {_user_id: MacroUserIdStr<'static>,_document_id: &str,_request: &CreateTaskRequest,+ _attribution: &activity::Attribution,) -> Result<(), DocumentError> {panic!("unexpected handle_task_properties call")}@@ -471,6 +472,7 @@ impl DocumentCreationService for FakeDocumentService {_user_id: MacroUserIdStr<'static>,_document_id: &str,_request: &CreateTaskRequest,+ _attribution: &activity::Attribution,) -> Result<(), DocumentError> {panic!("unexpected creation handle_task_properties call")}diff --git a/crates/documents/src/inbound/toolset/edit_document/test.rs b/crates/documents/src/inbound/toolset/edit_document/test.rsindex fb02557de6..0ae51675f9 100644--- a/crates/documents/src/inbound/toolset/edit_document/test.rs+++ b/crates/documents/src/inbound/toolset/edit_document/test.rs@@ -206,6 +206,7 @@ impl DocumentService for FakeDocumentService {_user_id: MacroUserIdStr<'static>,_document_id: &str,_request: &CreateTaskRequest,+ _attribution: &activity::Attribution,) -> Result<(), DocumentError> {panic!("unexpected handle_task_properties call")}@@ -257,6 +258,7 @@ impl DocumentCreationService for FakeDocumentService {_user_id: MacroUserIdStr<'static>,_document_id: &str,_request: &CreateTaskRequest,+ _attribution: &activity::Attribution,) -> Result<(), DocumentError> {panic!("unexpected handle_task_properties call")}diff --git a/crates/github/Cargo.toml b/crates/github/Cargo.tomlindex 1eb225df2a..1b363a88b7 100644--- a/crates/github/Cargo.toml+++ b/crates/github/Cargo.toml@@ -38,6 +38,7 @@ sync = [][dependencies]+activity = { path = "../activity", default-features = false }anyhow = { workspace = true }base64 = { workspace = true }chrono = { workspace = true }diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rsindex c1ac363dc4..09a1e03190 100644--- a/crates/github/src/domain/service/sync/test.rs+++ b/crates/github/src/domain/service/sync/test.rs@@ -292,6 +292,7 @@ impl DocumentService for StubDocumentService {_user_id: MacroUserIdStr<'static>,_document_id: &str,_request: &documents::domain::models::CreateTaskRequest,+ _attribution: &activity::Attribution,) -> Result<(), DocumentError> {unimplemented!()}diff --git a/crates/properties/src/domain/activity/test.rs b/crates/properties/src/domain/activity/test.rsindex acfeac1f94..82f8dbff26 100644--- a/crates/properties/src/domain/activity/test.rs+++ b/crates/properties/src/domain/activity/test.rs@@ -64,8 +64,11 @@ fn task_property_update_maps_to_property_changed_on_the_document() {let Ingest::Insert(activities) = event.event.ingest(event.event_id) else {panic!("expected activities");};- // Tasks are documents in the soup vocabulary.+ // Tasks are documents in the soup vocabulary. A user-only+ // `actor_user_id` (main's TaskPropertiesAdapter receipt) is Direct(user):+ // the feed renders "You" for that owner.assert_eq!(activities[0].entity_type, ActivityEntityType::Document);+ assert_eq!(activities[0].actor.as_ref(), "macro|[email protected]");assert_eq!(activities[0].subject_id, "macro|[email protected]");match &activities[0].action {Action::PropertyChanged(change) => {diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rsindex af2550f40d..d16406ca2c 100644--- a/crates/webhook/src/domain/ingestion/test.rs+++ b/crates/webhook/src/domain/ingestion/test.rs@@ -574,6 +574,7 @@ fn channel_event_cases() -> Vec<EventCase> {ChannelTopicEvent::Created(ChannelCreatedMetadata {channel_id,actor: sender(owner),+ on_behalf_of: None,channel_type: ChannelType::Team,channel_name: Some("general".to_string()),participant_user_ids: vec![user_id(owner)],diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 5562f26ece..956e0b2673 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -1905,6 +1905,7 @@ export type ChannelCreatedMetadata = {* Type of channel that was created.*/channel_type: ChannelType;+ on_behalf_of?: null | MacroUserIdStr;/*** Active participants after creation (including the owner).*/diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex dcabeb7d37..9fe7d858e8 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -15259,6 +15259,17 @@"$ref": "#/components/schemas/ChannelType","description": "Type of channel that was created."},+ "on_behalf_of": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "User the actor created the channel for, when the actor is a bot."+ }+ ]+ },"participant_user_ids": {"type": "array","items": {diff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rsindex 763759b7c7..56c19feba7 100644--- a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs@@ -24,7 +24,7 @@ use crate::{use authentication_service::service::user::create_user::create_user;use authentication_service::service::user::support_channel_welcome::post_support_channel_welcome;use channels::domain::{- models::{ChannelType, CreateChannelRequest, Sender},+ models::{ChannelType, CreateChannelRequest},ports::ChannelService,};use favorites::domain::ports::FavoritesService;@@ -441,9 +441,8 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an};let channel = match channel_service- .create_channel(- Sender::new_from_user(owner_id.clone()),- None,+ .create_system_channel(+ owner_id.clone(),CreateChannelRequest {name: Some(support_channel_name),channel_type: ChannelType::Private,diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex d2f2967d83..1a75f3f76a 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -41,7 +41,7 @@ use connection::{outbound::connection_gateway_client::ConnectionGatewayImpl,};use connection_gateway_client::client::ConnectionGatewayClient;-use documents_hex::domain::ports::TaskPropertiesPort;+use documents_hex::domain::ports::{TaskPropertiesPort, task_property_edit_receipt};use documents_hex::domain::service::DocumentServiceImpl;use documents_hex::inbound::axum_router::DocumentRouterState;use documents_hex::outbound::pg_document_repo::PgDocumentRepo;@@ -51,12 +51,7 @@ use email::{domain::{ports::ReadonlyEmailPreviewAdapter, service::EmailServiceImpl},outbound::EmailPgRepo,};-use entity_access::{- domain::{- models::EditAccessLevel, ports::EntityAccessService as _, service::EntityAccessServiceImpl,- },- outbound::PgAccessRepository,-};+use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};use favorites::{domain::service::FavoritesServiceImpl, inbound::axum_router::FavoritesRouterState,outbound::pg_favorites_repo::PgFavoritesRepo,@@ -264,20 +259,18 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {entity_id: &str,property_definition_id: uuid::Uuid,value: Option<models_properties::api::requests::SetPropertyValue>,+ attribution: &activity::Attribution,) -> anyhow::Result<()> {use properties::PropertiesService as _;let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)?;-- let entity_access_receipt = self- .entity_access_service- .generate_entity_access_receipt::<EditAccessLevel>(- &user_id,- None,- entity_id,- model_entity::EntityType::Document,- )- .await?;+ let entity_access_receipt = task_property_edit_receipt(+ self.entity_access_service.as_ref(),+ &user_id,+ attribution,+ entity_id,+ )+ .await?;self.properties.set_entity_property(&entity_access_receipt, property_definition_id, value).awaitdiff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rsindex 6663a0579e..aa55a24228 100644--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs@@ -668,6 +668,7 @@ fn channel_event_cases() -> Vec<(ChannelTopicEvent, ChannelEventDescription)> {ChannelTopicEvent::Created(ChannelCreatedMetadata {channel_id: CHANNEL_ID,actor: sender.clone(),+ on_behalf_of: None,channel_type: ChannelType::Private,channel_name: Some("general".to_string()),participant_user_ids: vec![user_id()],