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(soup): let thread viewers open document and call agent sessions (#9187)

Wolf Mermelstein79efaae08079
diff --git a/crates/soup/AGENTS.md b/crates/soup/AGENTS.md
index 227d0c48f0..80d713ba2d 100644
--- a/crates/soup/AGENTS.md
+++ b/crates/soup/AGENTS.md
@@ -78,6 +78,10 @@ rows, initiatives, ...) and get back a single unified, paginated result.
the caller's mailbox. Keep browser requests bounded; never expand every CRM
record into client-side filters or raise ingress limits to fit them.
+- Agent sessions named by id (an `Id` literal in `cursor_soup`, which GraphQL
+ `agentSession` and its log use, and `by_ids`) also accept a grant on the
+ document or call whose live thread the session runs in, matching
+ `entity_access`. Broad lists use session grants only.
- `expanded/` vs `unexpanded/` queries exist because hydrating full entities
is expensive — don't widen `unexpanded` to return hydrated data; add a new
`expanded` path instead.
diff --git a/crates/soup/src/outbound/pg_soup_repo/agent_session.rs b/crates/soup/src/outbound/pg_soup_repo/agent_session.rs
index c08e4b4103..202764d967 100644
--- a/crates/soup/src/outbound/pg_soup_repo/agent_session.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/agent_session.rs
@@ -120,15 +120,26 @@ pub(super) async fn cursor_soup(
// `$1` is the requesting user for every clause in this query: the source
// id CTE, the history join, and any `Owner` literal that binds it again.
query.push_bind(req.user_id.as_ref().to_string());
+ let named_ids = explicitly_named_ids(filter);
query.push(ACCESS_SQL);
- query.push(" AND (");
+ // A session the query names is also readable through its thread's parent,
+ // like the session's own REST read; GraphQL `agentSession` loads this way.
+ // Broad lists stay limited to session grants so every document thread's
+ // sessions do not flood Home and Recent.
+ query.push("(");
+ query.push(SESSION_GRANT_SQL);
+ query.push(" OR (s.id = ANY(");
+ query.push_bind(named_ids.clone());
+ query.push(") AND ");
+ query.push(PARENT_THREAD_GRANT_SQL);
+ query.push(")) AND (");
push_filter(&mut query, filter);
query.push(")");
// Hidden inline mentions and DM contexts are absent from broad lists. A
// query that names the session still returns it, so favorites and direct
// id lookups keep working.
query.push(" AND (s.visibility <> 'hidden' OR s.id = ANY(");
- query.push_bind(explicitly_named_ids(filter));
+ query.push_bind(named_ids);
query.push("))");
if let (Some(timestamp), Some(id)) = (parts.timestamp, parts.id) {
query.push(format!(" AND ({sort}, s.id) < ("));
@@ -149,6 +160,7 @@ pub(super) async fn cursor_soup(
.collect()
}
+#[tracing::instrument(err, skip_all, fields(entity_count = req.entities.len()))]
pub(super) async fn by_ids(
db: &PgPool,
req: AdvancedSortParams<'_>,
@@ -166,7 +178,12 @@ pub(super) async fn by_ids(
let mut query = QueryBuilder::<Postgres>::new(SELECT_SQL);
query.push_bind(req.user_id.as_ref().to_string());
query.push(ACCESS_SQL);
- query.push(" AND s.id = ANY(");
+ // Every session here is named, so its thread's parent grants apply too.
+ query.push("(");
+ query.push(SESSION_GRANT_SQL);
+ query.push(" OR ");
+ query.push(PARENT_THREAD_GRANT_SQL);
+ query.push(") AND s.id = ANY(");
query.push_bind(ids);
query.push(") ORDER BY s.modified_at DESC, s.id DESC");
query
@@ -226,8 +243,9 @@ const SELECT_SQL: &str = r#"
WHERE cp.user_id = "#;
/// Continues [`SELECT_SQL`] after the user id bind: the remaining source-id
-/// arms, the row projection, the history join, and the access predicate.
-/// Every `$1` here refers back to that same bind.
+/// arms, the row projection, and the history join, ending at `WHERE` so the
+/// caller appends its access predicate. Every `$1` here refers back to that
+/// same bind.
const ACCESS_SQL: &str = r#" AND cp.left_at IS NULL
UNION ALL
SELECT t.team_id::text FROM team_user t WHERE t.user_id = $1
@@ -259,13 +277,30 @@ const ACCESS_SQL: &str = r#" AND cp.left_at IS NULL
ON uh."itemId" = s.id::text
AND uh."itemType" = 'agent_session'
AND uh."userId" = $1
- WHERE EXISTS (
+ WHERE "#;
+
+/// Continues [`ACCESS_SQL`]: the viewer holds a grant on the session itself.
+const SESSION_GRANT_SQL: &str = r#"EXISTS (
SELECT 1 FROM entity_access ea
WHERE ea.entity_id = s.id
AND ea.entity_type = 'agent_session'
AND ea.source_id IN (SELECT source_id FROM user_source_ids)
)"#;
+/// The viewer holds a grant on the document or call whose live thread the
+/// session runs in. Mirrors the parent inheritance `entity_access` applies to
+/// agent sessions, over the same stored grants Soup reads for documents.
+const PARENT_THREAD_GRANT_SQL: &str = r#"EXISTS (
+ SELECT 1 FROM comms_messages m
+ JOIN comms_message_threads t ON t.root_id = m.id AND t.deleted_at IS NULL
+ JOIN entity_access ea
+ ON ea.entity_id::text = m.parent_entity_id
+ AND ea.entity_type = m.parent_entity_type
+ WHERE m.id = s.thread_id
+ AND m.parent_entity_type IN ('document', 'call')
+ AND ea.source_id IN (SELECT source_id FROM user_source_ids)
+ )"#;
+
fn sort_sql(sort: SimpleSortMethod) -> &'static str {
match sort {
SimpleSortMethod::CreatedAt => "s.created_at",
diff --git a/crates/soup/src/outbound/pg_soup_repo/agent_session/test.rs b/crates/soup/src/outbound/pg_soup_repo/agent_session/test.rs
index 32b7b1acc6..f1e6661b32 100644
--- a/crates/soup/src/outbound/pg_soup_repo/agent_session/test.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/agent_session/test.rs
@@ -590,3 +590,107 @@ async fn unlisted_runs_leave_lists_that_exclude_them(pool: PgPool) -> anyhow::Re
assert_eq!(ids(&listed), vec![fixture.shared]);
Ok(())
}
+
+/// A session started from a document or call thread inherits the parent's
+/// viewers, as the session's REST read and its inline chip already do, so
+/// opening it by id works for someone who prompted it or saw it in the thread.
+/// Broad lists stay limited to grants on the session itself.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn by_ids_inherits_the_parent_thread_access(pool: PgPool) -> anyhow::Result<()> {
+ let fixture = seed(&pool).await?;
+ let entities = [EntityType::AgentSession.with_entity_string(fixture.private.to_string())];
+
+ for kind in ["document", "call"] {
+ let root = Uuid::now_v7();
+ // A call's thread root carries the call's own id.
+ let parent = if kind == "call" { root } else { Uuid::now_v7() };
+ sqlx::query!(
+ r#"INSERT INTO comms_messages (id, parent_entity_type, parent_entity_id, sender_id, content)
+ VALUES ($1, $2, $3, $4, '@macro look')"#,
+ root,
+ kind,
+ parent.to_string(),
+ OWNER,
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ "UPDATE agent_session SET thread_id = $1 WHERE id = $2",
+ root,
+ fixture.private,
+ )
+ .execute(&pool)
+ .await?;
+ let stranger_items = by_ids(
+ &pool,
+ AdvancedSortParams {
+ entities: &entities,
+ user_id: MacroUserIdStr::parse_from_str(STRANGER)?,
+ },
+ )
+ .await?;
+ assert!(
+ stranger_items.is_empty(),
+ "no access to the {kind} means no access to its session"
+ );
+
+ sqlx::query!(
+ r#"
+ INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ($1, $2, $3, 'user', 'view')
+ "#,
+ parent,
+ kind,
+ STRANGER,
+ )
+ .execute(&pool)
+ .await?;
+ let viewer_items = by_ids(
+ &pool,
+ AdvancedSortParams {
+ entities: &entities,
+ user_id: MacroUserIdStr::parse_from_str(STRANGER)?,
+ },
+ )
+ .await?;
+ assert_eq!(ids(&viewer_items), vec![fixture.private], "{kind} viewer");
+
+ // GraphQL `agentSession` loads through a cursor query naming the id.
+ let named = cursor_soup(
+ &pool,
+ request(
+ STRANGER,
+ Some(Expr::val(AgentSessionLiteral::Id(fixture.private))),
+ ),
+ )
+ .await?;
+ assert_eq!(ids(&named), vec![fixture.private], "{kind} viewer by id");
+
+ let listed = cursor_soup(
+ &pool,
+ request(STRANGER, Some(Expr::val(AgentSessionLiteral::Include))),
+ )
+ .await?;
+ assert!(listed.is_empty(), "{kind} access does not list the session");
+
+ sqlx::query!(
+ "UPDATE comms_message_threads SET deleted_at = NOW() WHERE root_id = $1",
+ root,
+ )
+ .execute(&pool)
+ .await?;
+ let after_delete = by_ids(
+ &pool,
+ AdvancedSortParams {
+ entities: &entities,
+ user_id: MacroUserIdStr::parse_from_str(STRANGER)?,
+ },
+ )
+ .await?;
+ assert!(
+ after_delete.is_empty(),
+ "a deleted {kind} thread no longer shares its session"
+ );
+ }
+ Ok(())
+}