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(agent-session): list a session only for the people who prompt it directly (#9218)

Wolf Mermelstein747afa9e0d33
diff --git a/.sqlx/query-033e9194f7049bc2d50a2b7107920bb8a45cb962b1e5d01092a1ae091b75a520.json b/.sqlx/query-033e9194f7049bc2d50a2b7107920bb8a45cb962b1e5d01092a1ae091b75a520.json
new file mode 100644
index 0000000000..811c09dd0d
--- /dev/null
+++ b/.sqlx/query-033e9194f7049bc2d50a2b7107920bb8a45cb962b1e5d01092a1ae091b75a520.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_session_follower (agent_session_id, user_id)\n VALUES ($1, $2)\n ON CONFLICT DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "033e9194f7049bc2d50a2b7107920bb8a45cb962b1e5d01092a1ae091b75a520"
+}
diff --git a/.sqlx/query-1ae9bf87fd179805f80b52d9f0c0eb9c2e4be6f4d45209df64ed297cad4b59ed.json b/.sqlx/query-1ae9bf87fd179805f80b52d9f0c0eb9c2e4be6f4d45209df64ed297cad4b59ed.json
deleted file mode 100644
index 77afd1d753..0000000000
--- a/.sqlx/query-1ae9bf87fd179805f80b52d9f0c0eb9c2e4be6f4d45209df64ed297cad4b59ed.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT DISTINCT entity_id\n FROM entity_access\n WHERE entity_type = 'agent_session'\n AND source_id = ANY($1)\n AND (cardinality($2::uuid[]) = 0 OR entity_id = ANY($2))\n -- Inline @macro sessions stay out of search unless asked for by\n -- id. A grant with no session row (tests, a deleted session) is\n -- not hidden: the predicate only matches a hidden row.\n AND (\n entity_id = ANY($2)\n OR NOT EXISTS (\n SELECT 1 FROM agent_session s\n WHERE s.id = entity_access.entity_id\n AND s.visibility = 'hidden'\n )\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "entity_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "TextArray",
- "UuidArray"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "1ae9bf87fd179805f80b52d9f0c0eb9c2e4be6f4d45209df64ed297cad4b59ed"
-}
diff --git a/.sqlx/query-40aa2870ced2b5ddb9a4213d20db77c27e47ef6735b9a592621e4839efe176ce.json b/.sqlx/query-40aa2870ced2b5ddb9a4213d20db77c27e47ef6735b9a592621e4839efe176ce.json
new file mode 100644
index 0000000000..5cbd19d3d2
--- /dev/null
+++ b/.sqlx/query-40aa2870ced2b5ddb9a4213d20db77c27e47ef6735b9a592621e4839efe176ce.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT DISTINCT entity_id\n FROM entity_access\n WHERE entity_type = 'agent_session'\n AND source_id = ANY($1)\n AND (cardinality($2::uuid[]) = 0 OR entity_id = ANY($2))\n -- Hidden sessions (thread-started, DM contexts) stay out of search\n -- unless asked for by id. A grant with no session row (tests, a deleted session) is\n -- not hidden: the predicate only matches a hidden row.\n AND (\n entity_id = ANY($2)\n OR NOT EXISTS (\n SELECT 1 FROM agent_session s\n WHERE s.id = entity_access.entity_id\n AND s.visibility = 'hidden'\n )\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "40aa2870ced2b5ddb9a4213d20db77c27e47ef6735b9a592621e4839efe176ce"
+}
diff --git a/crates/agent_harness/src/domain/queue.rs b/crates/agent_harness/src/domain/queue.rs
index f4e96f6c3a..ea83cddff3 100644
--- a/crates/agent_harness/src/domain/queue.rs
+++ b/crates/agent_harness/src/domain/queue.rs
@@ -26,6 +26,7 @@ use agent_fold::domain::model::TurnId;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
use agent_session::domain::events::{InFlightTurnSummary, TurnSummary};
use agent_session::domain::model::AgentSessionId;
+use agent_session::domain::model::PrompterKind;
use agent_session::domain::model::StoredQueuedAction;
use agent_session::domain::ports::QueuedControl;
use bot_id::BotId;
@@ -162,6 +163,32 @@ impl From<&QueuedEntry> for QueuedControl {
}
impl QueuedEntry {
+ /// Who the turn this entry opens acts for: a system turn acts for nobody,
+ /// even when the batch names a user.
+ pub fn prompter_kind(&self) -> PrompterKind {
+ if matches!(&self.action, AgentAction::Prompt(prompt) if prompt.notifications.as_ref().is_some_and(|input| input.system_turn))
+ {
+ PrompterKind::System
+ } else {
+ PrompterKind::User
+ }
+ }
+
+ /// The person who typed this prompt into the session itself, from the
+ /// session view or the API: a human prompt with no thread to announce
+ /// into and no trigger behind it. A mention in a channel, document or call
+ /// thread carries its origin (`announce`), and a runtime forwarding a
+ /// triggered prompt carries its `context`; neither counts. A tool that
+ /// prompts on a person's behalf with no trigger counts as theirs.
+ /// Following a session is what lists a hidden one for this person.
+ pub fn direct_prompter(&self) -> Option<&MacroUserIdStr<'static>> {
+ let typed = matches!(self.action, AgentAction::Prompt(_))
+ && self.prompter_kind() == PrompterKind::User
+ && self.announce.is_none()
+ && self.context.is_none();
+ self.actor.as_ref().filter(|_| typed)
+ }
+
/// The durable form written to the session store.
pub fn to_stored(&self) -> anyhow::Result<StoredQueuedAction> {
Ok(StoredQueuedAction {
diff --git a/crates/agent_harness/src/domain/queue/test.rs b/crates/agent_harness/src/domain/queue/test.rs
index 859f07d82d..ec24f67388 100644
--- a/crates/agent_harness/src/domain/queue/test.rs
+++ b/crates/agent_harness/src/domain/queue/test.rs
@@ -303,3 +303,62 @@ fn the_cap_refuses_the_overflowing_entry() {
Err(QueueError::Full)
);
}
+
+/// Only a person's prompt typed into the session itself follows it. A thread
+/// mention names its origin, a runtime-forwarded trigger names its context,
+/// and system turns, bot turns and compaction act for nobody in particular.
+#[test]
+fn only_a_human_prompt_from_the_session_itself_has_a_direct_prompter() {
+ let person = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ let direct = QueuedEntry {
+ actor: Some(person.clone()),
+ ..prompt_entry("from the session view")
+ };
+ assert_eq!(direct.direct_prompter(), Some(&person));
+
+ let thread_mention = QueuedEntry {
+ announce: Some(AnnounceOrigin {
+ reply_placement: Default::default(),
+ reuse_origin_message: false,
+ parent: messages::domain::models::MessageParent::Call(Uuid::from_u128(0xf0)),
+ thread_id: Uuid::from_u128(0xf1),
+ message_id: Uuid::from_u128(0xf2),
+ }),
+ ..direct.clone()
+ };
+ let forwarded_trigger = QueuedEntry {
+ context: Some(TriggerContext::Requested(
+ trigger_context::RequestedContext {
+ requested_by: trigger_context::ContextPerson {
+ id: person.to_string(),
+ name: "Prompter".to_owned(),
+ email: None,
+ },
+ requested_at: Utc::now(),
+ repo_url: None,
+ },
+ )),
+ ..direct.clone()
+ };
+ let system_turn = QueuedEntry {
+ action: AgentAction::notification(Vec::new()),
+ ..direct.clone()
+ };
+ let bot_turn = QueuedEntry {
+ actor: None,
+ ..direct.clone()
+ };
+ let compaction = QueuedEntry {
+ action: AgentAction::Compact,
+ ..direct.clone()
+ };
+ for (name, entry) in [
+ ("thread mention", thread_mention),
+ ("forwarded trigger", forwarded_trigger),
+ ("system turn", system_turn),
+ ("bot turn", bot_turn),
+ ("compaction", compaction),
+ ] {
+ assert_eq!(entry.direct_prompter(), None, "{name}");
+ }
+}
diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rs
index bf9b265234..69bebb5f65 100644
--- a/crates/agent_harness/src/domain/service/queue.rs
+++ b/crates/agent_harness/src/domain/service/queue.rs
@@ -1610,20 +1610,25 @@ where
// moment the prompt lands: the egress proxy judges every call by who
// prompted the turn it belongs to, and it may be serving the call on
// another replica.
- if let Err(error) = self
- .sessions
- .set_turn_prompter(
- session_id,
- &TurnPrompter {
- action_id: entry.action_id,
- user: entry.actor.clone(),
- kind: if matches!(&entry.action, AgentAction::Prompt(prompt) if prompt.notifications.as_ref().is_some_and(|input| input.system_turn)) {
- agent_session::domain::model::PrompterKind::System
- } else { agent_session::domain::model::PrompterKind::User },
- },
- )
- .await
- {
+ // A prompt typed into the session itself also follows it for its
+ // sender, which lists a session started from a thread for them.
+ let recorded = async {
+ self.sessions
+ .set_turn_prompter(
+ session_id,
+ &TurnPrompter {
+ action_id: entry.action_id,
+ user: entry.actor.clone(),
+ kind: entry.prompter_kind(),
+ },
+ )
+ .await?;
+ if let Some(user) = entry.direct_prompter() {
+ self.sessions.add_follower(session_id, user).await?;
+ }
+ Ok::<_, AgentSessionError>(())
+ };
+ if let Err(error) = recorded.await {
// A claimed conversation turn fails as an undelivered one
// does, so its journal never shows it running.
if let Some(store) = conversation_store {
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 2b0064e4dd..8482c49dec 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -6,6 +6,7 @@ mod chat_reply;
mod coding_preferences;
mod external_mcp;
mod external_replies;
+mod followers;
mod notifications;
mod owned_purge;
mod presentation;
diff --git a/crates/agent_harness/src/domain/service/test/followers.rs b/crates/agent_harness/src/domain/service/test/followers.rs
new file mode 100644
index 0000000000..f7b46e84f3
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/test/followers.rs
@@ -0,0 +1,66 @@
+use super::*;
+
+fn other_person() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")
+}
+
+/// Mentioning the agent in a thread, by its starter or anyone following up
+/// there, follows the session for nobody; neither does a runtime forwarding a
+/// triggered prompt nor a bot acting for nobody. A prompt a person types into
+/// the session itself follows it for that person, owner or not.
+#[tokio::test]
+async fn only_prompts_typed_into_the_session_follow_it() {
+ let ((service, repo, containers, _announcer, _runtimes), mut turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = live_session(&service, &containers, id).await;
+ let agent = container.agent();
+ turns.settled(id).await;
+ assert!(
+ repo.followers(id).is_empty(),
+ "the opening mention follows nothing"
+ );
+
+ let follow_up = service.execute(
+ id,
+ HarnessCommand::Deliver(forward_message("a follow-up in the thread")),
+ );
+ let (result, ()) = tokio::join!(follow_up, agent.completes_prompt());
+ result.expect("a thread follow-up should deliver");
+ turns.settled(id).await;
+
+ for (actor, context) in [(Some(other_person()), Some(trigger())), (None, None)] {
+ let prompted = service.control_event(
+ id,
+ ControlEvent {
+ action: AgentAction::prompt("not typed by a person"),
+ action_id: None,
+ actor,
+ context,
+ },
+ );
+ let (result, ()) = tokio::join!(prompted, agent.completes_prompt());
+ result.expect("the prompt should deliver");
+ turns.settled(id).await;
+ }
+ assert!(
+ repo.followers(id).is_empty(),
+ "thread, forwarded and bot prompts follow nothing"
+ );
+
+ for person in [other_person(), sender()] {
+ let prompted = service.control_event(
+ id,
+ ControlEvent {
+ action: AgentAction::prompt("typed into the session"),
+ action_id: None,
+ actor: Some(person),
+ context: None,
+ },
+ );
+ let (result, ()) = tokio::join!(prompted, agent.completes_prompt());
+ result.expect("a direct prompt should deliver");
+ turns.settled(id).await;
+ }
+ assert_eq!(repo.followers(id), vec![other_person(), sender()]);
+}
diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rs
index 26e9cedd2e..e6b6c04dae 100644
--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs
@@ -182,6 +182,14 @@ impl AgentSessionRepo for StubSessions {
unimplemented!("this adapter does not dispatch turns")
}
+ async fn add_follower(
+ &self,
+ _id: AgentSessionId,
+ _user: &macro_user_id::user_id::MacroUserIdStr<'static>,
+ ) -> SessionResult<()> {
+ unimplemented!("this adapter does not dispatch turns")
+ }
+
async fn turn_prompter(
&self,
_id: AgentSessionId,
diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rs
index dd767fdf78..07545bf5b3 100644
--- a/crates/agent_harness/src/outbound/routing/test.rs
+++ b/crates/agent_harness/src/outbound/routing/test.rs
@@ -226,6 +226,14 @@ impl AgentSessionRepo for FixedBotSessions {
unimplemented!("this adapter does not dispatch turns")
}
+ async fn add_follower(
+ &self,
+ _id: AgentSessionId,
+ _user: &MacroUserIdStr<'static>,
+ ) -> SessionResult<()> {
+ unimplemented!("this adapter does not dispatch turns")
+ }
+
async fn turn_prompter(
&self,
_id: AgentSessionId,
diff --git a/crates/agent_session/AGENTS.md b/crates/agent_session/AGENTS.md
index 93d45082bb..448a0b34b5 100644
--- a/crates/agent_session/AGENTS.md
+++ b/crates/agent_session/AGENTS.md
@@ -95,6 +95,14 @@ restore, so a session auto-archives at most once. A session archives for pull
requests once every linked pull request is closed and at least one merged;
links with no `github_pull_request` row count as open.
+Followers: a session started from a thread (`SessionPurpose::visibility`, any
+agent) is `hidden`. The harness calls `add_follower` beside `set_turn_prompter`
+for a prompt typed into the session itself (`QueuedEntry::direct_prompter`: a
+human prompt with no `announce` origin and no trigger `context`), recording an
+`agent_session_follower` row; Soup lists hidden sessions for their followers.
+Thread mentions, runtime-forwarded triggers, system and bot turns record
+nothing. Following never grants access.
+
Session names: the first prompt names a session (`set_name_if_default`), and
after each turn that ends with a reply, `domain/retitle.rs` hands the
conversation digest to the namer. `name_generation::ClassifiedRetitle` asks Jev
@@ -109,7 +117,9 @@ through `set_name` clears it, so a name a person chose is never replaced.
## Gotchas
- Where a session is shown is `agent_session.visibility` (`listed`,
- `unlisted`, `hidden`); `hidden` replaces `list_hidden`. Never read or write
+ `unlisted`, `hidden`), set at creation and changed later only by warm
+ claims and the DM-context backfill (`list_visibility.rs`).
+ `hidden` replaces `list_hidden`. Never read or write
`list_hidden`: until a later migration drops it, the
`agent_session_hidden_sync` trigger keeps it in step for replicas on older
code, and it must keep sorting before `agent_session_legacy_warm_write`
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index 6316b98e27..afbc8cb081 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -225,18 +225,16 @@ impl SessionPurpose {
}
/// Where a session created for this purpose is shown. Speculative,
- /// DM-backing and inline @macro thread sessions are reached through what
- /// they back, so they are hidden; a routine's run follows its routine.
- pub fn visibility(
- self,
- bot_id: BotId,
- thread_id: Option<Uuid>,
- hide_agent_dms: bool,
- ) -> SessionVisibility {
+ /// DM-backing and thread sessions (any agent started by a mention or an
+ /// assignment in a thread) are reached through what they back, so they
+ /// are hidden until someone prompts them directly (see
+ /// [`AgentSessionRepo::add_follower`](super::ports::AgentSessionRepo::add_follower));
+ /// a routine's run follows its routine.
+ pub fn visibility(self, thread_id: Option<Uuid>, hide_agent_dms: bool) -> SessionVisibility {
let hidden = match self {
Self::Warm => true,
Self::AgentDm => hide_agent_dms,
- Self::Standalone => bot_id == bot_id::MACRO_NEW_BOT_ID && thread_id.is_some(),
+ Self::Standalone => thread_id.is_some(),
Self::Dispatched => false,
Self::Routine { visibility } => return visibility,
};
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index 7b0768c1b8..2139737504 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -466,6 +466,15 @@ pub trait AgentSessionRepo: Send + Sync + 'static {
prompter: &TurnPrompter,
) -> impl Future<Output = Result<()>> + Send;
+ /// Record that `user` prompted the session `id` directly, from the
+ /// session itself, so a hidden session lists for them. Idempotent; grants
+ /// nothing.
+ fn add_follower(
+ &self,
+ id: AgentSessionId,
+ user: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
/// Who prompted the turn `id` is running or last ran; `None` before its
/// first dispatch.
fn turn_prompter(
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index 59837271bd..6913b7b11d 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -219,6 +219,14 @@ pub trait AgentSessionService: Send + Sync + 'static {
prompter: &TurnPrompter,
) -> impl Future<Output = Result<()>> + Send;
+ /// Record that `user` prompted the session `id` directly, from the
+ /// session itself, so a hidden session lists for them.
+ fn add_follower(
+ &self,
+ id: AgentSessionId,
+ user: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
/// Read the persisted identity of the current turn during recovery.
fn turn_prompter(
&self,
@@ -907,6 +915,10 @@ where
self.repo.set_turn_prompter(id, prompter).await
}
+ async fn add_follower(&self, id: AgentSessionId, user: &MacroUserIdStr<'static>) -> Result<()> {
+ self.repo.add_follower(id, user).await
+ }
+
async fn turn_prompter(&self, id: AgentSessionId) -> Result<Option<TurnPrompter>> {
self.repo.turn_prompter(id).await
}
@@ -2051,6 +2063,10 @@ where
self.repo.set_turn_prompter(id, prompter).await
}
+ async fn add_follower(&self, id: AgentSessionId, user: &MacroUserIdStr<'static>) -> Result<()> {
+ self.repo.add_follower(id, user).await
+ }
+
async fn turn_prompter(&self, id: AgentSessionId) -> Result<Option<TurnPrompter>> {
self.repo.turn_prompter(id).await
}
diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rs
index 4075de625a..d2fa44185a 100644
--- a/crates/agent_session/src/domain/service/test.rs
+++ b/crates/agent_session/src/domain/service/test.rs
@@ -818,6 +818,10 @@ impl AgentSessionRepo for BlockingPromptLogs {
self.repo.set_turn_prompter(id, prompter).await
}
+ async fn add_follower(&self, id: AgentSessionId, user: &MacroUserIdStr<'static>) -> Result<()> {
+ self.repo.add_follower(id, user).await
+ }
+
async fn turn_prompter(
&self,
id: AgentSessionId,
diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rs
index 307afc4ac4..e0856fc432 100644
--- a/crates/agent_session/src/outbound/postgres.rs
+++ b/crates/agent_session/src/outbound/postgres.rs
@@ -451,7 +451,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {
conversation,
thread_id.is_some() || originating_message_id.is_some(),
)?;
- let visibility = purpose.visibility(bot_id, thread_id, self.list_policy.hide_agent_dms);
+ let visibility = purpose.visibility(thread_id, self.list_policy.hide_agent_dms);
let warm = purpose == crate::domain::model::SessionPurpose::Warm;
let row = sqlx::query_as!(
AgentSessionRow,
@@ -923,6 +923,22 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {
Ok(())
}
+ async fn add_follower(&self, id: AgentSessionId, user: &MacroUserIdStr<'static>) -> Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO agent_session_follower (agent_session_id, user_id)
+ VALUES ($1, $2)
+ ON CONFLICT DO NOTHING
+ "#,
+ id.as_uuid(),
+ user.as_ref(),
+ )
+ .execute(&self.pool)
+ .await
+ .context("failed to record the session's follower")?;
+ Ok(())
+ }
+
async fn turn_prompter(&self, id: AgentSessionId) -> Result<Option<TurnPrompter>> {
let row = sqlx::query!(
r#"
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index 12d1f58102..0baba2c911 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -1,5 +1,6 @@
use super::*;
mod auto_archive;
+mod follower;
mod list_activity;
mod queue;
mod recovery;
@@ -1290,37 +1291,35 @@ async fn create_records_the_session_in_the_owners_history(pool: PgPool) {
assert_eq!(history[0].item_type, "agent_session");
}
-/// Inline `@macro` (the agent-session Macro bot, born on a thread) starts
-/// hidden from lists. The same bot started with no thread, and any other
-/// bot, is listed immediately.
+/// A session born on a thread (a mention in a channel, document or call)
+/// starts hidden from lists, whichever agent runs it: the thread is where it
+/// is reached. The same bots started with no thread are listed immediately.
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn inline_macro_sessions_start_hidden(pool: PgPool) {
+async fn thread_sessions_start_hidden_for_every_agent(pool: PgPool) {
let repo = test_repo(&pool);
- create_test_bot(&pool).await;
+ let other_bot = create_test_bot(&pool).await;
let (_channel_id, thread_id, originating_message_id) =
insert_originating_thread_fixture(&pool).await;
- let inline = create_session(
- &repo,
- new_session(
- bot_id::MACRO_NEW_BOT_ID,
- Some(thread_id),
- Some(originating_message_id),
- ),
- )
- .await;
- let composer = create_session(&repo, new_session(bot_id::MACRO_NEW_BOT_ID, None, None)).await;
+ for bot in [bot_id::MACRO_NEW_BOT_ID, other_bot] {
+ let inline = create_session(
+ &repo,
+ new_session(bot, Some(thread_id), Some(originating_message_id)),
+ )
+ .await;
+ let composer = create_session(&repo, new_session(bot, None, None)).await;
- assert_eq!(
- inline.visibility,
- SessionVisibility::Hidden,
- "the thread session starts hidden"
- );
- assert_eq!(
- composer.visibility,
- SessionVisibility::Listed,
- "a composer session is listed"
- );
+ assert_eq!(
+ inline.visibility,
+ SessionVisibility::Hidden,
+ "{bot}: the thread session starts hidden"
+ );
+ assert_eq!(
+ composer.visibility,
+ SessionVisibility::Listed,
+ "{bot}: a composer session is listed"
+ );
+ }
}
/// Replicas still on code that knows only `list_hidden` keep reading and
diff --git a/crates/agent_session/src/outbound/postgres/test/follower.rs b/crates/agent_session/src/outbound/postgres/test/follower.rs
new file mode 100644
index 0000000000..dd1ff3c64c
--- /dev/null
+++ b/crates/agent_session/src/outbound/postgres/test/follower.rs
@@ -0,0 +1,57 @@
+use super::*;
+
+const PROMPTER: &str = "macro|[email protected]";
+
+/// Following a session records each person once, whoever owns it, and
+/// touches neither access nor history: listing it is Soup's job, and who may
+/// read it stays with `entity_access`.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn following_records_each_person_once_and_grants_nothing(pool: PgPool) {
+ let repo = test_repo(&pool);
+ let bot_id = create_test_bot(&pool).await;
+ insert_user(&pool, PROMPTER).await;
+ let session = create_session(&repo, new_session(bot_id, None, None)).await;
+ let access = || async {
+ sqlx::query!(
+ r#"
+ SELECT source_id, access_level::text AS "access_level!"
+ FROM entity_access
+ WHERE entity_id = $1
+ ORDER BY source_id
+ "#,
+ session.id.as_uuid(),
+ )
+ .fetch_all(&pool)
+ .await
+ .expect("read the session's grants")
+ .into_iter()
+ .map(|row| (row.source_id, row.access_level))
+ .collect::<Vec<_>>()
+ };
+ let history = || async {
+ sqlx::query_scalar!(
+ r#"SELECT "userId" FROM "UserHistory" WHERE "itemId" = $1 ORDER BY "userId""#,
+ session.id.as_uuid().to_string(),
+ )
+ .fetch_all(&pool)
+ .await
+ .expect("read the session's history")
+ };
+ let access_before = access().await;
+ let history_before = history().await;
+
+ for user in [PROMPTER, PROMPTER, OWNER] {
+ repo.add_follower(session.id, &user_id(user)).await.unwrap();
+ }
+
+ let followers = sqlx::query_scalar!(
+ "SELECT user_id FROM agent_session_follower WHERE agent_session_id = $1 ORDER BY user_id",
+ session.id.as_uuid(),
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert_eq!(followers, vec![OWNER.to_string(), PROMPTER.to_string()]);
+ assert_eq!(access().await, access_before);
+ assert_eq!(history().await, history_before);
+}
diff --git a/crates/agent_session/src/outbound/postgres/warm/test.rs b/crates/agent_session/src/outbound/postgres/warm/test.rs
index 5ef62ce53e..992e4f670d 100644
--- a/crates/agent_session/src/outbound/postgres/warm/test.rs
+++ b/crates/agent_session/src/outbound/postgres/warm/test.rs
@@ -131,15 +131,15 @@ fn warm_policy_rejects_message_provenance() {
SessionPurpose::Warm
);
assert_eq!(
- SessionPurpose::AgentDm.visibility(bot_id::MACRO_NEW_BOT_ID, None, true),
+ SessionPurpose::AgentDm.visibility(None, true),
SessionVisibility::Hidden
);
assert_eq!(
- SessionPurpose::AgentDm.visibility(bot_id::MACRO_NEW_BOT_ID, None, false),
+ SessionPurpose::AgentDm.visibility(None, false),
SessionVisibility::Listed
);
assert_eq!(
- SessionPurpose::Standalone.visibility(bot_id::MACRO_NEW_BOT_ID, None, true),
+ SessionPurpose::Standalone.visibility(None, true),
SessionVisibility::Listed
);
}
diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rs
index e825d145f0..c6dc44a7df 100644
--- a/crates/agent_session/src/testing.rs
+++ b/crates/agent_session/src/testing.rs
@@ -88,6 +88,8 @@ pub struct InMemoryAgentSessionRepo {
queues: Arc<Mutex<HashMap<AgentSessionId, Vec<StoredQueuedAction>>>>,
/// Session -> who prompted its turn, mirroring the `turn_*` columns.
turn_prompters: Arc<Mutex<HashMap<AgentSessionId, TurnPrompter>>>,
+ /// People who prompted each session directly, in the order they did.
+ followers: Arc<Mutex<HashMap<AgentSessionId, Vec<MacroUserIdStr<'static>>>>>,
/// Sessions an agent conversation sends its messages to, mirroring the
/// current rows of `agent_conversation_sessions`.
conversation_sessions: Arc<Mutex<std::collections::HashSet<AgentSessionId>>>,
@@ -111,6 +113,17 @@ impl InMemoryAgentSessionRepo {
.insert(session.id, session);
}
+ /// Who prompted `session` directly, in the order they first did.
+ #[must_use]
+ pub fn followers(&self, session: AgentSessionId) -> Vec<MacroUserIdStr<'static>> {
+ self.followers
+ .lock()
+ .expect("followers poisoned")
+ .get(&session)
+ .cloned()
+ .unwrap_or_default()
+ }
+
/// Make `session` the one an agent conversation's channel sends its
/// messages to.
pub fn answer_conversation(&self, session: AgentSessionId) {
@@ -216,9 +229,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
created_at: now,
modified_at: now,
source: params.purpose.source(),
- visibility: params
- .purpose
- .visibility(params.bot_id, params.thread_id, false),
+ visibility: params.purpose.visibility(params.thread_id, false),
};
if let Some(hash) = params.egress_token_hash {
self.egress_token_hashes
@@ -396,6 +407,16 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
Ok(())
}
+ async fn add_follower(&self, id: AgentSessionId, user: &MacroUserIdStr<'static>) -> Result<()> {
+ self.get(id).await?;
+ let mut followers = self.followers.lock().expect("followers poisoned");
+ let session = followers.entry(id).or_default();
+ if !session.contains(user) {
+ session.push(user.clone());
+ }
+ Ok(())
+ }
+
async fn turn_prompter(&self, id: AgentSessionId) -> Result<Option<TurnPrompter>> {
Ok(self
.turn_prompters
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 664b917fc4..14acfc648a 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
@@ -28,8 +28,8 @@ pub async fn accessible_session_ids(
WHERE entity_type = 'agent_session'
AND source_id = ANY($1)
AND (cardinality($2::uuid[]) = 0 OR entity_id = ANY($2))
- -- Inline @macro sessions stay out of search unless asked for by
- -- id. A grant with no session row (tests, a deleted session) is
+ -- Hidden sessions (thread-started, DM contexts) stay out of search
+ -- unless asked for by id. A grant with no session row (tests, a deleted session) is
-- not hidden: the predicate only matches a hidden row.
AND (
entity_id = ANY($2)
diff --git a/crates/macro_db_client/migrations/20261104161806_agent_session_follower.sql b/crates/macro_db_client/migrations/20261104161806_agent_session_follower.sql
new file mode 100644
index 0000000000..13db26f0e7
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261104161806_agent_session_follower.sql
@@ -0,0 +1,10 @@
+-- People who prompted a session directly, from the session itself rather than
+-- by mentioning its agent in a thread. A hidden session (one started from a
+-- thread) lists for them in Home, Recent and Agents while they can still read
+-- it. Grants nothing: access stays with entity_access.
+CREATE TABLE agent_session_follower (
+ agent_session_id UUID NOT NULL REFERENCES agent_session (id) ON DELETE CASCADE,
+ user_id TEXT NOT NULL REFERENCES "User" (id) ON DELETE CASCADE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (agent_session_id, user_id)
+);
diff --git a/crates/soup/AGENTS.md b/crates/soup/AGENTS.md
index 110ae65749..42822ffad9 100644
--- a/crates/soup/AGENTS.md
+++ b/crates/soup/AGENTS.md
@@ -83,7 +83,11 @@ rows, initiatives, ...) and get back a single unified, paginated result.
- 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.
+ `entity_access`. Broad lists use session grants only, and leave out
+ `hidden` sessions (thread-started, DM contexts) except for their followers
+ (`agent_session_follower`, people who prompted the session from the session
+ itself), who may also read them through the thread's parent. The notified
+ and work feeds share that rule through `notified::agent_session_gate`.
- `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 3ba8d57b50..6885ce1320 100644
--- a/crates/soup/src/outbound/pg_soup_repo/agent_session.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/agent_session.rs
@@ -125,23 +125,29 @@ pub(super) async fn cursor_soup(
query.push_bind(req.user_id.as_ref().to_string());
let named_ids = explicitly_named_ids(filter);
query.push(ACCESS_SQL);
- // 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.
+ // A session the query names, or one the viewer follows, is also readable
+ // through its thread's parent, like the session's own REST read; GraphQL
+ // `agentSession` loads this way. Other broad-list rows 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(" OR ((s.id = ANY(");
query.push_bind(named_ids.clone());
+ query.push(") OR ");
+ query.push(FOLLOWED_SQL);
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
+ // Hidden thread sessions and DM contexts are absent from broad lists,
+ // except for the people who prompted them from the session itself. 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(" AND (s.visibility <> 'hidden' OR ");
+ query.push(FOLLOWED_SQL);
+ query.push(" OR s.id = ANY(");
query.push_bind(named_ids);
query.push("))");
if let (Some(timestamp), Some(id)) = (parts.timestamp, parts.id) {
@@ -292,10 +298,17 @@ const SESSION_GRANT_SQL: &str = r#"EXISTS (
AND ea.source_id IN (SELECT source_id FROM user_source_ids)
)"#;
+/// The viewer (`$1`) prompted the session `s` from the session itself, which
+/// lists it for them even when it is hidden. Grants nothing on its own.
+pub(super) const FOLLOWED_SQL: &str = r#"EXISTS (
+ SELECT 1 FROM agent_session_follower f
+ WHERE f.agent_session_id = s.id AND f.user_id = $1
+ )"#;
+
/// 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 (
+pub(super) 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
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 619e812777..b2a2276220 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
@@ -405,7 +405,7 @@ async fn by_ids_respects_access(pool: PgPool) -> anyhow::Result<()> {
Ok(())
}
-/// An inline `@macro` session (hidden) is missing from broad lists for
+/// A hidden session (one started from a thread) is missing from broad lists for
/// everyone, but a named id still finds it and hydrating by id still works.
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn hidden_sessions_stay_out_of_broad_lists(pool: PgPool) -> anyhow::Result<()> {
@@ -695,3 +695,99 @@ async fn by_ids_inherits_the_parent_thread_access(pool: PgPool) -> anyhow::Resul
}
Ok(())
}
+
+/// A session started from a document thread is hidden, so mentioning the
+/// agent there lists it for nobody, owner included. Prompting it from the
+/// session itself follows it: it then lists for that one person while they
+/// can still read it, through a session grant or the thread's parent.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_hidden_thread_session_lists_only_for_its_followers(pool: PgPool) -> anyhow::Result<()> {
+ let fixture = seed(&pool).await?;
+ let document = Uuid::now_v7();
+ let root = Uuid::now_v7();
+ sqlx::query!(
+ r#"INSERT INTO comms_messages (id, parent_entity_type, parent_entity_id, sender_id, content)
+ VALUES ($1, 'document', $2, $3, '@agent look')"#,
+ root,
+ document.to_string(),
+ OWNER,
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ "UPDATE agent_session SET thread_id = $1, visibility = 'hidden' WHERE id = $2",
+ root,
+ fixture.private,
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ($1, 'document', $2, 'user', 'edit')
+ "#,
+ document,
+ STRANGER,
+ )
+ .execute(&pool)
+ .await?;
+ let include = || Some(Expr::val(AgentSessionLiteral::Include));
+
+ assert_eq!(
+ ids(&cursor_soup(&pool, request(OWNER, include())).await?),
+ vec![fixture.shared],
+ "the owner's mention lists nothing"
+ );
+ assert!(
+ cursor_soup(&pool, request(STRANGER, include()))
+ .await?
+ .is_empty(),
+ "a document editor who never prompted it directly sees nothing"
+ );
+
+ sqlx::query!(
+ "INSERT INTO agent_session_follower (agent_session_id, user_id) VALUES ($1, $2)",
+ fixture.private,
+ STRANGER,
+ )
+ .execute(&pool)
+ .await?;
+ assert_eq!(
+ ids(&cursor_soup(&pool, request(STRANGER, include())).await?),
+ vec![fixture.private],
+ "the follower reads it through the document and lists it"
+ );
+ assert_eq!(
+ ids(&cursor_soup(&pool, request(OWNER, include())).await?),
+ vec![fixture.shared],
+ "another person's follow changes nothing for the owner"
+ );
+
+ sqlx::query!(
+ "INSERT INTO agent_session_follower (agent_session_id, user_id) VALUES ($1, $2)",
+ fixture.private,
+ OWNER,
+ )
+ .execute(&pool)
+ .await?;
+ assert_eq!(
+ ids(&cursor_soup(&pool, request(OWNER, include())).await?),
+ vec![fixture.private, fixture.shared],
+ "the owner follows it once they prompt it directly"
+ );
+
+ sqlx::query!(
+ "DELETE FROM entity_access WHERE entity_id = $1 AND source_id = $2",
+ document,
+ STRANGER,
+ )
+ .execute(&pool)
+ .await?;
+ assert!(
+ cursor_soup(&pool, request(STRANGER, include()))
+ .await?
+ .is_empty(),
+ "following never outlives access"
+ );
+ Ok(())
+}
diff --git a/crates/soup/src/outbound/pg_soup_repo/notified.rs b/crates/soup/src/outbound/pg_soup_repo/notified.rs
index 64500c9749..1bd228754d 100644
--- a/crates/soup/src/outbound/pg_soup_repo/notified.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/notified.rs
@@ -134,7 +134,9 @@ pub(super) fn foreign_entity_gate(filter: Option<&EntityFilterAst>) -> String {
/// the same user / channel / team ids the query's `user_source_ids` CTE
/// already collects - the predicate the agent-session leg's own queries use.
/// The filter's row predicates the gate can express apply as well, since
-/// hydration by id does not re-apply them.
+/// hydration by id does not re-apply them. A session the viewer follows is
+/// shown even while hidden, and readable through its thread's parent, as in
+/// the agent-session leg's broad lists.
pub(super) fn agent_session_gate(filter: Option<&EntityFilterAst>) -> String {
let tree = filter.and_then(|filter| filter.agent_session_filter.as_deref());
let implied = implied_conjuncts_sql(tree, |literal| match literal {
@@ -167,17 +169,23 @@ pub(super) fn agent_session_gate(filter: Option<&EntityFilterAst>) -> String {
uuid_guarded(
ID_SQL,
format!(
- r#"EXISTS (
+ r#"(EXISTS (
SELECT 1 FROM entity_access ea
WHERE ea.entity_id = {ID_SQL}::uuid
AND ea.entity_type = 'agent_session'
AND ea.source_id IN (SELECT source_id FROM user_source_ids)
- ) AND (
+ ) OR EXISTS (
+ SELECT 1 FROM agent_session s
+ WHERE s.id = {ID_SQL}::uuid AND {followed} AND {parent_thread}
+ )) AND (
({named}) OR NOT EXISTS (
SELECT 1 FROM agent_session s
WHERE s.id = {ID_SQL}::uuid AND s.visibility = 'hidden'
+ AND NOT {followed}
)
- ){matching}"#
+ ){matching}"#,
+ followed = super::agent_session::FOLLOWED_SQL,
+ parent_thread = super::agent_session::PARENT_THREAD_GRANT_SQL,
),
)
}
diff --git a/crates/soup/src/outbound/pg_soup_repo/notified/test/hidden_sessions.rs b/crates/soup/src/outbound/pg_soup_repo/notified/test/hidden_sessions.rs
index fa73bdb1bd..40ec3cdd04 100644
--- a/crates/soup/src/outbound/pg_soup_repo/notified/test/hidden_sessions.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/notified/test/hidden_sessions.rs
@@ -176,3 +176,47 @@ async fn unlisted_runs_with_notifications_stay_out_of_feeds_that_exclude_them(
assert!(!keys(&notified).contains(&(EntityType::AgentSession, mine.to_string())));
Ok(())
}
+
+/// A hidden session its owner follows (they prompted it from the session
+/// itself) is back in Home's notified and work feeds for them.
+#[sqlx::test(
+ fixtures(path = "../../../../../fixtures", scripts("notified_at")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn followed_hidden_sessions_return_to_broad_feeds(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let (mine, _) = seed_agent_sessions(&pool).await?;
+ let sources = sources();
+ let include = EntityFilterAst {
+ agent_session_filter: Some(Arc::new(Expr::val(AgentSessionLiteral::Include))),
+ ..Default::default()
+ };
+ sqlx::query!(
+ "UPDATE agent_session SET visibility = 'hidden', for_warming = FALSE WHERE id = $1",
+ mine
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ "INSERT INTO agent_session_follower (agent_session_id, user_id) VALUES ($1, $2)",
+ mine,
+ USER_1,
+ )
+ .execute(&pool)
+ .await?;
+
+ let notified =
+ notified_soup_page(&pool, req(Some(&include), &[], &sources, EVERYTHING)).await?;
+ assert!(keys(&notified).contains(&(EntityType::AgentSession, mine.to_string())));
+ assert_eq!(
+ work_feed_soup_page(
+ &pool,
+ work_request(&include, &sources, WorkFeedSoupMode::Attention, None)
+ )
+ .await?
+ .len(),
+ 1
+ );
+ Ok(())
+}
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index 3b7030d8af..c43c5d61a9 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -303,7 +303,9 @@ remain visible when the entire timeline fits without scrolling.
## Agent session entities
-The Agents list includes owned and shared sessions. Rows show the shared agent
+The Agents list includes owned and shared sessions, except sessions started
+from a thread, which list only for people who prompted them from the session
+itself (see [Home](home.md)). Rows show the shared agent
icon and session title; opening one navigates to `/app/agent/<id>`. The session title
menu uses the shared entity actions: Favorite/Unfavorite and Copy link, plus
Rename and Delete for the owner. Rename uses the shared rename dialog, not a
diff --git a/docs/agent-guide/home.md b/docs/agent-guide/home.md
index 74449ac96c..c2467af888 100644
--- a/docs/agent-guide/home.md
+++ b/docs/agent-guide/home.md
@@ -127,6 +127,17 @@ them back. The DM remains in Channels/DMs; authorized direct session links and
explicitly saved favorites still open their context. Verify this alongside an
ordinary standalone session, which remains listed.
+A session started from a thread (a mention in a channel, document or call, or a
+task assignment) stays out of Home, Recent and the Agents sidebar for everyone,
+owner included, whichever agent runs it; the thread is where it is reached.
+Follow-up mentions in that thread list it for nobody either. A person who
+prompts the session from the session view itself (after **Open session**)
+follows it: from then on it lists for them in Home, Recent and Agents while they
+can still open it, and nobody else's lists change. Prompting never changes
+anyone's access. Verify with two accounts: mention an agent in a document
+thread and check neither lists it, then have the second account open the
+session, send a prompt, and check the row appears for that account only.
+
The Agents workspace uses a single left dot for activity and unread state in
place of the sparkle. Clicking a session row in Home or the Agents sidebar
clears the row's loaded unread dot immediately; a failed read write restores