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(chat): keep the AI from surfacing or reading its own running chat (#4963)

Eric Hayes89de0935292b
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 66e97aef5d..120f8080bb 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -676,6 +676,10 @@ pub struct ToolServiceContext {
pub email_tool_context: ToolEmailToolContext,
pub call_tool_context: ToolCallToolContext,
pub notification_tool_context: ToolNotificationToolContext,
+ /// Built per-request via a manual `FromRef` below so it can carry the
+ /// running chat's id — the derive's field-clone would freeze it at
+ /// startup with no chat id set.
+ #[from_ref(skip)]
pub chat_tool_context: ToolChatToolContext,
pub channel_tool_context: ToolChannelToolContext,
pub team_tool_context: ToolTeamToolContext,
@@ -701,6 +705,26 @@ impl FromRef<ToolServiceContext> for SoupToolContext<ToolSoupService, ToolEmailS
SoupToolContext {
service: ctx.soup_service.clone(),
email_service: ctx.email_service.clone(),
+ self_chat_id: self_chat_id(ctx),
}
}
}
+
+impl FromRef<ToolServiceContext> for ToolChatToolContext {
+ fn from_ref(ctx: &ToolServiceContext) -> Self {
+ ChatToolContext {
+ service: ctx.chat_tool_context.service.clone(),
+ entity_access_service: ctx.chat_tool_context.entity_access_service.clone(),
+ self_chat_id: self_chat_id(ctx),
+ }
+ }
+}
+
+/// Entity id of the chat this request belongs to, when the request is an
+/// interactive chat session. `None` for every other feature, in which case
+/// nothing about the running chat should be excluded/blocked.
+fn self_chat_id(ctx: &ToolServiceContext) -> Option<uuid::Uuid> {
+ matches!(ctx.usage_context.feature, ai_usage::AiFeature::Chat)
+ .then_some(ctx.usage_context.entity)
+ .flatten()
+}
diff --git a/crates/chat/src/inbound/toolset/mod.rs b/crates/chat/src/inbound/toolset/mod.rs
index f3e32c049f..16a61225e0 100644
--- a/crates/chat/src/inbound/toolset/mod.rs
+++ b/crates/chat/src/inbound/toolset/mod.rs
@@ -10,6 +10,7 @@ use ai_toolset::AsyncToolCollection;
use entity_access::domain::ports::EntityAccessService;
use read_chat::ReadChat;
use std::sync::Arc;
+use uuid::Uuid;
/// Service context for chat AI tools.
pub struct ChatToolContext<CSvc, ESvc>
@@ -21,6 +22,10 @@ where
pub service: Arc<CSvc>,
/// The entity access service — used to generate access receipts.
pub entity_access_service: Arc<ESvc>,
+ /// Entity id of the chat this request belongs to, when the request is an
+ /// interactive chat session. `None` for every other feature, in which
+ /// case reads are never blocked as "the current chat".
+ pub self_chat_id: Option<Uuid>,
}
impl<CSvc, ESvc> Clone for ChatToolContext<CSvc, ESvc>
@@ -32,6 +37,7 @@ where
Self {
service: self.service.clone(),
entity_access_service: self.entity_access_service.clone(),
+ self_chat_id: self.self_chat_id,
}
}
}
@@ -46,6 +52,7 @@ where
Self {
service: Arc::new(service),
entity_access_service: Arc::new(entity_access_service),
+ self_chat_id: None,
}
}
}
diff --git a/crates/chat/src/inbound/toolset/read_chat.rs b/crates/chat/src/inbound/toolset/read_chat.rs
index d66da9dbbb..5434b59dd9 100644
--- a/crates/chat/src/inbound/toolset/read_chat.rs
+++ b/crates/chat/src/inbound/toolset/read_chat.rs
@@ -9,6 +9,7 @@ use entity_access::domain::{
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
+use uuid::Uuid;
use super::ChatToolContext;
@@ -64,6 +65,18 @@ where
) -> ToolResult<Self::Output> {
tracing::info!(params=?self, "Read chat");
+ if let Some(self_chat_id) = service_context.self_chat_id
+ && Uuid::parse_str(&self.chat_id) == Ok(self_chat_id)
+ {
+ return Err(ToolCallError {
+ description: "This is the chat you are currently running in — you already \
+ have its full message history in context, so it cannot be read via this \
+ tool. Use ReadChat only to read a different chat."
+ .to_string(),
+ internal_error: anyhow::anyhow!("attempted to read the currently running chat"),
+ });
+ }
+
let receipt = service_context
.entity_access_service
.generate_entity_access_receipt::<ViewAccessLevel>(
diff --git a/crates/chat/src/inbound/toolset/test.rs b/crates/chat/src/inbound/toolset/test.rs
index 364e1e6fc8..9a7ce37a5d 100644
--- a/crates/chat/src/inbound/toolset/test.rs
+++ b/crates/chat/src/inbound/toolset/test.rs
@@ -16,3 +16,572 @@ fn test_read_chat_schema_validation() {
"Description should contain expected text"
);
}
+
+mod self_read_guard {
+ use super::super::ChatToolContext;
+ use crate::domain::models::{
+ ChatErr, ChatResponse, CreateChatArgs, GetChatResponse, PatchChatArgs, Result,
+ };
+ use crate::domain::ports::ChatService;
+ use crate::inbound::toolset::read_chat::ReadChat;
+ use ai_toolset::tool_object::UserToolResponse;
+ use ai_toolset::{AsyncTool, RequestContext, ServiceContext};
+ use entity_access::domain::models::{
+ AccessError, AccessLevel, BotId, CallChannelInfo, Entity, EntityAccessReceipt,
+ EntityPermission, EntityType, RequiredPermission, UserTeamInfo,
+ };
+ use entity_access::domain::ports::EntityAccessService;
+ use macro_user_id::lowercased::Lowercase;
+ use macro_user_id::user_id::{MacroUserId, MacroUserIdStr};
+ use uuid::Uuid;
+
+ /// A [`ChatService`] that panics if any method is invoked — used to prove
+ /// the self-read guard returns before ever touching the service.
+ struct UnreachableChatService;
+
+ impl ChatService for UnreachableChatService {
+ async fn create(
+ &self,
+ _user_id: MacroUserIdStr<'static>,
+ _args: CreateChatArgs,
+ ) -> Result<String> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+
+ async fn get_chat(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::ViewAccessLevel,
+ >,
+ ) -> Result<GetChatResponse> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+
+ async fn copy_chat(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::ViewAccessLevel,
+ >,
+ ) -> Result<String> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+
+ async fn delete(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ ) -> Result<()> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+
+ async fn permanently_delete(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ ) -> Result<()> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+
+ async fn patch(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ _args: PatchChatArgs,
+ ) -> Result<()> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+
+ async fn revert_delete(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ ) -> Result<()> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+
+ async fn get_permissions(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::EditAccessLevel,
+ >,
+ ) -> Result<models_permissions::share_permission::SharePermissionV2> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+
+ async fn update_tool_call(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _new_args: serde_json::Value,
+ ) -> Result<()> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+
+ async fn update_tool_response(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _response: UserToolResponse<serde_json::Value>,
+ ) -> Result<()> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+
+ async fn call_tool(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _args: Option<serde_json::Value>,
+ ) -> Result<serde_json::Value> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+
+ async fn reject_tool_call(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ _message_id: &str,
+ _tool_call_id: &str,
+ ) -> Result<()> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+ }
+
+ /// An [`EntityAccessService`] that panics if any method is invoked — used
+ /// to prove the self-read guard returns before checking access.
+ #[derive(Clone)]
+ struct UnreachableAccessService;
+
+ impl EntityAccessService for UnreachableAccessService {
+ async fn generate_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_org_id: Option<i64>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> std::result::Result<EntityAccessReceipt<T>, AccessError> {
+ unreachable!("guard should short-circuit before checking access")
+ }
+
+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _bot_id: BotId,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> std::result::Result<EntityAccessReceipt<T>, AccessError> {
+ unreachable!("guard should short-circuit before checking access")
+ }
+
+ async fn get_access_level(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> std::result::Result<Option<AccessLevel>, AccessError> {
+ unreachable!("guard should short-circuit before checking access")
+ }
+
+ async fn check_access(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> std::result::Result<AccessLevel, AccessError> {
+ unreachable!("guard should short-circuit before checking access")
+ }
+
+ async fn check_public_access(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> std::result::Result<AccessLevel, AccessError> {
+ unreachable!("guard should short-circuit before checking access")
+ }
+
+ async fn get_entity_permission(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _user_org_id: Option<i64>,
+ ) -> std::result::Result<EntityPermission, AccessError> {
+ unreachable!("guard should short-circuit before checking access")
+ }
+
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> std::result::Result<(EntityPermission, Uuid), AccessError> {
+ unreachable!("guard should short-circuit before checking access")
+ }
+
+ async fn get_users_by_entity(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> std::result::Result<Vec<MacroUserIdStr<'static>>, AccessError> {
+ unreachable!("guard should short-circuit before checking access")
+ }
+
+ async fn get_call_channel(
+ &self,
+ _call_id: &sqlx::types::Uuid,
+ ) -> std::result::Result<Option<CallChannelInfo>, AccessError> {
+ unreachable!("guard should short-circuit before checking access")
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &sqlx::types::Uuid,
+ ) -> std::result::Result<Option<CallChannelInfo>, AccessError> {
+ unreachable!("guard should short-circuit before checking access")
+ }
+
+ async fn get_user_team(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> std::result::Result<Option<UserTeamInfo>, AccessError> {
+ unreachable!("guard should short-circuit before checking access")
+ }
+ }
+
+ /// A [`ChatService`] that returns a canned successful response, so tests
+ /// unrelated to the self-read guard can exercise the happy path.
+ struct StubChatService;
+
+ impl ChatService for StubChatService {
+ async fn create(
+ &self,
+ _user_id: MacroUserIdStr<'static>,
+ _args: CreateChatArgs,
+ ) -> Result<String> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
+ }
+
+ async fn get_chat(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::ViewAccessLevel,
+ >,
+ ) -> Result<GetChatResponse> {
+ #[allow(deprecated)]
+ let chat_id = entity_access_receipt.entity().entity_id.clone();
+ Ok(GetChatResponse {
+ chat: ChatResponse {
+ id: chat_id,
+ user_id: "macro|[email protected]".to_string(),
+ project_id: None,
+ name: "Other Chat".to_string(),
+ messages: Vec::new(),
+ model: None,
+ created_at: None,
+ updated_at: None,
+ },
+ user_access_level: AccessLevel::Owner,
+ })
+ }
+
+ async fn copy_chat(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::ViewAccessLevel,
+ >,
+ ) -> Result<String> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
+ }
+
+ async fn delete(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ ) -> Result<()> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
+ }
+
+ async fn permanently_delete(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ ) -> Result<()> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
+ }
+
+ async fn patch(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ _args: PatchChatArgs,
+ ) -> Result<()> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
+ }
+
+ async fn revert_delete(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ ) -> Result<()> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
+ }
+
+ async fn get_permissions(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::EditAccessLevel,
+ >,
+ ) -> Result<models_permissions::share_permission::SharePermissionV2> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
+ }
+
+ async fn update_tool_call(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _new_args: serde_json::Value,
+ ) -> Result<()> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
+ }
+
+ async fn update_tool_response(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _response: UserToolResponse<serde_json::Value>,
+ ) -> Result<()> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
+ }
+
+ async fn call_tool(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ _message_id: &str,
+ _tool_call_id: &str,
+ _args: Option<serde_json::Value>,
+ ) -> Result<serde_json::Value> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
+ }
+
+ async fn reject_tool_call(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::OwnerAccessLevel,
+ >,
+ _message_id: &str,
+ _tool_call_id: &str,
+ ) -> Result<()> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
+ }
+ }
+
+ /// An [`EntityAccessService`] that always grants owner-level access, so
+ /// tests unrelated to the self-read guard can exercise the happy path.
+ #[derive(Clone)]
+ struct StubAccessService;
+
+ impl EntityAccessService for StubAccessService {
+ async fn generate_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ _user_org_id: Option<i64>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> std::result::Result<EntityAccessReceipt<T>, AccessError> {
+ EntityAccessReceipt::try_new_authenticated_user(
+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),
+ Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ )
+ }
+
+ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ _bot_id: BotId,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> std::result::Result<EntityAccessReceipt<T>, AccessError> {
+ EntityAccessReceipt::try_new_authenticated_user(
+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),
+ Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ )
+ }
+
+ async fn get_access_level(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> std::result::Result<Option<AccessLevel>, AccessError> {
+ Ok(Some(AccessLevel::Owner))
+ }
+
+ async fn check_access(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> std::result::Result<AccessLevel, AccessError> {
+ Ok(AccessLevel::Owner)
+ }
+
+ async fn check_public_access(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> std::result::Result<AccessLevel, AccessError> {
+ Ok(AccessLevel::Owner)
+ }
+
+ async fn get_entity_permission(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _user_org_id: Option<i64>,
+ ) -> std::result::Result<EntityPermission, AccessError> {
+ Ok(EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ })
+ }
+
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> std::result::Result<(EntityPermission, Uuid), AccessError> {
+ unimplemented!("stub does not support CRM entity access")
+ }
+
+ async fn get_users_by_entity(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> std::result::Result<Vec<MacroUserIdStr<'static>>, AccessError> {
+ Ok(vec![])
+ }
+
+ async fn get_call_channel(
+ &self,
+ _call_id: &sqlx::types::Uuid,
+ ) -> std::result::Result<Option<CallChannelInfo>, AccessError> {
+ unimplemented!()
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &sqlx::types::Uuid,
+ ) -> std::result::Result<Option<CallChannelInfo>, AccessError> {
+ unimplemented!()
+ }
+
+ async fn get_user_team(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> std::result::Result<Option<UserTeamInfo>, AccessError> {
+ unimplemented!()
+ }
+ }
+
+ fn request_context() -> RequestContext {
+ RequestContext::new(MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap())
+ }
+
+ #[tokio::test]
+ async fn blocks_reading_the_currently_running_chat() {
+ let self_chat_id = Uuid::new_v4();
+ let tool = ReadChat {
+ chat_id: self_chat_id.to_string(),
+ };
+ let context = ServiceContext(ChatToolContext {
+ service: std::sync::Arc::new(UnreachableChatService),
+ entity_access_service: std::sync::Arc::new(UnreachableAccessService),
+ self_chat_id: Some(self_chat_id),
+ });
+
+ let result = tool.call(context, request_context()).await;
+
+ let err = result.expect_err("reading the running chat should be refused");
+ assert!(
+ err.description.contains("currently running"),
+ "error should tell the model this is its own chat: {}",
+ err.description
+ );
+ }
+
+ #[tokio::test]
+ async fn allows_reading_a_different_chat() {
+ let self_chat_id = Uuid::new_v4();
+ let other_chat_id = Uuid::new_v4();
+ let tool = ReadChat {
+ chat_id: other_chat_id.to_string(),
+ };
+ let context = ServiceContext(ChatToolContext {
+ service: std::sync::Arc::new(StubChatService),
+ entity_access_service: std::sync::Arc::new(StubAccessService),
+ self_chat_id: Some(self_chat_id),
+ });
+
+ let result = tool.call(context, request_context()).await;
+
+ assert!(result.is_ok(), "{:?}", result.err());
+ assert_eq!(result.unwrap().chat_id, other_chat_id.to_string());
+ }
+
+ #[tokio::test]
+ async fn allows_reading_any_chat_outside_a_chat_session() {
+ let chat_id = Uuid::new_v4();
+ let tool = ReadChat {
+ chat_id: chat_id.to_string(),
+ };
+ let context = ServiceContext(ChatToolContext {
+ service: std::sync::Arc::new(StubChatService),
+ entity_access_service: std::sync::Arc::new(StubAccessService),
+ self_chat_id: None,
+ });
+
+ let result = tool.call(context, request_context()).await;
+
+ assert!(result.is_ok(), "{:?}", result.err());
+ }
+}
diff --git a/crates/soup/src/inbound/toolset/list_entities.rs b/crates/soup/src/inbound/toolset/list_entities.rs
index 02e50159f9..e3f86a7fef 100644
--- a/crates/soup/src/inbound/toolset/list_entities.rs
+++ b/crates/soup/src/inbound/toolset/list_entities.rs
@@ -736,12 +736,14 @@ where
.map(|sets| sets.applied_tag_by_option_id())
.unwrap_or_default();
- let items: Vec<EntityItem> = paginated
+ let mut items: Vec<EntityItem> = paginated
.items
.into_iter()
.map(|EnrichedSoupItem { item, .. }| EntityItem::from_soup_item(item, &tag_map))
.collect();
+ retain_excluding_self_chat(&mut items, service_context.self_chat_id);
+
// Build summary
let summary = build_summary(&items, has_more, &self.effective_include_types());
@@ -749,6 +751,15 @@ where
}
}
+/// Drop the chat the agent is currently running inside from `items` so it
+/// never surfaces itself in its own results.
+pub(super) fn retain_excluding_self_chat(items: &mut Vec<EntityItem>, self_chat_id: Option<Uuid>) {
+ let Some(self_chat_id) = self_chat_id else {
+ return;
+ };
+ items.retain(|item| !matches!(item, EntityItem::AiChat { id, .. } if *id == self_chat_id));
+}
+
async fn fetch_caller_tag_sets<T, E>(
service_context: &ServiceContext<SoupToolContext<T, E>>,
request_context: &RequestContext,
diff --git a/crates/soup/src/inbound/toolset/mod.rs b/crates/soup/src/inbound/toolset/mod.rs
index 4bb50eb48c..b56e1756ed 100644
--- a/crates/soup/src/inbound/toolset/mod.rs
+++ b/crates/soup/src/inbound/toolset/mod.rs
@@ -9,6 +9,7 @@ use crate::domain::ports::SoupService;
use ai_toolset::AsyncToolCollection;
use email::domain::ports::EmailService;
use std::sync::Arc;
+use uuid::Uuid;
pub use list_entities::{EntityItem, ItemType, ListEntities, ListEntitiesResponse, SortBy};
@@ -18,6 +19,10 @@ pub struct SoupToolContext<T: SoupService, E: EmailService> {
pub service: Arc<T>,
/// The email service instance for resolving email links
pub email_service: Arc<E>,
+ /// Entity id of the chat this request belongs to, when the request is an
+ /// interactive chat session. `None` for every other feature, in which
+ /// case nothing is excluded from the results.
+ pub self_chat_id: Option<Uuid>,
}
impl<T: SoupService, E: EmailService> Clone for SoupToolContext<T, E> {
@@ -25,6 +30,7 @@ impl<T: SoupService, E: EmailService> Clone for SoupToolContext<T, E> {
Self {
service: self.service.clone(),
email_service: self.email_service.clone(),
+ self_chat_id: self.self_chat_id,
}
}
}
@@ -35,6 +41,7 @@ impl<T: SoupService, E: EmailService> SoupToolContext<T, E> {
Self {
service: Arc::new(service),
email_service: Arc::new(email_service),
+ self_chat_id: None,
}
}
}
diff --git a/crates/soup/src/inbound/toolset/test.rs b/crates/soup/src/inbound/toolset/test.rs
index f4a44490ca..931b53b1e6 100644
--- a/crates/soup/src/inbound/toolset/test.rs
+++ b/crates/soup/src/inbound/toolset/test.rs
@@ -1,4 +1,4 @@
-use super::list_entities::build_summary;
+use super::list_entities::{build_summary, retain_excluding_self_chat};
#[allow(unused_imports)]
use super::*;
use ai_toolset::schema::generate_validated_input_schema;
@@ -447,6 +447,60 @@ fn test_from_soup_item_resolves_tags_via_caller_map() {
}
}
+#[test]
+fn test_retain_excluding_self_chat_drops_only_the_current_chat() {
+ let self_chat_id = Uuid::new_v4();
+ let other_chat_id = Uuid::new_v4();
+ let mut items = vec![
+ EntityItem::AiChat {
+ id: self_chat_id,
+ name: "Current chat".to_string(),
+ tags: vec![],
+ },
+ EntityItem::AiChat {
+ id: other_chat_id,
+ name: "Other chat".to_string(),
+ tags: vec![],
+ },
+ EntityItem::Document {
+ id: Uuid::new_v4(),
+ name: "doc.md".to_string(),
+ file_type: None,
+ sub_type: None,
+ tags: vec![],
+ },
+ ];
+
+ retain_excluding_self_chat(&mut items, Some(self_chat_id));
+
+ assert_eq!(items.len(), 2, "the current chat should be dropped");
+ assert!(
+ items
+ .iter()
+ .any(|item| matches!(item, EntityItem::AiChat { id, .. } if *id == other_chat_id)),
+ "unrelated chats should be kept"
+ );
+ assert!(
+ items
+ .iter()
+ .any(|item| matches!(item, EntityItem::Document { .. })),
+ "non-chat items should be kept"
+ );
+}
+
+#[test]
+fn test_retain_excluding_self_chat_is_noop_without_a_running_chat() {
+ let mut items = vec![EntityItem::AiChat {
+ id: Uuid::new_v4(),
+ name: "Some chat".to_string(),
+ tags: vec![],
+ }];
+
+ retain_excluding_self_chat(&mut items, None);
+
+ assert_eq!(items.len(), 1, "nothing to exclude outside a chat session");
+}
+
// run `cargo test -p soup inbound::toolset::test::print_input_schema -- --nocapture --include-ignored`
#[test]
#[ignore = "prints the input schema"]