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.

fix(agents): a private agent's channel watches its session, not steers it (#7203)

Wolf Mermelstein9ca99adbf4cf
diff --git a/.sqlx/query-6bf4a202d18927cb11bbc49cd3c8afee35cb36bda2e7aa621316f36a6b62873e.json b/.sqlx/query-6bf4a202d18927cb11bbc49cd3c8afee35cb36bda2e7aa621316f36a6b62873e.json
new file mode 100644
index 0000000000..03507d5fde
--- /dev/null
+++ b/.sqlx/query-6bf4a202d18927cb11bbc49cd3c8afee35cb36bda2e7aa621316f36a6b62873e.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT owner_user_id IS NOT NULL AS \"owned_by_user!\" FROM bots WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "owned_by_user!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "6bf4a202d18927cb11bbc49cd3c8afee35cb36bda2e7aa621316f36a6b62873e"
+}
diff --git a/crates/agent_session/src/domain/sharing.rs b/crates/agent_session/src/domain/sharing.rs
index 3cc3433b98..2914fdde24 100644
--- a/crates/agent_session/src/domain/sharing.rs
+++ b/crates/agent_session/src/domain/sharing.rs
@@ -21,6 +21,28 @@ use super::{
#[cfg(test)]
mod test;
+/// Who owns the bot a session runs as, for deciding what its originating
+/// channel may do with the session.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SessionBotOwnership {
+ /// A user's private agent.
+ User,
+ /// A team agent, or a first-party system bot that belongs to everyone.
+ Shared,
+}
+
+/// The access the channel a session was invoked from gets to it.
+///
+/// The invocation was public there, so the channel may always watch. It may
+/// also steer, unless the bot is someone's private agent: those sessions
+/// only their owner drives.
+pub fn originating_channel_access(bot: SessionBotOwnership) -> AccessLevel {
+ match bot {
+ SessionBotOwnership::User => AccessLevel::View,
+ SessionBotOwnership::Shared => AccessLevel::Edit,
+ }
+}
+
/// Persistence capability for session sharing, independent of transport.
pub trait SessionSharingRepo: Send + Sync + 'static {
/// Read canonical sharing settings and direct channel grants.
diff --git a/crates/agent_session/src/domain/sharing/test.rs b/crates/agent_session/src/domain/sharing/test.rs
index 3d5a6c041c..d97f5d9f21 100644
--- a/crates/agent_session/src/domain/sharing/test.rs
+++ b/crates/agent_session/src/domain/sharing/test.rs
@@ -238,3 +238,19 @@ async fn effective_owner_access_does_not_substitute_for_the_session_owner() {
}
assert!(repo.writes.lock().unwrap().is_empty());
}
+
+#[test]
+fn a_private_agents_channel_may_watch_but_not_steer() {
+ assert_eq!(
+ originating_channel_access(SessionBotOwnership::User),
+ AccessLevel::View
+ );
+}
+
+#[test]
+fn a_shared_agents_channel_may_steer() {
+ assert_eq!(
+ originating_channel_access(SessionBotOwnership::Shared),
+ AccessLevel::Edit
+ );
+}
diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rs
index 5492b7563f..97f6bf3b8f 100644
--- a/crates/agent_session/src/outbound/postgres.rs
+++ b/crates/agent_session/src/outbound/postgres.rs
@@ -27,6 +27,7 @@ use crate::domain::ports::{
AgentSessionLogRepo, AgentSessionRepo, ExternalSessionRepo, REPLICA_STALE_AFTER,
SessionOwnership,
};
+use crate::domain::sharing::{SessionBotOwnership, originating_channel_access};
use crate::outbound::connection_gateway_realtime::SessionAudience;
use agent_client_protocol::schema::v1::SessionId;
use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};
@@ -37,8 +38,7 @@ use bots::domain::ports::BotRepo;
use bots::outbound::pg_bots_repo::PgBotsRepo;
use chrono::{DateTime, Utc};
use entity_access_db_utils::{
- AccessLevel, EntityAccessSourceType, EntityType, delete_entity_access_rows,
- insert_entity_access_row,
+ EntityAccessSourceType, EntityType, delete_entity_access_rows, insert_entity_access_row,
};
use entity_registry::BotFacts;
use entity_registry_db_utils::{
@@ -412,11 +412,11 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {
_ => registry_unknown(error, "failed to register the agent session"),
})?;
- // The channel the bot was invoked in can steer the session: the
- // invocation was public there, so that audience is. Read from the
- // message rather than taken from the caller, so the channel is always
- // the one the message actually sits in. A session created without a
- // message - directly, rather than from a channel - is its owner's alone.
+ // The channel the bot was invoked in gets the session, at the level
+ // `originating_channel_access` grants. Read from the message rather
+ // than taken from the caller, so the channel is always the one the
+ // message actually sits in. A session created without a message -
+ // directly, rather than from a channel - is its owner's alone.
let origin_channel_id = match originating_message_id {
Some(message_id) => sqlx::query_scalar!(
r#"SELECT parent_entity_id::uuid AS "channel_id!" FROM comms_messages WHERE parent_entity_type = 'channel' AND id = $1"#,
@@ -429,13 +429,28 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {
};
if let Some(channel_id) = origin_channel_id {
+ // Read in the transaction, so the grant matches the bot's owner
+ // at creation. System bots have no row.
+ let owned_by_user = sqlx::query_scalar!(
+ r#"SELECT owner_user_id IS NOT NULL AS "owned_by_user!" FROM bots WHERE id = $1"#,
+ bot_id.as_uuid(),
+ )
+ .fetch_optional(&mut *transaction)
+ .await
+ .context("failed to read the session bot's owner")?
+ .unwrap_or(false);
+ let bot = if owned_by_user {
+ SessionBotOwnership::User
+ } else {
+ SessionBotOwnership::Shared
+ };
insert_entity_access_row(
&mut transaction,
&id.as_uuid(),
EntityType::AgentSession,
&channel_id.to_string(),
EntityAccessSourceType::Channel,
- AccessLevel::Edit,
+ originating_channel_access(bot),
)
.await
.context("failed to grant the originating channel access to the agent session")?;
diff --git a/crates/agent_session/src/outbound/postgres/sharing/test.rs b/crates/agent_session/src/outbound/postgres/sharing/test.rs
index c5902570d0..ac3209258d 100644
--- a/crates/agent_session/src/outbound/postgres/sharing/test.rs
+++ b/crates/agent_session/src/outbound/postgres/sharing/test.rs
@@ -30,7 +30,8 @@ async fn existing_channel_grants_are_visible_before_settings_are_created(pool: P
settings.channel_share_permissions,
Some(vec![ChannelSharePermission {
channel_id: channel.to_string(),
- access_level: AccessLevel::Edit
+ // `create_test_bot` is a private agent.
+ access_level: AccessLevel::View
}])
);
}
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index 58051e8f3f..b8d1c476fe 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -10,6 +10,7 @@ use agent_runtime_protocol::domain::schema::v0::{AcpMessage, SystemEvent};
use bots::domain::models::{BotOwner, CreateBotRequest};
use bots::domain::ports::BotRepo;
use bots::outbound::pg_bots_repo::PgBotsRepo;
+use entity_access_db_utils::AccessLevel;
use entity_registry::OwnerGrantPolicy;
use entity_registry_db_utils::OwnedEntityRegistrar;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
@@ -1130,7 +1131,8 @@ async fn create_grants_the_owner_and_the_originating_channel(pool: PgPool) {
(
origin_channel_id.to_string(),
"channel".to_string(),
- "edit".to_string(),
+ // `create_test_bot` is a private agent.
+ "view".to_string(),
),
];
expected.sort();
@@ -2810,3 +2812,65 @@ fn log_json_drops_null_bytes_before_it_reaches_postgres() {
])
);
}
+
+async fn channel_grant(pool: &PgPool, session: AgentSessionId, channel_id: Uuid) -> String {
+ sqlx::query_scalar!(
+ r#"SELECT access_level::text AS "access_level!" FROM entity_access WHERE entity_id = $1 AND entity_type = 'agent_session' AND source_id = $2"#,
+ session.as_uuid(),
+ channel_id.to_string(),
+ )
+ .fetch_one(pool)
+ .await
+ .expect("originating channel grant")
+}
+
+/// A private agent's channel watches its session; a team agent's or a
+/// system bot's channel can also steer it.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn the_originating_channel_steers_only_shared_agents_sessions(pool: PgPool) {
+ let repo = test_repo(&pool);
+ let private_bot = create_test_bot(&pool).await;
+
+ let team_id = macro_uuid::generate_uuid_v7();
+ let team_owner = "macro|[email protected]";
+ insert_user(&pool, team_owner).await;
+ sqlx::query!(
+ "INSERT INTO team (id, name, owner_id) VALUES ($1, 'Agents', $2)",
+ team_id,
+ team_owner,
+ )
+ .execute(&pool)
+ .await
+ .expect("create team");
+ let team_bot = PgBotsRepo::new(pool.clone())
+ .create_owned_bot(
+ BotOwner::Team { team_id },
+ user_id(team_owner),
+ CreateBotRequest {
+ team_id: Some(team_id),
+ name: "Team Agent".to_string(),
+ handle: format!("team-agent-{}", macro_uuid::generate_uuid_v7()),
+ description: None,
+ avatar_url: None,
+ has_agent: None,
+ },
+ )
+ .await
+ .expect("create team bot")
+ .id;
+
+ for (bot, expected) in [
+ (private_bot, "view"),
+ (team_bot, "edit"),
+ (bot_id::CURSOR_BOT_ID, "edit"),
+ ] {
+ let (channel_id, thread_id, message_id) = insert_originating_thread_fixture(&pool).await;
+ let session =
+ create_session(&repo, new_session(bot, Some(thread_id), Some(message_id))).await;
+ assert_eq!(
+ channel_grant(&pool, session.id, channel_id).await,
+ expected,
+ "bot {bot}"
+ );
+ }
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs
index 7f121efd43..fa02536d64 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs
@@ -51,7 +51,8 @@ pub async fn accessible_session_ids(
///
/// A session's grants are written when it is created: the owner with
/// owner, and - when the session was opened by a mention - the channel that
-/// mention was posted in as editor. Channel membership is not copied into
+/// mention was posted in, as editor, or as viewer when the bot is a user's
+/// private agent. Channel membership is not copied into
/// `entity_access`; it arrives here through `source_ids`, so adding someone
/// to that channel gives them the session on their next request.
///