Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(documents): let agents reply to and resolve document comments (#6860)
gbirmaneeaee4566494
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdxindex 73ef685c32..c8110d180f 100644--- a/apps/docs/AI/mcp/tools/index.mdx+++ b/apps/docs/AI/mcp/tools/index.mdx@@ -70,6 +70,8 @@ These pages are generated from Macro's Rust MCP tool registry.- [ReadThread](/AI/mcp/tools/read-thread)- [RenameChannel](/AI/mcp/tools/rename-channel)- [RenameDocument](/AI/mcp/tools/rename-document)+- [ReplyToDocumentComment](/AI/mcp/tools/reply-to-document-comment)+- [ResolveDocumentComment](/AI/mcp/tools/resolve-document-comment)- [SearchSkills](/AI/mcp/tools/search-skills)- [SearchTools](/AI/mcp/tools/search-tools)- [SelfKnowledge](/AI/mcp/tools/self-knowledge)diff --git a/apps/docs/AI/mcp/tools/reply-to-document-comment.mdx b/apps/docs/AI/mcp/tools/reply-to-document-comment.mdxnew file mode 100644index 0000000000..a782124d5b--- /dev/null+++ b/apps/docs/AI/mcp/tools/reply-to-document-comment.mdx@@ -0,0 +1,16 @@+---+title: ReplyToDocumentComment+description: "Reply in a comment thread on a document, or post a new comment in the document's Discussion panel, on behalf of the user. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. Cannot start a new inline comment on selected text."+---++# ReplyToDocumentComment++Reply in a comment thread on a document, or post a new comment in the document's Discussion panel, on behalf of the user. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. Cannot start a new inline comment on selected text.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `documentId` | string | Yes | The id of the document the comment is on. |+| `content` | string | Yes | Comment content in macro markdown format. This uses the same syntax as markdown documents. |+| `threadId` | string | No | The id of the inline or Discussion thread to reply in, from ReadContent. Omit to post a new Discussion comment on the document as a whole. |diff --git a/apps/docs/AI/mcp/tools/resolve-document-comment.mdx b/apps/docs/AI/mcp/tools/resolve-document-comment.mdxnew file mode 100644index 0000000000..db82844f74--- /dev/null+++ b/apps/docs/AI/mcp/tools/resolve-document-comment.mdx@@ -0,0 +1,16 @@+---+title: ResolveDocumentComment+description: "Resolve or reopen a comment thread on a document on behalf of the user. Only use this when explicitly asked to resolve or reopen a comment. Thread ids come from the comments ReadContent returns."+---++# ResolveDocumentComment++Resolve or reopen a comment thread on a document on behalf of the user. Only use this when explicitly asked to resolve or reopen a comment. Thread ids come from the comments ReadContent returns.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `documentId` | string | Yes | The id of the document the comment is on. |+| `threadId` | string | Yes | The id of the inline or Discussion thread, from ReadContent. |+| `resolved` | boolean | No | True to resolve the thread, false to reopen a resolved thread. Defaults to true. |diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.jsonindex ec52dbd3cb..04b8f88eeb 100644--- a/apps/docs/config/tool-pages.json+++ b/apps/docs/config/tool-pages.json@@ -61,6 +61,8 @@"AI/mcp/tools/read-thread","AI/mcp/tools/rename-channel","AI/mcp/tools/rename-document",+ "AI/mcp/tools/reply-to-document-comment",+ "AI/mcp/tools/resolve-document-comment","AI/mcp/tools/search-skills","AI/mcp/tools/search-tools","AI/mcp/tools/self-knowledge",diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex 809c658f6e..6502b490e8 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -132,6 +132,8 @@"AI/mcp/tools/read-thread","AI/mcp/tools/rename-channel","AI/mcp/tools/rename-document",+ "AI/mcp/tools/reply-to-document-comment",+ "AI/mcp/tools/resolve-document-comment","AI/mcp/tools/search-skills","AI/mcp/tools/search-tools","AI/mcp/tools/self-knowledge",diff --git a/apps/web/src/lib/core/component/AI/component/tool/DocumentComments.tsx b/apps/web/src/lib/core/component/AI/component/tool/DocumentComments.tsxnew file mode 100644index 0000000000..dc4b33a37d--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/DocumentComments.tsx@@ -0,0 +1,83 @@+import { ItemPreview } from '@core/component/ItemPreview';+import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg';+import ChatCircle from '@phosphor-icons/core/regular/chat-circle.svg';+import CheckCircle from '@phosphor-icons/core/regular/check-circle.svg';+import { createSignal, Suspense } from 'solid-js';+import { BaseTool } from './BaseTool';+import { Tool } from './Tool';+import { createToolRenderer } from './ToolRenderer';++function DocumentPreview(props: { documentId: string }) {+ return (+ <Suspense>+ <ItemPreview+ class="inline-flex align-middle ring-0"+ id={props.documentId}+ type="document"+ />+ </Suspense>+ );+}++export const replyToDocumentCommentHandler = createToolRenderer({+ name: 'ReplyToDocumentComment',+ render: (ctx) => {+ const [expanded, setExpanded] = createSignal(false);+ const verb = () => {+ const reply = ctx.tool.data.threadId != null;+ if (ctx.response)+ return reply ? 'Replied to a comment on' : 'Commented on';+ return reply ? 'Reply to a comment on' : 'Comment on';+ };++ return (+ <BaseTool+ icon={ChatCircle}+ renderContext={ctx.renderContext}+ type="call"+ response={+ expanded() ? (+ <p class="whitespace-pre-wrap break-words rounded-lg border border-edge-muted bg-ink/[0.02] p-3 text-xs text-ink">+ {ctx.tool.data.content}+ </p>+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <span class="min-w-0">+ {verb()} <DocumentPreview documentId={ctx.tool.data.documentId} />+ </span>+ <Tool.ResultToggle+ expanded={expanded()}+ onToggle={() => setExpanded((value) => !value)}+ showToggle={!!ctx.tool.data.content}+ />+ </div>+ </BaseTool>+ );+ },+});++export const resolveDocumentCommentHandler = createToolRenderer({+ name: 'ResolveDocumentComment',+ render: (ctx) => {+ const resolving = () => ctx.tool.data.resolved !== false;+ const verb = () => {+ if (resolving()) return ctx.response ? 'Resolved' : 'Resolve';+ return ctx.response ? 'Reopened' : 'Reopen';+ };++ return (+ <BaseTool+ icon={resolving() ? CheckCircle : ArrowCounterClockwise}+ renderContext={ctx.renderContext}+ type="call"+ >+ <div class="min-w-0 flex-1">+ {verb()} a comment on{' '}+ <DocumentPreview documentId={ctx.tool.data.documentId} />+ </div>+ </BaseTool>+ );+ },+});diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex f311122dac..eea7b41446 100644--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx@@ -33,6 +33,10 @@ import { createTagHandler } from './CreateTag';import { getCompanyHandler, listCompaniesHandler } from './Crm';import { deleteTagHandler } from './DeleteTag';import { displayResultsHandler } from './DisplayResults';+import {+ replyToDocumentCommentHandler,+ resolveDocumentCommentHandler,+} from './DocumentComments';import { editDocumentHandler } from './EditDocument';import { editTagHandler } from './EditTag';import { getThreadHandler } from './GetThread';@@ -167,6 +171,8 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {ReadProject: readProjectHandler,RenameChannel: renameChannelHandler,RenameDocument: renameDocumentHandler,+ ReplyToDocumentComment: replyToDocumentCommentHandler,+ ResolveDocumentComment: resolveDocumentCommentHandler,SearchSkills: searchSkillsHandler,SearchTools: searchToolsHandler,SelfKnowledge: selfKnowledgeHandler,diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex 24227bc462..c1f277881c 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -5087,6 +5087,30 @@ export const RenameDocumentResponse = z.object({message: z.string(),});+export const ReplyToDocumentComment = z.object({+ documentId: z.string().uuid(),+ content: z.string(),+ threadId: z.union([z.string().uuid(), z.null()]).optional(),+});++export const ReplyToDocumentCommentResponse = z.object({+ documentId: z.string().uuid(),+ threadId: z.string().uuid(),+ commentId: z.string().uuid(),+});++export const ResolveDocumentComment = z.object({+ documentId: z.string().uuid(),+ threadId: z.string().uuid(),+ resolved: z.boolean().optional(),+});++export const ResolveDocumentCommentResponse = z.object({+ documentId: z.string().uuid(),+ threadId: z.string().uuid(),+ resolved: z.boolean(),+});+export const SearchSkills = z.object({name: z.string(),matchType: zdiff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.tsindex eb10d2ec0a..aba3672502 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts@@ -195,6 +195,14 @@ type ToolParserMap = {call: types.RenameDocument;response: types.RenameDocumentResponse;};+ ReplyToDocumentComment: {+ call: types.ReplyToDocumentComment;+ response: types.ReplyToDocumentCommentResponse;+ };+ ResolveDocumentComment: {+ call: types.ResolveDocumentComment;+ response: types.ResolveDocumentCommentResponse;+ };SearchSkills: {call: types.SearchSkills;response: types.SearchSkillsResponse;@@ -451,6 +459,14 @@ const toolParserMap = {call: schemas.RenameDocument,response: schemas.RenameDocumentResponse,},+ ReplyToDocumentComment: {+ call: schemas.ReplyToDocumentComment,+ response: schemas.ReplyToDocumentCommentResponse,+ },+ ResolveDocumentComment: {+ call: schemas.ResolveDocumentComment,+ response: schemas.ResolveDocumentCommentResponse,+ },SearchSkills: {call: schemas.SearchSkills,response: schemas.SearchSkillsResponse,@@ -700,6 +716,14 @@ type ToolDataMap = {call: types.RenameDocument;response: types.RenameDocumentResponse;};+ ReplyToDocumentComment: {+ call: types.ReplyToDocumentComment;+ response: types.ReplyToDocumentCommentResponse;+ };+ ResolveDocumentComment: {+ call: types.ResolveDocumentComment;+ response: types.ResolveDocumentCommentResponse;+ };SearchSkills: {call: types.SearchSkills;response: types.SearchSkillsResponse;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.tsindex 5f293b32c9..128496f4d0 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@@ -5581,6 +5581,74 @@ export interface RenameDocumentResponse {*/message: string;}+/**+ * Reply in a comment thread on a document, or post a new comment in the document's Discussion panel, on behalf of the user. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. Cannot start a new inline comment on selected text.+ */+export interface ReplyToDocumentComment {+ /**+ * The id of the document the comment is on.+ */+ documentId: string;+ /**+ * Comment content in macro markdown format. This uses the same syntax as markdown documents.+ */+ content: string;+ /**+ * The id of the inline or Discussion thread to reply in, from ReadContent. Omit to post a new Discussion comment on the document as a whole.+ */+ threadId?: string | null;+}+/**+ * The posted comment.+ */+export interface ReplyToDocumentCommentResponse {+ /**+ * The document the comment was posted on.+ */+ documentId: string;+ /**+ * The thread the comment is in; a new Discussion comment starts its own.+ */+ threadId: string;+ /**+ * The posted comment.+ */+ commentId: string;+}+/**+ * Resolve or reopen a comment thread on a document on behalf of the user. Only use this when explicitly asked to resolve or reopen a comment. Thread ids come from the comments ReadContent returns.+ */+export interface ResolveDocumentComment {+ /**+ * The id of the document the comment is on.+ */+ documentId: string;+ /**+ * The id of the inline or Discussion thread, from ReadContent.+ */+ threadId: string;+ /**+ * True to resolve the thread, false to reopen a resolved thread. Defaults to true.+ */+ resolved?: boolean;+}+/**+ * The thread's state after the change.+ */+export interface ResolveDocumentCommentResponse {+ /**+ * The document the thread is on.+ */+ documentId: string;+ /**+ * The thread that was changed.+ */+ threadId: string;+ /**+ * Whether the thread is now resolved.+ */+ resolved: boolean;+}/*** Search the user's skills by name. Skills are markdown documents containing instructions for AI to read and follow; when the user references a skill (or a request matches one), find it with this tool and then read its instructions with ReadContent using the returned document id. This is keyword search against skill names: pass 1-3 targeted keywords that would literally appear in the skill's name, not a natural-language description. Matching defaults to prefix; set matchType to 'exact' for whole-token matching. Only skills the user can access are returned, most recently updated first.*/diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex 59a8e42759..e70faa654c 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -269,17 +269,18 @@ pub async fn build_tool_service_context_from_env(// broker events that drive live search indexing), so agent-sent messages// notify mentioned users and stream to connected clients instead of landing// silently.+ let side_effect_clients = ChannelSideEffectClients {+ connection_gateway: Arc::new(ConnectionGatewayClient::new(+ env.internal_api_key.to_string(),+ connection_gateway_url,+ )),+ sqs: aws_sqs_client,+ macro_event_broker: macro_event_broker.clone(),+ };let channel_tool_context = crate::tool_context::build_channel_tool_context_with_side_effects(pool.clone(),Arc::new(lexical_client.clone()),- ChannelSideEffectClients {- connection_gateway: Arc::new(ConnectionGatewayClient::new(- env.internal_api_key.to_string(),- connection_gateway_url,- )),- sqs: aws_sqs_client,- macro_event_broker: macro_event_broker.clone(),- },+ &side_effect_clients,);let document_service = documents::domain::service::DocumentServiceImpl {repo: document_repo,@@ -305,7 +306,11 @@ pub async fn build_tool_service_context_from_env(sync_client.as_ref().clone(),ReqwestEditingWorkerClient::new(ai_editing_worker_url, Arc::new(reqwest::Client::new())),env.document_permission_jwt.to_string(),- crate::tool_context::message_reader(pool.clone()),+ crate::tool_context::build_message_service_with_side_effects(+ pool.clone(),+ Arc::new(lexical_client.clone()),+ &side_effect_clients,+ ),);let properties_tool_context = crate::tool_context::build_properties_tool_context(diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rsindex 85bd7f658f..e014f0a80f 100644--- a/crates/ai_tools/src/lib.rs+++ b/crates/ai_tools/src/lib.rs@@ -68,9 +68,10 @@ pub use tool_context::{build_bot_tool_context, build_calendar_tool_context,build_channel_tool_context_with_dispatcher, build_channel_tool_context_with_side_effects,build_channel_tool_context_without_side_effects, build_crm_tool_context,+ build_message_service_with_side_effects, build_message_service_without_side_effects,build_project_tool_context, build_properties_service, build_properties_tool_context,build_reminders_tool_context, build_skill_tool_context, build_task_properties_adapter,- build_team_repository, build_team_tool_context, message_reader,+ build_team_repository, build_team_tool_context,};pub type AiToolSet = AsyncToolCollection<ToolServiceContext>;diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex 103d09855c..dac1dee74b 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -209,13 +209,16 @@ pub fn build_channel_tool_context_without_side_effects()}-/// Read-only view of the shared message tables for tools that only read-/// conversations, such as a document's comments. It publishes no events, so it-/// is exposed only through [`messages::domain::api::MessageReader`].-pub fn message_reader(pool: sqlx::PgPool) -> Arc<dyn messages::domain::api::MessageReader> {- Arc::new(messages::domain::service::MessageService::new(- messages::outbound::pg_message_repo::PgMessageRepository::new(pool),+/// Shared message service with no side effects. Messages posted through it+/// are persisted but notify no one, so it is only for tests and read paths.+pub fn build_message_service_without_side_effects(+ pool: sqlx::PgPool,+ lexical_client: Arc<lexical_client::LexicalClient>,+) -> Arc<dyn messages::domain::api::MessageServiceApi> {+ Arc::new(shared_message_service(+ pool,messages::domain::ports::NoMessageEventPublisher,+ lexical_client,))}@@ -269,14 +272,47 @@ pub struct ChannelSideEffectClients {pub fn build_channel_tool_context_with_side_effects(pool: sqlx::PgPool,lexical_client: Arc<lexical_client::LexicalClient>,- clients: ChannelSideEffectClients,+ clients: &ChannelSideEffectClients,) -> ToolChannelToolContext {- let notification_ingress = Arc::new(SqsNotificationIngress {+ let dispatcher = channel_event_dispatcher(&pool, clients);+ let messages = message_service_with_side_effects(+ pool.clone(),+ lexical_client.clone(),+ clients,+ dispatcher.clone(),+ );+ build_channel_tool_context_with_dispatcher(pool, dispatcher, lexical_client, messages)+}++/// Build the shared message service with the same delivery as the+/// document-storage message API: channel side effects for channel messages,+/// and realtime updates and comment notifications for document discussions.+/// Hosts that let the agent comment on documents need this so participants+/// are notified.+pub fn build_message_service_with_side_effects(+ pool: sqlx::PgPool,+ lexical_client: Arc<lexical_client::LexicalClient>,+ clients: &ChannelSideEffectClients,+) -> Arc<dyn messages::domain::api::MessageServiceApi> {+ let dispatcher = channel_event_dispatcher(&pool, clients);+ message_service_with_side_effects(pool, lexical_client, clients, dispatcher)+}++fn notification_ingress(+ clients: &ChannelSideEffectClients,+) -> Arc<SqsNotificationIngress<notification::outbound::queue::SqsQueue>> {+ Arc::new(SqsNotificationIngress {queue: notification::outbound::queue::SqsQueue::new(clients.sqs.clone(),macro_queues::NotificationIngressQueue::new().to_string(),),- });+ })+}++fn channel_event_dispatcher(+ pool: &sqlx::PgPool,+ clients: &ChannelSideEffectClients,+) -> ToolChannelEventDispatcher {let contacts_ingress = Arc::new(SqsContactsIngress {queue: SqsContactsQueue::new(clients.sqs.clone(),@@ -286,36 +322,52 @@ pub fn build_channel_tool_context_with_side_effects(let side_effects = ChannelSideEffectService::new(PgChannelSideEffectContext::new(pool.clone()),ConnectionGatewayChannelRealtimePublisher::new(clients.connection_gateway.clone()),- NotificationChannelSender::new(notification_ingress),+ NotificationChannelSender::new(notification_ingress(clients)),ContactsChannelDispatcher::new(contacts_ingress),).with_macro_event_broker(clients.macro_event_broker.clone());- let dispatcher: ToolChannelEventDispatcher =- Arc::new(SpawnedChannelEventDispatcher::new(side_effects));+ Arc::new(SpawnedChannelEventDispatcher::new(side_effects))+}++fn message_service_with_side_effects(+ pool: sqlx::PgPool,+ lexical_client: Arc<lexical_client::LexicalClient>,+ clients: &ChannelSideEffectClients,+ dispatcher: ToolChannelEventDispatcher,+) -> Arc<dyn messages::domain::api::MessageServiceApi> {let access = entity_access::domain::service::EntityAccessServiceImpl::new(entity_access::outbound::PgAccessRepository::new(pool.clone()),);+ let realtime = messages::outbound::connection_gateway::ConnectionGatewayMessages(+ clients.connection_gateway.clone(),+ );let effects = messages::domain::effects::MessageEffects::new(- messages::outbound::broker::BrokerMessagePublisher::new(clients.macro_event_broker),+ messages::outbound::broker::BrokerMessagePublisher::new(clients.macro_event_broker.clone()),messages::domain::ports::NoMessageEventPublisher,- channels::domain::message_delivery::ChannelMessageDelivery::new(- PgChannelsRepo::new(pool.clone()),- dispatcher.clone(),- channels::outbound::pg_channel_reference_share_permissions::PgChannelReferenceSharePermissions::new(- pool.clone(),- Arc::new(access),- ),- messages::outbound::connection_gateway::ConnectionGatewayMessages(- clients.connection_gateway,+ messages::domain::delivery::ParentMessagePublisher::new(+ channels::domain::message_delivery::ChannelMessageDelivery::new(+ PgChannelsRepo::new(pool.clone()),+ dispatcher,+ channels::outbound::pg_channel_reference_share_permissions::PgChannelReferenceSharePermissions::new(+ pool.clone(),+ Arc::new(access.clone()),+ ),+ realtime.clone(),),+ messages::domain::delivery::DiscussionDelivery::new(+ messages::outbound::pg_discussion_context::PgDiscussionContext(pool.clone()),+ messages::outbound::entity_access_audience::EntityAccessMessageAudience(access),+ realtime,+ messages::outbound::notification_sender::MessageNotificationSender(+ notification_ingress(clients),+ ),+ )+ .with_sharing(messages::outbound::pg_discussion_context::PgDiscussionContext(+ pool.clone(),+ )),),);- let messages = Arc::new(shared_message_service(- pool.clone(),- effects,- lexical_client.clone(),- ));- build_channel_tool_context_with_dispatcher(pool, dispatcher, lexical_client, messages)+ Arc::new(shared_message_service(pool, effects, lexical_client))}/// Build the channel AI tool context wired to `dispatcher`, so messages sent bydiff --git a/crates/documents/src/inbound/toolset.rs b/crates/documents/src/inbound/toolset.rsindex b80e850d9b..2461085c62 100644--- a/crates/documents/src/inbound/toolset.rs+++ b/crates/documents/src/inbound/toolset.rs@@ -5,9 +5,13 @@ mod edit_document;mod read_content;mod read_metadata;mod rename_document;+mod reply_to_document_comment;+mod resolve_document_comment;mod spreadsheet;mod upload_file;+#[cfg(test)]+mod comment_test;#[cfg(test)]mod test;@@ -24,6 +28,8 @@ use crate::{read_content::ReadContent,read_metadata::ReadMetadata,rename_document::RenameDocument,+ reply_to_document_comment::ReplyToDocumentComment,+ resolve_document_comment::ResolveDocumentComment,spreadsheet::{CalculateSpreadsheet, EditSpreadsheet, ReadSpreadsheet},upload_file::UploadFile,},@@ -33,14 +39,18 @@ use crate::{},};use activity::{Actor, Attribution};-use ai_toolset::AsyncToolCollection;+use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};use bot_id::BotId;-use entity_access::domain::ports::EntityAccessService;+use entity_access::domain::{+ models::{AccessError, BotAccessScope, EntityAccessReceipt, EntityType},+ ports::EntityAccessService,+};use lexical_client::LexicalClient;use macro_user_id::user_id::MacroUserIdStr;-use messages::domain::api::MessageReader;+use messages::domain::{api::MessageServiceApi, ports::MessageError, service::MessageWrite};use std::sync::Arc;use sync_service_client::SyncServiceClient;+use uuid::Uuid;/// Default backend-owned document creation use case for document tools.pub type DefaultDocumentToolCreator<DSvc> = DocumentCreator<@@ -76,6 +86,9 @@ pub struct DocumentToolContext</// A document's comment threads, read by the ReadContent tool.pub comments: Arc<dyn DocumentComments>,+ /// Shared message service the comment tools reply and resolve through.+ pub messages: Arc<dyn MessageServiceApi>,+/// Permission-scoped deterministic spreadsheet workflows.pub spreadsheet: Arc<crate::domain::spreadsheet::SpreadsheetService<DSvc, EDSvc>>,@@ -106,6 +119,7 @@ impl<creator: self.creator.clone(),editing: self.editing.clone(),comments: self.comments.clone(),+ messages: self.messages.clone(),spreadsheet: self.spreadsheet.clone(),document_permission_jwt_secret: self.document_permission_jwt_secret.clone(),recorder: self.recorder.clone(),@@ -128,7 +142,7 @@ impl<sync_service_client: SyncServiceClient,editing: EDSvc,document_permission_jwt_secret: String,- messages: Arc<dyn MessageReader>,+ messages: Arc<dyn MessageServiceApi>,) -> Self {let service = Arc::new(service);let lexical_client = Arc::new(lexical_client);@@ -143,7 +157,7 @@ impl<NoOpDocumentMentionTracker,);let comments = Arc::new(DocumentCommentReader::new(- messages,+ messages.clone(),LexicalCommentMarks::new(lexical_client.clone()),));let editing = Arc::new(editing);@@ -161,6 +175,7 @@ impl<creator,editing,comments,+ messages,spreadsheet,document_permission_jwt_secret,recorder: Arc::new(ai_usage::NoOpUsageRecorder),@@ -180,6 +195,24 @@ impl<self}+ /// Mint the bot's comment capability on the document on behalf of the+ /// requesting user: the same comment access the web composer requires.+ pub async fn require_comment_write(+ &self,+ request_context: &RequestContext,+ document_id: Uuid,+ ) -> Result<EntityAccessReceipt<MessageWrite>, ToolCallError> {+ self.entity_access_service+ .generate_bot_entity_access_receipt::<MessageWrite>(+ self.actor,+ BotAccessScope::user(request_context.user_id.clone()),+ &document_id.to_string(),+ EntityType::Document,+ )+ .await+ .map_err(comment_access_error)+ }+/// Attribution for a write these tools make for `user`.pub fn attribution(&self, user: MacroUserIdStr<'static>) -> Attribution {Attribution::delegated(Actor::new_from_bot(self.actor), user)@@ -201,7 +234,43 @@ where.add_tool::<UploadFile, DocumentToolContext<DSvc, ESvc, EDSvc>>().add_tool::<RenameDocument, DocumentToolContext<DSvc, ESvc, EDSvc>>().add_tool::<EditDocument, DocumentToolContext<DSvc, ESvc, EDSvc>>()+ .add_tool::<ReplyToDocumentComment, DocumentToolContext<DSvc, ESvc, EDSvc>>()+ .add_tool::<ResolveDocumentComment, DocumentToolContext<DSvc, ESvc, EDSvc>>().add_tool::<ReadSpreadsheet, DocumentToolContext<DSvc, ESvc, EDSvc>>().add_tool::<CalculateSpreadsheet, DocumentToolContext<DSvc, ESvc, EDSvc>>().add_tool::<EditSpreadsheet, DocumentToolContext<DSvc, ESvc, EDSvc>>()}++fn comment_access_error(err: AccessError) -> ToolCallError {+ let description = match err {+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {+ "you need comment access to the document to comment on it"+ }+ AccessError::NotFound(_) => "document not found",+ AccessError::BadRequest(_) => "invalid document id",+ AccessError::Unavailable(_) | AccessError::Internal(_) => {+ "failed to verify access to the document"+ }+ };+ ToolCallError {+ description: description.to_string(),+ internal_error: err.into(),+ }+}++fn comment_error(description: &'static str) -> impl FnOnce(MessageError) -> ToolCallError {+ move |err| {+ let description = match &err {+ MessageError::NotFound => "comment thread not found on this document".to_string(),+ MessageError::Forbidden => {+ "you need comment access to the document to comment on it".to_string()+ }+ MessageError::Invalid(reason) => format!("{description}: {reason}"),+ MessageError::Repository(_) => description.to_string(),+ };+ ToolCallError {+ description,+ internal_error: anyhow::Error::new(err),+ }+ }+}diff --git a/crates/documents/src/inbound/toolset/comment_test.rs b/crates/documents/src/inbound/toolset/comment_test.rsnew file mode 100644index 0000000000..00562b4059--- /dev/null+++ b/crates/documents/src/inbound/toolset/comment_test.rs@@ -0,0 +1,389 @@+use std::sync::{Arc, Mutex};++use ai_toolset::{AsyncTool, RequestContext, ServiceContext};+use channel_sender::ChannelSender;+use chrono::{TimeZone, Utc};+use entity_access::domain::models::{EntityAccessAuth, EntityAccessReceipt, EntityType};+use lexical_client::LexicalClient;+use macro_user_id::user_id::MacroUserIdStr;+use messages::domain::{+ api::{MessageCommands, MessageReader},+ models::{+ Message, MessageAttribution, MessageParent, MessageThread, PostMessage,+ PostMessageNotificationPolicy, ThreadPatch, ThreadState,+ },+ ports::{MessageError, MessagePage, MessagePatch, MessageTimelineQuery},+ service::{MessageView, MessageWrite},+};+use models_permissions::share_permission::access_level::AccessLevel;+use sync_service_client::SyncServiceClient;+use uuid::Uuid;++use super::{+ DocumentToolContext,+ edit_document::test::{FakeDocumentService, FakeEditingWorker, FakeEntityAccessService},+ reply_to_document_comment::ReplyToDocumentComment,+ resolve_document_comment::ResolveDocumentComment,+};++const USER: &str = "macro|[email protected]";+const DOCUMENT: Uuid = Uuid::from_u128(0x019fd3b9_3c6c_7c05_89c2_a27f0121813b);+const THREAD: Uuid = Uuid::from_u128(7);++/// Records the comment writes the tools make; `thread_exists` false answers+/// them as the message service does for a thread not on the document.+#[derive(Clone)]+pub(in crate::inbound::toolset) struct FakeMessages {+ thread_exists: bool,+ posts: Arc<Mutex<Vec<(EntityAccessReceipt<MessageWrite>, PostMessage)>>>,+ thread_patches: Arc<Mutex<Vec<(EntityAccessReceipt<MessageWrite>, Uuid, ThreadPatch)>>>,+}++impl Default for FakeMessages {+ fn default() -> Self {+ Self {+ thread_exists: true,+ posts: Arc::default(),+ thread_patches: Arc::default(),+ }+ }+}++#[async_trait::async_trait]+impl MessageReader for FakeMessages {+ async fn get(+ &self,+ _access: EntityAccessReceipt<MessageView>,+ _id: Uuid,+ ) -> Result<Message, MessageError> {+ panic!("unexpected get call")+ }+ async fn get_thread(+ &self,+ _access: EntityAccessReceipt<MessageView>,+ _root: Uuid,+ ) -> Result<MessageThread, MessageError> {+ panic!("unexpected get_thread call")+ }+ async fn timeline(+ &self,+ _access: EntityAccessReceipt<MessageView>,+ _query: MessageTimelineQuery,+ ) -> Result<MessagePage, MessageError> {+ panic!("unexpected timeline call")+ }+ async fn preceding(+ &self,+ _access: EntityAccessReceipt<MessageView>,+ _id: Uuid,+ _limit: u16,+ ) -> Result<Vec<Message>, MessageError> {+ panic!("unexpected preceding call")+ }+ async fn resolve_legacy(+ &self,+ _access: EntityAccessReceipt<MessageView>,+ _id: i64,+ _is_thread: bool,+ ) -> Result<Message, MessageError> {+ panic!("unexpected resolve_legacy call")+ }+}++#[async_trait::async_trait]+impl MessageCommands for FakeMessages {+ async fn post(+ &self,+ access: EntityAccessReceipt<MessageWrite>,+ input: PostMessage,+ ) -> Result<Message, MessageError> {+ if input.thread_id.is_some() && !self.thread_exists {+ return Err(MessageError::NotFound);+ }+ let at = Utc.with_ymd_and_hms(2026, 9, 23, 12, 0, 0).unwrap();+ let message = Message {+ id: Uuid::from_u128(99),+ parent: MessageParent::parse("document", &access.entity().entity_id).unwrap(),+ thread_id: input.thread_id,+ sender_id: ChannelSender::try_from(+ bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string(),+ )+ .unwrap(),+ imported_author: None,+ bot_profile: None,+ mentions: vec![],+ triggered_by: Some(USER.to_owned()),+ content: input.content.clone(),+ created_at: at,+ updated_at: at,+ edited_at: None,+ deleted_at: None,+ attachments: vec![],+ reactions: vec![],+ };+ self.posts.lock().unwrap().push((access, input));+ Ok(message)+ }+ async fn patch(+ &self,+ _access: EntityAccessReceipt<MessageWrite>,+ _id: Uuid,+ _input: MessagePatch,+ ) -> Result<Message, MessageError> {+ panic!("unexpected patch call")+ }+ async fn delete(+ &self,+ _access: EntityAccessReceipt<MessageWrite>,+ _id: Uuid,+ _nonce: Option<String>,+ ) -> Result<Message, MessageError> {+ panic!("unexpected delete call")+ }+ async fn react(+ &self,+ _access: EntityAccessReceipt<MessageWrite>,+ _id: Uuid,+ _emoji: String,+ _add: bool,+ _nonce: Option<String>,+ ) -> Result<Message, MessageError> {+ panic!("unexpected react call")+ }+ async fn typing(+ &self,+ _access: EntityAccessReceipt<MessageWrite>,+ _root: Option<Uuid>,+ _active: bool,+ _nonce: Option<String>,+ ) -> Result<(), MessageError> {+ panic!("unexpected typing call")+ }+ async fn patch_thread(+ &self,+ access: EntityAccessReceipt<MessageWrite>,+ root_id: Uuid,+ patch: ThreadPatch,+ ) -> Result<ThreadState, MessageError> {+ if !self.thread_exists {+ return Err(MessageError::NotFound);+ }+ let at = Utc.with_ymd_and_hms(2026, 9, 23, 12, 0, 0).unwrap();+ let state = ThreadState {+ root_id,+ user_id: "macro|[email protected]".to_owned(),+ resolved: patch.resolved.unwrap_or_default(),+ anchor: None,+ created_at: at,+ updated_at: at,+ deleted_at: None,+ };+ self.thread_patches+ .lock()+ .unwrap()+ .push((access, root_id, patch));+ Ok(state)+ }+ async fn delete_thread(+ &self,+ _access: EntityAccessReceipt<MessageWrite>,+ _root_id: Uuid,+ _nonce: Option<String>,+ ) -> Result<ThreadState, MessageError> {+ panic!("unexpected delete_thread call")+ }+}++type TestToolContext =+ DocumentToolContext<FakeDocumentService, FakeEntityAccessService, FakeEditingWorker>;++fn context(access_level: AccessLevel, messages: FakeMessages) -> ServiceContext<TestToolContext> {+ ServiceContext(DocumentToolContext::new(+ FakeDocumentService::new("md"),+ FakeEntityAccessService { access_level },+ LexicalClient::new("unused".to_owned(), "http://localhost/lexical".to_owned()),+ SyncServiceClient::new("unused".to_owned(), "http://localhost/sync".to_owned()),+ FakeEditingWorker::default(),+ "unused-jwt-secret".to_owned(),+ Arc::new(messages),+ ))+}++fn request() -> RequestContext {+ RequestContext::new(MacroUserIdStr::try_from(USER.to_owned()).unwrap())+}++/// The write went to the document as the tool actor bot on the user's behalf.+fn assert_bot_on_document(access: &EntityAccessReceipt<MessageWrite>) {+ assert_eq!(access.entity().entity_id, DOCUMENT.to_string());+ assert_eq!(access.entity().entity_type, EntityType::Document);+ assert!(matches!(access.auth(), EntityAccessAuth::Bot(_)));+ assert_eq!(+ access.acting_user_id().map(|user| user.as_ref()),+ Some(USER)+ );+}++#[tokio::test]+async fn reply_posts_in_the_thread_as_the_bot_for_the_user() {+ let messages = FakeMessages::default();+ let response = ReplyToDocumentComment {+ document_id: DOCUMENT,+ content: "Fixed in the latest draft.".to_owned(),+ thread_id: Some(THREAD),+ }+ .call(context(AccessLevel::Comment, messages.clone()), request())+ .await+ .unwrap();++ assert_eq!(response.document_id, DOCUMENT);+ assert_eq!(response.thread_id, THREAD);+ assert_eq!(response.comment_id, Uuid::from_u128(99));+ let posts = messages.posts.lock().unwrap();+ let [(access, post)] = posts.as_slice() else {+ panic!("expected one post, got {}", posts.len());+ };+ assert_bot_on_document(access);+ assert_eq!(post.thread_id, Some(THREAD));+ assert_eq!(post.content, "Fixed in the latest draft.");+ assert_eq!(post.attribution, MessageAttribution::ActingUser);+ assert_eq!(+ post.notification_policy,+ PostMessageNotificationPolicy::Default+ );+ assert!(post.anchor.is_none());+}++#[tokio::test]+async fn reply_without_a_thread_starts_a_discussion_comment() {+ let messages = FakeMessages::default();+ let response = ReplyToDocumentComment {+ document_id: DOCUMENT,+ content: "Summary of the open questions.".to_owned(),+ thread_id: None,+ }+ .call(context(AccessLevel::Comment, messages.clone()), request())+ .await+ .unwrap();++ assert_eq!(response.thread_id, response.comment_id);+ let posts = messages.posts.lock().unwrap();+ assert_eq!(posts.len(), 1);+ assert_eq!(posts[0].1.thread_id, None);+ assert!(posts[0].1.anchor.is_none());+}++#[tokio::test]+async fn reply_needs_comment_access() {+ let messages = FakeMessages::default();+ let error = ReplyToDocumentComment {+ document_id: DOCUMENT,+ content: "Looks good.".to_owned(),+ thread_id: Some(THREAD),+ }+ .call(context(AccessLevel::View, messages.clone()), request())+ .await+ .unwrap_err();++ assert!(+ error.description.contains("comment access"),+ "{}",+ error.description+ );+ assert!(messages.posts.lock().unwrap().is_empty());+}++#[tokio::test]+async fn reply_to_a_thread_not_on_the_document_says_so() {+ let messages = FakeMessages {+ thread_exists: false,+ ..FakeMessages::default()+ };+ let error = ReplyToDocumentComment {+ document_id: DOCUMENT,+ content: "Done.".to_owned(),+ thread_id: Some(THREAD),+ }+ .call(context(AccessLevel::Edit, messages), request())+ .await+ .unwrap_err();++ assert_eq!(+ error.description,+ "comment thread not found on this document"+ );+}++#[tokio::test]+async fn resolve_resolves_the_thread_as_the_bot_for_the_user() {+ let messages = FakeMessages::default();+ let response = ResolveDocumentComment {+ document_id: DOCUMENT,+ thread_id: THREAD,+ resolved: true,+ }+ .call(context(AccessLevel::Comment, messages.clone()), request())+ .await+ .unwrap();++ assert_eq!(response.thread_id, THREAD);+ assert!(response.resolved);+ let patches = messages.thread_patches.lock().unwrap();+ let [(access, root, patch)] = patches.as_slice() else {+ panic!("expected one thread update, got {}", patches.len());+ };+ assert_bot_on_document(access);+ assert_eq!(*root, THREAD);+ assert_eq!(patch.resolved, Some(true));+ assert!(!patch.detach_anchor);+}++#[tokio::test]+async fn resolve_false_reopens_the_thread() {+ let messages = FakeMessages::default();+ let response = ResolveDocumentComment {+ document_id: DOCUMENT,+ thread_id: THREAD,+ resolved: false,+ }+ .call(context(AccessLevel::Comment, messages.clone()), request())+ .await+ .unwrap();++ assert!(!response.resolved);+ assert_eq!(+ messages.thread_patches.lock().unwrap()[0].2.resolved,+ Some(false)+ );+}++#[test]+fn resolve_defaults_to_resolving() {+ let tool: ResolveDocumentComment = serde_json::from_value(serde_json::json!({+ "documentId": DOCUMENT,+ "threadId": THREAD,+ }))+ .unwrap();++ assert!(tool.resolved);+}++#[tokio::test]+async fn resolve_needs_comment_access() {+ let messages = FakeMessages::default();+ let error = ResolveDocumentComment {+ document_id: DOCUMENT,+ thread_id: THREAD,+ resolved: true,+ }+ .call(context(AccessLevel::View, messages.clone()), request())+ .await+ .unwrap_err();++ assert!(+ error.description.contains("comment access"),+ "{}",+ error.description+ );+ assert!(messages.thread_patches.lock().unwrap().is_empty());+}diff --git a/crates/documents/src/inbound/toolset/edit_document.rs b/crates/documents/src/inbound/toolset/edit_document.rsindex 180e79c304..4c9a438d1a 100644--- a/crates/documents/src/inbound/toolset/edit_document.rs+++ b/crates/documents/src/inbound/toolset/edit_document.rs@@ -21,7 +21,7 @@ use serde::{Deserialize, Serialize};use super::DocumentToolContext;#[cfg(test)]-mod test;+pub(super) mod test;#[derive(Debug, Deserialize, JsonSchema)]#[schemars(diff --git a/crates/documents/src/inbound/toolset/edit_document/test.rs b/crates/documents/src/inbound/toolset/edit_document/test.rsindex 71aeb16931..01bbf02afe 100644--- a/crates/documents/src/inbound/toolset/edit_document/test.rs+++ b/crates/documents/src/inbound/toolset/edit_document/test.rs@@ -45,12 +45,12 @@ fn document_with_file_type(file_type: Option<&str>) -> DocumentBasic {}}-struct FakeDocumentService {+pub(in crate::inbound::toolset) struct FakeDocumentService {file_type: Option<String>,}impl FakeDocumentService {- fn new(file_type: &str) -> Self {+ pub(in crate::inbound::toolset) fn new(file_type: &str) -> Self {Self {file_type: Some(file_type.to_string()),}@@ -273,8 +273,19 @@ impl DocumentCreationService for FakeDocumentService {}}-#[derive(Clone, Default)]-struct FakeEntityAccessService;+/// Grants the user, and bots acting for them, `access_level` on every entity.+#[derive(Clone)]+pub(in crate::inbound::toolset) struct FakeEntityAccessService {+ pub(in crate::inbound::toolset) access_level: AccessLevel,+}++impl Default for FakeEntityAccessService {+ fn default() -> Self {+ Self {+ access_level: AccessLevel::Owner,+ }+ }+}impl EntityAccessService for FakeEntityAccessService {async fn generate_entity_access_receipt<T: RequiredPermission>(@@ -292,19 +303,29 @@ impl EntityAccessService for FakeEntityAccessService {entity_type,},EntityPermission::AccessLevel {- access_level: AccessLevel::Owner,+ access_level: self.access_level,},)}async fn generate_bot_entity_access_receipt<T: RequiredPermission>(&self,- _bot_id: BotId,- _scope: BotAccessScope,- _entity_id: &str,- _entity_type: EntityType,+ bot_id: BotId,+ scope: BotAccessScope,+ entity_id: &str,+ entity_type: EntityType,) -> Result<EntityAccessReceipt<T>, AccessError> {- panic!("unexpected generate_bot_entity_access_receipt call")+ EntityAccessReceipt::try_new_bot(+ bot_id.into_storage_id(),+ (&scope).into(),+ entity_access::domain::models::Entity {+ entity_id: entity_id.to_string(),+ entity_type,+ },+ EntityPermission::AccessLevel {+ access_level: self.access_level,+ },+ )}async fn get_access_level(@@ -385,7 +406,7 @@ impl EntityAccessService for FakeEntityAccessService {}#[derive(Clone, Default)]-struct FakeEditingWorker {+pub(in crate::inbound::toolset) struct FakeEditingWorker {edit_calls: Arc<Mutex<Vec<String>>>,modes: Arc<Mutex<Vec<EditMode>>>,tokens: Arc<Mutex<Vec<DocumentPermissionToken>>>,@@ -442,7 +463,7 @@ fn tool_context() -> ServiceContext<TestToolContext> {ServiceContext(DocumentToolContext::new(service,- FakeEntityAccessService,+ FakeEntityAccessService::default(),LexicalClient::new("unused-internal-key".to_string(),"http://localhost/lexical".to_string(),@@ -453,7 +474,7 @@ fn tool_context(),editing,"unused-jwt-secret".to_string(),- std::sync::Arc::new(messages::domain::api::MockMessageReader::new()),+ std::sync::Arc::new(crate::inbound::toolset::comment_test::FakeMessages::default()),))}diff --git a/crates/documents/src/inbound/toolset/reply_to_document_comment.rs b/crates/documents/src/inbound/toolset/reply_to_document_comment.rsnew file mode 100644index 0000000000..4e7809777c--- /dev/null+++ b/crates/documents/src/inbound/toolset/reply_to_document_comment.rs@@ -0,0 +1,96 @@+//! ReplyToDocumentComment tool for answering document comments in place.++use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolResult};+use ai_toolset::{ToolAnnotated, ToolAnnotations};+use async_trait::async_trait;+use entity_access::domain::ports::EntityAccessService;+use messages::domain::models::{MessageAttribution, PostMessage, PostMessageNotificationPolicy};+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::{DocumentToolContext, comment_error};+use crate::domain::ports::{+ DocumentService, create::DocumentCreationService, editing::EditingWorkerService,+};++#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ReplyToDocumentComment",+ description = "Reply in a comment thread on a document, or post a new comment in the document's Discussion panel, on behalf of the user. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. Cannot start a new inline comment on selected text."+)]+pub struct ReplyToDocumentComment {+ #[schemars(description = "The id of the document the comment is on.")]+ pub document_id: Uuid,++ #[schemars(+ description = "Comment content in macro markdown format. This uses the same syntax as markdown documents."+ )]+ pub content: String,++ #[schemars(+ description = "The id of the inline or Discussion thread to reply in, from ReadContent. Omit to post a new Discussion comment on the document as a whole."+ )]+ pub thread_id: Option<Uuid>,+}++/// The posted comment.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ReplyToDocumentCommentResponse {+ /// The document the comment was posted on.+ pub document_id: Uuid,+ /// The thread the comment is in; a new Discussion comment starts its own.+ pub thread_id: Uuid,+ /// The posted comment.+ pub comment_id: Uuid,+}++impl ToolAnnotated for ReplyToDocumentComment {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Reply to document comment");+}++#[async_trait]+impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for ReplyToDocumentComment+where+ DSvc: DocumentService + DocumentCreationService,+ ESvc: EntityAccessService,+ EDSvc: EditingWorkerService,+{+ type Output = ReplyToDocumentCommentResponse;++ async fn call(+ &self,+ service_context: ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let access = service_context+ .require_comment_write(&request_context, self.document_id)+ .await?;++ let message = service_context+ .messages+ .post(+ access,+ PostMessage {+ attribution: MessageAttribution::ActingUser,+ notification_policy: PostMessageNotificationPolicy::Default,+ content: self.content.clone(),+ thread_id: self.thread_id,+ anchor: None,+ mentions: vec![],+ attachments: vec![],+ nonce: None,+ },+ )+ .await+ .map_err(comment_error("unable to post the comment"))?;++ Ok(ReplyToDocumentCommentResponse {+ document_id: self.document_id,+ thread_id: message.thread_id.unwrap_or(message.id),+ comment_id: message.id,+ })+ }+}diff --git a/crates/documents/src/inbound/toolset/resolve_document_comment.rs b/crates/documents/src/inbound/toolset/resolve_document_comment.rsnew file mode 100644index 0000000000..44bef4b2bf--- /dev/null+++ b/crates/documents/src/inbound/toolset/resolve_document_comment.rs@@ -0,0 +1,95 @@+//! ResolveDocumentComment tool for resolving and reopening document comment threads.++use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolResult};+use ai_toolset::{ToolAnnotated, ToolAnnotations};+use async_trait::async_trait;+use entity_access::domain::ports::EntityAccessService;+use messages::domain::models::ThreadPatch;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::{DocumentToolContext, comment_error};+use crate::domain::ports::{+ DocumentService, create::DocumentCreationService, editing::EditingWorkerService,+};++fn default_resolved() -> bool {+ true+}++#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ResolveDocumentComment",+ description = "Resolve or reopen a comment thread on a document on behalf of the user. Only use this when explicitly asked to resolve or reopen a comment. Thread ids come from the comments ReadContent returns."+)]+pub struct ResolveDocumentComment {+ #[schemars(description = "The id of the document the comment is on.")]+ pub document_id: Uuid,++ #[schemars(description = "The id of the inline or Discussion thread, from ReadContent.")]+ pub thread_id: Uuid,++ #[serde(default = "default_resolved")]+ #[schemars(+ description = "True to resolve the thread, false to reopen a resolved thread. Defaults to true."+ )]+ pub resolved: bool,+}++/// The thread's state after the change.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ResolveDocumentCommentResponse {+ /// The document the thread is on.+ pub document_id: Uuid,+ /// The thread that was changed.+ pub thread_id: Uuid,+ /// Whether the thread is now resolved.+ pub resolved: bool,+}++impl ToolAnnotated for ResolveDocumentComment {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Resolve document comment");+}++#[async_trait]+impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for ResolveDocumentComment+where+ DSvc: DocumentService + DocumentCreationService,+ ESvc: EntityAccessService,+ EDSvc: EditingWorkerService,+{+ type Output = ResolveDocumentCommentResponse;++ async fn call(+ &self,+ service_context: ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ let access = service_context+ .require_comment_write(&request_context, self.document_id)+ .await?;++ let state = service_context+ .messages+ .patch_thread(+ access,+ self.thread_id,+ ThreadPatch {+ resolved: Some(self.resolved),+ detach_anchor: false,+ nonce: None,+ },+ )+ .await+ .map_err(comment_error("unable to update the comment thread"))?;++ Ok(ResolveDocumentCommentResponse {+ document_id: self.document_id,+ thread_id: state.root_id,+ resolved: state.resolved,+ })+ }+}diff --git a/crates/documents/src/inbound/toolset/test.rs b/crates/documents/src/inbound/toolset/test.rsindex 562401d63e..0ace903af6 100644--- a/crates/documents/src/inbound/toolset/test.rs+++ b/crates/documents/src/inbound/toolset/test.rs@@ -64,3 +64,39 @@ fn test_rename_document_schema_validation() {"Description should contain expected text");}++#[test]+fn test_reply_to_document_comment_schema_validation() {+ let result = generate_validated_input_schema::<ReplyToDocumentComment>();+ assert!(result.is_ok(), "{:?}", result);++ let validated = result.unwrap();+ assert_eq!(+ validated.name, "ReplyToDocumentComment",+ "Tool name should match the schemars title"+ );+ assert!(+ validated+ .description+ .contains("Only use this when explicitly asked"),+ "Description should limit when the tool posts"+ );+}++#[test]+fn test_resolve_document_comment_schema_validation() {+ let result = generate_validated_input_schema::<ResolveDocumentComment>();+ assert!(result.is_ok(), "{:?}", result);++ let validated = result.unwrap();+ assert_eq!(+ validated.name, "ResolveDocumentComment",+ "Tool name should match the schemars title"+ );+ assert!(+ validated+ .description+ .contains("Only use this when explicitly asked"),+ "Description should limit when the tool resolves"+ );+}diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex f34ade5250..e98bca2bda 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -353,6 +353,12 @@ The agent has workspace tools (it can list your documents, read channels, createrender `displayResults` views). Requests go to `POST /cognition/stream/chat/message`; resultsstream over the app's websocket, not the HTTP response.+When asked, the agent also answers document comments in place. A reply row reads+**Replied to a comment on** (or **Commented on** for a new Discussion comment) followed+by the document, and expands to the posted text; a resolve row reads **Resolved** or+**Reopened a comment on** the document. The comment is posted as the agent with a+**from <user>** pill, and needs the user's comment access to the document.+## Agent sessions asking a questionFor manual testing on local or deployed development environments, senddiff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex cede6c0218..8c01ee0001 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -287,7 +287,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arsync_service_client.as_ref().clone(),test_editing_client,"test-jwt-secret".to_string(),- ai_tools::message_reader(pool.clone()),+ ai_tools::build_message_service_without_side_effects(+ pool.clone(),+ std::sync::Arc::new(test_lexical_client.clone()),+ ),);let search_service_client = Arc::new(search_service_client);diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rsindex 63fe77e4ef..7a381a8ebb 100644--- a/services/document_cognition_service/src/main.rs+++ b/services/document_cognition_service/src/main.rs@@ -319,6 +319,19 @@ async fn main() -> anyhow::Result<()> {ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone())),macro_event_broker.clone(),);+ // Messages sent by AI tools (chat, agents) dispatch the same side effects+ // as the document-storage message API, so mentions, replies and document+ // comments notify recipients and stream to connected clients.+ let channels_connection_gateway =+ Arc::new(connection_gateway_client::ConnectionGatewayClient::new(+ internal_api_key.clone(),+ ConnectionGatewayUrl::new()?.to_string(),+ ));+ let side_effect_clients = ai_tools::ChannelSideEffectClients {+ connection_gateway: channels_connection_gateway.clone(),+ sqs: aws_sdk_sqs::Client::new(&aws_config),+ macro_event_broker: macro_event_broker.clone(),+ };let lexical_client_for_tools = (*lexical_client).clone();let document_tool_context = DocumentToolContext::new(document_service,@@ -330,7 +343,11 @@ async fn main() -> anyhow::Result<()> {std::sync::Arc::new(reqwest::Client::new()),),config.document_permission_jwt.as_ref().to_string(),- ai_tools::message_reader(db.clone()),+ ai_tools::build_message_service_with_side_effects(+ db.clone(),+ lexical_client.clone(),+ &side_effect_clients,+ ),);tracing::info!("initialized document tool context");@@ -431,22 +448,10 @@ async fn main() -> anyhow::Result<()> {tracing::info!("initialized chat tool context");- // Channel messages sent by AI tools (chat, agents) dispatch the same side- // effects as the document-storage channel API, so mentions and replies- // notify recipients and stream to connected clients.- let channels_connection_gateway =- Arc::new(connection_gateway_client::ConnectionGatewayClient::new(- internal_api_key.clone(),- ConnectionGatewayUrl::new()?.to_string(),- ));let channel_tool_context = ai_tools::build_channel_tool_context_with_side_effects(db.clone(),lexical_client.clone(),- ai_tools::ChannelSideEffectClients {- connection_gateway: channels_connection_gateway.clone(),- sqs: aws_sdk_sqs::Client::new(&aws_config),- macro_event_broker: macro_event_broker.clone(),- },+ &side_effect_clients,);let recorder = ai_usage::pg_recorder(db.clone());diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex 1faba05ecc..c8c79e5cff 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -263,6 +263,17 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Toforeign_entity_service: ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone())),macro_event_broker: macro_event_broker.clone(),};+ // Messages sent through MCP tools dispatch the same side effects as the+ // document-storage message API, so mentions, replies and document comments+ // notify recipients and stream to connected clients.+ let side_effect_clients = ai_tools::ChannelSideEffectClients {+ connection_gateway: Arc::new(connection_gateway_client::ConnectionGatewayClient::new(+ config.internal_api_key.to_string(),+ ConnectionGatewayUrl::new()?.to_string(),+ )),+ sqs: queue_aws_client,+ macro_event_broker: macro_event_broker.clone(),+ };let lexical_client_for_tools = (*lexical_client).clone();let document_tool_context = DocumentToolContext::new(document_service,@@ -271,7 +282,11 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Tosync_service_client.clone(),ReqwestEditingWorkerClient::from_url(ai_editing_worker_url),config.document_permission_jwt.to_string(),- ai_tools::message_reader(db.clone()),+ ai_tools::build_message_service_with_side_effects(+ db.clone(),+ lexical_client.clone(),+ &side_effect_clients,+ ),);let properties_tool_context = ai_tools::build_properties_tool_context(@@ -341,20 +356,10 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<ToEntityAccessServiceImpl::new(PgAccessRepository::new(db.clone())),);- // Channel messages sent through MCP tools dispatch the same side effects- // as the document-storage channel API, so mentions and replies notify- // recipients and stream to connected clients.let channel_tool_context = ai_tools::build_channel_tool_context_with_side_effects(db.clone(),lexical_client.clone(),- ai_tools::ChannelSideEffectClients {- connection_gateway: Arc::new(connection_gateway_client::ConnectionGatewayClient::new(- config.internal_api_key.to_string(),- ConnectionGatewayUrl::new()?.to_string(),- )),- sqs: queue_aws_client,- macro_event_broker: macro_event_broker.clone(),- },+ &side_effect_clients,);let project_tool_context = ai_tools::build_project_tool_context(