Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(channels): share items a bot creates for a request with its channel (#9134)

Wolf Mermelstein1d268de1729b
diff --git a/.sqlx/query-89835128d6e633aa3393cad0af7101be91b8b2e630edf176388456f62727ff41.json b/.sqlx/query-89835128d6e633aa3393cad0af7101be91b8b2e630edf176388456f62727ff41.json
new file mode 100644
index 0000000000..30ccc36952
--- /dev/null
+++ b/.sqlx/query-89835128d6e633aa3393cad0af7101be91b8b2e630edf176388456f62727ff41.json
@@ -0,0 +1,32 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT item.entity_type AS \"entity_type!\", item.entity_id AS \"entity_id!\"\n FROM UNNEST($1::text[], $2::text[]) AS item(entity_type, entity_id)\n WHERE EXISTS (\n SELECT 1\n FROM activity_events event\n WHERE event.entity_type = item.entity_type\n AND event.entity_id = item.entity_id\n AND event.action = 'created'\n AND event.actor_id = $3\n AND event.subject_id = $4\n AND event.occurred_at >= $5\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_type!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "TextArray",
+ "Text",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null,
+ null
+ ]
+ },
+ "hash": "89835128d6e633aa3393cad0af7101be91b8b2e630edf176388456f62727ff41"
+}
diff --git a/.sqlx/query-bd42148ae46bf135b6acf9531d0f545db61637e5cd120c0a2497d771654dafc4.json b/.sqlx/query-bd42148ae46bf135b6acf9531d0f545db61637e5cd120c0a2497d771654dafc4.json
new file mode 100644
index 0000000000..4a34d43956
--- /dev/null
+++ b/.sqlx/query-bd42148ae46bf135b6acf9531d0f545db61637e5cd120c0a2497d771654dafc4.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT max(created_at) AS \"sent_at\"\n FROM (\n SELECT created_at\n FROM comms_messages\n WHERE id = $1 AND sender_id = $2 AND created_at < $3\n UNION ALL\n SELECT created_at\n FROM comms_messages\n WHERE thread_id = $1 AND sender_id = $2 AND created_at < $3\n AND deleted_at IS NULL\n ) request\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sent_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "bd42148ae46bf135b6acf9531d0f545db61637e5cd120c0a2497d771654dafc4"
+}
diff --git a/apps/docs/AI/mcp/tools/share-with-channel.mdx b/apps/docs/AI/mcp/tools/share-with-channel.mdx
index d75b716365..7c47706672 100644
--- a/apps/docs/AI/mcp/tools/share-with-channel.mdx
+++ b/apps/docs/AI/mcp/tools/share-with-channel.mdx
@@ -7,7 +7,7 @@ description: >-
# ShareWithChannel
-Share an item with the current members of a channel by writing a channel entity-access grant. Call it only after the user agrees to share that item, or when they already asked you to share it. entityType is the stored type: calendar_event for a calendar chip, document, project, database, form, call, thread, agent_session, or external_chat. entityId is that item's id. A calendar event can be shared only by someone who holds it on their own calendar, and private or confidential events are refused. Sharing again is safe when a grant already exists.
+Share an item with the current members of a channel by writing a channel entity-access grant. Call it only when the user asks you to share an existing item; items you create while answering a channel message and link in your reply as a mention chip or attachment are already shared with that channel. entityType is the stored type: calendar_event for a calendar chip, document, project, database, form, call, thread, agent_session, or external_chat. entityId is that item's id. A calendar event can be shared only by someone who holds it on their own calendar, and private or confidential events are refused. Sharing again is safe when a grant already exists.
## Parameters
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index d2657e769c..e82c9087bc 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -15510,7 +15510,7 @@ export interface SetSenderPolicyResponse {
summary: string;
}
/**
- * Share an item with the current members of a channel by writing a channel entity-access grant. Call it only after the user agrees to share that item, or when they already asked you to share it. entityType is the stored type: calendar_event for a calendar chip, document, project, database, form, call, thread, agent_session, or external_chat. entityId is that item's id. A calendar event can be shared only by someone who holds it on their own calendar, and private or confidential events are refused. Sharing again is safe when a grant already exists.
+ * Share an item with the current members of a channel by writing a channel entity-access grant. Call it only when the user asks you to share an existing item; items you create while answering a channel message and link in your reply as a mention chip or attachment are already shared with that channel. entityType is the stored type: calendar_event for a calendar chip, document, project, database, form, call, thread, agent_session, or external_chat. entityId is that item's id. A calendar event can be shared only by someone who holds it on their own calendar, and private or confidential events are refused. Sharing again is safe when a grant already exists.
*/
export interface ShareWithChannel {
/**
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 7f56f48279..85a2ddd98e 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -400,6 +400,9 @@ fn message_service_with_side_effects(
Arc::new(access.clone()),
),
realtime.clone(),
+ channels::outbound::pg_agent_creations::PgAgentCreations::new(
+ pool.clone(),
+ ),
),
messages::domain::delivery::DiscussionDelivery::new(
messages::outbound::pg_discussion_context::PgDiscussionContext(pool.clone())
diff --git a/crates/channels/AGENTS.md b/crates/channels/AGENTS.md
index 1829cc7671..4effc609c8 100644
--- a/crates/channels/AGENTS.md
+++ b/crates/channels/AGENTS.md
@@ -58,6 +58,15 @@ DMs, and the shared message store other domains discuss things on.
- Human DM messages to nonusers use immediate email, including mentions and replies; empty DM creation, bot messages, and silent/mentions-only policies do not trigger this path. Keep registered recipients on their normal notification routes.
+- A person's message shares every item it links; a bot message posted for a
+ person (`triggered_by`) shares, as that person, only the linked items the
+ sending bot created for them while answering: `created` rows in
+ `activity_events` by that bot on the person's behalf since the person's
+ latest message in the thread before the reply (`PgAgentCreations`). The same
+ bound covers classic `@Macro` and agent session turns. Activity lands asynchronously, so misses are
+ re-checked after 5 s and 30 s in a spawned task. Creations recorded under
+ another bot (`MACRO_AI_BOT_ID` for Claude/Codex/Cursor MCP tools) or the
+ user (projects, chats, calls) never match, and fail safe as unshared.
- DM invitation emails must stay distinguishable from channel invites (#7964) —
don't collapse the two email templates.
- Legacy document/CRM/channel message paths were removed (#6732); don't
diff --git a/crates/channels/Cargo.toml b/crates/channels/Cargo.toml
index 472c55c63b..f81ad198be 100644
--- a/crates/channels/Cargo.toml
+++ b/crates/channels/Cargo.toml
@@ -143,7 +143,7 @@ sqlx = { workspace = true, optional = true }
static_file_service_client = { path = "../static_file_service_client", optional = true }
strum = { workspace = true }
thiserror = { workspace = true }
-tokio = { workspace = true, features = ["macros", "sync"], optional = true }
+tokio = { workspace = true, features = ["macros", "sync", "time"], optional = true }
tokio-retry = { workspace = true, optional = true }
tracing = { workspace = true }
utoipa = { workspace = true, optional = true }
@@ -168,6 +168,6 @@ mockall = { workspace = true }
rdkafka = { workspace = true }
rootcause = { workspace = true }
serde_json = { workspace = true }
-tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal"] }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal", "test-util"] }
tower = { workspace = true }
tracing-subscriber = { workspace = true }
diff --git a/crates/channels/src/domain/message_delivery.rs b/crates/channels/src/domain/message_delivery.rs
index 121fb34b5d..98d8e1efed 100644
--- a/crates/channels/src/domain/message_delivery.rs
+++ b/crates/channels/src/domain/message_delivery.rs
@@ -1,9 +1,17 @@
//! Channel side effects for messages committed by the shared message service.
use super::{
events::{ChannelEvent, ReactionNotificationContext},
- models::{ChannelMetadata, MutatedMessage, ReferencedShareItem, Sender},
- ports::{ChannelEventDispatcher, ChannelReferenceSharePermissions, ChannelRepo},
+ models::{
+ ChannelMetadata, MutatedMessage, ReferenceShareOutcome, ReferenceShareResult,
+ ReferencedShareItem, Sender,
+ },
+ ports::{
+ AgentCreations, ChannelEventDispatcher, ChannelReferenceSharePermissions, ChannelRepo,
+ },
};
+use bot_id::BotId;
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
use messages::domain::{
delivery::MessageRealtime,
models::{
@@ -11,6 +19,8 @@ use messages::domain::{
},
ports::{MessageChange, MessageEvent, MessageEventPublisher},
};
+use std::time::Duration;
+use tracing::Instrument;
use uuid::Uuid;
#[cfg(test)]
@@ -21,25 +31,31 @@ mod test;
/// message service commits a channel message, and sends the common
/// `message_update` payload to the channel's participants.
#[derive(Clone)]
-pub struct ChannelMessageDelivery<R, E, P, G> {
+pub struct ChannelMessageDelivery<R, E, P, G, C> {
repo: R,
events: E,
permissions: P,
realtime: G,
+ creations: C,
}
-impl<R, E, P, G> ChannelMessageDelivery<R, E, P, G> {
+impl<R, E, P, G, C> ChannelMessageDelivery<R, E, P, G, C> {
/// Compose existing channel policies with the shared realtime transport.
- pub fn new(repo: R, events: E, permissions: P, realtime: G) -> Self {
+ pub fn new(repo: R, events: E, permissions: P, realtime: G, creations: C) -> Self {
Self {
repo,
events,
permissions,
realtime,
+ creations,
}
}
}
+/// Activity is ingested asynchronously, so a creation the agent just made may
+/// not be recorded yet when its reply is delivered.
+const CREATION_RECHECK_DELAYS: [Duration; 2] = [Duration::from_secs(5), Duration::from_secs(30)];
+
fn persisted(channel_id: Uuid, message: &Message) -> MutatedMessage {
MutatedMessage {
id: message.id,
@@ -55,17 +71,167 @@ fn persisted(channel_id: Uuid, message: &Message) -> MutatedMessage {
}
}
+/// The person a bot message was posted for.
+fn triggering_person(message: &Message) -> Option<MacroUserIdStr<'static>> {
+ let id = message.triggered_by.clone()?;
+ MacroUserIdStr::try_from(id)
+ .inspect_err(|error| tracing::warn!(?error, "unparseable triggered_by"))
+ .ok()
+}
+
+/// Record on the current span how many items were shared and how many the person could not share.
+fn record_share_outcomes(results: &[ReferenceShareResult]) {
+ let shared = results
+ .iter()
+ .filter(|result| result.outcome == ReferenceShareOutcome::Shared)
+ .count();
+ let span = tracing::Span::current();
+ span.record("shared", shared);
+ span.record("not_permitted", results.len() - shared);
+}
+
+/// Share the `pending` items once their creation by `bot` is recorded, giving
+/// up on any still unrecorded after the last re-check.
+async fn recheck_agent_creations<C, P>(
+ creations: C,
+ permissions: P,
+ bot: BotId,
+ requested_at: DateTime<Utc>,
+ person: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ mut pending: Vec<ReferencedShareItem>,
+) where
+ C: AgentCreations,
+ P: ChannelReferenceSharePermissions,
+{
+ for (attempt, delay) in CREATION_RECHECK_DELAYS.into_iter().enumerate() {
+ tokio::time::sleep(delay).await;
+ let created = match creations
+ .created_since(bot, &person, requested_at, pending.clone())
+ .await
+ {
+ Ok(created) => created,
+ Err(error) => {
+ tracing::warn!(error = ?error.into(), attempt, "agent creation re-check failed");
+ continue;
+ }
+ };
+ if created.is_empty() {
+ continue;
+ }
+ pending.retain(|item| !created.contains(item));
+ match permissions
+ .update_channel_share_permissions_for_referenced_items(
+ person.clone(),
+ channel_id,
+ created,
+ )
+ .await
+ {
+ Ok(results) => record_share_outcomes(&results),
+ Err(error) => {
+ tracing::warn!(error = ?error.into(), attempt, "sharing agent creations failed");
+ }
+ }
+ if pending.is_empty() {
+ return;
+ }
+ }
+ tracing::info!(
+ unshared = pending.len(),
+ "linked items the bot did not create for this request stay unshared"
+ );
+}
+
fn repo_error(error: impl Into<anyhow::Error>) -> rootcause::Report {
rootcause::report!("channel message delivery failed: {}", error.into())
}
-impl<R, E, P, G> ChannelMessageDelivery<R, E, P, G>
+impl<R, E, P, G, C> ChannelMessageDelivery<R, E, P, G, C>
where
R: ChannelRepo,
E: ChannelEventDispatcher,
- P: ChannelReferenceSharePermissions,
+ P: ChannelReferenceSharePermissions + Clone,
G: MessageRealtime,
+ C: AgentCreations,
{
+ /// Share, as `person`, the linked items that `bot` created for them since
+ /// their latest message in this thread before `replied_at`, the request
+ /// the reply answers. One bound covers classic bot replies and agent
+ /// session turns alike. Items without a creation record yet are
+ /// re-checked in the background; the rest, including anything that
+ /// existed before the request, stay unshared.
+ #[tracing::instrument(
+ skip(self, person, items),
+ fields(
+ items = items.len(),
+ created = tracing::field::Empty,
+ shared = tracing::field::Empty,
+ not_permitted = tracing::field::Empty,
+ ),
+ err
+ )]
+ async fn share_agent_creations(
+ &self,
+ bot: BotId,
+ person: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ thread_root: Uuid,
+ replied_at: DateTime<Utc>,
+ items: Vec<ReferencedShareItem>,
+ ) -> anyhow::Result<()> {
+ let Some(requested_at) = self
+ .creations
+ .request_sent_at(thread_root, &person, replied_at)
+ .await
+ .map_err(Into::into)?
+ else {
+ return Ok(());
+ };
+ let created = self
+ .creations
+ .created_since(bot, &person, requested_at, items.clone())
+ .await
+ .map_err(Into::into)?;
+ tracing::Span::current().record("created", created.len());
+ let pending: Vec<_> = items
+ .into_iter()
+ .filter(|item| !created.contains(item))
+ .collect();
+ if !pending.is_empty() {
+ let pending_count = pending.len();
+ tokio::spawn(
+ recheck_agent_creations(
+ self.creations.clone(),
+ self.permissions.clone(),
+ bot,
+ requested_at,
+ person.clone(),
+ channel_id,
+ pending,
+ )
+ .instrument(tracing::info_span!(
+ "channels.recheck_agent_creations",
+ %channel_id,
+ %bot,
+ %thread_root,
+ pending = pending_count,
+ shared = tracing::field::Empty,
+ not_permitted = tracing::field::Empty,
+ )),
+ );
+ }
+ if !created.is_empty() {
+ let results = self
+ .permissions
+ .update_channel_share_permissions_for_referenced_items(person, channel_id, created)
+ .await
+ .map_err(Into::into)?;
+ record_share_outcomes(&results);
+ }
+ Ok(())
+ }
+
async fn channel_metadata(
&self,
channel_id: Uuid,
@@ -90,12 +256,13 @@ where
}
}
-impl<R, E, P, G> MessageEventPublisher for ChannelMessageDelivery<R, E, P, G>
+impl<R, E, P, G, C> MessageEventPublisher for ChannelMessageDelivery<R, E, P, G, C>
where
R: ChannelRepo,
E: ChannelEventDispatcher,
- P: ChannelReferenceSharePermissions,
+ P: ChannelReferenceSharePermissions + Clone,
G: MessageRealtime,
+ C: AgentCreations,
{
async fn publish(&self, event: MessageEvent) -> Result<(), rootcause::Report> {
let MessageParent::Channel(channel_id) = event.parent else {
@@ -122,38 +289,55 @@ where
message, mentions, ..
} = &event.change
{
- if let Some(user) = actor.as_user() {
- let items = message
- .attachments
- .iter()
- .filter_map(|attachment| {
- ReferencedShareItem::from_raw(
- attachment.entity_id.clone(),
- &attachment.entity_type,
- )
- })
- .chain(mentions.iter().filter_map(|mention| {
- ReferencedShareItem::from_raw(
- mention.entity_id.clone(),
- &mention.entity_type,
- )
- }))
- .collect::<Vec<_>>();
- if !items.is_empty()
- && let Err(error) = self
- .permissions
+ let items = message
+ .attachments
+ .iter()
+ .filter_map(|attachment| {
+ ReferencedShareItem::from_raw(
+ attachment.entity_id.clone(),
+ &attachment.entity_type,
+ )
+ })
+ .chain(mentions.iter().filter_map(|mention| {
+ ReferencedShareItem::from_raw(mention.entity_id.clone(), &mention.entity_type)
+ }))
+ .collect::<Vec<_>>();
+ if !items.is_empty() {
+ // A person shares what they link. A bot shares, as the person
+ // it posted for, only what it created for their request.
+ let shared = if let Some(user) = actor.as_user() {
+ self.permissions
.update_channel_share_permissions_for_referenced_items(
user.clone(),
channel_id,
items,
)
.await
+ .map(drop)
+ .map_err(Into::into)
+ } else if let Some(bot) = actor.as_bot()
+ && let Some(person) = triggering_person(message)
{
+ self.share_agent_creations(
+ bot.bot_id(),
+ person,
+ channel_id,
+ message.thread_id.unwrap_or(message.id),
+ message.created_at,
+ items,
+ )
+ .await
+ } else {
+ Ok(())
+ };
+ if let Err(error) = shared {
side_effect_error = Some(repo_error(error));
}
- if let Err(error) = self.repo.upsert_activity(actor.clone(), channel_id).await {
- side_effect_error = Some(repo_error(error));
- }
+ }
+ if actor.as_user().is_some()
+ && let Err(error) = self.repo.upsert_activity(actor.clone(), channel_id).await
+ {
+ side_effect_error = Some(repo_error(error));
}
if let Err(error) = self.repo.touch_channel_updated_at(channel_id).await {
side_effect_error = Some(repo_error(error));
diff --git a/crates/channels/src/domain/message_delivery/test.rs b/crates/channels/src/domain/message_delivery/test.rs
index 2da0c273a6..1e1b495e53 100644
--- a/crates/channels/src/domain/message_delivery/test.rs
+++ b/crates/channels/src/domain/message_delivery/test.rs
@@ -1,21 +1,28 @@
use super::*;
use crate::domain::{
- models::{ChannelInfo, ChannelParticipant, ChannelType, ParticipantRole},
+ models::{
+ ChannelInfo, ChannelParticipant, ChannelType, ParticipantRole, ReferencedShareItemType,
+ },
ports::MockChannelRepo,
};
use chrono::Utc;
use macro_user_id::user_id::MacroUserIdStr;
use messages::domain::models::{MessageAttachment, SimpleMention};
+use std::time::Duration;
use std::{
collections::HashSet,
sync::{Arc, Mutex},
};
+/// Who shared which item ids.
+type Share = (String, Vec<String>);
+
#[derive(Clone, Default)]
struct Log {
events: Arc<Mutex<Vec<ChannelEvent>>>,
live: Arc<Mutex<Vec<(String, HashSet<String>)>>>,
- shares: Arc<Mutex<usize>>,
+ shares: Arc<Mutex<Vec<Share>>>,
+ shared: Arc<tokio::sync::Notify>,
fail_live: bool,
}
@@ -50,18 +57,68 @@ impl ChannelReferenceSharePermissions for Log {
type Err = anyhow::Error;
async fn update_channel_share_permissions_for_referenced_items(
&self,
- _: MacroUserIdStr<'static>,
+ actor: MacroUserIdStr<'static>,
_: Uuid,
- _: Vec<ReferencedShareItem>,
+ items: Vec<ReferencedShareItem>,
) -> Result<Vec<crate::domain::models::ReferenceShareResult>, Self::Err> {
- *self.shares.lock().unwrap() += 1;
+ self.shares.lock().unwrap().push((
+ actor.to_string(),
+ items
+ .iter()
+ .map(|item| item.entity_id().to_owned())
+ .collect(),
+ ));
+ self.shared.notify_one();
anyhow::bail!("sharing temporarily unavailable")
}
}
+/// What bots created for MEMBER, who asked in the thread when `asked` is set.
+#[derive(Clone, Default)]
+struct Creations {
+ asked: bool,
+ created: Arc<Mutex<Vec<(BotId, ReferencedShareItem)>>>,
+ lookups: Arc<Mutex<usize>>,
+}
+
+impl AgentCreations for Creations {
+ type Err = anyhow::Error;
+ async fn request_sent_at(
+ &self,
+ thread_root: Uuid,
+ person: &MacroUserIdStr<'static>,
+ _: DateTime<Utc>,
+ ) -> Result<Option<DateTime<Utc>>, Self::Err> {
+ assert_eq!(
+ thread_root,
+ Uuid::from_u128(1),
+ "the root message is the thread"
+ );
+ assert_eq!(person.as_ref(), MEMBER);
+ Ok(self.asked.then(Utc::now))
+ }
+ async fn created_since(
+ &self,
+ bot: BotId,
+ _: &MacroUserIdStr<'static>,
+ _: DateTime<Utc>,
+ items: Vec<ReferencedShareItem>,
+ ) -> Result<Vec<ReferencedShareItem>, Self::Err> {
+ *self.lookups.lock().unwrap() += 1;
+ let created = self.created.lock().unwrap();
+ Ok(items
+ .into_iter()
+ .filter(|item| created.contains(&(bot, item.clone())))
+ .collect())
+ }
+}
+
const CHANNEL: Uuid = Uuid::from_u128(2);
const MEMBER: &str = "macro|[email protected]";
const SENDER: &str = "macro|[email protected]";
+const BOT: &str = "bot|00000000-0000-0000-0000-00000000b07a";
+const DOCUMENT: Uuid = Uuid::from_u128(3);
+const EXISTING_DOCUMENT: Uuid = Uuid::from_u128(8);
fn repo() -> MockChannelRepo {
let mut repo = MockChannelRepo::new();
@@ -157,7 +214,13 @@ fn live_users() -> HashSet<String> {
#[tokio::test]
async fn a_post_emits_the_channel_notification_event_and_the_common_payload() {
let log = Log::default();
- let delivery = ChannelMessageDelivery::new(repo(), log.clone(), log.clone(), log.clone());
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ Creations::default(),
+ );
assert!(
delivery
.publish(event(MessageChange::Posted {
@@ -169,7 +232,14 @@ async fn a_post_emits_the_channel_notification_event_and_the_common_payload() {
.is_err(),
"the sharing failure is reported after every other effect ran"
);
- assert_eq!(*log.shares.lock().unwrap(), 1);
+ assert_eq!(
+ *log.shares.lock().unwrap(),
+ [(
+ SENDER.to_owned(),
+ vec![DOCUMENT.to_string(), DOCUMENT.to_string()]
+ )],
+ "a person shares everything they link"
+ );
let events = log.events.lock().unwrap();
let [
ChannelEvent::MessagePosted {
@@ -197,7 +267,13 @@ async fn a_post_emits_the_channel_notification_event_and_the_common_payload() {
#[tokio::test]
async fn an_edit_that_notifies_as_a_post_emits_the_posted_event() {
let log = Log::default();
- let delivery = ChannelMessageDelivery::new(repo(), log.clone(), log.clone(), log.clone());
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ Creations::default(),
+ );
let previous = MessageAttachment {
id: Uuid::from_u128(5),
entity_type: "document".into(),
@@ -235,7 +311,13 @@ async fn an_edit_that_notifies_as_a_post_emits_the_posted_event() {
#[tokio::test]
async fn plain_edits_deletions_reactions_and_typing_only_send_the_common_payload() {
let log = Log::default();
- let delivery = ChannelMessageDelivery::new(repo(), log.clone(), log.clone(), log.clone());
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ Creations::default(),
+ );
for change in [
MessageChange::Edited {
notification_policy: PatchMessageNotificationPolicy::Default,
@@ -273,7 +355,13 @@ async fn plain_edits_deletions_reactions_and_typing_only_send_the_common_payload
#[tokio::test]
async fn added_reaction_carries_author_notification_context() {
let log = Log::default();
- let delivery = ChannelMessageDelivery::new(repo(), log.clone(), log.clone(), log.clone());
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ Creations::default(),
+ );
let mut reaction = event(MessageChange::ReactionChanged {
message: message(),
emoji: "👍".to_string(),
@@ -295,7 +383,13 @@ async fn added_reaction_carries_author_notification_context() {
#[tokio::test]
async fn removed_reaction_sends_no_author_notification() {
let log = Log::default();
- let delivery = ChannelMessageDelivery::new(repo(), log.clone(), log.clone(), log.clone());
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ Creations::default(),
+ );
let mut reaction = event(MessageChange::ReactionChanged {
message: message(),
emoji: "👍".to_string(),
@@ -311,7 +405,13 @@ async fn removed_reaction_sends_no_author_notification() {
#[tokio::test]
async fn thread_updates_stay_off_the_channel_side_effect_path() {
let log = Log::default();
- let delivery = ChannelMessageDelivery::new(repo(), log.clone(), log.clone(), log.clone());
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ Creations::default(),
+ );
delivery
.publish(event(MessageChange::ThreadUpdated {
state: messages::domain::models::ThreadState {
@@ -336,7 +436,13 @@ async fn realtime_failure_is_reported() {
fail_live: true,
..Default::default()
};
- let delivery = ChannelMessageDelivery::new(repo(), log.clone(), log.clone(), log.clone());
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ Creations::default(),
+ );
assert!(
delivery
.publish(event(MessageChange::MessageDeleted { message: message() }))
@@ -348,9 +454,160 @@ async fn realtime_failure_is_reported() {
#[tokio::test]
async fn document_events_are_rejected() {
let log = Log::default();
- let delivery = ChannelMessageDelivery::new(repo(), log.clone(), log.clone(), log.clone());
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ Creations::default(),
+ );
let mut event = event(MessageChange::MessageDeleted { message: message() });
event.parent = MessageParent::parse("document", "doc").unwrap();
assert!(delivery.publish(event).await.is_err());
assert!(log.events.lock().unwrap().is_empty());
}
+
+fn document(id: Uuid) -> ReferencedShareItem {
+ ReferencedShareItem::new(id.to_string(), ReferencedShareItemType::Document)
+}
+
+/// The agent's post for MEMBER linking the attached DOCUMENT and EXISTING_DOCUMENT.
+fn agent_post(triggered_by: Option<&str>) -> MessageEvent {
+ let mut posted = event(MessageChange::Posted {
+ notification_policy: Default::default(),
+ message: Message {
+ sender_id: BOT.to_owned().try_into().unwrap(),
+ triggered_by: triggered_by.map(str::to_owned),
+ ..message()
+ },
+ mentions: vec![SimpleMention {
+ entity_type: "document".into(),
+ entity_id: EXISTING_DOCUMENT.to_string(),
+ }],
+ });
+ posted.actor = BOT.to_owned();
+ posted
+}
+
+/// MEMBER asked in the thread, and `bot` created `items` for them since.
+fn asked_and(bot: BotId, items: Vec<ReferencedShareItem>) -> Creations {
+ Creations {
+ asked: true,
+ created: Arc::new(Mutex::new(
+ items.into_iter().map(|item| (bot, item)).collect(),
+ )),
+ ..Default::default()
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn an_agent_shares_what_it_created_for_the_request_and_not_what_already_existed() {
+ let log = Log::default();
+ let creations = asked_and(BotId::TEST_A, vec![document(DOCUMENT)]);
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ creations.clone(),
+ );
+
+ let _ = delivery.publish(agent_post(Some(MEMBER))).await;
+ // Let every background re-check for the existing document run out.
+ tokio::time::sleep(Duration::from_secs(60)).await;
+
+ assert_eq!(
+ *log.shares.lock().unwrap(),
+ [(MEMBER.to_owned(), vec![DOCUMENT.to_string()])]
+ );
+ assert_eq!(
+ *creations.lookups.lock().unwrap(),
+ 3,
+ "one lookup and two re-checks"
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_creation_recorded_after_delivery_is_shared_by_the_re_check() {
+ let log = Log::default();
+ let creations = asked_and(BotId::TEST_A, vec![]);
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ creations.clone(),
+ );
+
+ delivery.publish(agent_post(Some(MEMBER))).await.unwrap();
+ assert!(log.shares.lock().unwrap().is_empty());
+ creations
+ .created
+ .lock()
+ .unwrap()
+ .push((BotId::TEST_A, document(DOCUMENT)));
+ log.shared.notified().await;
+
+ assert_eq!(
+ *log.shares.lock().unwrap(),
+ [(MEMBER.to_owned(), vec![DOCUMENT.to_string()])]
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn what_another_bot_created_is_not_shared() {
+ let log = Log::default();
+ let creations = asked_and(BotId::TEST_B, vec![document(DOCUMENT)]);
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ creations.clone(),
+ );
+
+ delivery.publish(agent_post(Some(MEMBER))).await.unwrap();
+ tokio::time::sleep(Duration::from_secs(60)).await;
+
+ assert!(log.shares.lock().unwrap().is_empty());
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_reply_to_no_request_from_the_person_shares_nothing() {
+ let log = Log::default();
+ let creations = Creations {
+ asked: false,
+ ..asked_and(BotId::TEST_A, vec![document(DOCUMENT)])
+ };
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ creations.clone(),
+ );
+
+ delivery.publish(agent_post(Some(MEMBER))).await.unwrap();
+ tokio::time::sleep(Duration::from_secs(60)).await;
+
+ assert!(log.shares.lock().unwrap().is_empty());
+ assert_eq!(*creations.lookups.lock().unwrap(), 0);
+}
+
+#[tokio::test(start_paused = true)]
+async fn an_agent_post_for_nobody_shares_nothing() {
+ let log = Log::default();
+ let creations = asked_and(BotId::TEST_A, vec![document(DOCUMENT)]);
+ let delivery = ChannelMessageDelivery::new(
+ repo(),
+ log.clone(),
+ log.clone(),
+ log.clone(),
+ creations.clone(),
+ );
+
+ delivery.publish(agent_post(None)).await.unwrap();
+ tokio::time::sleep(Duration::from_secs(60)).await;
+
+ assert!(log.shares.lock().unwrap().is_empty());
+}
diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rs
index c2c3e5e5d9..c533de0ff8 100644
--- a/crates/channels/src/domain/ports.rs
+++ b/crates/channels/src/domain/ports.rs
@@ -964,6 +964,31 @@ pub trait ChannelReferenceSharePermissions: Send + Sync + 'static {
) -> impl Future<Output = Result<Vec<ReferenceShareResult>, Self::Err>> + Send;
}
+/// What a bot created for a person while answering them, so its channel
+/// reply shares only those items.
+pub trait AgentCreations: Clone + Send + Sync + 'static {
+ /// Error type for creation lookups.
+ type Err: Into<anyhow::Error> + Send;
+
+ /// When `person` last wrote in the thread rooted at `thread_root` before
+ /// `before`: the request a bot reply posted then is answering.
+ fn request_sent_at(
+ &self,
+ thread_root: Uuid,
+ person: &MacroUserIdStr<'static>,
+ before: DateTime<Utc>,
+ ) -> impl Future<Output = Result<Option<DateTime<Utc>>, Self::Err>> + Send;
+
+ /// The `items` that `bot` recorded creating on `person`'s behalf at or after `since`.
+ fn created_since(
+ &self,
+ bot: BotId,
+ person: &MacroUserIdStr<'static>,
+ since: DateTime<Utc>,
+ items: Vec<ReferencedShareItem>,
+ ) -> impl Future<Output = Result<Vec<ReferencedShareItem>, Self::Err>> + Send;
+}
+
/// Errors that can occur while mutating channels.
#[derive(Debug, thiserror::Error)]
pub enum ChannelMutationErr {
diff --git a/crates/channels/src/inbound/toolset/share_with_channel.rs b/crates/channels/src/inbound/toolset/share_with_channel.rs
index 9994e86673..96b1684c83 100644
--- a/crates/channels/src/inbound/toolset/share_with_channel.rs
+++ b/crates/channels/src/inbound/toolset/share_with_channel.rs
@@ -75,7 +75,7 @@ impl ChannelShareEntityType {
#[serde(rename_all = "camelCase")]
#[schemars(
title = "ShareWithChannel",
- description = "Share an item with the current members of a channel by writing a channel entity-access grant. Call it only after the user agrees to share that item, or when they already asked you to share it. entityType is the stored type: calendar_event for a calendar chip, document, project, database, form, call, thread, agent_session, or external_chat. entityId is that item's id. A calendar event can be shared only by someone who holds it on their own calendar, and private or confidential events are refused. Sharing again is safe when a grant already exists."
+ description = "Share an item with the current members of a channel by writing a channel entity-access grant. Call it only when the user asks you to share an existing item; items you create while answering a channel message and link in your reply as a mention chip or attachment are already shared with that channel. entityType is the stored type: calendar_event for a calendar chip, document, project, database, form, call, thread, agent_session, or external_chat. entityId is that item's id. A calendar event can be shared only by someone who holds it on their own calendar, and private or confidential events are refused. Sharing again is safe when a grant already exists."
)]
pub struct ShareWithChannel {
/// Channel whose current members should receive the grant.
diff --git a/crates/channels/src/outbound/mod.rs b/crates/channels/src/outbound/mod.rs
index 56a8c3d2bf..d954e9122d 100644
--- a/crates/channels/src/outbound/mod.rs
+++ b/crates/channels/src/outbound/mod.rs
@@ -8,6 +8,8 @@ pub mod contacts_dispatcher;
pub mod entity_access_comment_parents;
/// Notification adapter for channel notification side effects.
pub mod notification_sender;
+/// Postgres adapter for what a bot created for a person's request.
+pub mod pg_agent_creations;
/// Postgres adapter for channel reference share-permission side effects.
pub mod pg_channel_reference_share_permissions;
/// Postgres repository for channels.
diff --git a/crates/channels/src/outbound/pg_agent_creations.rs b/crates/channels/src/outbound/pg_agent_creations.rs
new file mode 100644
index 0000000000..b2c3af4f3f
--- /dev/null
+++ b/crates/channels/src/outbound/pg_agent_creations.rs
@@ -0,0 +1,115 @@
+//! Postgres adapter answering what a bot created for a person's request,
+//! from the thread's messages and the activity log.
+
+use crate::domain::{models::ReferencedShareItem, ports::AgentCreations};
+use bot_id::BotId;
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+#[cfg(test)]
+mod test;
+
+/// Reads channel requests and bots' recorded creations from Postgres.
+#[derive(Clone)]
+pub struct PgAgentCreations {
+ pool: PgPool,
+}
+
+impl PgAgentCreations {
+ /// Create the adapter over `pool`.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl AgentCreations for PgAgentCreations {
+ type Err = sqlx::Error;
+
+ #[tracing::instrument(skip(self, person), err)]
+ async fn request_sent_at(
+ &self,
+ thread_root: Uuid,
+ person: &MacroUserIdStr<'static>,
+ before: DateTime<Utc>,
+ ) -> Result<Option<DateTime<Utc>>, Self::Err> {
+ // The root by primary key, replies by the (thread_id, created_at) index.
+ sqlx::query_scalar!(
+ r#"
+ SELECT max(created_at) AS "sent_at"
+ FROM (
+ SELECT created_at
+ FROM comms_messages
+ WHERE id = $1 AND sender_id = $2 AND created_at < $3
+ UNION ALL
+ SELECT created_at
+ FROM comms_messages
+ WHERE thread_id = $1 AND sender_id = $2 AND created_at < $3
+ AND deleted_at IS NULL
+ ) request
+ "#,
+ thread_root,
+ person.as_ref(),
+ before,
+ )
+ .fetch_one(&self.pool)
+ .await
+ }
+
+ #[tracing::instrument(skip(self, person, items), fields(items = items.len()), err)]
+ async fn created_since(
+ &self,
+ bot: BotId,
+ person: &MacroUserIdStr<'static>,
+ since: DateTime<Utc>,
+ items: Vec<ReferencedShareItem>,
+ ) -> Result<Vec<ReferencedShareItem>, Self::Err> {
+ if items.is_empty() {
+ return Ok(items);
+ }
+ let entity_types: Vec<String> = items
+ .iter()
+ // activity_events stores the same entity type names.
+ .map(|item| item.entity_type().as_str().to_owned())
+ .collect();
+ let entity_ids: Vec<String> = items
+ .iter()
+ .map(|item| item.entity_id().to_owned())
+ .collect();
+ let actor = bot.into_storage_id();
+ // One idx_activity_events_entity_action_timeline probe per linked item.
+ let created = sqlx::query!(
+ r#"
+ SELECT item.entity_type AS "entity_type!", item.entity_id AS "entity_id!"
+ FROM UNNEST($1::text[], $2::text[]) AS item(entity_type, entity_id)
+ WHERE EXISTS (
+ SELECT 1
+ FROM activity_events event
+ WHERE event.entity_type = item.entity_type
+ AND event.entity_id = item.entity_id
+ AND event.action = 'created'
+ AND event.actor_id = $3
+ AND event.subject_id = $4
+ AND event.occurred_at >= $5
+ )
+ "#,
+ &entity_types,
+ &entity_ids,
+ actor.as_ref(),
+ person.as_ref(),
+ since,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(items
+ .into_iter()
+ .filter(|item| {
+ created.iter().any(|row| {
+ row.entity_type == item.entity_type().as_str()
+ && row.entity_id == item.entity_id()
+ })
+ })
+ .collect())
+ }
+}
diff --git a/crates/channels/src/outbound/pg_agent_creations/test.rs b/crates/channels/src/outbound/pg_agent_creations/test.rs
new file mode 100644
index 0000000000..bfd390b87a
--- /dev/null
+++ b/crates/channels/src/outbound/pg_agent_creations/test.rs
@@ -0,0 +1,167 @@
+use super::*;
+use crate::domain::models::ReferencedShareItemType;
+use chrono::{Duration, SubsecRound};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+const THREAD_ROOT: Uuid = Uuid::from_u128(1);
+const REPLYING_BOT: BotId = BotId::TEST_A;
+const OTHER_BOT: BotId = BotId::TEST_B;
+const PERSON: &str = "macro|[email protected]";
+const SOMEONE_ELSE: &str = "macro|[email protected]";
+
+fn person() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(PERSON.to_owned()).unwrap()
+}
+
+async fn post(pool: &PgPool, id: Uuid, thread_id: Option<Uuid>, sender: &str, at: DateTime<Utc>) {
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_messages
+ (id, thread_id, sender_id, content, parent_entity_type, parent_entity_id, created_at)
+ VALUES ($1, $2, $3, 'message', 'document', 'parent', $4)
+ "#,
+ id,
+ thread_id,
+ sender,
+ at,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+async fn record_creation(
+ pool: &PgPool,
+ actor: BotId,
+ subject: &str,
+ document_id: &str,
+ at: DateTime<Utc>,
+) {
+ let actor = actor.into_storage_id();
+ sqlx::query!(
+ r#"
+ INSERT INTO activity_events (id, actor_id, subject_id, action, entity_type, entity_id, occurred_at)
+ VALUES ($1, $2, $3, 'created', 'document', $4, $5)
+ "#,
+ Uuid::now_v7(),
+ actor.as_ref(),
+ subject,
+ document_id,
+ at,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+fn document(id: &str) -> ReferencedShareItem {
+ ReferencedShareItem::new(id, ReferencedShareItemType::Document)
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn the_request_is_the_persons_latest_message_in_the_thread_before_the_reply(pool: PgPool) {
+ let root_at = Utc::now() - Duration::hours(1);
+ let follow_up_at = root_at + Duration::minutes(10);
+ let reply_at = follow_up_at + Duration::minutes(1);
+ post(&pool, THREAD_ROOT, None, PERSON, root_at).await;
+ post(
+ &pool,
+ Uuid::from_u128(2),
+ Some(THREAD_ROOT),
+ PERSON,
+ follow_up_at,
+ )
+ .await;
+ post(
+ &pool,
+ Uuid::from_u128(3),
+ Some(THREAD_ROOT),
+ SOMEONE_ELSE,
+ reply_at,
+ )
+ .await;
+ post(
+ &pool,
+ Uuid::from_u128(4),
+ Some(THREAD_ROOT),
+ PERSON,
+ reply_at + Duration::minutes(1),
+ )
+ .await;
+ let creations = PgAgentCreations::new(pool);
+
+ assert_eq!(
+ creations
+ .request_sent_at(THREAD_ROOT, &person(), reply_at)
+ .await
+ .unwrap(),
+ Some(follow_up_at.trunc_subsecs(6)),
+ "a later message from the person, or anyone else's, is not the request"
+ );
+ assert_eq!(
+ creations
+ .request_sent_at(THREAD_ROOT, &person(), root_at + Duration::seconds(1))
+ .await
+ .unwrap(),
+ Some(root_at.trunc_subsecs(6)),
+ "the person's root message is a request too"
+ );
+ assert_eq!(
+ creations
+ .request_sent_at(Uuid::from_u128(9), &person(), reply_at)
+ .await
+ .unwrap(),
+ None
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn only_what_the_replying_bot_created_for_the_person_since_the_request_counts(pool: PgPool) {
+ let requested_at = Utc::now() - Duration::minutes(5);
+ let after = requested_at + Duration::seconds(1);
+ record_creation(
+ &pool,
+ REPLYING_BOT,
+ PERSON,
+ "created-for-the-request",
+ after,
+ )
+ .await;
+ record_creation(
+ &pool,
+ REPLYING_BOT,
+ PERSON,
+ "created-before",
+ requested_at - Duration::days(1),
+ )
+ .await;
+ record_creation(&pool, OTHER_BOT, PERSON, "created-by-another-bot", after).await;
+ record_creation(
+ &pool,
+ REPLYING_BOT,
+ SOMEONE_ELSE,
+ "created-for-someone-else",
+ after,
+ )
+ .await;
+ let creations = PgAgentCreations::new(pool);
+
+ assert_eq!(
+ creations
+ .created_since(
+ REPLYING_BOT,
+ &person(),
+ requested_at,
+ vec![
+ document("created-for-the-request"),
+ document("created-before"),
+ document("created-by-another-bot"),
+ document("created-for-someone-else"),
+ document("never-recorded"),
+ ],
+ )
+ .await
+ .unwrap(),
+ vec![document("created-for-the-request")]
+ );
+}
diff --git a/crates/prompt/src/channel_mention.rs b/crates/prompt/src/channel_mention.rs
index e7771431e7..d4fc608801 100644
--- a/crates/prompt/src/channel_mention.rs
+++ b/crates/prompt/src/channel_mention.rs
@@ -36,30 +36,17 @@ Sending email is not available from a channel: there is no SendEmail tool here.
draft or send an email, say you cannot do that from a channel and suggest asking Macro in an AI
chat or using the email composer.
-## Sharing what you create or link
-
-Linking an item in a channel does not give the channel access to it; only sharing does. So
-whenever your reply links an item you created, edited, or found this turn (a document,
-calendar event, chat, database, form, project, call, email thread, or agent session), the
-last line of your reply must be exactly:
-
-Do you want me to share this with the members of the channel?
-
-Ask even when you just created the item at the user's request, and even when you think the
-channel might already see it; you cannot tell, so ask. Do not share it in the same turn.
-Name the item only when "this" would be ambiguous. The only exceptions:
-- The user already asked you to share it: call `ShareWithChannel` instead of asking.
-- The item is this channel or a message already in it.
-
-Before you send any reply, check: does it link an item? If so, is that question the last
-line? If not, add it.
-
-A later message in this thread that agrees ("yes", "yeah", "please", "go ahead", "share it")
-answers that question. Call `ShareWithChannel` for that item and this channel — `channelId` is
-the `id` on the conversation parent above; a calendar chip is entity type `calendar_event` and
-its `documentId` is the event id — then reply with only "Okay." Do not repeat the earlier answer. Agreement to a
-different question is not agreement to share. If they decline, acknowledge in a few words and
-do not share. If the tool says you cannot share it, say that plainly instead of "Okay."
+## Sharing what you link
+
+Items you create while answering this message and link in your reply, as a mention chip (the
+XML mention tags) or an attachment, are shared with this channel as the person who asked you.
+Existing items you link are not shared, including ones you created for an earlier message. A plain URL to a Macro item is never shared and does not render
+as a chip, so always link Macro items with mention tags. Never ask whether to share.
+
+Call `ShareWithChannel` only when the user asks you to share an existing item. `channelId` is
+the `id` on the conversation parent above; a calendar chip is entity type `calendar_event`
+whose `entityId` is the chip's `documentId`. If the tool says you cannot share it, say that
+plainly.
"##;
static INTENT: &str = "The model replies to the marked mention, treats the <thread> block as \
@@ -69,10 +56,10 @@ user's time zone when the block names one — asking rather than silently assumi
does not — treats tool calls as executing immediately (no composer or pending \
confirmation to point the user at), only takes explicitly requested actions, checks before \
creating events with attendees, declines email drafting/sending with a pointer to AI chat \
-or the email composer, and when a reply links an item ends \
-by asking \"Do you want me to share this with the members of the channel?\" — always, \
-including for items it just created, since linking does not grant access — then, on a yes \
-in the thread, calls ShareWithChannel and replies only \"Okay.\"";
+or the email composer, links Macro items only as mention chips (never \
+plain URLs), knowing that linked items it created while answering the message are shared with \
+the channel as the person who asked while existing items it links are not, never asks whether to share, \
+and calls ShareWithChannel only when the user asks to share an existing item.";
/// The channel-mention prompt for the Macro channel bot.
pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
@@ -82,17 +69,21 @@ mod test {
use super::PROMPT;
#[test]
- fn a_linked_item_is_offered_to_the_channel_and_shared_only_after_yes() {
+ fn items_created_for_the_message_are_shared_and_the_bot_never_asks() {
let instructions = PROMPT.instructions.as_ref();
+ assert!(instructions.contains("Items you create while answering this message and link"));
+ assert!(instructions.contains("Existing items you link are not shared"));
+ assert!(instructions.contains("A plain URL to a Macro item is never shared"));
+ assert!(instructions.contains("Never ask whether to share."));
+ assert!(!instructions.contains("Do you want me to share this"));
assert!(
- instructions.contains("Do you want me to share this with the members of the channel?")
+ instructions.contains(
+ "`ShareWithChannel` only when the user asks you to share an existing item"
+ )
);
- assert!(instructions.contains("`ShareWithChannel`"));
- assert!(instructions.contains("Ask even when you just created the item"));
- assert!(instructions.contains("reply with only \"Okay.\""));
assert!(instructions.contains("calendar_event"));
assert!(instructions.contains("`channelId` is\nthe `id` on the conversation parent"));
- assert!(instructions.contains("its `documentId` is the event id"));
- assert!(PROMPT.intent.contains("ShareWithChannel"));
+ assert!(instructions.contains("whose `entityId` is the chip's `documentId`"));
+ assert!(PROMPT.intent.contains("never asks whether to share"));
}
}
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index acdb40ff24..c27bad3758 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -447,13 +447,15 @@ event without attendees creates the event right away (unlike AI chat, where crea
for the user to confirm a composer card). For an event with attendees the bot is prompted to
ask for confirmation in the thread first, since Google sends the invitations the moment the
event is created — no invitation goes out from the initial request. It cannot draft or send
-email at all. When that reply links something the rest of the channel may not already open
-(a calendar event, document, or similar chip), it ends by asking "Do you want me to share this
-with the members of the channel?" A yes in the thread — "yes", "please", "go ahead" — is
-enough: the bot replies "Okay." and grants current members access. It does not share before
-that yes unless the request already asked it to. A decline is not shared. Private and
-confidential calendar events stay unshared, and a calendar event can only be shared by
-someone who holds it on their own calendar. The bot's prompt carries the current date and time in the mentioning user's
+email at all. A bot or agent reply posted for a person shares, as that person, the linked items
+(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 in
+the thread before the reply. Activity arrives asynchronously, so missing rows are re-checked
+after 5 and 30 seconds. Existing items it links, plain URLs, and bot posts with no person
+behind them share nothing. The bot never asks whether to share; it calls `ShareWithChannel` when asked to
+share an existing item. Private and confidential calendar events stay unshared, and a
+calendar event can only be shared by someone who holds it on their own calendar.
+The bot's prompt carries the current date and time in the mentioning user's
own time zone (their primary calendar's), so it resolves relative times ("tomorrow at 4",
"EOD") without asking; when no calendar is connected the prompt falls back to UTC and the
bot asks before scheduling a specific clock time. Within the rollout, `@Macro` — plus
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index bbbb0fce13..156b1538da 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -1073,8 +1073,14 @@ async fn run() -> anyhow::Result<()> {
channels::domain::message_delivery::ChannelMessageDelivery::new(
PgChannelsRepo::new(pool.clone()),
SpawnedChannelEventDispatcher::new(side_effects),
- channels::domain::service::NoopChannelReferenceSharePermissions,
+ channels::outbound::pg_channel_reference_share_permissions::PgChannelReferenceSharePermissions::new(
+ pool.clone(),
+ entity_access.clone(),
+ ),
message_realtime.clone(),
+ channels::outbound::pg_agent_creations::PgAgentCreations::new(
+ pool.clone(),
+ ),
),
messages::domain::delivery::DiscussionDelivery::new(
messages::outbound::pg_discussion_context::PgDiscussionContext(pool.clone())
diff --git a/services/authentication_service/src/server.rs b/services/authentication_service/src/server.rs
index 1fe7847494..2eb77ee063 100644
--- a/services/authentication_service/src/server.rs
+++ b/services/authentication_service/src/server.rs
@@ -464,6 +464,7 @@ pub async fn run() -> anyhow::Result<()> {
messages::outbound::connection_gateway::ConnectionGatewayMessages(
connection_gateway_client,
),
+ channels::outbound::pg_agent_creations::PgAgentCreations::new(db.clone()),
),
),
)
diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rs
index c3654cdf0d..d892f47202 100644
--- a/services/document_storage_service/src/server.rs
+++ b/services/document_storage_service/src/server.rs
@@ -1285,6 +1285,7 @@ pub async fn run() -> anyhow::Result<()> {
SpawnedChannelEventDispatcher::new(channel_side_effects.clone()),
PgChannelReferenceSharePermissions::new(db.clone(), entity_access_service.clone()),
message_realtime,
+ channels::outbound::pg_agent_creations::PgAgentCreations::new(db.clone()),
);
let message_service = Arc::new(
messages::domain::service::MessageService::new(