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(discussions): address any item's Discussion from the AI tools (#8466)

gbirmanaef660778c78
diff --git a/Cargo.lock b/Cargo.lock
index 7d41f6840b..f1364fb425 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -12688,6 +12688,7 @@ name = "messages"
version = "0.1.0"
dependencies = [
"activity",
+ "ai_toolset",
"async-trait",
"axum",
"bot_id",
@@ -12710,6 +12711,7 @@ dependencies = [
"model_notifications",
"model_owner",
"models_pagination",
+ "models_permissions",
"models_properties",
"notification",
"properties",
diff --git a/apps/docs/AI/mcp/tools/comment-on-document.mdx b/apps/docs/AI/mcp/tools/comment-on-document.mdx
deleted file mode 100644
index 99189ea015..0000000000
--- a/apps/docs/AI/mcp/tools/comment-on-document.mdx
+++ /dev/null
@@ -1,19 +0,0 @@
----
-title: CommentOnDocument
-description: >-
- Comment on a document on behalf of the user.
----
-
-# CommentOnDocument
-
-Comment on a document on behalf of the user. Pass threadId to reply in an existing inline or Discussion thread; pass quote to start a new inline comment on a passage of a Macro markdown or Word (DOCX) document; omit both to start a new Discussion comment on the document as a whole. Replies and Discussion comments support any document type. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. For an inline comment, quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. Do not combine threadId with quote. occurrence only applies with quote. Comments made here stay in Macro and are not written into a Word file; for comments that must travel with a Word document to its recipient (a redline for a counterparty), use EditWordDocument's addComment operation instead.
-
-## Parameters
-
-| Parameter | Type | Required | Description |
-| --- | --- | --- | --- |
-| `documentId` | string | Yes | The id of the document to comment 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. Cannot be combined with quote. Omit both threadId and quote to post a new Discussion comment on the document as a whole. |
-| `quote` | string | No | The passage to comment on, quoted exactly as the document reads: plain text without markdown syntax such as ** or link brackets. Keep it to the words the comment is about; a longer quote is more likely to be unique. Starts a new inline comment on a markdown or Word (DOCX) document. Cannot be combined with threadId. |
-| `occurrence` | integer | No | Which appearance of the quoted passage to comment on, counting from 1 in document order. Only applies with quote; only needed when the passage appears more than once. |
diff --git a/apps/docs/AI/mcp/tools/comment-on-text.mdx b/apps/docs/AI/mcp/tools/comment-on-text.mdx
new file mode 100644
index 0000000000..9bc14efe28
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/comment-on-text.mdx
@@ -0,0 +1,19 @@
+---
+title: CommentOnText
+description: >-
+ Start an inline comment on a passage of a Macro markdown or Word (DOCX)
+ document on behalf of the user, anchored to the quoted text.
+---
+
+# CommentOnText
+
+Start an inline comment on a passage of a Macro markdown or Word (DOCX) document on behalf of the user, anchored to the quoted text. Only use this when explicitly asked to comment on specific text. Quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. For a comment on a document as a whole, or a reply in an existing thread, use Comment. Comments made here stay in Macro and are not written into a Word file; for comments that must travel with a Word document to its recipient (a redline for a counterparty), use EditWordDocument's addComment operation instead.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `documentId` | string | Yes | The id of the document to comment on. |
+| `content` | string | Yes | Comment content in macro markdown format. This uses the same syntax as markdown documents. |
+| `quote` | string | Yes | The passage to comment on, quoted exactly as the document reads: plain text without markdown syntax such as ** or link brackets. Keep it to the words the comment is about; a longer quote is more likely to be unique. |
+| `occurrence` | integer | No | Which appearance of the quoted passage to comment on, counting from 1 in document order. Only needed when the passage appears more than once. |
diff --git a/apps/docs/AI/mcp/tools/comment.mdx b/apps/docs/AI/mcp/tools/comment.mdx
new file mode 100644
index 0000000000..1d5994bda5
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/comment.mdx
@@ -0,0 +1,20 @@
+---
+title: Comment
+description: >-
+ Add a comment to the Discussion of a document, task, Tasks project
+ (initiative), CRM company or CRM contact on behalf of the user, or reply in an
+ existing comment thread on any of them.
+---
+
+# Comment
+
+Add a comment to the Discussion of a document, task, Tasks project (initiative), CRM company or CRM contact on behalf of the user, or reply in an existing comment thread on any of them. For a new comment, address the item by entityType and entityId. For a reply, pass threadId; a thread id is enough to find its item, so entityType and entityId may be omitted. Thread ids come from ReadDiscussion, or from ReadContent for a document. Only use this when explicitly asked to comment or reply. Write content in Macro markdown and link people and items with the same mention tags as in documents; they render as chips and notify the people mentioned. To comment on a passage of text in a document, use CommentOnText instead; for a message in a channel, use SendChannelMessage.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `entityType` | `"document"` \| `"initiative"` \| `"crm_company"` \| `"crm_contact"` | No | The kind of item to comment on. Required with entityId for a new comment; optional for a reply. |
+| `entityId` | string | No | The id of the item to comment on. Required with entityType for a new comment; optional for a reply. |
+| `threadId` | string | No | The id of the thread to reply in. Omit to start a new Discussion comment on the item. |
+| `content` | string | Yes | Comment content in Macro markdown, the same syntax as markdown documents, including mention tags. |
diff --git a/apps/docs/AI/mcp/tools/delete-comment.mdx b/apps/docs/AI/mcp/tools/delete-comment.mdx
new file mode 100644
index 0000000000..58ea5224ac
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/delete-comment.mdx
@@ -0,0 +1,16 @@
+---
+title: DeleteComment
+description: >-
+ Delete a comment or reply in the Discussion of a document, task, Tasks
+ project, CRM company or CRM contact.
+---
+
+# DeleteComment
+
+Delete a comment or reply in the Discussion of a document, task, Tasks project, CRM company or CRM contact. Deleting the first comment of a thread deletes the whole thread with its replies. Authors can delete their own comments, and the item's owner can delete any comment. This cannot be undone. A comment id is enough to find its item. Comment ids come from ReadDiscussion, or from ReadContent for a document. Use only when the user explicitly asks to delete a comment; use ResolveComment to close a thread instead.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `commentId` | string | Yes | The id of the comment or reply to delete. Pass the thread id to delete the whole thread. |
diff --git a/apps/docs/AI/mcp/tools/delete-document-comment.mdx b/apps/docs/AI/mcp/tools/delete-document-comment.mdx
deleted file mode 100644
index 142266122d..0000000000
--- a/apps/docs/AI/mcp/tools/delete-document-comment.mdx
+++ /dev/null
@@ -1,16 +0,0 @@
----
-title: DeleteDocumentComment
-description: >-
- Delete a comment or reply on a document.
----
-
-# DeleteDocumentComment
-
-Delete a comment or reply on a document. Deleting the first comment of a thread deletes the whole thread with its replies. Authors can delete their own comments, and the document owner can delete any comment. This cannot be undone. Comment ids come from the comments ReadContent returns. Use only when the user explicitly asks to delete a comment; use ResolveDocumentComment to close a thread instead.
-
-## Parameters
-
-| Parameter | Type | Required | Description |
-| --- | --- | --- | --- |
-| `documentId` | string | Yes | The id of the document the comment is on. |
-| `commentId` | string | Yes | The id of the comment or reply to delete, from ReadContent. Pass the thread id to delete the whole thread. |
diff --git a/apps/docs/AI/mcp/tools/edit-comment.mdx b/apps/docs/AI/mcp/tools/edit-comment.mdx
new file mode 100644
index 0000000000..886c79291d
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/edit-comment.mdx
@@ -0,0 +1,17 @@
+---
+title: EditComment
+description: >-
+ Replace the text of a comment or reply in the Discussion of a document, task,
+ Tasks project, CRM company or CRM contact.
+---
+
+# EditComment
+
+Replace the text of a comment or reply in the Discussion of a document, task, Tasks project, CRM company or CRM contact. Only a comment's author can edit it, so this edits comments the user wrote and comments this assistant wrote for them. A comment id is enough to find its item. Comment ids come from ReadDiscussion, or from ReadContent for a document. Use only when the user asks to edit a comment.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `commentId` | string | Yes | The id of the comment or reply to edit. For the first comment of a thread this is the thread id. |
+| `content` | string | Yes | The full replacement text of the comment, in Macro markdown. |
diff --git a/apps/docs/AI/mcp/tools/edit-document-comment.mdx b/apps/docs/AI/mcp/tools/edit-document-comment.mdx
deleted file mode 100644
index 6777da16cd..0000000000
--- a/apps/docs/AI/mcp/tools/edit-document-comment.mdx
+++ /dev/null
@@ -1,17 +0,0 @@
----
-title: EditDocumentComment
-description: >-
- Replace the text of a comment or reply on a document.
----
-
-# EditDocumentComment
-
-Replace the text of a comment or reply on a document. Only a comment's author can edit it, so this edits comments the user wrote and comments this assistant wrote for them. Comment ids come from the comments ReadContent returns. Use only when the user asks to edit a comment.
-
-## Parameters
-
-| Parameter | Type | Required | Description |
-| --- | --- | --- | --- |
-| `documentId` | string | Yes | The id of the document the comment is on. |
-| `commentId` | string | Yes | The id of the comment or reply to edit, from ReadContent. For the first comment of a thread this is the thread id. |
-| `content` | string | Yes | The full replacement text of the comment, in markdown. |
diff --git a/apps/docs/AI/mcp/tools/edit-word-document.mdx b/apps/docs/AI/mcp/tools/edit-word-document.mdx
index 608bc2045e..8e03cab620 100644
--- a/apps/docs/AI/mcp/tools/edit-word-document.mdx
+++ b/apps/docs/AI/mcp/tools/edit-word-document.mdx
@@ -8,7 +8,7 @@ description: >-
# EditWordDocument
-Edit an uploaded Word (.docx) document in place: an ordered batch of operations applied atomically to its live copy, so everyone with it open sees the change at once, and nothing changes if any operation fails. ReadWordDocument first and address paragraphs, tables and blocks by the ids it reports (they are not numbers). Use replaceText for wording changes (exact text within one paragraph; formatting is kept), setText to rewrite a whole paragraph, formatText for bold, italic, underline or strikethrough, insertParagraph to add paragraphs (each line of text becomes one; a style is optional), setStyle to change a paragraph style such as Heading1, delete to remove a paragraph, table or block, and addComment to add a Word comment on text. Only insertParagraph and addComment text may contain line breaks. Paragraphs inside table cells are edited the same way. Tracked changes (a redline): with trackChanges true, or when the document already tracks changes and trackChanges is omitted, edits are recorded as real Word revisions (insertions, deletions, formatting and style changes) that the counterparty can accept or reject in Word; pass trackChanges true whenever the user asks for a redline, tracked changes or a markup. Revisions and addComment comments are attributed to the requesting user by name, not to you; pass author only when the user names someone else (a firm or another person). addComment comments are saved in the file and travel with it to Word; use them for comments meant for whoever receives the document, and CommentOnDocument for discussion inside Macro. Returns the changed blocks as they now read, with the ids of new paragraphs; check them. At most 50 operations.
+Edit an uploaded Word (.docx) document in place: an ordered batch of operations applied atomically to its live copy, so everyone with it open sees the change at once, and nothing changes if any operation fails. ReadWordDocument first and address paragraphs, tables and blocks by the ids it reports (they are not numbers). Use replaceText for wording changes (exact text within one paragraph; formatting is kept), setText to rewrite a whole paragraph, formatText for bold, italic, underline or strikethrough, insertParagraph to add paragraphs (each line of text becomes one; a style is optional), setStyle to change a paragraph style such as Heading1, delete to remove a paragraph, table or block, and addComment to add a Word comment on text. Only insertParagraph and addComment text may contain line breaks. Paragraphs inside table cells are edited the same way. Tracked changes (a redline): with trackChanges true, or when the document already tracks changes and trackChanges is omitted, edits are recorded as real Word revisions (insertions, deletions, formatting and style changes) that the counterparty can accept or reject in Word; pass trackChanges true whenever the user asks for a redline, tracked changes or a markup. Revisions and addComment comments are attributed to the requesting user by name, not to you; pass author only when the user names someone else (a firm or another person). addComment comments are saved in the file and travel with it to Word; use them for comments meant for whoever receives the document, and Comment or CommentOnText for discussion inside Macro. Returns the changed blocks as they now read, with the ids of new paragraphs; check them. At most 50 operations.
## Parameters
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdx
index f394844a92..eed3cb4974 100644
--- a/apps/docs/AI/mcp/tools/index.mdx
+++ b/apps/docs/AI/mcp/tools/index.mdx
@@ -14,7 +14,8 @@ These pages are generated from Macro's Rust MCP tool registry.
- [BulkSetEntityPropertyOptions](/AI/mcp/tools/bulk-set-entity-property-options)
- [CalculateSpreadsheet](/AI/mcp/tools/calculate-spreadsheet)
- [ChangeBooking](/AI/mcp/tools/change-booking)
-- [CommentOnDocument](/AI/mcp/tools/comment-on-document)
+- [Comment](/AI/mcp/tools/comment)
+- [CommentOnText](/AI/mcp/tools/comment-on-text)
- [ConfigureAgent](/AI/mcp/tools/configure-agent)
- [ConfigureBot](/AI/mcp/tools/configure-bot)
- [ContentSearch](/AI/mcp/tools/content-search)
@@ -40,8 +41,8 @@ These pages are generated from Macro's Rust MCP tool registry.
- [DeleteCalendarEvent](/AI/mcp/tools/delete-calendar-event)
- [DeleteCallRecord](/AI/mcp/tools/delete-call-record)
- [DeleteChannelMessage](/AI/mcp/tools/delete-channel-message)
+- [DeleteComment](/AI/mcp/tools/delete-comment)
- [DeleteDatabaseView](/AI/mcp/tools/delete-database-view)
-- [DeleteDocumentComment](/AI/mcp/tools/delete-document-comment)
- [DeleteImportEntity](/AI/mcp/tools/delete-import-entity)
- [DeleteInitiative](/AI/mcp/tools/delete-initiative)
- [DeleteRoutine](/AI/mcp/tools/delete-routine)
@@ -51,8 +52,8 @@ These pages are generated from Macro's Rust MCP tool registry.
- [DuplicateItem](/AI/mcp/tools/duplicate-item)
- [EditBookingLink](/AI/mcp/tools/edit-booking-link)
- [EditChannelMessage](/AI/mcp/tools/edit-channel-message)
+- [EditComment](/AI/mcp/tools/edit-comment)
- [EditDocument](/AI/mcp/tools/edit-document)
-- [EditDocumentComment](/AI/mcp/tools/edit-document-comment)
- [EditForm](/AI/mcp/tools/edit-form)
- [EditPipeline](/AI/mcp/tools/edit-pipeline)
- [EditPresentation](/AI/mcp/tools/edit-presentation)
@@ -117,6 +118,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [ReadChannelThread](/AI/mcp/tools/read-channel-thread)
- [ReadContent](/AI/mcp/tools/read-content)
- [ReadDesign](/AI/mcp/tools/read-design)
+- [ReadDiscussion](/AI/mcp/tools/read-discussion)
- [ReadForm](/AI/mcp/tools/read-form)
- [ReadIllustratorDocument](/AI/mcp/tools/read-illustrator-document)
- [ReadInitiative](/AI/mcp/tools/read-initiative)
@@ -133,7 +135,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [RenameChannel](/AI/mcp/tools/rename-channel)
- [RenameDocument](/AI/mcp/tools/rename-document)
- [RenameItem](/AI/mcp/tools/rename-item)
-- [ResolveDocumentComment](/AI/mcp/tools/resolve-document-comment)
+- [ResolveComment](/AI/mcp/tools/resolve-comment)
- [RunRoutine](/AI/mcp/tools/run-routine)
- [SaveDatabaseQuery](/AI/mcp/tools/save-database-query)
- [SaveDatabaseView](/AI/mcp/tools/save-database-view)
diff --git a/apps/docs/AI/mcp/tools/read-discussion.mdx b/apps/docs/AI/mcp/tools/read-discussion.mdx
new file mode 100644
index 0000000000..539c0c8a95
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/read-discussion.mdx
@@ -0,0 +1,18 @@
+---
+title: ReadDiscussion
+description: >-
+ Read the comment threads in the Discussion of a document, task, Tasks project
+ (initiative), CRM company or CRM contact: each thread's id, resolved state and
+ comments, with their ids, authors and text, oldest thread first.
+---
+
+# ReadDiscussion
+
+Read the comment threads in the Discussion of a document, task, Tasks project (initiative), CRM company or CRM contact: each thread's id, resolved state and comments, with their ids, authors and text, oldest thread first. Thread and comment ids are what Comment, EditComment, DeleteComment and ResolveComment take. For a document, ReadContent returns the same threads alongside the content, with the live text each inline comment is on.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `entityType` | `"document"` \| `"initiative"` \| `"crm_company"` \| `"crm_contact"` | Yes | The kinds of item that carry a Discussion. |
+| `entityId` | string | Yes | The id of the item. |
diff --git a/apps/docs/AI/mcp/tools/resolve-comment.mdx b/apps/docs/AI/mcp/tools/resolve-comment.mdx
new file mode 100644
index 0000000000..cd14ce2f2d
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/resolve-comment.mdx
@@ -0,0 +1,17 @@
+---
+title: ResolveComment
+description: >-
+ Resolve or reopen a comment thread in the Discussion of a document, task,
+ Tasks project, CRM company or CRM contact on behalf of the user.
+---
+
+# ResolveComment
+
+Resolve or reopen a comment thread in the Discussion of a document, task, Tasks project, CRM company or CRM contact on behalf of the user. A thread id is enough to find its item. Only use this when explicitly asked to resolve or reopen a comment. Thread ids come from ReadDiscussion, or from ReadContent for a document.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `threadId` | string | Yes | The id of the thread to resolve or reopen. |
+| `resolved` | boolean | No | True to resolve the thread, false to reopen a resolved thread. Defaults to true. |
diff --git a/apps/docs/AI/mcp/tools/resolve-document-comment.mdx b/apps/docs/AI/mcp/tools/resolve-document-comment.mdx
deleted file mode 100644
index a75b4a472f..0000000000
--- a/apps/docs/AI/mcp/tools/resolve-document-comment.mdx
+++ /dev/null
@@ -1,17 +0,0 @@
----
-title: ResolveDocumentComment
-description: >-
- Resolve or reopen a comment thread on a document on behalf of the user.
----
-
-# 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.json
index 003fc6902e..1a83b5cf46 100644
--- a/apps/docs/config/tool-pages.json
+++ b/apps/docs/config/tool-pages.json
@@ -5,7 +5,8 @@
"AI/mcp/tools/bulk-set-entity-property-options",
"AI/mcp/tools/calculate-spreadsheet",
"AI/mcp/tools/change-booking",
- "AI/mcp/tools/comment-on-document",
+ "AI/mcp/tools/comment",
+ "AI/mcp/tools/comment-on-text",
"AI/mcp/tools/configure-agent",
"AI/mcp/tools/configure-bot",
"AI/mcp/tools/content-search",
@@ -31,8 +32,8 @@
"AI/mcp/tools/delete-calendar-event",
"AI/mcp/tools/delete-call-record",
"AI/mcp/tools/delete-channel-message",
+ "AI/mcp/tools/delete-comment",
"AI/mcp/tools/delete-database-view",
- "AI/mcp/tools/delete-document-comment",
"AI/mcp/tools/delete-import-entity",
"AI/mcp/tools/delete-initiative",
"AI/mcp/tools/delete-routine",
@@ -42,8 +43,8 @@
"AI/mcp/tools/duplicate-item",
"AI/mcp/tools/edit-booking-link",
"AI/mcp/tools/edit-channel-message",
+ "AI/mcp/tools/edit-comment",
"AI/mcp/tools/edit-document",
- "AI/mcp/tools/edit-document-comment",
"AI/mcp/tools/edit-form",
"AI/mcp/tools/edit-pipeline",
"AI/mcp/tools/edit-presentation",
@@ -108,6 +109,7 @@
"AI/mcp/tools/read-channel-thread",
"AI/mcp/tools/read-content",
"AI/mcp/tools/read-design",
+ "AI/mcp/tools/read-discussion",
"AI/mcp/tools/read-form",
"AI/mcp/tools/read-illustrator-document",
"AI/mcp/tools/read-initiative",
@@ -124,7 +126,7 @@
"AI/mcp/tools/rename-channel",
"AI/mcp/tools/rename-document",
"AI/mcp/tools/rename-item",
- "AI/mcp/tools/resolve-document-comment",
+ "AI/mcp/tools/resolve-comment",
"AI/mcp/tools/run-routine",
"AI/mcp/tools/save-database-query",
"AI/mcp/tools/save-database-view",
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index 0e37114564..00fc4c79c7 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -76,7 +76,8 @@
"AI/mcp/tools/bulk-set-entity-property-options",
"AI/mcp/tools/calculate-spreadsheet",
"AI/mcp/tools/change-booking",
- "AI/mcp/tools/comment-on-document",
+ "AI/mcp/tools/comment",
+ "AI/mcp/tools/comment-on-text",
"AI/mcp/tools/configure-agent",
"AI/mcp/tools/configure-bot",
"AI/mcp/tools/content-search",
@@ -102,8 +103,8 @@
"AI/mcp/tools/delete-calendar-event",
"AI/mcp/tools/delete-call-record",
"AI/mcp/tools/delete-channel-message",
+ "AI/mcp/tools/delete-comment",
"AI/mcp/tools/delete-database-view",
- "AI/mcp/tools/delete-document-comment",
"AI/mcp/tools/delete-import-entity",
"AI/mcp/tools/delete-initiative",
"AI/mcp/tools/delete-routine",
@@ -113,8 +114,8 @@
"AI/mcp/tools/duplicate-item",
"AI/mcp/tools/edit-booking-link",
"AI/mcp/tools/edit-channel-message",
+ "AI/mcp/tools/edit-comment",
"AI/mcp/tools/edit-document",
- "AI/mcp/tools/edit-document-comment",
"AI/mcp/tools/edit-form",
"AI/mcp/tools/edit-pipeline",
"AI/mcp/tools/edit-presentation",
@@ -179,6 +180,7 @@
"AI/mcp/tools/read-channel-thread",
"AI/mcp/tools/read-content",
"AI/mcp/tools/read-design",
+ "AI/mcp/tools/read-discussion",
"AI/mcp/tools/read-form",
"AI/mcp/tools/read-illustrator-document",
"AI/mcp/tools/read-initiative",
@@ -195,7 +197,7 @@
"AI/mcp/tools/rename-channel",
"AI/mcp/tools/rename-document",
"AI/mcp/tools/rename-item",
- "AI/mcp/tools/resolve-document-comment",
+ "AI/mcp/tools/resolve-comment",
"AI/mcp/tools/run-routine",
"AI/mcp/tools/save-database-query",
"AI/mcp/tools/save-database-view",
diff --git a/apps/web/src/features/block-agent/state/tool-approval-wording.ts b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
index ca8fa1e1e0..02b822f203 100644
--- a/apps/web/src/features/block-agent/state/tool-approval-wording.ts
+++ b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
@@ -19,7 +19,8 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
`change property options in ${whose} workspace`,
CalculateSpreadsheet: (whose) => `calculate in ${whose} spreadsheets`,
ChangeBooking: (whose) => `change a booking on ${whose} calendar`,
- CommentOnDocument: (whose) => `comment on ${whose} documents`,
+ Comment: (whose) => `comment on ${whose} items`,
+ CommentOnText: (whose) => `comment on ${whose} documents`,
ConfigureAgent: (whose) => `change ${whose} agents`,
ConfigureBot: (whose) => `change ${whose} bots`,
ContentSearch: (whose) => `search ${whose} workspace`,
@@ -44,7 +45,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
DeleteCallRecord: (whose) => `delete ${whose} calls`,
DeleteChannelMessage: (whose) => `delete messages from ${whose} account`,
DeleteDatabaseView: (whose) => `delete a view from ${whose} databases`,
- DeleteDocumentComment: (whose) => `delete comments on ${whose} documents`,
+ DeleteComment: (whose) => `delete comments on ${whose} items`,
DeleteImportEntity: (whose) => `delete an import from ${whose} workspace`,
DeleteInitiative: (whose) => `delete ${whose} initiatives`,
DeleteRoutine: (whose) => `delete ${whose} routines`,
@@ -58,7 +59,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
EditBookingLink: (whose) => `edit ${whose} booking links`,
EditChannelMessage: (whose) => `edit messages from ${whose} account`,
EditDocument: (whose) => `edit ${whose} documents`,
- EditDocumentComment: (whose) => `edit comments on ${whose} documents`,
+ EditComment: (whose) => `edit comments on ${whose} items`,
EditForm: (whose) => `edit ${whose} forms`,
EditPipeline: (whose) => `change ${whose} pipelines`,
EditPresentation: (whose) => `edit ${whose} presentations`,
@@ -131,6 +132,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
ReadAgentSession: (whose) => `read ${whose} agent sessions`,
ReadChat: (whose) => `read ${whose} chats`,
ReadContent: (whose) => `read ${whose} documents`,
+ ReadDiscussion: (whose) => `read comments on ${whose} items`,
ReadDesign: (whose) => `read ${whose} designs`,
ReadForm: (whose) => `read ${whose} forms`,
ReadIllustratorDocument: (whose) => `read ${whose} Illustrator files`,
@@ -149,7 +151,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
RenameChannel: (whose) => `rename ${whose} channels`,
RenameDocument: (whose) => `rename ${whose} documents`,
RenameItem: (whose) => `rename items in ${whose} workspace`,
- ResolveDocumentComment: (whose) => `resolve comments on ${whose} documents`,
+ ResolveComment: (whose) => `resolve or reopen comments on ${whose} items`,
RunRoutine: (whose) => `run ${whose} routines`,
SaveDatabaseQuery: (whose) => `save a query in ${whose} databases`,
SaveDatabaseView: (whose) => `save a view in ${whose} databases`,
diff --git a/apps/web/src/lib/core/component/AI/component/tool/Comments.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/Comments.test.tsx
new file mode 100644
index 0000000000..ad150a4d8f
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/Comments.test.tsx
@@ -0,0 +1,162 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import type { Component, JSX, ParentProps } from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+import { afterEach, expect, it, vi } from 'vitest';
+import {
+ commentHandler,
+ commentOnTextHandler,
+ deleteCommentHandler,
+ readDiscussionHandler,
+} from './Comments';
+
+vi.mock('@core/component/ItemPreview', () => ({
+ ItemPreview: (props: { id: string; type: string }) => (
+ <span data-item-type={props.type}>{props.id}</span>
+ ),
+}));
+vi.mock('@ui', () => ({
+ Layer: (props: ParentProps) => props.children,
+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button
+ type="button"
+ onClick={props.onClick}
+ aria-expanded={props['aria-expanded']}
+ >
+ {props.children}
+ </button>
+ ),
+}));
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+const initiativeId = '01992d2f-8444-7000-8000-000000000001';
+const documentId = '01992d2f-8444-7000-8000-000000000002';
+const companyId = '01992d2f-8444-7000-8000-000000000003';
+const threadId = '01992d2f-8444-7000-8000-000000000007';
+const commentId = '01992d2f-8444-7000-8000-000000000008';
+
+const handlers = {
+ Comment: commentHandler,
+ CommentOnText: commentOnTextHandler,
+ DeleteComment: deleteCommentHandler,
+ ReadDiscussion: readDiscussionHandler,
+};
+
+function tool(name: keyof typeof handlers, data: unknown, response?: unknown) {
+ return render(() => (
+ <Dynamic
+ component={handlers[name].render as Component<Record<string, unknown>>}
+ tool={{ name, data }}
+ response={response === undefined ? undefined : { name, data: response }}
+ renderContext={{
+ isStreaming: response === undefined,
+ grouped: false,
+ followedBy: () => false,
+ }}
+ />
+ ));
+}
+
+it('names the item a reply landed on once the response carries it', () => {
+ tool('Comment', { threadId, content: 'Done.' });
+ expect(
+ screen.getByText('Reply to a comment on a comment thread')
+ ).toBeTruthy();
+ cleanup();
+
+ tool(
+ 'Comment',
+ { threadId, content: 'Done.' },
+ { entityType: 'initiative', entityId: initiativeId, threadId, commentId }
+ );
+ expect(screen.getByText('Replied to a comment on')).toBeTruthy();
+ expect(screen.getByText(initiativeId).getAttribute('data-item-type')).toBe(
+ 'initiative'
+ );
+ fireEvent.click(screen.getByRole('button'));
+ expect(screen.getByText('Done.')).toBeTruthy();
+});
+
+it('shows a new comment on the item it was addressed to', () => {
+ tool('Comment', {
+ entityType: 'crm_company',
+ entityId: companyId,
+ content: 'Renewal is due.',
+ });
+ expect(screen.getByText('Comment on')).toBeTruthy();
+ expect(screen.getByText(companyId).getAttribute('data-item-type')).toBe(
+ 'crm_company'
+ );
+});
+
+it('keeps the quoted passage with an inline comment', () => {
+ tool(
+ 'CommentOnText',
+ { documentId, quote: 'ships on Friday', content: 'Still right?' },
+ { documentId, threadId, commentId: threadId, markedText: 'ships on Friday' }
+ );
+ expect(screen.getByText('Commented on text in')).toBeTruthy();
+ expect(screen.getByText(documentId).getAttribute('data-item-type')).toBe(
+ 'document'
+ );
+ fireEvent.click(screen.getByRole('button'));
+ expect(screen.getByText('ships on Friday')).toBeTruthy();
+ expect(screen.getByText('Still right?')).toBeTruthy();
+});
+
+it('lists every thread of a discussion with its comments', () => {
+ tool('ReadDiscussion', { entityType: 'crm_company', entityId: companyId });
+ expect(screen.queryByRole('button')).toBeNull();
+ cleanup();
+
+ tool(
+ 'ReadDiscussion',
+ { entityType: 'crm_company', entityId: companyId },
+ {
+ entityType: 'crm_company',
+ entityId: companyId,
+ threads: [
+ {
+ id: threadId,
+ resolved: true,
+ comments: [
+ {
+ id: threadId,
+ author: 'macro|[email protected]',
+ content: 'First comment',
+ createdAt: '2026-10-21T12:00:00Z',
+ },
+ {
+ id: commentId,
+ author: 'macro|[email protected]',
+ createdAt: '2026-10-21T12:05:00Z',
+ },
+ ],
+ },
+ ],
+ }
+ );
+ fireEvent.click(screen.getByRole('button'));
+ expect(screen.getByText('First comment')).toBeTruthy();
+ expect(screen.getByText('Deleted comment')).toBeTruthy();
+ expect(screen.getByText('Resolved')).toBeTruthy();
+});
+
+it('says when a whole thread was deleted', () => {
+ tool(
+ 'DeleteComment',
+ { commentId: threadId },
+ {
+ entityType: 'document',
+ entityId: documentId,
+ commentId: threadId,
+ deletedThread: true,
+ }
+ );
+ expect(screen.getByText(/Deleted a comment thread on/)).toBeTruthy();
+ expect(screen.getByText(documentId).getAttribute('data-item-type')).toBe(
+ 'document'
+ );
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/Comments.tsx b/apps/web/src/lib/core/component/AI/component/tool/Comments.tsx
new file mode 100644
index 0000000000..dd518bb56f
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/Comments.tsx
@@ -0,0 +1,317 @@
+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 ChatsCircle from '@phosphor-icons/core/regular/chats-circle.svg';
+import CheckCircle from '@phosphor-icons/core/regular/check-circle.svg';
+import PencilSimple from '@phosphor-icons/core/regular/pencil-simple.svg';
+import Trash from '@phosphor-icons/core/regular/trash.svg';
+import type { ItemType } from '@service-storage/itemType';
+import { createSignal, For, Show, Suspense } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { Tool } from './Tool';
+import { createToolRenderer } from './ToolRenderer';
+
+/** The preview type of each kind of item that carries a Discussion. */
+const ITEM_TYPES: Record<string, ItemType> = {
+ document: 'document',
+ initiative: 'initiative',
+ crm_company: 'crm_company',
+ crm_contact: 'crm_contact',
+};
+
+function discussionItem(
+ entityType: string | null | undefined,
+ entityId: string | null | undefined
+): { id: string; type: ItemType } | undefined {
+ if (!entityType || !entityId) return undefined;
+ const type = ITEM_TYPES[entityType];
+ return type ? { id: entityId, type } : undefined;
+}
+
+/** The item a comment is on, once it is known; a reply by thread id learns it from the response. */
+function ItemLink(props: {
+ item: { id: string; type: ItemType } | undefined;
+ fallback: string;
+}) {
+ return (
+ <Show when={props.item} fallback={props.fallback}>
+ {(item) => (
+ <Suspense>
+ <ItemPreview
+ class="inline-flex align-middle ring-0"
+ id={item().id}
+ type={item().type}
+ />
+ </Suspense>
+ )}
+ </Show>
+ );
+}
+
+function CommentBody(props: { markedText?: string; content: string }) {
+ return (
+ <div class="flex flex-col gap-2 rounded-lg border border-edge-muted bg-ink/[0.02] p-3 text-xs text-ink">
+ <Show when={props.markedText}>
+ {(text) => (
+ <blockquote class="whitespace-pre-wrap break-words border-l-2 border-edge-muted pl-2 text-ink-muted">
+ {text()}
+ </blockquote>
+ )}
+ </Show>
+ <p class="whitespace-pre-wrap break-words">{props.content}</p>
+ </div>
+ );
+}
+
+export const readDiscussionHandler = createToolRenderer({
+ name: 'ReadDiscussion',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const threads = () => ctx.response?.data.threads ?? [];
+ const item = () =>
+ discussionItem(ctx.tool.data.entityType, ctx.tool.data.entityId);
+
+ return (
+ <BaseTool
+ icon={ChatsCircle}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() ? (
+ <div class="flex flex-col gap-3 rounded-lg border border-edge-muted bg-ink/[0.02] p-3 text-xs text-ink">
+ <For each={threads()}>
+ {(thread) => (
+ <div class="flex flex-col gap-1">
+ <Show when={thread.markedText}>
+ {(text) => (
+ <blockquote class="whitespace-pre-wrap break-words border-l-2 border-edge-muted pl-2 text-ink-muted">
+ {text()}
+ </blockquote>
+ )}
+ </Show>
+ <For each={thread.comments}>
+ {(comment) => (
+ <p class="whitespace-pre-wrap break-words">
+ {comment.content ?? 'Deleted comment'}
+ </p>
+ )}
+ </For>
+ <Show when={thread.resolved}>
+ <span class="text-ink-muted">Resolved</span>
+ </Show>
+ </div>
+ )}
+ </For>
+ </div>
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span class="min-w-0">
+ {ctx.response ? 'Read the discussion on' : 'Read the discussion on'}{' '}
+ <ItemLink item={item()} fallback="an item" />
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={threads().length > 0}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const commentHandler = createToolRenderer({
+ name: 'Comment',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const reply = () => ctx.tool.data.threadId != null;
+ const item = () =>
+ discussionItem(
+ ctx.response?.data.entityType ?? ctx.tool.data.entityType,
+ ctx.response?.data.entityId ?? ctx.tool.data.entityId
+ );
+ const verb = () => {
+ if (reply())
+ return ctx.response
+ ? 'Replied to a comment on'
+ : 'Reply to a comment on';
+ return ctx.response ? 'Commented on' : 'Comment on';
+ };
+
+ return (
+ <BaseTool
+ icon={ChatCircle}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() ? (
+ <CommentBody content={ctx.tool.data.content} />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span class="min-w-0">
+ {verb()}{' '}
+ <ItemLink
+ item={item()}
+ fallback={reply() ? 'a comment thread' : 'an item'}
+ />
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!ctx.tool.data.content}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const commentOnTextHandler = createToolRenderer({
+ name: 'CommentOnText',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const markedText = () =>
+ ctx.response?.data.markedText ?? ctx.tool.data.quote;
+
+ return (
+ <BaseTool
+ icon={ChatCircle}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() ? (
+ <CommentBody
+ markedText={markedText()}
+ content={ctx.tool.data.content}
+ />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span class="min-w-0">
+ {ctx.response ? 'Commented on text in' : 'Comment on text in'}{' '}
+ <ItemLink
+ item={{ id: ctx.tool.data.documentId, type: 'document' }}
+ fallback="a document"
+ />
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!ctx.tool.data.content}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const resolveCommentHandler = createToolRenderer({
+ name: 'ResolveComment',
+ render: (ctx) => {
+ const resolving = () => ctx.tool.data.resolved !== false;
+ const verb = () => {
+ if (resolving()) return ctx.response ? 'Resolved' : 'Resolve';
+ return ctx.response ? 'Reopened' : 'Reopen';
+ };
+ const item = () =>
+ discussionItem(
+ ctx.response?.data.entityType,
+ ctx.response?.data.entityId
+ );
+
+ return (
+ <BaseTool
+ icon={resolving() ? CheckCircle : ArrowCounterClockwise}
+ renderContext={ctx.renderContext}
+ type="call"
+ >
+ <div class="min-w-0 flex-1">
+ {verb()} a comment{' '}
+ <Show when={item()}>
+ {(item) => (
+ <>
+ on <ItemLink item={item()} fallback="" />
+ </>
+ )}
+ </Show>
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const editCommentHandler = createToolRenderer({
+ name: 'EditComment',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const item = () =>
+ discussionItem(
+ ctx.response?.data.entityType,
+ ctx.response?.data.entityId
+ );
+
+ return (
+ <BaseTool
+ icon={PencilSimple}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() ? (
+ <CommentBody content={ctx.tool.data.content} />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span class="min-w-0">
+ {ctx.response ? 'Edited a comment' : 'Edit a comment'}{' '}
+ <Show when={item()}>
+ {(item) => (
+ <>
+ on <ItemLink item={item()} fallback="" />
+ </>
+ )}
+ </Show>
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!ctx.tool.data.content}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
+export const deleteCommentHandler = createToolRenderer({
+ name: 'DeleteComment',
+ render: (ctx) => {
+ const noun = () =>
+ ctx.response?.data.deletedThread ? 'a comment thread' : 'a comment';
+ const item = () =>
+ discussionItem(
+ ctx.response?.data.entityType,
+ ctx.response?.data.entityId
+ );
+
+ return (
+ <BaseTool icon={Trash} renderContext={ctx.renderContext} type="call">
+ <div class="min-w-0 flex-1">
+ {ctx.response ? 'Deleted' : 'Delete'} {noun()}{' '}
+ <Show when={item()}>
+ {(item) => (
+ <>
+ on <ItemLink item={item()} fallback="" />
+ </>
+ )}
+ </Show>
+ </div>
+ </BaseTool>
+ );
+ },
+});
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.tsx
deleted file mode 100644
index 8257504714..0000000000
--- a/apps/web/src/lib/core/component/AI/component/tool/DocumentComments.tsx
+++ /dev/null
@@ -1,151 +0,0 @@
-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 PencilSimple from '@phosphor-icons/core/regular/pencil-simple.svg';
-import Trash from '@phosphor-icons/core/regular/trash.svg';
-import { createSignal, Show, 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 commentOnDocumentHandler = createToolRenderer({
- name: 'CommentOnDocument',
- render: (ctx) => {
- const [expanded, setExpanded] = createSignal(false);
- const markedText = () =>
- ctx.response?.data.markedText ?? ctx.tool.data.quote;
-
- const verb = () => {
- if (ctx.tool.data.threadId != null)
- return ctx.response
- ? 'Replied to a comment on'
- : 'Reply to a comment on';
- if (ctx.tool.data.quote != null)
- return ctx.response ? 'Commented on text in' : 'Comment on text in';
- return ctx.response ? 'Commented on' : 'Comment on';
- };
-
- return (
- <BaseTool
- icon={ChatCircle}
- renderContext={ctx.renderContext}
- type="call"
- response={
- expanded() ? (
- <div class="flex flex-col gap-2 rounded-lg border border-edge-muted bg-ink/[0.02] p-3 text-xs text-ink">
- <Show when={markedText()}>
- {(text) => (
- <blockquote class="whitespace-pre-wrap break-words border-l-2 border-edge-muted pl-2 text-ink-muted">
- {text()}
- </blockquote>
- )}
- </Show>
- <p class="whitespace-pre-wrap break-words">
- {ctx.tool.data.content}
- </p>
- </div>
- ) : 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>
- );
- },
-});
-
-export const editDocumentCommentHandler = createToolRenderer({
- name: 'EditDocumentComment',
- render: (ctx) => {
- const [expanded, setExpanded] = createSignal(false);
-
- return (
- <BaseTool
- icon={PencilSimple}
- 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">
- {ctx.response ? 'Edited a comment on' : 'Edit a comment on'}{' '}
- <DocumentPreview documentId={ctx.tool.data.documentId} />
- </span>
- <Tool.ResultToggle
- expanded={expanded()}
- onToggle={() => setExpanded((value) => !value)}
- showToggle={!!ctx.tool.data.content}
- />
- </div>
- </BaseTool>
- );
- },
-});
-
-export const deleteDocumentCommentHandler = createToolRenderer({
- name: 'DeleteDocumentComment',
- render: (ctx) => {
- const noun = () =>
- ctx.response?.data.deletedThread ? 'a comment thread' : 'a comment';
-
- return (
- <BaseTool icon={Trash} renderContext={ctx.renderContext} type="call">
- <div class="min-w-0 flex-1">
- {ctx.response ? 'Deleted' : 'Delete'} {noun()} 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.tsx
index 7ec476284f..617e158183 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
@@ -74,6 +74,14 @@ import {
listCodingAgentsHandler,
} from './CodingAgents';
import { decideHandler, generateObjectHandler } from './Cognition';
+import {
+ commentHandler,
+ commentOnTextHandler,
+ deleteCommentHandler,
+ editCommentHandler,
+ readDiscussionHandler,
+ resolveCommentHandler,
+} from './Comments';
import { createDocumentHandler } from './CreateDocument';
import { createProjectHandler } from './CreateProject';
import { createSkillHandler } from './CreateSkill';
@@ -91,12 +99,6 @@ import {
} from './DesignDocument';
import { discoverConnectorsHandler } from './DiscoverConnectors';
import { displayResultsHandler } from './DisplayResults';
-import {
- commentOnDocumentHandler,
- deleteDocumentCommentHandler,
- editDocumentCommentHandler,
- resolveDocumentCommentHandler,
-} from './DocumentComments';
import { editDocumentHandler } from './EditDocument';
import { editTagHandler } from './EditTag';
import {
@@ -312,10 +314,12 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
ReadSkill: readSkillHandler,
RenameChannel: renameChannelHandler,
RenameDocument: renameDocumentHandler,
- CommentOnDocument: commentOnDocumentHandler,
- ResolveDocumentComment: resolveDocumentCommentHandler,
- EditDocumentComment: editDocumentCommentHandler,
- DeleteDocumentComment: deleteDocumentCommentHandler,
+ ReadDiscussion: readDiscussionHandler,
+ Comment: commentHandler,
+ CommentOnText: commentOnTextHandler,
+ ResolveComment: resolveCommentHandler,
+ EditComment: editCommentHandler,
+ DeleteComment: deleteCommentHandler,
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.ts
index ccc4c813ec..753c909b90 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
@@ -905,19 +905,81 @@ export const Booking = z.object({
questionLabels: z.record(z.string()).optional(),
});
-export const CommentOnDocument = z.object({
+export const Comment = z.object({
+ entityType: z
+ .union([
+ z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('initiative'),
+ z.literal('crm_company'),
+ z.literal('crm_contact'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ z.null(),
+ ])
+ .optional(),
+ entityId: z.union([z.string(), z.null()]).optional(),
+ threadId: z.union([z.string().uuid(), z.null()]).optional(),
+ content: z.string(),
+});
+
+export const CommentResponse = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('initiative'),
+ z.literal('crm_company'),
+ z.literal('crm_contact'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ entityId: z.string(),
+ threadId: z.string().uuid(),
+ commentId: z.string().uuid(),
+});
+
+export const CommentOnText = z.object({
documentId: z.string().uuid(),
content: z.string(),
- threadId: z.union([z.string().uuid(), z.null()]).optional(),
- quote: z.union([z.string(), z.null()]).optional(),
+ quote: z.string(),
occurrence: z.union([z.number().int().gte(1), z.null()]).optional(),
});
-export const CommentOnDocumentResponse = z.object({
+export const CommentOnTextResponse = z.object({
documentId: z.string().uuid(),
threadId: z.string().uuid(),
commentId: z.string().uuid(),
- markedText: z.union([z.string(), z.null()]).optional(),
+ markedText: z.string(),
});
export const ConfigureAgent = z.object({
@@ -4288,6 +4350,37 @@ export const DeleteChannelMessageResponse = z.object({
summary: z.string(),
});
+export const DeleteComment = z.object({ commentId: z.string().uuid() });
+
+export const DeleteCommentResponse = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('initiative'),
+ z.literal('crm_company'),
+ z.literal('crm_contact'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ entityId: z.string(),
+ commentId: z.string().uuid(),
+ deletedThread: z.boolean(),
+});
+
export const DeleteDatabaseView = z.object({
databaseId: z.string().uuid(),
viewId: z.string().uuid(),
@@ -4300,17 +4393,6 @@ export const DeletedDatabaseView = z.object({
name: z.string(),
});
-export const DeleteDocumentComment = z.object({
- documentId: z.string().uuid(),
- commentId: z.string().uuid(),
-});
-
-export const DeleteDocumentCommentResponse = z.object({
- documentId: z.string().uuid(),
- commentId: z.string().uuid(),
- deletedThread: z.boolean(),
-});
-
export const DeleteImportEntity = z.object({ id: z.string().uuid() });
export const DeleteImportEntityResponse = z.object({
@@ -4656,6 +4738,39 @@ export const EditChannelMessageResponse = z.object({
summary: z.string(),
});
+export const EditComment = z.object({
+ commentId: z.string().uuid(),
+ content: z.string(),
+});
+
+export const EditCommentResponse = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('initiative'),
+ z.literal('crm_company'),
+ z.literal('crm_contact'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ entityId: z.string(),
+ commentId: z.string().uuid(),
+});
+
export const EditDocument = z.object({
document_id: z.string(),
instructions: z.string(),
@@ -4667,17 +4782,6 @@ export const EditDocumentResponse = z.object({
clarification: z.union([z.string(), z.null()]).optional(),
});
-export const EditDocumentComment = z.object({
- documentId: z.string().uuid(),
- commentId: z.string().uuid(),
- content: z.string(),
-});
-
-export const EditDocumentCommentResponse = z.object({
- documentId: z.string().uuid(),
- commentId: z.string().uuid(),
-});
-
export const EditForm = z.object({
formId: z.string().uuid(),
changes: z.array(
@@ -12502,6 +12606,79 @@ export const ReadDesign = z.object({
export const ReadDesignResponse = z.object({ content: z.string() });
+export const ReadDiscussion = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('initiative'),
+ z.literal('crm_company'),
+ z.literal('crm_contact'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ entityId: z.string(),
+});
+
+export const ReadDiscussionResponse = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('initiative'),
+ z.literal('crm_company'),
+ z.literal('crm_contact'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ entityId: z.string(),
+ threads: z.array(
+ z.object({
+ id: z.string().uuid(),
+ resolved: z.boolean(),
+ markedText: z.union([z.string(), z.null()]).optional(),
+ comments: z.array(
+ z.object({
+ id: z.string().uuid(),
+ author: z.string(),
+ authorName: z.union([z.string(), z.null()]).optional(),
+ content: z.union([z.string(), z.null()]).optional(),
+ createdAt: z.string().datetime({ offset: true }),
+ editedAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
+ })
+ ),
+ })
+ ),
+});
+
export const ReadForm = z.object({
formId: z.string().uuid(),
view: z
@@ -14042,14 +14219,36 @@ export const RenameItemResponse = z.object({
name: z.string(),
});
-export const ResolveDocumentComment = z.object({
- documentId: z.string().uuid(),
+export const ResolveComment = z.object({
threadId: z.string().uuid(),
resolved: z.boolean().optional(),
});
-export const ResolveDocumentCommentResponse = z.object({
- documentId: z.string().uuid(),
+export const ResolveCommentResponse = z.object({
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('document'),
+ z.literal('initiative'),
+ z.literal('crm_company'),
+ z.literal('crm_contact'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ entityId: z.string(),
threadId: z.string().uuid(),
resolved: z.boolean(),
});
diff --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.ts
index 80b95ca599..b7d9964d39 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
@@ -26,9 +26,10 @@ type ToolParserMap = {
response: types.SpreadsheetResponse;
};
ChangeBooking: { call: types.ChangeBooking; response: types.Booking };
- CommentOnDocument: {
- call: types.CommentOnDocument;
- response: types.CommentOnDocumentResponse;
+ Comment: { call: types.Comment; response: types.CommentResponse };
+ CommentOnText: {
+ call: types.CommentOnText;
+ response: types.CommentOnTextResponse;
};
ConfigureAgent: {
call: types.ConfigureAgent;
@@ -109,14 +110,14 @@ type ToolParserMap = {
call: types.DeleteChannelMessage;
response: types.DeleteChannelMessageResponse;
};
+ DeleteComment: {
+ call: types.DeleteComment;
+ response: types.DeleteCommentResponse;
+ };
DeleteDatabaseView: {
call: types.DeleteDatabaseView;
response: types.DeletedDatabaseView;
};
- DeleteDocumentComment: {
- call: types.DeleteDocumentComment;
- response: types.DeleteDocumentCommentResponse;
- };
DeleteImportEntity: {
call: types.DeleteImportEntity;
response: types.DeleteImportEntityResponse;
@@ -159,14 +160,11 @@ type ToolParserMap = {
call: types.EditChannelMessage;
response: types.EditChannelMessageResponse;
};
+ EditComment: { call: types.EditComment; response: types.EditCommentResponse };
EditDocument: {
call: types.EditDocument;
response: types.EditDocumentResponse;
};
- EditDocumentComment: {
- call: types.EditDocumentComment;
- response: types.EditDocumentCommentResponse;
- };
EditForm: { call: types.EditForm; response: types.MutationResult };
EditPipeline: {
call: types.EditPipeline;
@@ -375,6 +373,10 @@ type ToolParserMap = {
ReadChat: { call: types.ReadChat; response: types.ReadChatResponse };
ReadContent: { call: types.ReadContent; response: types.ReadContentResponse };
ReadDesign: { call: types.ReadDesign; response: types.ReadDesignResponse };
+ ReadDiscussion: {
+ call: types.ReadDiscussion;
+ response: types.ReadDiscussionResponse;
+ };
ReadForm: { call: types.ReadForm; response: types.ReadResult };
ReadIllustratorDocument: {
call: types.ReadIllustratorDocument;
@@ -425,9 +427,9 @@ type ToolParserMap = {
response: types.RenameDocumentResponse;
};
RenameItem: { call: types.RenameItem; response: types.RenameItemResponse };
- ResolveDocumentComment: {
- call: types.ResolveDocumentComment;
- response: types.ResolveDocumentCommentResponse;
+ ResolveComment: {
+ call: types.ResolveComment;
+ response: types.ResolveCommentResponse;
};
RunRoutine: { call: types.RunRoutine; response: types.RoutineRunStarted };
SaveDatabaseQuery: {
@@ -538,9 +540,10 @@ const toolParserMap = {
response: schemas.SpreadsheetResponse,
},
ChangeBooking: { call: schemas.ChangeBooking, response: schemas.Booking },
- CommentOnDocument: {
- call: schemas.CommentOnDocument,
- response: schemas.CommentOnDocumentResponse,
+ Comment: { call: schemas.Comment, response: schemas.CommentResponse },
+ CommentOnText: {
+ call: schemas.CommentOnText,
+ response: schemas.CommentOnTextResponse,
},
ConfigureAgent: {
call: schemas.ConfigureAgent,
@@ -624,14 +627,14 @@ const toolParserMap = {
call: schemas.DeleteChannelMessage,
response: schemas.DeleteChannelMessageResponse,
},
+ DeleteComment: {
+ call: schemas.DeleteComment,
+ response: schemas.DeleteCommentResponse,
+ },
DeleteDatabaseView: {
call: schemas.DeleteDatabaseView,
response: schemas.DeletedDatabaseView,
},
- DeleteDocumentComment: {
- call: schemas.DeleteDocumentComment,
- response: schemas.DeleteDocumentCommentResponse,
- },
DeleteImportEntity: {
call: schemas.DeleteImportEntity,
response: schemas.DeleteImportEntityResponse,
@@ -677,14 +680,14 @@ const toolParserMap = {
call: schemas.EditChannelMessage,
response: schemas.EditChannelMessageResponse,
},
+ EditComment: {
+ call: schemas.EditComment,
+ response: schemas.EditCommentResponse,
+ },
EditDocument: {
call: schemas.EditDocument,
response: schemas.EditDocumentResponse,
},
- EditDocumentComment: {
- call: schemas.EditDocumentComment,
- response: schemas.EditDocumentCommentResponse,
- },
EditForm: { call: schemas.EditForm, response: schemas.MutationResult },
EditPipeline: {
call: schemas.EditPipeline,
@@ -926,6 +929,10 @@ const toolParserMap = {
call: schemas.ReadDesign,
response: schemas.ReadDesignResponse,
},
+ ReadDiscussion: {
+ call: schemas.ReadDiscussion,
+ response: schemas.ReadDiscussionResponse,
+ },
ReadForm: { call: schemas.ReadForm, response: schemas.ReadResult },
ReadIllustratorDocument: {
call: schemas.ReadIllustratorDocument,
@@ -982,9 +989,9 @@ const toolParserMap = {
call: schemas.RenameItem,
response: schemas.RenameItemResponse,
},
- ResolveDocumentComment: {
- call: schemas.ResolveDocumentComment,
- response: schemas.ResolveDocumentCommentResponse,
+ ResolveComment: {
+ call: schemas.ResolveComment,
+ response: schemas.ResolveCommentResponse,
},
RunRoutine: { call: schemas.RunRoutine, response: schemas.RoutineRunStarted },
SaveDatabaseQuery: {
@@ -1115,9 +1122,10 @@ type ToolDataMap = {
response: types.SpreadsheetResponse;
};
ChangeBooking: { call: types.ChangeBooking; response: types.Booking };
- CommentOnDocument: {
- call: types.CommentOnDocument;
- response: types.CommentOnDocumentResponse;
+ Comment: { call: types.Comment; response: types.CommentResponse };
+ CommentOnText: {
+ call: types.CommentOnText;
+ response: types.CommentOnTextResponse;
};
ConfigureAgent: {
call: types.ConfigureAgent;
@@ -1198,14 +1206,14 @@ type ToolDataMap = {
call: types.DeleteChannelMessage;
response: types.DeleteChannelMessageResponse;
};
+ DeleteComment: {
+ call: types.DeleteComment;
+ response: types.DeleteCommentResponse;
+ };
DeleteDatabaseView: {
call: types.DeleteDatabaseView;
response: types.DeletedDatabaseView;
};
- DeleteDocumentComment: {
- call: types.DeleteDocumentComment;
- response: types.DeleteDocumentCommentResponse;
- };
DeleteImportEntity: {
call: types.DeleteImportEntity;
response: types.DeleteImportEntityResponse;
@@ -1248,14 +1256,11 @@ type ToolDataMap = {
call: types.EditChannelMessage;
response: types.EditChannelMessageResponse;
};
+ EditComment: { call: types.EditComment; response: types.EditCommentResponse };
EditDocument: {
call: types.EditDocument;
response: types.EditDocumentResponse;
};
- EditDocumentComment: {
- call: types.EditDocumentComment;
- response: types.EditDocumentCommentResponse;
- };
EditForm: { call: types.EditForm; response: types.MutationResult };
EditPipeline: {
call: types.EditPipeline;
@@ -1464,6 +1469,10 @@ type ToolDataMap = {
ReadChat: { call: types.ReadChat; response: types.ReadChatResponse };
ReadContent: { call: types.ReadContent; response: types.ReadContentResponse };
ReadDesign: { call: types.ReadDesign; response: types.ReadDesignResponse };
+ ReadDiscussion: {
+ call: types.ReadDiscussion;
+ response: types.ReadDiscussionResponse;
+ };
ReadForm: { call: types.ReadForm; response: types.ReadResult };
ReadIllustratorDocument: {
call: types.ReadIllustratorDocument;
@@ -1514,9 +1523,9 @@ type ToolDataMap = {
response: types.RenameDocumentResponse;
};
RenameItem: { call: types.RenameItem; response: types.RenameItemResponse };
- ResolveDocumentComment: {
- call: types.ResolveDocumentComment;
- response: types.ResolveDocumentCommentResponse;
+ ResolveComment: {
+ call: types.ResolveComment;
+ response: types.ResolveCommentResponse;
};
RunRoutine: { call: types.RunRoutine; response: types.RoutineRunStarted };
SaveDatabaseQuery: {
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.ts
index 9102a60369..8b06181a18 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
@@ -209,6 +209,14 @@ export type BookingStatus =
| 'cancelled'
| 'processing'
| 'failed';
+/**
+ * The kinds of item that carry a Discussion.
+ */
+export type DiscussionParentType =
+ | 'document'
+ | 'initiative'
+ | 'crm_company'
+ | 'crm_contact';
/**
* The runtimes an agent can be moved onto.
*/
@@ -5554,9 +5562,48 @@ export interface Booking {
};
}
/**
- * Comment on a document on behalf of the user. Pass threadId to reply in an existing inline or Discussion thread; pass quote to start a new inline comment on a passage of a Macro markdown or Word (DOCX) document; omit both to start a new Discussion comment on the document as a whole. Replies and Discussion comments support any document type. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. For an inline comment, quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. Do not combine threadId with quote. occurrence only applies with quote. Comments made here stay in Macro and are not written into a Word file; for comments that must travel with a Word document to its recipient (a redline for a counterparty), use EditWordDocument's addComment operation instead.
+ * Add a comment to the Discussion of a document, task, Tasks project (initiative), CRM company or CRM contact on behalf of the user, or reply in an existing comment thread on any of them. For a new comment, address the item by entityType and entityId. For a reply, pass threadId; a thread id is enough to find its item, so entityType and entityId may be omitted. Thread ids come from ReadDiscussion, or from ReadContent for a document. Only use this when explicitly asked to comment or reply. Write content in Macro markdown and link people and items with the same mention tags as in documents; they render as chips and notify the people mentioned. To comment on a passage of text in a document, use CommentOnText instead; for a message in a channel, use SendChannelMessage.
+ */
+export interface Comment {
+ /**
+ * The kind of item to comment on. Required with entityId for a new comment; optional for a reply.
+ */
+ entityType?: DiscussionParentType | null;
+ /**
+ * The id of the item to comment on. Required with entityType for a new comment; optional for a reply.
+ */
+ entityId?: string | null;
+ /**
+ * The id of the thread to reply in. Omit to start a new Discussion comment on the item.
+ */
+ threadId?: string | null;
+ /**
+ * Comment content in Macro markdown, the same syntax as markdown documents, including mention tags.
+ */
+ content: string;
+}
+/**
+ * The posted comment.
+ */
+export interface CommentResponse {
+ entityType: DiscussionParentType;
+ /**
+ * The item the comment is on.
+ */
+ entityId: string;
+ /**
+ * The thread the comment is in; a new comment starts its own.
+ */
+ threadId: string;
+ /**
+ * The posted comment.
+ */
+ commentId: string;
+}
+/**
+ * Start an inline comment on a passage of a Macro markdown or Word (DOCX) document on behalf of the user, anchored to the quoted text. Only use this when explicitly asked to comment on specific text. Quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. For a comment on a document as a whole, or a reply in an existing thread, use Comment. Comments made here stay in Macro and are not written into a Word file; for comments that must travel with a Word document to its recipient (a redline for a counterparty), use EditWordDocument's addComment operation instead.
*/
-export interface CommentOnDocument {
+export interface CommentOnText {
/**
* The id of the document to comment on.
*/
@@ -5566,28 +5613,24 @@ export interface CommentOnDocument {
*/
content: string;
/**
- * The id of the inline or Discussion thread to reply in, from ReadContent. Cannot be combined with quote. Omit both threadId and quote to post a new Discussion comment on the document as a whole.
- */
- threadId?: string | null;
- /**
- * The passage to comment on, quoted exactly as the document reads: plain text without markdown syntax such as ** or link brackets. Keep it to the words the comment is about; a longer quote is more likely to be unique. Starts a new inline comment on a markdown or Word (DOCX) document. Cannot be combined with threadId.
+ * The passage to comment on, quoted exactly as the document reads: plain text without markdown syntax such as ** or link brackets. Keep it to the words the comment is about; a longer quote is more likely to be unique.
*/
- quote?: string | null;
+ quote: string;
/**
- * Which appearance of the quoted passage to comment on, counting from 1 in document order. Only applies with quote; only needed when the passage appears more than once.
+ * Which appearance of the quoted passage to comment on, counting from 1 in document order. Only needed when the passage appears more than once.
*/
occurrence?: number | null;
}
/**
* The posted comment.
*/
-export interface CommentOnDocumentResponse {
+export interface CommentOnTextResponse {
/**
* The document the comment was posted on.
*/
documentId: string;
/**
- * The thread the comment is in; a new comment starts its own.
+ * The thread the comment starts.
*/
threadId: string;
/**
@@ -5595,9 +5638,9 @@ export interface CommentOnDocumentResponse {
*/
commentId: string;
/**
- * The text the new inline comment is anchored to, as the document reads.
+ * The text the comment is anchored to, as the document reads.
*/
- markedText?: string | null;
+ markedText: string;
}
/**
* Update the instructions or settings of an AI agent the current user can manage. Provide only the fields that should change; everything else keeps its current value. Read the agent first with ListAgents: instructions are replaced whole, so to edit them, apply the edit to the current text and pass the complete result. Changes apply to sessions opened afterwards; running sessions keep the instructions they started with. Use ConfigureBot for the display name, handle, description, or picture, and ManageBotChannelAccess for plain webhook bots.
@@ -8096,6 +8139,33 @@ export interface DeleteChannelMessageResponse {
*/
summary: string;
}
+/**
+ * Delete a comment or reply in the Discussion of a document, task, Tasks project, CRM company or CRM contact. Deleting the first comment of a thread deletes the whole thread with its replies. Authors can delete their own comments, and the item's owner can delete any comment. This cannot be undone. A comment id is enough to find its item. Comment ids come from ReadDiscussion, or from ReadContent for a document. Use only when the user explicitly asks to delete a comment; use ResolveComment to close a thread instead.
+ */
+export interface DeleteComment {
+ /**
+ * The id of the comment or reply to delete. Pass the thread id to delete the whole thread.
+ */
+ commentId: string;
+}
+/**
+ * The deleted comment.
+ */
+export interface DeleteCommentResponse {
+ entityType: DiscussionParentType;
+ /**
+ * The item the comment was on.
+ */
+ entityId: string;
+ /**
+ * The deleted comment.
+ */
+ commentId: string;
+ /**
+ * Whether the whole thread was deleted.
+ */
+ deletedThread: boolean;
+}
/**
* Delete a saved table or board view of a Macro database by its id, from DescribeDatabase. Views are shared with everyone who can open the database, so deleting one needs edit access and removes it for everyone. The table and its records stay; a board's hand-arranged card order goes with it. Only do it when the user asked for that view to go.
*/
@@ -8130,36 +8200,6 @@ export interface DeletedDatabaseView {
*/
name: string;
}
-/**
- * Delete a comment or reply on a document. Deleting the first comment of a thread deletes the whole thread with its replies. Authors can delete their own comments, and the document owner can delete any comment. This cannot be undone. Comment ids come from the comments ReadContent returns. Use only when the user explicitly asks to delete a comment; use ResolveDocumentComment to close a thread instead.
- */
-export interface DeleteDocumentComment {
- /**
- * The id of the document the comment is on.
- */
- documentId: string;
- /**
- * The id of the comment or reply to delete, from ReadContent. Pass the thread id to delete the whole thread.
- */
- commentId: string;
-}
-/**
- * The deleted comment.
- */
-export interface DeleteDocumentCommentResponse {
- /**
- * The document the comment was on.
- */
- documentId: string;
- /**
- * The deleted comment.
- */
- commentId: string;
- /**
- * Whether the whole thread was deleted.
- */
- deletedThread: boolean;
-}
/**
* Decline a staged import candidate on the user's behalf. The item is remembered as declined so it won't be proposed again; only the user's own staged items can be declined.
*/
@@ -8556,6 +8596,33 @@ export interface EditChannelMessageResponse {
*/
summary: string;
}
+/**
+ * Replace the text of a comment or reply in the Discussion of a document, task, Tasks project, CRM company or CRM contact. Only a comment's author can edit it, so this edits comments the user wrote and comments this assistant wrote for them. A comment id is enough to find its item. Comment ids come from ReadDiscussion, or from ReadContent for a document. Use only when the user asks to edit a comment.
+ */
+export interface EditComment {
+ /**
+ * The id of the comment or reply to edit. For the first comment of a thread this is the thread id.
+ */
+ commentId: string;
+ /**
+ * The full replacement text of the comment, in Macro markdown.
+ */
+ content: string;
+}
+/**
+ * The edited comment.
+ */
+export interface EditCommentResponse {
+ entityType: DiscussionParentType;
+ /**
+ * The item the comment is on.
+ */
+ entityId: string;
+ /**
+ * The edited comment.
+ */
+ commentId: string;
+}
/**
* Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips; profileId/slug/url for booking links. To insert document-card(s), include each document's documentId and documentName.
*/
@@ -8584,36 +8651,6 @@ export interface EditDocumentResponse {
*/
clarification?: string | null;
}
-/**
- * Replace the text of a comment or reply on a document. Only a comment's author can edit it, so this edits comments the user wrote and comments this assistant wrote for them. Comment ids come from the comments ReadContent returns. Use only when the user asks to edit a comment.
- */
-export interface EditDocumentComment {
- /**
- * The id of the document the comment is on.
- */
- documentId: string;
- /**
- * The id of the comment or reply to edit, from ReadContent. For the first comment of a thread this is the thread id.
- */
- commentId: string;
- /**
- * The full replacement text of the comment, in markdown.
- */
- content: string;
-}
-/**
- * The edited comment.
- */
-export interface EditDocumentCommentResponse {
- /**
- * The document the comment is on.
- */
- documentId: string;
- /**
- * The edited comment.
- */
- commentId: string;
-}
/**
* Edit the live form using typed targeted operations. ReadForm provides stable question/section IDs. Edits produce granular CRDT updates; concurrent changes merge using the same rules as the builder. Omitted fields stay unchanged. Invalid merged layouts are refused. Changes can add or move questions/sections, edit requiredness/help/screeners and attach an existing booking target. New columns use explicit stable IDs. Question labels follow backing column names; rename them through database tools. Removing a question keeps its column and answers. Schema retyping and conditional column cleanup are unsupported. Keep screeners after the questions they test and booking last. Read the current form after a timeout or partial result before proceeding. Opening and sharing require SetFormAccess.
*/
@@ -9397,7 +9434,7 @@ export interface EditTagResponse {
summary: string;
}
/**
- * Edit an uploaded Word (.docx) document in place: an ordered batch of operations applied atomically to its live copy, so everyone with it open sees the change at once, and nothing changes if any operation fails. ReadWordDocument first and address paragraphs, tables and blocks by the ids it reports (they are not numbers). Use replaceText for wording changes (exact text within one paragraph; formatting is kept), setText to rewrite a whole paragraph, formatText for bold, italic, underline or strikethrough, insertParagraph to add paragraphs (each line of text becomes one; a style is optional), setStyle to change a paragraph style such as Heading1, delete to remove a paragraph, table or block, and addComment to add a Word comment on text. Only insertParagraph and addComment text may contain line breaks. Paragraphs inside table cells are edited the same way. Tracked changes (a redline): with trackChanges true, or when the document already tracks changes and trackChanges is omitted, edits are recorded as real Word revisions (insertions, deletions, formatting and style changes) that the counterparty can accept or reject in Word; pass trackChanges true whenever the user asks for a redline, tracked changes or a markup. Revisions and addComment comments are attributed to the requesting user by name, not to you; pass author only when the user names someone else (a firm or another person). addComment comments are saved in the file and travel with it to Word; use them for comments meant for whoever receives the document, and CommentOnDocument for discussion inside Macro. Returns the changed blocks as they now read, with the ids of new paragraphs; check them. At most 50 operations.
+ * Edit an uploaded Word (.docx) document in place: an ordered batch of operations applied atomically to its live copy, so everyone with it open sees the change at once, and nothing changes if any operation fails. ReadWordDocument first and address paragraphs, tables and blocks by the ids it reports (they are not numbers). Use replaceText for wording changes (exact text within one paragraph; formatting is kept), setText to rewrite a whole paragraph, formatText for bold, italic, underline or strikethrough, insertParagraph to add paragraphs (each line of text becomes one; a style is optional), setStyle to change a paragraph style such as Heading1, delete to remove a paragraph, table or block, and addComment to add a Word comment on text. Only insertParagraph and addComment text may contain line breaks. Paragraphs inside table cells are edited the same way. Tracked changes (a redline): with trackChanges true, or when the document already tracks changes and trackChanges is omitted, edits are recorded as real Word revisions (insertions, deletions, formatting and style changes) that the counterparty can accept or reject in Word; pass trackChanges true whenever the user asks for a redline, tracked changes or a markup. Revisions and addComment comments are attributed to the requesting user by name, not to you; pass author only when the user names someone else (a firm or another person). addComment comments are saved in the file and travel with it to Word; use them for comments meant for whoever receives the document, and Comment or CommentOnText for discussion inside Macro. Returns the changed blocks as they now read, with the ids of new paragraphs; check them. At most 50 operations.
*/
export interface EditWordDocument {
/**
@@ -13213,6 +13250,83 @@ export interface ReadDesignResponse {
*/
content: string;
}
+/**
+ * Read the comment threads in the Discussion of a document, task, Tasks project (initiative), CRM company or CRM contact: each thread's id, resolved state and comments, with their ids, authors and text, oldest thread first. Thread and comment ids are what Comment, EditComment, DeleteComment and ResolveComment take. For a document, ReadContent returns the same threads alongside the content, with the live text each inline comment is on.
+ */
+export interface ReadDiscussion {
+ entityType: DiscussionParentType;
+ /**
+ * The id of the item.
+ */
+ entityId: string;
+}
+/**
+ * The item's Discussion.
+ */
+export interface ReadDiscussionResponse {
+ entityType: DiscussionParentType;
+ /**
+ * The item.
+ */
+ entityId: string;
+ /**
+ * The live threads, oldest first.
+ */
+ threads: DiscussionThread[];
+}
+/**
+ * A comment thread: its first comment followed by the replies.
+ */
+export interface DiscussionThread {
+ /**
+ * The thread id, which is the id of its first comment. Replies and
+ * resolution address the thread by this id.
+ */
+ id: string;
+ /**
+ * Whether the thread has been resolved.
+ */
+ resolved: boolean;
+ /**
+ * For an inline comment on a document, the text it was written on;
+ * absent for a comment on the item as a whole. ReadContent has the
+ * text as the document reads now.
+ */
+ markedText?: string | null;
+ /**
+ * The comments in order, first comment first.
+ */
+ comments: DiscussionComment[];
+}
+/**
+ * A single comment in a thread.
+ */
+export interface DiscussionComment {
+ /**
+ * The comment id.
+ */
+ id: string;
+ /**
+ * The user or bot id of the author.
+ */
+ author: string;
+ /**
+ * The author's display name, for bots and imported comments.
+ */
+ authorName?: string | null;
+ /**
+ * The comment body in markdown; absent when the comment was deleted.
+ */
+ content?: string | null;
+ /**
+ * When the comment was written.
+ */
+ createdAt: string;
+ /**
+ * When the comment was last edited.
+ */
+ editedAt?: string | null;
+}
/**
* Read a known form before editing. Authoring view requires Edit and returns the actual durable collaborative draft, current schema, stable IDs and current settings. Respondent view returns only safe projected content, never hidden booking targets or response rows. Optional summary requires Edit. After a partial write, inspect the returned formId before making further changes. A respondent link may exist while responses are closed; check acceptingResponses.
*/
@@ -13860,15 +13974,11 @@ export interface RenameItemResponse {
name: 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.
+ * Resolve or reopen a comment thread in the Discussion of a document, task, Tasks project, CRM company or CRM contact on behalf of the user. A thread id is enough to find its item. Only use this when explicitly asked to resolve or reopen a comment. Thread ids come from ReadDiscussion, or from ReadContent for a document.
*/
-export interface ResolveDocumentComment {
+export interface ResolveComment {
/**
- * The id of the document the comment is on.
- */
- documentId: string;
- /**
- * The id of the inline or Discussion thread, from ReadContent.
+ * The id of the thread to resolve or reopen.
*/
threadId: string;
/**
@@ -13879,11 +13989,12 @@ export interface ResolveDocumentComment {
/**
* The thread's state after the change.
*/
-export interface ResolveDocumentCommentResponse {
+export interface ResolveCommentResponse {
+ entityType: DiscussionParentType;
/**
- * The document the thread is on.
+ * The item the thread is on.
*/
- documentId: string;
+ entityId: string;
/**
* The thread that was changed.
*/
diff --git a/crates/agent_code_mode/src/domain/service.rs b/crates/agent_code_mode/src/domain/service.rs
index 173f8d27e4..f2f3b4e92a 100644
--- a/crates/agent_code_mode/src/domain/service.rs
+++ b/crates/agent_code_mode/src/domain/service.rs
@@ -229,10 +229,12 @@ pub fn covered_by_code_sdk(name: &str, user_tool: bool) -> bool {
| "RenameDocument"
| "MoveToProject"
| "MoveToTrash"
- | "CommentOnDocument"
- | "DeleteDocumentComment"
- | "EditDocumentComment"
- | "ResolveDocumentComment"
+ | "ReadDiscussion"
+ | "Comment"
+ | "CommentOnText"
+ | "DeleteComment"
+ | "EditComment"
+ | "ResolveComment"
| "ReadProject"
| "CreateProject"
| "SetFavorite"
diff --git a/crates/ai_tools/AGENTS.md b/crates/ai_tools/AGENTS.md
index b11680a95b..8e21b0dc7c 100644
--- a/crates/ai_tools/AGENTS.md
+++ b/crates/ai_tools/AGENTS.md
@@ -34,8 +34,8 @@ execution, display) that don't belong to a single domain.
- Depends on: nearly every domain crate with tools (`forms`, `activity`,
`agent_session`, `anthropic`, `initiative`, `collab_surface`, `favorites`,
- `routines`, `ai_billing`, `ai_usage`, `ai_toolset`, `agent`), plus
- `bot_id`, `attachment`, `static_file`.
+ `messages`, `routines`, `ai_billing`, `ai_usage`, `ai_toolset`, `agent`),
+ plus `bot_id`, `attachment`, `static_file`.
- Used by: `document_storage_service`, `document_cognition_service`,
`agent_harness_service`, `mcp_service`.
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index bf291d7412..72cbec9f70 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -72,7 +72,7 @@ macro_aws_config = { path = "../macro_aws_config" }
macro_db_client = { path = "../macro_db_client" }
macro_env_var = { path = "../macro_env_var" }
macro_event_broker = { path = "../macro_event_broker" }
-messages = { path = "../messages", features = ["broker", "delivery"] }
+messages = { path = "../messages", features = ["ai_tools", "broker", "delivery"] }
macro_queues = { path = "../macro_queues" }
macro_user_id = { path = "../macro_user_id" }
mcp_client = { path = "../mcp_client" }
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index e35a689a87..367fc4070b 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -627,6 +627,9 @@ pub async fn build_tool_service_context_from_env(
recorder.clone(),
)?,
cognition_tool_context: build_cognition_tool_context()?,
+ message_tool_context: crate::tool_context::build_message_tool_context(
+ &document_tool_context,
+ ),
document_tool_context,
properties_tool_context,
email_tool_context,
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 8cae86e033..8dd95bcf4a 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -47,6 +47,7 @@ use email::inbound::toolset::{email_toolset, mcp_toolset as email_mcp_toolset};
use favorites::inbound::toolset::favorites_toolset;
use import::inbound::toolset::import_toolset;
use initiative::inbound::toolset::initiative_toolset;
+use messages::inbound::toolset::message_toolset;
use notification::inbound::ai_tool::{item_notification_preference_toolset, notification_toolset};
use projects::inbound::toolset::project_toolset;
use properties::inbound::toolset::properties_toolset;
@@ -86,10 +87,10 @@ pub use tool_context::{
ToolFavoritesService, ToolFavoritesToolContext, ToolForeignEntityService, ToolFormsToolContext,
ToolFrecencyService, ToolGithubPullRequestService, ToolImageGenerationToolContext,
ToolImportService, ToolImportToolContext, ToolInitiativeToolContext,
- ToolItemNotificationPreferenceToolContext, ToolMcpSelector, ToolNotificationQueue,
- ToolNotificationService, ToolNotificationToolContext, ToolPipedreamConnection,
- ToolPipelineService, ToolPipelineToolContext, ToolPipelineWorkflows, ToolProjectService,
- ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext,
+ ToolItemNotificationPreferenceToolContext, ToolMcpSelector, ToolMessageToolContext,
+ ToolNotificationQueue, ToolNotificationService, ToolNotificationToolContext,
+ ToolPipedreamConnection, ToolPipelineService, ToolPipelineToolContext, ToolPipelineWorkflows,
+ ToolProjectService, ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext,
ToolReadAgentSessionContext, ToolServiceContext, ToolSkillService, ToolSkillToolContext,
ToolSoupService, ToolSystemPropertiesService, ToolTableEventPublisher, ToolTeamCalendarService,
ToolTeamCalendarToolContext, ToolTeamService, ToolTeamToolContext, ToolUserEmailService,
@@ -102,11 +103,12 @@ pub use tool_context::{
build_databases_tool_context, build_favorites_service, build_favorites_tool_context,
build_forms_tool_context, build_image_generation_tool_context, build_initiative_tool_context,
build_item_notification_preference_tool_context, build_message_service_with_side_effects,
- build_message_service_without_side_effects, build_pipeline_tool_context,
- build_project_tool_context, build_properties_service, build_properties_service_with_broker,
- build_properties_tool_context, build_read_agent_session_context, build_routine_tool_context,
- build_skill_tool_context, build_task_properties_adapter, build_team_calendar_tool_context,
- build_team_repository, build_team_tool_context,
+ build_message_service_without_side_effects, build_message_tool_context,
+ build_pipeline_tool_context, build_project_tool_context, build_properties_service,
+ build_properties_service_with_broker, build_properties_tool_context,
+ build_read_agent_session_context, build_routine_tool_context, build_skill_tool_context,
+ build_task_properties_adapter, build_team_calendar_tool_context, build_team_repository,
+ build_team_tool_context,
};
pub use tool_context::{ToolConnectorToolContext, build_connector_tool_context};
#[cfg(any(test, feature = "test-support"))]
@@ -165,6 +167,7 @@ pub(crate) fn subagent_toolset() -> AiToolSet {
.add_subtoolset::<ToolCognitionToolContext>(cognition_toolset())
.add_subtoolset::<ToolProjectToolContext>(project_toolset())
.add_subtoolset::<ToolFavoritesToolContext>(favorites_toolset())
+ .add_subtoolset::<ToolMessageToolContext>(message_toolset())
.add_subtoolset::<ToolInitiativeToolContext>(initiative_toolset())
.add_subtoolset::<ToolPropertiesToolContext>(properties_toolset())
.add_subtoolset::<ToolCallToolContext>(call_toolset())
diff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rs
index a2a8a5523d..7932f84a04 100644
--- a/crates/ai_tools/src/test.rs
+++ b/crates/ai_tools/src/test.rs
@@ -122,8 +122,10 @@ fn project_workflows_are_available_in_every_host_alongside_folder_and_property_t
"UpdateInitiativeSharing",
"ReadInitiativeActivity",
"SetEntityProperty",
- "CommentOnDocument",
- "ResolveDocumentComment",
+ "ReadDiscussion",
+ "Comment",
+ "CommentOnText",
+ "ResolveComment",
"CreateProject",
"ReadProject",
];
@@ -160,8 +162,8 @@ fn app_item_actions_are_available_in_every_host() {
"DeleteChannelMessage",
"ReactToChannelMessage",
"OpenDirectMessage",
- "EditDocumentComment",
- "DeleteDocumentComment",
+ "EditComment",
+ "DeleteComment",
"CreateSkill",
"MoveToTrash",
"DuplicateItem",
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 187e1be181..a51fb71ec3 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1103,6 +1103,21 @@ pub type ToolDocumentToolContext = DocumentToolContext<
documents::outbound::editing_worker_client::ReqwestEditingWorkerClient,
>;
+/// Type alias for the discussion tool context.
+pub type ToolMessageToolContext =
+ messages::inbound::toolset::MessageToolContext<ToolEntityAccessService>;
+
+/// Build the discussion tool context over the message service and access
+/// checks the document tools comment through, so a host wires one message
+/// service for every Discussion.
+pub fn build_message_tool_context(documents: &ToolDocumentToolContext) -> ToolMessageToolContext {
+ messages::inbound::toolset::MessageToolContext::new(
+ documents.messages.clone(),
+ documents.entity_access_service.clone(),
+ )
+ .with_actor(documents.actor)
+}
+
/// Type alias for the foreign entity service implementation used by AI tools.
pub type ToolForeignEntityService = ForeignEntityServiceImpl<PgForeignEntityRepo>;
@@ -1833,6 +1848,9 @@ pub struct ToolServiceContext {
pub project_tool_context: ToolProjectToolContext,
/// Favorite toggles; the same favorites back `soup_service`'s favorites filter.
pub favorites_tool_context: ToolFavoritesToolContext,
+ /// The Discussion of any item: the same message service the document
+ /// tools comment through.
+ pub message_tool_context: ToolMessageToolContext,
/// Native task project lifecycle, properties, sharing and history.
pub initiative_tool_context: ToolInitiativeToolContext,
pub team_tool_context: ToolTeamToolContext,
@@ -1903,6 +1921,7 @@ impl ToolServiceContext {
/// call this once when they build the context for that agent's session.
pub fn with_actor(mut self, actor: bot_id::BotId) -> Self {
self.document_tool_context = self.document_tool_context.with_actor(actor);
+ self.message_tool_context = self.message_tool_context.with_actor(actor);
self.image_generation_tool_context = self.image_generation_tool_context.with_actor(actor);
self.properties_tool_context = self.properties_tool_context.with_actor(actor);
self.project_tool_context = self.project_tool_context.with_actor(actor);
diff --git a/crates/documents/AGENTS.md b/crates/documents/AGENTS.md
index 964745bc78..f664b1faae 100644
--- a/crates/documents/AGENTS.md
+++ b/crates/documents/AGENTS.md
@@ -28,7 +28,10 @@ word docs, Illustrator/Photoshop files).
markdown backfill, comments, AI-editing tools, and file-type domain services
(spreadsheet, presentation, word, illustrator, photoshop).
- Not here: realtime collaborative sync of document content → sync-service;
- the lexical markdown node/editor implementation → `packages/lexical-core`.
+ the lexical markdown node/editor implementation → `packages/lexical-core`;
+ Discussion comments, replies and thread state on any entity → the `messages`
+ toolset (this crate keeps only `CommentOnText`, the inline comment that
+ places a mark).
## Boundaries
diff --git a/crates/documents/src/domain/comments.rs b/crates/documents/src/domain/comments.rs
index d1fcff8511..76048b6c8b 100644
--- a/crates/documents/src/domain/comments.rs
+++ b/crates/documents/src/domain/comments.rs
@@ -8,25 +8,19 @@ use std::{collections::HashMap, sync::Arc};
use chrono::{DateTime, Utc};
use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
-use futures::{StreamExt, TryStreamExt, stream};
+use futures::{StreamExt, stream};
use messages::domain::{
api::MessageReader,
- models::{Message, MessageListItem, ThreadAnchor},
- ports::{MessageError, MessageTimelineQuery},
+ discussions::{live_roots, with_replies},
+ models::{Message, MessageThread, ThreadAnchor},
+ ports::MessageError,
service::MessageView,
};
use uuid::Uuid;
use super::models::DocumentError;
-/// Discussions read per timeline page, the most the message service returns.
-const PAGE_SIZE: u16 = 100;
-
-/// Most discussions returned for one document, newest kept, so a heavily
-/// discussed document cannot crowd its own content out of an agent's context.
-pub const MAX_DISCUSSIONS: usize = 500;
-
-/// Concurrent thread and mark lookups for one read.
+/// Concurrent mark lookups for one read.
const LOOKUP_CONCURRENCY: usize = 8;
/// Reads what a comment mark covers in the live document.
@@ -161,7 +155,7 @@ pub struct DocumentDiscussion {
#[async_trait::async_trait]
pub trait DocumentComments: Send + Sync + 'static {
/// Every live discussion on the document, oldest first, capped at
- /// [`MAX_DISCUSSIONS`].
+ /// [`messages::domain::discussions::MAX_DISCUSSIONS`].
async fn discussions(
&self,
receipt: EntityAccessReceipt<ViewAccessLevel>,
@@ -180,78 +174,13 @@ impl<M: CommentMarks> DocumentCommentReader<M> {
Self { messages, marks }
}
- async fn roots(
- &self,
- access: &EntityAccessReceipt<MessageView>,
- ) -> Result<Vec<MessageListItem>, MessageError> {
- let mut roots = Vec::new();
- let mut cursor = None;
- loop {
- let page = self
- .messages
- .timeline(
- access.clone(),
- MessageTimelineQuery {
- cursor,
- limit: Some(PAGE_SIZE),
- ..Default::default()
- },
- )
- .await?;
- // A deleted first comment with no live replies is not returned,
- // so it must not count toward the cap.
- roots.extend(
- page.items.into_iter().filter(|item| {
- item.message.deleted_at.is_none() || item.thread.reply_count > 0
- }),
- );
- if roots.len() >= MAX_DISCUSSIONS {
- tracing::warn!(count = roots.len(), "document discussions truncated");
- roots.truncate(MAX_DISCUSSIONS);
- return Ok(roots);
- }
- match page.next_cursor {
- Some(next) => cursor = Some(next),
- None => return Ok(roots),
- }
- }
- }
-
- /// Replies of the threads whose timeline preview does not hold them all.
- async fn full_replies(
- &self,
- access: &EntityAccessReceipt<MessageView>,
- roots: &[MessageListItem],
- ) -> Result<HashMap<Uuid, Vec<Message>>, MessageError> {
- let partial: Vec<Uuid> = roots
- .iter()
- .filter(|item| item.thread.reply_count > item.thread.preview.len() as i64)
- .map(|item| item.message.id)
- .collect();
- stream::iter(partial)
- .map(|root| async move {
- let thread = self.messages.get_thread(access.clone(), root).await?;
- Ok::<_, MessageError>((root, thread.replies))
- })
- .buffer_unordered(LOOKUP_CONCURRENCY)
- .try_collect()
- .await
- }
-
/// What each markdown mark covers now. A failed lookup leaves the mark
/// out, so the snapshot stands in rather than failing the read.
async fn live_marks(
&self,
document_id: &str,
- roots: &[MessageListItem],
+ mark_ids: Vec<Uuid>,
) -> HashMap<Uuid, Option<String>> {
- let mark_ids: Vec<Uuid> = roots
- .iter()
- .filter_map(|item| match &item.state.anchor {
- Some(ThreadAnchor::Markdown { mark_id, .. }) => Some(*mark_id),
- _ => None,
- })
- .collect();
stream::iter(mark_ids)
.map(|mark_id| async move {
self.marks
@@ -281,60 +210,43 @@ impl<M: CommentMarks> DocumentComments for DocumentCommentReader<M> {
let access = receipt
.try_into_requirement::<MessageView>()
.map_err(|_| DocumentError::Unauthorized)?;
- let roots = self.roots(&access).await.map_err(message_error)?;
- let (replies, marks) = futures::join!(
- self.full_replies(&access, &roots),
- self.live_marks(&document_id, &roots)
+ let roots = live_roots(self.messages.as_ref(), &access)
+ .await
+ .map_err(message_error)?;
+ let mark_ids: Vec<Uuid> = roots
+ .iter()
+ .filter_map(|item| match &item.state.anchor {
+ Some(ThreadAnchor::Markdown { mark_id, .. }) => Some(*mark_id),
+ _ => None,
+ })
+ .collect();
+ let (threads, marks) = futures::join!(
+ with_replies(self.messages.as_ref(), &access, roots),
+ self.live_marks(&document_id, mark_ids)
);
- let mut replies = replies.map_err(message_error)?;
- Ok(roots
+ Ok(threads
+ .map_err(message_error)?
.into_iter()
- .rev()
- .filter_map(|item| {
- let replies = replies
- .remove(&item.message.id)
- .unwrap_or(item.thread.preview);
- discussion(
- item.message,
- item.state.resolved,
- item.state.anchor,
- replies,
- &marks,
- )
- })
+ .map(|thread| discussion(thread, &marks))
.collect())
}
}
-/// A thread whose first comment was deleted is kept only while it has replies.
-fn discussion(
- root: Message,
- resolved: bool,
- anchor: Option<ThreadAnchor>,
- replies: Vec<Message>,
- marks: &HashMap<Uuid, Option<String>>,
-) -> Option<DocumentDiscussion> {
- if root.deleted_at.is_some() && replies.is_empty() {
- return None;
- }
- let kind = match anchor {
+fn discussion(thread: MessageThread, marks: &HashMap<Uuid, Option<String>>) -> DocumentDiscussion {
+ let kind = match thread.state.anchor {
None => CommentThreadKind::Discussion,
Some(_) => CommentThreadKind::Inline,
};
- Some(DocumentDiscussion {
- id: root.id,
+ DocumentDiscussion {
+ id: thread.root.id,
kind,
- resolved,
- anchor: comment_anchor(anchor, marks),
- comments: std::iter::once(root)
- .chain(
- replies
- .into_iter()
- .filter(|reply| reply.deleted_at.is_none()),
- )
+ resolved: thread.state.resolved,
+ anchor: comment_anchor(thread.state.anchor, marks),
+ comments: std::iter::once(thread.root)
+ .chain(thread.replies)
.map(comment)
.collect(),
- })
+ }
}
fn comment_anchor(
diff --git a/crates/documents/src/domain/comments/test.rs b/crates/documents/src/domain/comments/test.rs
index b85ca20bf4..1ea47669c3 100644
--- a/crates/documents/src/domain/comments/test.rs
+++ b/crates/documents/src/domain/comments/test.rs
@@ -5,7 +5,11 @@ use entity_access::domain::models::{Entity, EntityPermission, EntityType};
use macro_user_id::user_id::MacroUserIdStr;
use messages::domain::{
api::MockMessageReader,
- models::{BotSenderProfile, MessageParent, MessageThread, MessageThreadPreview, ThreadState},
+ discussions::{MAX_DISCUSSIONS, PAGE_SIZE},
+ models::{
+ BotSenderProfile, MessageListItem, MessageParent, MessageThread, MessageThreadPreview,
+ ThreadState,
+ },
ports::{MessageCursor, MessagePage},
};
use models_permissions::share_permission::access_level::AccessLevel;
diff --git a/crates/documents/src/inbound/toolset.rs b/crates/documents/src/inbound/toolset.rs
index c55cf3ad2d..4e670de2c8 100644
--- a/crates/documents/src/inbound/toolset.rs
+++ b/crates/documents/src/inbound/toolset.rs
@@ -1,19 +1,16 @@
//! Toolset inbound adapter for Documents.
-mod comment_on_document;
+mod comment_on_text;
mod create_document;
mod create_skill;
-mod delete_document_comment;
mod design;
mod edit_document;
-mod edit_document_comment;
mod illustrator;
mod photoshop;
mod presentation;
mod read_content;
mod read_metadata;
mod rename_document;
-mod resolve_document_comment;
mod spreadsheet;
mod upload_file;
mod word_document;
@@ -35,20 +32,17 @@ use crate::{
domain::ports::mentions::NoOpDocumentMentionTracker,
domain::presentation::{NoPresentationFiles, PresentationFiles, PresentationService},
inbound::toolset::{
- comment_on_document::CommentOnDocument,
+ comment_on_text::CommentOnText,
create_document::CreateDocument,
create_skill::CreateSkill,
- delete_document_comment::DeleteDocumentComment,
design::ReadDesign,
edit_document::EditDocument,
- edit_document_comment::EditDocumentComment,
illustrator::ReadIllustratorDocument,
photoshop::ReadPhotoshopDocument,
presentation::{EditPresentation, ReadPresentation},
read_content::ReadContent,
read_metadata::ReadMetadata,
rename_document::RenameDocument,
- resolve_document_comment::ResolveDocumentComment,
spreadsheet::{CalculateSpreadsheet, EditSpreadsheet, ReadSpreadsheet},
upload_file::UploadFile,
word_document::{EditWordDocument, ReadWordDocument},
@@ -66,11 +60,7 @@ use entity_access::domain::{
};
use lexical_client::LexicalClient;
use macro_user_id::user_id::MacroUserIdStr;
-use messages::domain::{
- api::MessageServiceApi,
- ports::MessageError,
- service::{MessageView, MessageWrite},
-};
+use messages::domain::{api::MessageServiceApi, ports::MessageError, service::MessageWrite};
use model_owner::CreationPrincipal;
use std::sync::Arc;
use sync_service_client::SyncServiceClient;
@@ -350,47 +340,6 @@ impl<
.map_err(comment_access_error)
}
- /// Mint the write capability for changing an existing comment as its
- /// author: comments the tool actor bot posted are changed as the bot, and
- /// every other comment as the user, so the message service applies the
- /// same authorship and moderation rules as the web composer.
- pub async fn require_comment_author_write(
- &self,
- request_context: &RequestContext,
- document_id: Uuid,
- comment_id: Uuid,
- ) -> Result<EntityAccessReceipt<MessageWrite>, ToolCallError> {
- let view = self
- .entity_access_service
- .generate_entity_access_receipt::<MessageView>(
- &request_context.user_id,
- None,
- &document_id.to_string(),
- EntityType::Document,
- )
- .await
- .map_err(comment_access_error)?;
- let comment = self
- .messages
- .get(view, comment_id)
- .await
- .map_err(comment_error("unable to read the comment"))?;
- if comment.sender_id.as_ref() == self.actor.into_storage_id().as_ref() {
- return self
- .require_comment_write(request_context, document_id)
- .await;
- }
- self.entity_access_service
- .generate_entity_access_receipt::<MessageWrite>(
- &request_context.user_id,
- None,
- &document_id.to_string(),
- EntityType::Document,
- )
- .await
- .map_err(comment_access_error)
- }
-
/// Who these tools create entities as when acting for `user`.
pub fn creation_principal(&self, user: MacroUserIdStr<'static>) -> CreationPrincipal {
CreationPrincipal::BotForUser {
@@ -416,10 +365,7 @@ where
.add_tool::<UploadFile, DocumentToolContext<DSvc, ESvc, EDSvc>>()
.add_tool::<RenameDocument, DocumentToolContext<DSvc, ESvc, EDSvc>>()
.add_tool::<EditDocument, DocumentToolContext<DSvc, ESvc, EDSvc>>()
- .add_tool::<CommentOnDocument, DocumentToolContext<DSvc, ESvc, EDSvc>>()
- .add_tool::<ResolveDocumentComment, DocumentToolContext<DSvc, ESvc, EDSvc>>()
- .add_tool::<EditDocumentComment, DocumentToolContext<DSvc, ESvc, EDSvc>>()
- .add_tool::<DeleteDocumentComment, DocumentToolContext<DSvc, ESvc, EDSvc>>()
+ .add_tool::<CommentOnText, 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>>()
diff --git a/crates/documents/src/inbound/toolset/comment_on_document.rs b/crates/documents/src/inbound/toolset/comment_on_text.rs
similarity index 68%
rename from crates/documents/src/inbound/toolset/comment_on_document.rs
rename to crates/documents/src/inbound/toolset/comment_on_text.rs
index 949146111c..067cc398ce 100644
--- a/crates/documents/src/inbound/toolset/comment_on_document.rs
+++ b/crates/documents/src/inbound/toolset/comment_on_text.rs
@@ -1,4 +1,4 @@
-//! CommentOnDocument tool for posting document comments and replies.
+//! CommentOnText tool for inline comments on a passage of a document.
use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
use ai_toolset::{ToolAnnotated, ToolAnnotations};
@@ -27,10 +27,10 @@ use crate::domain::ports::{
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(
- title = "CommentOnDocument",
- description = "Comment on a document on behalf of the user. Pass threadId to reply in an existing inline or Discussion thread; pass quote to start a new inline comment on a passage of a Macro markdown or Word (DOCX) document; omit both to start a new Discussion comment on the document as a whole. Replies and Discussion comments support any document type. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. For an inline comment, quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. Do not combine threadId with quote. occurrence only applies with quote. Comments made here stay in Macro and are not written into a Word file; for comments that must travel with a Word document to its recipient (a redline for a counterparty), use EditWordDocument's addComment operation instead."
+ title = "CommentOnText",
+ description = "Start an inline comment on a passage of a Macro markdown or Word (DOCX) document on behalf of the user, anchored to the quoted text. Only use this when explicitly asked to comment on specific text. Quote the passage exactly as the document reads, as plain text without markdown syntax, within a single paragraph, heading, list item or table cell. If the passage appears more than once the tool refuses and lists each occurrence so you can choose one with occurrence, counting from 1; if the text is not found, read the document again rather than guessing. For a comment on a document as a whole, or a reply in an existing thread, use Comment. Comments made here stay in Macro and are not written into a Word file; for comments that must travel with a Word document to its recipient (a redline for a counterparty), use EditWordDocument's addComment operation instead."
)]
-pub struct CommentOnDocument {
+pub struct CommentOnText {
#[schemars(description = "The id of the document to comment on.")]
pub document_id: Uuid,
@@ -40,18 +40,13 @@ pub struct CommentOnDocument {
pub content: String,
#[schemars(
- description = "The id of the inline or Discussion thread to reply in, from ReadContent. Cannot be combined with quote. Omit both threadId and quote to post a new Discussion comment on the document as a whole."
+ description = "The passage to comment on, quoted exactly as the document reads: plain text without markdown syntax such as ** or link brackets. Keep it to the words the comment is about; a longer quote is more likely to be unique."
)]
- pub thread_id: Option<Uuid>,
-
- #[schemars(
- description = "The passage to comment on, quoted exactly as the document reads: plain text without markdown syntax such as ** or link brackets. Keep it to the words the comment is about; a longer quote is more likely to be unique. Starts a new inline comment on a markdown or Word (DOCX) document. Cannot be combined with threadId."
- )]
- pub quote: Option<String>,
+ pub quote: String,
#[schemars(
range(min = 1),
- description = "Which appearance of the quoted passage to comment on, counting from 1 in document order. Only applies with quote; only needed when the passage appears more than once."
+ description = "Which appearance of the quoted passage to comment on, counting from 1 in document order. Only needed when the passage appears more than once."
)]
pub occurrence: Option<u32>,
}
@@ -59,30 +54,29 @@ pub struct CommentOnDocument {
/// The posted comment.
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
-pub struct CommentOnDocumentResponse {
+pub struct CommentOnTextResponse {
/// The document the comment was posted on.
pub document_id: Uuid,
- /// The thread the comment is in; a new comment starts its own.
+ /// The thread the comment starts.
pub thread_id: Uuid,
/// The posted comment.
pub comment_id: Uuid,
- /// The text the new inline comment is anchored to, as the document reads.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub marked_text: Option<String>,
+ /// The text the comment is anchored to, as the document reads.
+ pub marked_text: String,
}
-impl ToolAnnotated for CommentOnDocument {
- const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Comment on document");
+impl ToolAnnotated for CommentOnText {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Comment on text");
}
#[async_trait]
-impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for CommentOnDocument
+impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for CommentOnText
where
DSvc: DocumentService + DocumentCreationService,
ESvc: EntityAccessService,
EDSvc: EditingWorkerService,
{
- type Output = CommentOnDocumentResponse;
+ type Output = CommentOnTextResponse;
#[tracing::instrument(skip_all, fields(document_id = %self.document_id), err)]
async fn call(
@@ -90,18 +84,6 @@ where
ctx: ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
- if self.thread_id.is_some() && self.quote.is_some() {
- return Err(ToolCallError {
- description: "threadId and quote cannot be combined: pass threadId to reply or quote to start a new inline comment".to_string(),
- internal_error: anyhow::anyhow!("threadId and quote both provided"),
- });
- }
- if self.occurrence.is_some() && self.quote.is_none() {
- return Err(ToolCallError {
- description: "occurrence only applies with quote: provide a quote to choose an appearance of the passage".to_string(),
- internal_error: anyhow::anyhow!("occurrence provided without quote"),
- });
- }
if self.occurrence == Some(0) {
return Err(ToolCallError {
description:
@@ -113,33 +95,6 @@ where
let access = ctx
.require_comment_write(&request_context, self.document_id)
.await?;
- let Some(quote) = &self.quote else {
- let message = ctx
- .messages
- .post(
- access,
- PostMessage {
- id: None,
- 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"))?;
-
- return Ok(CommentOnDocumentResponse {
- document_id: self.document_id,
- thread_id: message.thread_id.unwrap_or(message.id),
- comment_id: message.id,
- marked_text: None,
- });
- };
let document_id = self.document_id.to_string();
let document = ctx
@@ -152,10 +107,10 @@ where
})?;
match document.try_file_type() {
Some(FileType::Md) => {}
- Some(FileType::Docx) => return self.comment_on_docx_text(&ctx, access, quote).await,
+ Some(FileType::Docx) => return self.comment_on_docx_text(&ctx, access).await,
_ => {
return Err(ToolCallError {
- description: "inline comments anchor to text in Macro markdown and Word documents only; omit quote to comment on this document as a whole".to_string(),
+ description: "inline comments anchor to text in Macro markdown and Word documents only; use Comment to comment on this document as a whole".to_string(),
internal_error: anyhow::anyhow!(
"document file type {:?} does not support inline comments",
document.file_type
@@ -190,7 +145,7 @@ where
&document_id,
&document_token,
mark_id,
- quote,
+ &self.quote,
self.occurrence,
)
.await
@@ -244,16 +199,16 @@ where
}
};
- Ok(CommentOnDocumentResponse {
+ Ok(CommentOnTextResponse {
document_id: self.document_id,
thread_id: message.id,
comment_id: message.id,
- marked_text: Some(marked_text),
+ marked_text,
})
}
}
-impl CommentOnDocument {
+impl CommentOnText {
/// A Word document keeps its comment marks beside its collaborative
/// blocks, where the editor places a thread by the text it quotes and pins
/// it with a mark. The thread is posted with that quote and a fresh mark id;
@@ -262,8 +217,7 @@ impl CommentOnDocument {
&self,
ctx: &ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,
access: EntityAccessReceipt<MessageWrite>,
- quote: &str,
- ) -> ToolResult<CommentOnDocumentResponse>
+ ) -> ToolResult<CommentOnTextResponse>
where
DSvc: DocumentService + DocumentCreationService,
ESvc: EntityAccessService,
@@ -275,7 +229,7 @@ impl CommentOnDocument {
internal_error: anyhow::anyhow!("occurrence {:?} on a docx", self.occurrence),
});
}
- let marked_text = quote.trim();
+ let marked_text = self.quote.trim();
if marked_text.is_empty() {
return Err(ToolCallError {
description: "quote the passage to comment on".to_string(),
@@ -303,11 +257,11 @@ impl CommentOnDocument {
)
.await
.map_err(comment_error("unable to post the comment"))?;
- Ok(CommentOnDocumentResponse {
+ Ok(CommentOnTextResponse {
document_id: self.document_id,
thread_id: message.id,
comment_id: message.id,
- marked_text: Some(marked_text.to_owned()),
+ marked_text: marked_text.to_owned(),
})
}
}
diff --git a/crates/documents/src/inbound/toolset/comment_test.rs b/crates/documents/src/inbound/toolset/comment_test.rs
index b0b6ae6dc7..d2f61d82d4 100644
--- a/crates/documents/src/inbound/toolset/comment_test.rs
+++ b/crates/documents/src/inbound/toolset/comment_test.rs
@@ -10,7 +10,7 @@ use messages::domain::{
api::{MessageCommands, MessageReader},
models::{
Message, MessageAttribution, MessageParent, MessageThread, NewThreadAnchor, PostMessage,
- PostMessageNotificationPolicy, ThreadPatch, ThreadState,
+ ThreadPatch, ThreadState,
},
ports::{MessageError, MessagePage, MessagePatch, MessageTimelinePage, MessageTimelineQuery},
service::{MessageView, MessageWrite},
@@ -23,84 +23,19 @@ use crate::domain::permission_token::decode_permission_token;
use super::{
DocumentToolContext,
- comment_on_document::CommentOnDocument,
- delete_document_comment::DeleteDocumentComment,
+ comment_on_text::CommentOnText,
edit_document::test::{FakeDocumentService, FakeEditingWorker, FakeEntityAccessService},
- edit_document_comment::EditDocumentComment,
- 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)]
+/// Records the comment threads the tool posts.
+#[derive(Clone, Default)]
pub(in crate::inbound::toolset) struct FakeMessages {
- thread_exists: bool,
/// Refuse every post, as the message service does an anchor it rejects.
fail_posts: bool,
posts: Arc<Mutex<Vec<(EntityAccessReceipt<MessageWrite>, PostMessage)>>>,
- thread_patches: Arc<Mutex<Vec<(EntityAccessReceipt<MessageWrite>, Uuid, ThreadPatch)>>>,
- /// Author of the stored comment `get` returns; reads panic when unset.
- comment_author: Option<ChannelSender<'static>>,
- /// Whether the stored comment is a reply rather than a thread's first comment.
- comment_is_reply: bool,
- /// Refuse every comment edit or delete as the message service refuses a non-author.
- forbid_changes: bool,
- comment_patches: Arc<Mutex<Vec<(EntityAccessReceipt<MessageWrite>, Uuid, MessagePatch)>>>,
- comment_deletes: Arc<Mutex<Vec<(EntityAccessReceipt<MessageWrite>, Uuid)>>>,
-}
-
-impl FakeMessages {
- fn with_comment_by(author: ChannelSender<'static>) -> Self {
- Self {
- comment_author: Some(author),
- ..Self::default()
- }
- }
-
- fn stored_comment(&self, id: Uuid) -> Message {
- let at = Utc.with_ymd_and_hms(2026, 9, 23, 12, 0, 0).unwrap();
- Message {
- id,
- parent: MessageParent::parse("document", &DOCUMENT.to_string()).unwrap(),
- thread_id: self.comment_is_reply.then_some(THREAD),
- sender_id: self
- .comment_author
- .clone()
- .expect("test configured a stored comment"),
- guest_name: None,
- imported_author: None,
- bot_profile: None,
- mentions: vec![],
- triggered_by: None,
- content: "stored comment".to_owned(),
- created_at: at,
- updated_at: at,
- edited_at: None,
- deleted_at: None,
- attachments: vec![],
- reactions: vec![],
- }
- }
-}
-
-impl Default for FakeMessages {
- fn default() -> Self {
- Self {
- thread_exists: true,
- fail_posts: false,
- posts: Arc::default(),
- thread_patches: Arc::default(),
- comment_author: None,
- comment_is_reply: false,
- forbid_changes: false,
- comment_patches: Arc::default(),
- comment_deletes: Arc::default(),
- }
- }
}
#[async_trait::async_trait]
@@ -108,9 +43,9 @@ impl MessageReader for FakeMessages {
async fn get(
&self,
_access: EntityAccessReceipt<MessageView>,
- id: Uuid,
+ _id: Uuid,
) -> Result<Message, MessageError> {
- Ok(self.stored_comment(id))
+ panic!("unexpected get call")
}
async fn get_thread(
&self,
@@ -170,9 +105,6 @@ impl MessageCommands for FakeMessages {
access: EntityAccessReceipt<MessageWrite>,
input: PostMessage,
) -> Result<Message, MessageError> {
- if input.thread_id.is_some() && !self.thread_exists {
- return Err(MessageError::NotFound);
- }
if self.fail_posts {
return Err(MessageError::Invalid("anchor already in use"));
}
@@ -203,30 +135,19 @@ impl MessageCommands for FakeMessages {
}
async fn patch(
&self,
- access: EntityAccessReceipt<MessageWrite>,
- id: Uuid,
- input: MessagePatch,
+ _access: EntityAccessReceipt<MessageWrite>,
+ _id: Uuid,
+ _input: MessagePatch,
) -> Result<Message, MessageError> {
- if self.forbid_changes {
- return Err(MessageError::Forbidden);
- }
- self.comment_patches
- .lock()
- .unwrap()
- .push((access, id, input));
- Ok(self.stored_comment(id))
+ panic!("unexpected patch call")
}
async fn delete(
&self,
- access: EntityAccessReceipt<MessageWrite>,
- id: Uuid,
+ _access: EntityAccessReceipt<MessageWrite>,
+ _id: Uuid,
_nonce: Option<String>,
) -> Result<Message, MessageError> {
- if self.forbid_changes {
- return Err(MessageError::Forbidden);
- }
- self.comment_deletes.lock().unwrap().push((access, id));
- Ok(self.stored_comment(id))
+ panic!("unexpected delete call")
}
async fn react(
&self,
@@ -249,28 +170,11 @@ impl MessageCommands for FakeMessages {
}
async fn patch_thread(
&self,
- access: EntityAccessReceipt<MessageWrite>,
- root_id: Uuid,
- patch: ThreadPatch,
+ _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)
+ panic!("unexpected patch_thread call")
}
async fn delete_thread(
&self,
@@ -285,10 +189,6 @@ impl MessageCommands for FakeMessages {
type TestToolContext =
DocumentToolContext<FakeDocumentService, FakeEntityAccessService, FakeEditingWorker>;
-fn context(access_level: AccessLevel, messages: FakeMessages) -> ServiceContext<TestToolContext> {
- context_with(access_level, messages, "md", FakeEditingWorker::default())
-}
-
fn context_with(
access_level: AccessLevel,
messages: FakeMessages,
@@ -321,195 +221,10 @@ fn assert_bot_on_document(access: &EntityAccessReceipt<MessageWrite>) {
);
}
-#[tokio::test]
-async fn reply_posts_in_the_thread_as_the_bot_for_the_user() {
- let messages = FakeMessages::default();
- let response = CommentOnDocument {
- document_id: DOCUMENT,
- content: "Fixed in the latest draft.".to_owned(),
- thread_id: Some(THREAD),
- quote: None,
- occurrence: None,
- }
- .call(context(AccessLevel::Comment, messages.clone()), request())
- .await
- .unwrap();
-
- assert_eq!(response.document_id, DOCUMENT);
- assert_eq!(response.thread_id, THREAD);
- assert!(
- serde_json::to_value(&response)
- .unwrap()
- .get("markedText")
- .is_none()
- );
- 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 comment_without_a_thread_or_quote_starts_a_discussion_comment() {
- let messages = FakeMessages::default();
- let response = CommentOnDocument {
- document_id: DOCUMENT,
- content: "Summary of the open questions.".to_owned(),
- thread_id: None,
- quote: None,
- occurrence: None,
- }
- .call(context(AccessLevel::Comment, messages.clone()), request())
- .await
- .unwrap();
-
- assert_eq!(response.thread_id, response.comment_id);
- assert!(
- serde_json::to_value(&response)
- .unwrap()
- .get("markedText")
- .is_none()
- );
- 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 = CommentOnDocument {
- document_id: DOCUMENT,
- content: "Looks good.".to_owned(),
- thread_id: Some(THREAD),
- quote: None,
- occurrence: None,
- }
- .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 = CommentOnDocument {
- document_id: DOCUMENT,
- content: "Done.".to_owned(),
- thread_id: Some(THREAD),
- quote: None,
- occurrence: None,
- }
- .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());
-}
-
-fn comment_on_text(text: &str, occurrence: Option<u32>) -> CommentOnDocument {
- CommentOnDocument {
+fn comment_on_text(text: &str, occurrence: Option<u32>) -> CommentOnText {
+ CommentOnText {
document_id: DOCUMENT,
- thread_id: None,
- quote: Some(text.to_owned()),
+ quote: text.to_owned(),
occurrence,
content: "Is this date still right?".to_owned(),
}
@@ -564,7 +279,7 @@ async fn comment_on_text_places_the_mark_then_posts_a_thread_anchored_to_it() {
assert_eq!(response.document_id, DOCUMENT);
assert_eq!(response.thread_id, Uuid::from_u128(99));
assert_eq!(response.comment_id, Uuid::from_u128(99));
- assert_eq!(response.marked_text.as_deref(), Some("ships on Friday"));
+ assert_eq!(response.marked_text, "ships on Friday");
assert_eq!(
serde_json::to_value(&response).unwrap()["markedText"],
"ships on Friday"
@@ -693,7 +408,7 @@ async fn comment_on_docx_text_posts_a_thread_the_editor_places_by_its_quote() {
panic!("expected a text anchor, got {:?}", post.anchor);
};
assert_eq!(marked_text.as_deref(), Some("thirty (30) days"));
- assert_eq!(response.marked_text.as_deref(), Some("thirty (30) days"));
+ assert_eq!(response.marked_text, "thirty (30) days");
assert_eq!(response.thread_id, Uuid::from_u128(99));
}
@@ -770,251 +485,3 @@ async fn comment_on_text_rejects_occurrence_zero() {
);
assert!(editing.added_comment_marks.lock().unwrap().is_empty());
}
-
-#[tokio::test]
-async fn comment_rejects_thread_id_with_quote() {
- let messages = FakeMessages::default();
- let editing = FakeEditingWorker::default();
- let mut tool = comment_on_text("ships on Friday", None);
- tool.thread_id = Some(THREAD);
- let error = tool
- .call(
- context_with(
- AccessLevel::Comment,
- messages.clone(),
- "md",
- editing.clone(),
- ),
- request(),
- )
- .await
- .unwrap_err();
-
- assert!(
- error
- .description
- .contains("threadId and quote cannot be combined")
- );
- assert!(messages.posts.lock().unwrap().is_empty());
- assert!(editing.added_comment_marks.lock().unwrap().is_empty());
-}
-
-#[tokio::test]
-async fn comment_rejects_occurrence_without_quote() {
- for thread_id in [None, Some(THREAD)] {
- let messages = FakeMessages::default();
- let editing = FakeEditingWorker::default();
- let error = CommentOnDocument {
- document_id: DOCUMENT,
- content: "Looks good.".to_owned(),
- thread_id,
- quote: None,
- occurrence: Some(1),
- }
- .call(
- context_with(
- AccessLevel::Comment,
- messages.clone(),
- "md",
- editing.clone(),
- ),
- request(),
- )
- .await
- .unwrap_err();
-
- assert!(
- error
- .description
- .contains("occurrence only applies with quote")
- );
- assert!(messages.posts.lock().unwrap().is_empty());
- assert!(editing.added_comment_marks.lock().unwrap().is_empty());
- }
-}
-
-#[tokio::test]
-async fn discussion_comments_and_replies_support_non_markdown_documents() {
- for thread_id in [None, Some(THREAD)] {
- let messages = FakeMessages::default();
- let editing = FakeEditingWorker::default();
- let response = CommentOnDocument {
- document_id: DOCUMENT,
- content: "Looks good.".to_owned(),
- thread_id,
- quote: None,
- occurrence: None,
- }
- .call(
- context_with(
- AccessLevel::Comment,
- messages.clone(),
- "pdf",
- editing.clone(),
- ),
- request(),
- )
- .await
- .unwrap();
-
- assert_eq!(response.thread_id, thread_id.unwrap_or(response.comment_id));
- assert!(response.marked_text.is_none());
- let posts = messages.posts.lock().unwrap();
- assert_eq!(posts.len(), 1);
- assert_eq!(posts[0].1.thread_id, thread_id);
- assert!(posts[0].1.anchor.is_none());
- assert!(editing.added_comment_marks.lock().unwrap().is_empty());
- }
-}
-
-#[test]
-fn comment_optional_fields_can_be_omitted() {
- let tool: CommentOnDocument = serde_json::from_value(serde_json::json!({
- "documentId": DOCUMENT,
- "content": "Looks good.",
- }))
- .unwrap();
-
- assert!(tool.thread_id.is_none());
- assert!(tool.quote.is_none());
- assert!(tool.occurrence.is_none());
-}
-
-fn user_sender() -> ChannelSender<'static> {
- ChannelSender::try_from(USER.to_owned()).unwrap()
-}
-
-fn bot_sender() -> ChannelSender<'static> {
- ChannelSender::try_from(bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string()).unwrap()
-}
-
-fn assert_user_on_document(access: &EntityAccessReceipt<MessageWrite>) {
- assert_eq!(access.entity().entity_id, DOCUMENT.to_string());
- assert!(matches!(access.auth(), EntityAccessAuth::Authenticated(_)));
-}
-
-#[tokio::test]
-async fn edit_comment_rewrites_the_users_own_comment_as_the_user() {
- let messages = FakeMessages::with_comment_by(user_sender());
- let patches = messages.comment_patches.clone();
-
- EditDocumentComment {
- document_id: DOCUMENT,
- comment_id: THREAD,
- content: "clearer wording".to_owned(),
- }
- .call(context(AccessLevel::Comment, messages), request())
- .await
- .expect("the author can edit their comment");
-
- let patches = patches.lock().unwrap();
- let [(access, id, patch)] = patches.as_slice() else {
- panic!("expected one edit, got {}", patches.len());
- };
- assert_user_on_document(access);
- assert_eq!(*id, THREAD);
- assert_eq!(patch.content.as_deref(), Some("clearer wording"));
-}
-
-#[tokio::test]
-async fn edit_comment_rewrites_the_assistants_comment_as_the_bot() {
- let messages = FakeMessages::with_comment_by(bot_sender());
- let patches = messages.comment_patches.clone();
-
- EditDocumentComment {
- document_id: DOCUMENT,
- comment_id: THREAD,
- content: "corrected".to_owned(),
- }
- .call(context(AccessLevel::Comment, messages), request())
- .await
- .expect("the assistant can edit its own comment");
-
- assert_bot_on_document(&patches.lock().unwrap()[0].0);
-}
-
-#[tokio::test]
-async fn edit_comment_explains_that_only_the_author_can_edit() {
- let messages = FakeMessages {
- forbid_changes: true,
- ..FakeMessages::with_comment_by(user_sender())
- };
-
- let error = EditDocumentComment {
- document_id: DOCUMENT,
- comment_id: THREAD,
- content: "rewrite".to_owned(),
- }
- .call(context(AccessLevel::Comment, messages), request())
- .await
- .expect_err("the message service refused the edit");
-
- assert!(
- error.description.contains("author"),
- "{}",
- error.description
- );
-}
-
-#[tokio::test]
-async fn edit_comment_rejects_empty_text() {
- let error = EditDocumentComment {
- document_id: DOCUMENT,
- comment_id: THREAD,
- content: " ".to_owned(),
- }
- .call(
- context(AccessLevel::Comment, FakeMessages::default()),
- request(),
- )
- .await
- .expect_err("empty edits are refused");
-
- assert!(error.description.contains("DeleteDocumentComment"));
-}
-
-#[tokio::test]
-async fn delete_comment_reports_whether_the_thread_went_with_it() {
- let root = FakeMessages::with_comment_by(user_sender());
- let root_deletes = root.comment_deletes.clone();
- let response = DeleteDocumentComment {
- document_id: DOCUMENT,
- comment_id: THREAD,
- }
- .call(context(AccessLevel::Comment, root), request())
- .await
- .expect("the author can delete their comment");
- assert!(response.deleted_thread);
- assert_user_on_document(&root_deletes.lock().unwrap()[0].0);
-
- let reply = FakeMessages {
- comment_is_reply: true,
- ..FakeMessages::with_comment_by(user_sender())
- };
- let response = DeleteDocumentComment {
- document_id: DOCUMENT,
- comment_id: Uuid::from_u128(8),
- }
- .call(context(AccessLevel::Comment, reply), request())
- .await
- .expect("the author can delete their reply");
- assert!(!response.deleted_thread);
-}
-
-#[tokio::test]
-async fn delete_comment_explains_who_can_delete() {
- let messages = FakeMessages {
- forbid_changes: true,
- ..FakeMessages::with_comment_by(user_sender())
- };
-
- let error = DeleteDocumentComment {
- document_id: DOCUMENT,
- comment_id: THREAD,
- }
- .call(context(AccessLevel::Comment, messages), request())
- .await
- .expect_err("the message service refused the delete");
-
- assert!(error.description.contains("owner"), "{}", error.description);
-}
diff --git a/crates/documents/src/inbound/toolset/delete_document_comment.rs b/crates/documents/src/inbound/toolset/delete_document_comment.rs
deleted file mode 100644
index ecfacdad0e..0000000000
--- a/crates/documents/src/inbound/toolset/delete_document_comment.rs
+++ /dev/null
@@ -1,87 +0,0 @@
-//! DeleteDocumentComment tool for deleting a comment, reply, or whole thread.
-
-use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
-use ai_toolset::{ToolAnnotated, ToolAnnotations};
-use async_trait::async_trait;
-use entity_access::domain::ports::EntityAccessService;
-use messages::domain::ports::MessageError;
-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 = "DeleteDocumentComment",
- description = "Delete a comment or reply on a document. Deleting the first comment of a thread deletes the whole thread with its replies. Authors can delete their own comments, and the document owner can delete any comment. This cannot be undone. Comment ids come from the comments ReadContent returns. Use only when the user explicitly asks to delete a comment; use ResolveDocumentComment to close a thread instead."
-)]
-pub struct DeleteDocumentComment {
- #[schemars(description = "The id of the document the comment is on.")]
- pub document_id: Uuid,
-
- #[schemars(
- description = "The id of the comment or reply to delete, from ReadContent. Pass the thread id to delete the whole thread."
- )]
- pub comment_id: Uuid,
-}
-
-/// The deleted comment.
-#[derive(Debug, Serialize, JsonSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct DeleteDocumentCommentResponse {
- /// The document the comment was on.
- pub document_id: Uuid,
- /// The deleted comment.
- pub comment_id: Uuid,
- /// Whether the whole thread was deleted.
- pub deleted_thread: bool,
-}
-
-impl ToolAnnotated for DeleteDocumentComment {
- const ANNOTATIONS: ToolAnnotations =
- ToolAnnotations::destructive("Delete document comment").with_idempotent();
-}
-
-#[async_trait]
-impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for DeleteDocumentComment
-where
- DSvc: DocumentService + DocumentCreationService,
- ESvc: EntityAccessService,
- EDSvc: EditingWorkerService,
-{
- type Output = DeleteDocumentCommentResponse;
-
- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, document_id=%self.document_id, comment_id=%self.comment_id), err)]
- async fn call(
- &self,
- service_context: ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,
- request_context: RequestContext,
- ) -> ToolResult<Self::Output> {
- let access = service_context
- .require_comment_author_write(&request_context, self.document_id, self.comment_id)
- .await?;
- let deleted = service_context
- .messages
- .delete(access, self.comment_id, None)
- .await
- .map_err(|error| match error {
- MessageError::Forbidden => ToolCallError {
- description: "only the comment's author or the document owner can delete it"
- .to_string(),
- internal_error: anyhow::Error::new(error),
- },
- error => comment_error("unable to delete the comment")(error),
- })?;
-
- Ok(DeleteDocumentCommentResponse {
- document_id: self.document_id,
- comment_id: self.comment_id,
- deleted_thread: deleted.thread_id.is_none(),
- })
- }
-}
diff --git a/crates/documents/src/inbound/toolset/edit_document_comment.rs b/crates/documents/src/inbound/toolset/edit_document_comment.rs
deleted file mode 100644
index 27b0f85ab2..0000000000
--- a/crates/documents/src/inbound/toolset/edit_document_comment.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-//! EditDocumentComment tool for rewriting a comment or reply on a document.
-
-use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
-use ai_toolset::{ToolAnnotated, ToolAnnotations};
-use async_trait::async_trait;
-use entity_access::domain::ports::EntityAccessService;
-use messages::domain::ports::{MessageError, MessagePatch};
-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 = "EditDocumentComment",
- description = "Replace the text of a comment or reply on a document. Only a comment's author can edit it, so this edits comments the user wrote and comments this assistant wrote for them. Comment ids come from the comments ReadContent returns. Use only when the user asks to edit a comment."
-)]
-pub struct EditDocumentComment {
- #[schemars(description = "The id of the document the comment is on.")]
- pub document_id: Uuid,
-
- #[schemars(
- description = "The id of the comment or reply to edit, from ReadContent. For the first comment of a thread this is the thread id."
- )]
- pub comment_id: Uuid,
-
- #[schemars(description = "The full replacement text of the comment, in markdown.")]
- pub content: String,
-}
-
-/// The edited comment.
-#[derive(Debug, Serialize, JsonSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct EditDocumentCommentResponse {
- /// The document the comment is on.
- pub document_id: Uuid,
- /// The edited comment.
- pub comment_id: Uuid,
-}
-
-impl ToolAnnotated for EditDocumentComment {
- const ANNOTATIONS: ToolAnnotations =
- ToolAnnotations::destructive("Edit document comment").with_idempotent();
-}
-
-#[async_trait]
-impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for EditDocumentComment
-where
- DSvc: DocumentService + DocumentCreationService,
- ESvc: EntityAccessService,
- EDSvc: EditingWorkerService,
-{
- type Output = EditDocumentCommentResponse;
-
- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, document_id=%self.document_id, comment_id=%self.comment_id), err)]
- async fn call(
- &self,
- service_context: ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,
- request_context: RequestContext,
- ) -> ToolResult<Self::Output> {
- if self.content.trim().is_empty() {
- return Err(ToolCallError {
- description:
- "comment text must not be empty; use DeleteDocumentComment to remove a comment"
- .to_string(),
- internal_error: anyhow::anyhow!("empty comment edit"),
- });
- }
- let access = service_context
- .require_comment_author_write(&request_context, self.document_id, self.comment_id)
- .await?;
- service_context
- .messages
- .patch(
- access,
- self.comment_id,
- MessagePatch {
- content: Some(self.content.clone()),
- ..MessagePatch::default()
- },
- )
- .await
- .map_err(|error| match error {
- MessageError::Forbidden => ToolCallError {
- description: "only the comment's author can edit it".to_string(),
- internal_error: anyhow::Error::new(error),
- },
- error => comment_error("unable to edit the comment")(error),
- })?;
-
- Ok(EditDocumentCommentResponse {
- document_id: self.document_id,
- comment_id: self.comment_id,
- })
- }
-}
diff --git a/crates/documents/src/inbound/toolset/resolve_document_comment.rs b/crates/documents/src/inbound/toolset/resolve_document_comment.rs
deleted file mode 100644
index 44bef4b2bf..0000000000
--- a/crates/documents/src/inbound/toolset/resolve_document_comment.rs
+++ /dev/null
@@ -1,95 +0,0 @@
-//! 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.rs
index 468ed3d6fe..d75f764748 100644
--- a/crates/documents/src/inbound/toolset/test.rs
+++ b/crates/documents/src/inbound/toolset/test.rs
@@ -66,31 +66,13 @@ fn test_rename_document_schema_validation() {
}
#[test]
-fn test_resolve_document_comment_schema_validation() {
- let result = generate_validated_input_schema::<ResolveDocumentComment>();
+fn test_comment_on_text_schema_validation() {
+ let result = generate_validated_input_schema::<CommentOnText>();
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"
- );
-}
-
-#[test]
-fn test_comment_on_document_schema_validation() {
- let result = generate_validated_input_schema::<CommentOnDocument>();
- assert!(result.is_ok(), "{:?}", result);
-
- let validated = result.unwrap();
- assert_eq!(
- validated.name, "CommentOnDocument",
+ validated.name, "CommentOnText",
"Tool name should match the schemars title"
);
assert!(
@@ -102,44 +84,29 @@ fn test_comment_on_document_schema_validation() {
}
#[test]
-fn test_comment_on_document_schema_fields() {
- let schema = schemars::schema_for!(CommentOnDocument).to_value();
+fn test_comment_on_text_schema_fields() {
+ let schema = schemars::schema_for!(CommentOnText).to_value();
assert_eq!(
schema["required"],
- serde_json::json!(["documentId", "content"])
+ serde_json::json!(["documentId", "content", "quote"])
);
let properties = schema["properties"].as_object().unwrap();
- assert_eq!(properties.len(), 5);
- for name in ["documentId", "content", "threadId", "quote", "occurrence"] {
+ assert_eq!(properties.len(), 4);
+ for name in ["documentId", "content", "quote", "occurrence"] {
assert!(properties.contains_key(name), "missing {name}");
}
assert_eq!(properties["occurrence"]["minimum"], 1);
- let response = schemars::schema_for!(comment_on_document::CommentOnDocumentResponse).to_value();
+ let response = schemars::schema_for!(comment_on_text::CommentOnTextResponse).to_value();
assert_eq!(
response["required"],
- serde_json::json!(["documentId", "threadId", "commentId"])
+ serde_json::json!(["documentId", "threadId", "commentId", "markedText"])
);
- assert!(response["properties"].get("markedText").is_some());
}
#[test]
-fn test_comment_mutation_and_skill_schema_validation() {
- for (name, result) in [
- (
- "EditDocumentComment",
- generate_validated_input_schema::<EditDocumentComment>(),
- ),
- (
- "DeleteDocumentComment",
- generate_validated_input_schema::<DeleteDocumentComment>(),
- ),
- (
- "CreateSkill",
- generate_validated_input_schema::<CreateSkill>(),
- ),
- ] {
- let validated = result.unwrap_or_else(|error| panic!("{name}: {error:?}"));
- assert_eq!(validated.name, name);
- }
+fn test_create_skill_schema_validation() {
+ let validated = generate_validated_input_schema::<CreateSkill>()
+ .unwrap_or_else(|error| panic!("CreateSkill: {error:?}"));
+ assert_eq!(validated.name, "CreateSkill");
}
diff --git a/crates/documents/src/inbound/toolset/word_document.rs b/crates/documents/src/inbound/toolset/word_document.rs
index fa05e65567..0c27344416 100644
--- a/crates/documents/src/inbound/toolset/word_document.rs
+++ b/crates/documents/src/inbound/toolset/word_document.rs
@@ -38,7 +38,7 @@ pub struct ReadWordDocument {
#[serde(rename_all = "camelCase")]
#[schemars(
title = "EditWordDocument",
- description = "Edit an uploaded Word (.docx) document in place: an ordered batch of operations applied atomically to its live copy, so everyone with it open sees the change at once, and nothing changes if any operation fails. ReadWordDocument first and address paragraphs, tables and blocks by the ids it reports (they are not numbers). Use replaceText for wording changes (exact text within one paragraph; formatting is kept), setText to rewrite a whole paragraph, formatText for bold, italic, underline or strikethrough, insertParagraph to add paragraphs (each line of text becomes one; a style is optional), setStyle to change a paragraph style such as Heading1, delete to remove a paragraph, table or block, and addComment to add a Word comment on text. Only insertParagraph and addComment text may contain line breaks. Paragraphs inside table cells are edited the same way. Tracked changes (a redline): with trackChanges true, or when the document already tracks changes and trackChanges is omitted, edits are recorded as real Word revisions (insertions, deletions, formatting and style changes) that the counterparty can accept or reject in Word; pass trackChanges true whenever the user asks for a redline, tracked changes or a markup. Revisions and addComment comments are attributed to the requesting user by name, not to you; pass author only when the user names someone else (a firm or another person). addComment comments are saved in the file and travel with it to Word; use them for comments meant for whoever receives the document, and CommentOnDocument for discussion inside Macro. Returns the changed blocks as they now read, with the ids of new paragraphs; check them. At most 50 operations."
+ description = "Edit an uploaded Word (.docx) document in place: an ordered batch of operations applied atomically to its live copy, so everyone with it open sees the change at once, and nothing changes if any operation fails. ReadWordDocument first and address paragraphs, tables and blocks by the ids it reports (they are not numbers). Use replaceText for wording changes (exact text within one paragraph; formatting is kept), setText to rewrite a whole paragraph, formatText for bold, italic, underline or strikethrough, insertParagraph to add paragraphs (each line of text becomes one; a style is optional), setStyle to change a paragraph style such as Heading1, delete to remove a paragraph, table or block, and addComment to add a Word comment on text. Only insertParagraph and addComment text may contain line breaks. Paragraphs inside table cells are edited the same way. Tracked changes (a redline): with trackChanges true, or when the document already tracks changes and trackChanges is omitted, edits are recorded as real Word revisions (insertions, deletions, formatting and style changes) that the counterparty can accept or reject in Word; pass trackChanges true whenever the user asks for a redline, tracked changes or a markup. Revisions and addComment comments are attributed to the requesting user by name, not to you; pass author only when the user names someone else (a firm or another person). addComment comments are saved in the file and travel with it to Word; use them for comments meant for whoever receives the document, and Comment or CommentOnText for discussion inside Macro. Returns the changed blocks as they now read, with the ids of new paragraphs; check them. At most 50 operations."
)]
pub struct EditWordDocument {
/// Word document ID.
diff --git a/crates/messages/AGENTS.md b/crates/messages/AGENTS.md
index 6b837af7b9..50904af955 100644
--- a/crates/messages/AGENTS.md
+++ b/crates/messages/AGENTS.md
@@ -15,6 +15,14 @@ they need.
- `src/domain/api.rs`: `MessageServiceApi`, the boundary HTTP/agents/channel
adapters call through.
- `src/inbound/axum_router.rs`: the HTTP surface (feature `inbound`).
+- `src/inbound/toolset.rs`: the AI tools for any entity's Discussion
+ (`ReadDiscussion`, `Comment`, `EditComment`, `DeleteComment`,
+ `ResolveComment`; feature `ai_tools`), addressed by parent kind and id or by
+ a thread or comment id alone. `DiscussionParentType::from_parent` is
+ exhaustive: a new `MessageParent` variant decides there whether the tools
+ address it.
+- `src/domain/discussions.rs`: a parent's live threads with all replies, the
+ read both `ReadDiscussion` and the document comment reader share.
- `src/domain/service/guest_chat.rs` + `src/inbound/guest_chat.rs`: live guest
call discussions; the call domain verifies RTC credentials and membership.
- `src/outbound/pg_message_repo.rs` + `pg_discussion_context.rs`: Postgres
@@ -57,8 +65,8 @@ grant users another agent invocation's edit, deletion, or reaction authority.
## Gotchas
-- Most modules are feature-gated (`annotations`, `broker`, `delivery`,
- `inbound`, `outbound`, `ports`, `schema`); a caller enabling the wrong
+- Most modules are feature-gated (`ai_tools`, `annotations`, `broker`,
+ `delivery`, `inbound`, `outbound`, `ports`, `schema`); a caller enabling the wrong
combination gets a missing-module compile error, not a runtime one — check
`Cargo.toml`'s `[features]` table before adding a dependency edge.
diff --git a/crates/messages/Cargo.toml b/crates/messages/Cargo.toml
index 422ccc678f..ae95b8c86e 100644
--- a/crates/messages/Cargo.toml
+++ b/crates/messages/Cargo.toml
@@ -5,6 +5,7 @@ publish = false
version = "0.1.0"
[features]
+ai_tools = ["dep:ai_toolset", "dep:schemars", "ports"]
annotations = ["dep:model", "ports"]
broker = ["dep:macro_event_broker", "dep:macro_event_topics", "ports"]
default = []
@@ -36,6 +37,7 @@ test-utils = ["dep:mockall", "ports"]
[dependencies]
activity = { path = "../activity", default-features = false }
+ai_toolset = { path = "../ai_toolset", optional = true }
async-trait = { workspace = true, optional = true }
axum = { workspace = true, optional = true }
ip_extractor = { path = "../ip_extractor", optional = true }
@@ -78,4 +80,5 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
initiative = { path = "../initiative", default-features = false, features = ["postgres"] }
macro_db_migrator = { path = "../macro_db_migrator" }
+models_permissions = { path = "../models_permissions" }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/crates/messages/src/domain/discussions.rs b/crates/messages/src/domain/discussions.rs
new file mode 100644
index 0000000000..6bcb234742
--- /dev/null
+++ b/crates/messages/src/domain/discussions.rs
@@ -0,0 +1,117 @@
+//! A parent's live discussions as a reader of the whole entity sees them:
+//! every thread with all of its replies, oldest thread first.
+
+use std::collections::HashMap;
+
+use entity_access::domain::models::EntityAccessReceipt;
+use futures::{StreamExt, TryStreamExt, stream};
+use uuid::Uuid;
+
+use super::{
+ api::MessageReader,
+ models::{Message, MessageListItem, MessageThread},
+ ports::{MessageError, MessageTimelineQuery},
+ service::MessageView,
+};
+
+/// Discussions read per timeline page, the most the message service returns.
+pub const PAGE_SIZE: u16 = 100;
+
+/// Most discussions returned for one parent, newest kept, so a heavily
+/// discussed entity cannot crowd its own content out of an agent's context.
+pub const MAX_DISCUSSIONS: usize = 500;
+
+/// Concurrent thread lookups for one read.
+const LOOKUP_CONCURRENCY: usize = 8;
+
+/// Every live discussion on the parent `access` was minted for, oldest first,
+/// capped at [`MAX_DISCUSSIONS`]: [`live_roots`] followed by [`with_replies`].
+pub async fn live_threads<M: MessageReader + ?Sized>(
+ messages: &M,
+ access: &EntityAccessReceipt<MessageView>,
+) -> Result<Vec<MessageThread>, MessageError> {
+ let roots = live_roots(messages, access).await?;
+ with_replies(messages, access, roots).await
+}
+
+/// The live discussion roots on the parent `access` was minted for, newest
+/// first, capped at [`MAX_DISCUSSIONS`]. A deleted first comment with no live
+/// replies is not a live discussion.
+pub async fn live_roots<M: MessageReader + ?Sized>(
+ messages: &M,
+ access: &EntityAccessReceipt<MessageView>,
+) -> Result<Vec<MessageListItem>, MessageError> {
+ let mut roots = Vec::new();
+ let mut cursor = None;
+ loop {
+ let page = messages
+ .timeline(
+ access.clone(),
+ MessageTimelineQuery {
+ cursor,
+ limit: Some(PAGE_SIZE),
+ ..Default::default()
+ },
+ )
+ .await?;
+ // A deleted first comment with no live replies is not returned,
+ // so it must not count toward the cap.
+ roots.extend(
+ page.items
+ .into_iter()
+ .filter(|item| item.message.deleted_at.is_none() || item.thread.reply_count > 0),
+ );
+ if roots.len() >= MAX_DISCUSSIONS {
+ tracing::warn!(count = roots.len(), "discussions truncated");
+ roots.truncate(MAX_DISCUSSIONS);
+ return Ok(roots);
+ }
+ match page.next_cursor {
+ Some(next) => cursor = Some(next),
+ None => return Ok(roots),
+ }
+ }
+}
+
+/// The threads of `roots`, oldest first, each with its live replies: the
+/// timeline preview when it holds them all, else the full thread. A thread
+/// whose first comment was deleted is kept only while it has live replies.
+pub async fn with_replies<M: MessageReader + ?Sized>(
+ messages: &M,
+ access: &EntityAccessReceipt<MessageView>,
+ roots: Vec<MessageListItem>,
+) -> Result<Vec<MessageThread>, MessageError> {
+ let partial: Vec<Uuid> = roots
+ .iter()
+ .filter(|item| item.thread.reply_count > item.thread.preview.len() as i64)
+ .map(|item| item.message.id)
+ .collect();
+ let mut fetched: HashMap<Uuid, Vec<Message>> = stream::iter(partial)
+ .map(|root| async move {
+ let thread = messages.get_thread(access.clone(), root).await?;
+ Ok::<_, MessageError>((root, thread.replies))
+ })
+ .buffer_unordered(LOOKUP_CONCURRENCY)
+ .try_collect()
+ .await?;
+ Ok(roots
+ .into_iter()
+ .rev()
+ .filter_map(|item| {
+ let replies: Vec<Message> = fetched
+ .remove(&item.message.id)
+ .unwrap_or(item.thread.preview)
+ .into_iter()
+ .filter(|reply| reply.deleted_at.is_none())
+ .collect();
+ if item.message.deleted_at.is_some() && replies.is_empty() {
+ return None;
+ }
+ Some(MessageThread {
+ state: item.state,
+ root: item.message,
+ replies,
+ })
+ })
+ .collect())
+}
diff --git a/crates/messages/src/domain/mod.rs b/crates/messages/src/domain/mod.rs
index ac6beb3363..3a1ab5bcdb 100644
--- a/crates/messages/src/domain/mod.rs
+++ b/crates/messages/src/domain/mod.rs
@@ -7,6 +7,9 @@ pub mod api;
/// Contextual notifications and permission-aware realtime delivery.
#[cfg(feature = "ports")]
pub mod delivery;
+/// A parent's live discussions with all of their replies.
+#[cfg(feature = "ports")]
+pub mod discussions;
/// Independent delivery of committed facts.
#[cfg(feature = "ports")]
pub mod effects;
diff --git a/crates/messages/src/inbound/mod.rs b/crates/messages/src/inbound/mod.rs
index 25d3957d93..457bfd1c59 100644
--- a/crates/messages/src/inbound/mod.rs
+++ b/crates/messages/src/inbound/mod.rs
@@ -1,4 +1,9 @@
/// Parent-scoped message HTTP API.
+#[cfg(feature = "inbound")]
pub mod axum_router;
/// RTC-authenticated guest access to a call's discussion.
+#[cfg(feature = "inbound")]
pub mod guest_chat;
+/// AI tools for reading and writing any entity's Discussion.
+#[cfg(feature = "ai_tools")]
+pub mod toolset;
diff --git a/crates/messages/src/inbound/toolset.rs b/crates/messages/src/inbound/toolset.rs
new file mode 100644
index 0000000000..9edea2dcc7
--- /dev/null
+++ b/crates/messages/src/inbound/toolset.rs
@@ -0,0 +1,322 @@
+//! AI tools for the Discussion of every entity that carries one, addressed
+//! the way the rest of the system addresses a discussion: by the kind and id
+//! of its parent, or by a thread or comment id alone.
+
+mod comment;
+mod delete_comment;
+mod edit_comment;
+mod read_discussion;
+mod resolve_comment;
+
+#[cfg(test)]
+mod test;
+
+use std::sync::Arc;
+
+use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};
+use bot_id::BotId;
+use entity_access::domain::{
+ models::{AccessError, BotAccessScope, EntityAccessReceipt},
+ ports::EntityAccessService,
+};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+pub use comment::Comment;
+pub use delete_comment::DeleteComment;
+pub use edit_comment::EditComment;
+pub use read_discussion::ReadDiscussion;
+pub use resolve_comment::ResolveComment;
+
+use crate::domain::{
+ api::MessageServiceApi,
+ models::{InvalidParent, MessageParent},
+ ports::MessageError,
+ service::{MessageView, MessageWrite},
+};
+
+/// Service context for the discussion tools.
+pub struct MessageToolContext<ESvc: EntityAccessService> {
+ /// Shared message service the tools read and write discussions through.
+ pub messages: Arc<dyn MessageServiceApi>,
+ /// Mints the capabilities the message service requires.
+ pub entity_access_service: Arc<ESvc>,
+ /// The bot these tools post as, on behalf of the requesting user.
+ /// Defaults to Macro AI; hosts running a specific agent set it with
+ /// [`Self::with_actor`].
+ pub actor: BotId,
+}
+
+impl<ESvc: EntityAccessService> Clone for MessageToolContext<ESvc> {
+ fn clone(&self) -> Self {
+ Self {
+ messages: self.messages.clone(),
+ entity_access_service: self.entity_access_service.clone(),
+ actor: self.actor,
+ }
+ }
+}
+
+impl<ESvc: EntityAccessService> MessageToolContext<ESvc> {
+ /// Create a discussion tool context acting as Macro AI.
+ pub fn new(messages: Arc<dyn MessageServiceApi>, entity_access_service: Arc<ESvc>) -> Self {
+ Self {
+ messages,
+ entity_access_service,
+ actor: bot_id::MACRO_AI_BOT_ID,
+ }
+ }
+
+ /// Set the bot these tools act as.
+ pub fn with_actor(mut self, actor: BotId) -> Self {
+ self.actor = actor;
+ self
+ }
+
+ /// The requesting user's own view of a discussion.
+ async fn discussion_view(
+ &self,
+ request_context: &RequestContext,
+ parent: &MessageParent,
+ ) -> Result<EntityAccessReceipt<MessageView>, ToolCallError> {
+ self.entity_access_service
+ .generate_entity_access_receipt::<MessageView>(
+ &request_context.user_id,
+ None,
+ &parent.entity_id(),
+ parent.access_entity_type(),
+ )
+ .await
+ .map_err(access_error(parent, "view"))
+ }
+
+ /// The bot's comment capability on a discussion on behalf of the
+ /// requesting user: the same comment access the web composer requires.
+ async fn discussion_write(
+ &self,
+ request_context: &RequestContext,
+ parent: &MessageParent,
+ ) -> Result<EntityAccessReceipt<MessageWrite>, ToolCallError> {
+ self.entity_access_service
+ .generate_bot_entity_access_receipt::<MessageWrite>(
+ self.actor,
+ BotAccessScope::user(request_context.user_id.clone()),
+ &parent.entity_id(),
+ parent.access_entity_type(),
+ )
+ .await
+ .map_err(access_error(parent, "comment"))
+ }
+
+ /// The write capability for changing an existing comment as its author:
+ /// comments the tool actor bot posted are changed as the bot, and every
+ /// other comment as the user, so the message service applies the same
+ /// authorship and moderation rules as the web composer.
+ async fn comment_author_write(
+ &self,
+ request_context: &RequestContext,
+ parent: &MessageParent,
+ comment_id: Uuid,
+ ) -> Result<EntityAccessReceipt<MessageWrite>, ToolCallError> {
+ let view = self.discussion_view(request_context, parent).await?;
+ let comment = self
+ .messages
+ .get(view, comment_id)
+ .await
+ .map_err(comment_error("unable to read the comment"))?;
+ if comment.sender_id.as_ref() == self.actor.into_storage_id().as_ref() {
+ return self.discussion_write(request_context, parent).await;
+ }
+ self.entity_access_service
+ .generate_entity_access_receipt::<MessageWrite>(
+ &request_context.user_id,
+ None,
+ &parent.entity_id(),
+ parent.access_entity_type(),
+ )
+ .await
+ .map_err(access_error(parent, "comment"))
+ }
+
+ /// The Discussion a comment or thread belongs to, found from its id
+ /// alone. Grants nothing: the caller mints the parent's receipt before
+ /// reading or writing.
+ async fn discussion_of(
+ &self,
+ id: Uuid,
+ ) -> Result<(DiscussionParentType, MessageParent), ToolCallError> {
+ let parent = match self.messages.parent_of(id).await {
+ Ok(Some(parent)) => parent,
+ Ok(None) => {
+ return Err(ToolCallError {
+ description: format!("no comment or thread with id {id}"),
+ internal_error: MessageError::NotFound.into(),
+ });
+ }
+ Err(error) => {
+ return Err(ToolCallError {
+ description: "unable to look up the comment".to_owned(),
+ internal_error: error.into(),
+ });
+ }
+ };
+ match DiscussionParentType::from_parent(&parent) {
+ Some(kind) => Ok((kind, parent)),
+ None => Err(ToolCallError {
+ description: format!(
+ "{id} is a message in a {}, not a Discussion comment; use the channel message tools for it",
+ parent_noun(&parent)
+ ),
+ internal_error: MessageError::Invalid("message is not a discussion comment").into(),
+ }),
+ }
+ }
+}
+
+/// Create the discussion toolset.
+pub fn message_toolset<ESvc: EntityAccessService>() -> AsyncToolCollection<MessageToolContext<ESvc>>
+{
+ AsyncToolCollection::new()
+ .add_tool::<ReadDiscussion, MessageToolContext<ESvc>>()
+ .add_tool::<Comment, MessageToolContext<ESvc>>()
+ .add_tool::<EditComment, MessageToolContext<ESvc>>()
+ .add_tool::<DeleteComment, MessageToolContext<ESvc>>()
+ .add_tool::<ResolveComment, MessageToolContext<ESvc>>()
+}
+
+/// The kinds of item that carry a Discussion.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum DiscussionParentType {
+ /// A document of any type, including tasks, PDFs and uploaded files: the
+ /// id in a macro.com/app/<block>/<id> link such as /app/md/<id>,
+ /// /app/task/<id> or /app/pdf/<id>.
+ Document,
+ /// A Tasks project, which the API calls an initiative: the id in a
+ /// macro.com/app/tasks/projects/<id> link, the kind ReadInitiative reads.
+ /// Not a folder: folders (ReadProject) have no Discussion.
+ Initiative,
+ /// A CRM company, the kind GetCompany reads.
+ CrmCompany,
+ /// A CRM contact.
+ CrmContact,
+}
+
+impl DiscussionParentType {
+ /// The parent an item of this kind addresses, from its id.
+ fn parent(self, id: &str) -> Result<MessageParent, InvalidParent> {
+ let uuid = || id.parse::<Uuid>().map_err(|_| InvalidParent);
+ Ok(match self {
+ Self::Document => MessageParent::Document(id.to_owned().try_into()?),
+ Self::Initiative => MessageParent::Initiative(uuid()?),
+ Self::CrmCompany => MessageParent::CrmCompany(uuid()?),
+ Self::CrmContact => MessageParent::CrmContact(uuid()?),
+ })
+ }
+
+ /// The kind of a parent that carries a Discussion; `None` for a channel
+ /// or call, whose messages are not comments. Exhaustive on purpose: a new
+ /// parent decides here whether the discussion tools address it.
+ fn from_parent(parent: &MessageParent) -> Option<Self> {
+ match parent {
+ MessageParent::Document(_) => Some(Self::Document),
+ MessageParent::Initiative(_) => Some(Self::Initiative),
+ MessageParent::CrmCompany(_) => Some(Self::CrmCompany),
+ MessageParent::CrmContact(_) => Some(Self::CrmContact),
+ MessageParent::Channel(_) | MessageParent::Call(_) => None,
+ }
+ }
+
+ /// The word the application uses for an item of this kind.
+ fn noun(self) -> &'static str {
+ match self {
+ Self::Document => "document",
+ Self::Initiative => "project",
+ Self::CrmCompany => "company",
+ Self::CrmContact => "contact",
+ }
+ }
+}
+
+/// A parent addressed by kind and id, when both were given.
+fn parse_target(
+ entity_type: Option<DiscussionParentType>,
+ entity_id: Option<&str>,
+) -> Result<Option<(DiscussionParentType, MessageParent)>, ToolCallError> {
+ match (entity_type, entity_id) {
+ (None, None) => Ok(None),
+ (Some(kind), Some(id)) => {
+ kind.parent(id)
+ .map(|parent| Some((kind, parent)))
+ .map_err(|error| ToolCallError {
+ description: format!("{id} is not a valid {} id", kind.noun()),
+ internal_error: error.into(),
+ })
+ }
+ (Some(_), None) | (None, Some(_)) => Err(ToolCallError {
+ description: "entityType and entityId go together: pass both to address an item"
+ .to_owned(),
+ internal_error: InvalidParent.into(),
+ }),
+ }
+}
+
+/// The word the application uses for a parent, including the ones that
+/// carry no Discussion.
+fn parent_noun(parent: &MessageParent) -> &'static str {
+ match DiscussionParentType::from_parent(parent) {
+ Some(kind) => kind.noun(),
+ None => match parent {
+ MessageParent::Channel(_) => "channel",
+ _ => "call",
+ },
+ }
+}
+
+/// `need` is the access the tool spends on the parent: `view` or `comment`.
+fn access_error(
+ parent: &MessageParent,
+ need: &'static str,
+) -> impl FnOnce(AccessError) -> ToolCallError {
+ let kind = parent_noun(parent);
+ let id = parent.entity_id();
+ move |error| {
+ let description = match &error {
+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {
+ format!("you need {need} access to this {kind} to use its Discussion")
+ }
+ AccessError::NotFound(_) => format!(
+ "no {kind} with id {id}; check entityType: a Tasks project is initiative, a task or PDF is document, and a folder has no Discussion"
+ ),
+ AccessError::BadRequest(_) => format!("{id} is not a valid {kind} id"),
+ AccessError::Unavailable(_) | AccessError::Internal(_) => {
+ format!("failed to verify access to the {kind}")
+ }
+ };
+ ToolCallError {
+ description,
+ internal_error: error.into(),
+ }
+ }
+}
+
+fn comment_error(description: &'static str) -> impl FnOnce(MessageError) -> ToolCallError {
+ move |error| {
+ let description = match &error {
+ MessageError::NotFound => {
+ "comment thread not found in this item's Discussion".to_owned()
+ }
+ MessageError::Forbidden => {
+ "you need comment access to this item to comment on it".to_owned()
+ }
+ MessageError::Invalid(reason) => format!("{description}: {reason}"),
+ MessageError::Conflict => format!("{description}: message id already exists"),
+ MessageError::Repository(_) => description.to_owned(),
+ };
+ ToolCallError {
+ description,
+ internal_error: error.into(),
+ }
+ }
+}
diff --git a/crates/messages/src/inbound/toolset/comment.rs b/crates/messages/src/inbound/toolset/comment.rs
new file mode 100644
index 0000000000..5214c783d6
--- /dev/null
+++ b/crates/messages/src/inbound/toolset/comment.rs
@@ -0,0 +1,118 @@
+//! Comment tool for posting a Discussion comment or a reply on any item.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::{DiscussionParentType, MessageToolContext, comment_error, parse_target};
+use crate::domain::{
+ models::{MessageAttribution, PostMessage, PostMessageNotificationPolicy},
+ ports::MessageError,
+};
+
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "Comment",
+ description = "Add a comment to the Discussion of a document, task, Tasks project (initiative), CRM company or CRM contact on behalf of the user, or reply in an existing comment thread on any of them. For a new comment, address the item by entityType and entityId. For a reply, pass threadId; a thread id is enough to find its item, so entityType and entityId may be omitted. Thread ids come from ReadDiscussion, or from ReadContent for a document. Only use this when explicitly asked to comment or reply. Write content in Macro markdown and link people and items with the same mention tags as in documents; they render as chips and notify the people mentioned. To comment on a passage of text in a document, use CommentOnText instead; for a message in a channel, use SendChannelMessage."
+)]
+/// Post a Discussion comment on an item, or a reply in one of its threads.
+pub struct Comment {
+ /// The kind of item, with `entity_id`; optional for a reply.
+ #[schemars(
+ description = "The kind of item to comment on. Required with entityId for a new comment; optional for a reply."
+ )]
+ pub entity_type: Option<DiscussionParentType>,
+
+ /// The item, with `entity_type`; optional for a reply.
+ #[schemars(
+ description = "The id of the item to comment on. Required with entityType for a new comment; optional for a reply."
+ )]
+ pub entity_id: Option<String>,
+
+ /// The thread to reply in; absent starts a new thread.
+ #[schemars(
+ description = "The id of the thread to reply in. Omit to start a new Discussion comment on the item."
+ )]
+ pub thread_id: Option<Uuid>,
+
+ /// Macro Markdown body.
+ #[schemars(
+ description = "Comment content in Macro markdown, the same syntax as markdown documents, including mention tags."
+ )]
+ pub content: String,
+}
+
+/// The posted comment.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CommentResponse {
+ /// The kind of item the comment is on.
+ pub entity_type: DiscussionParentType,
+ /// The item the comment is on.
+ pub entity_id: String,
+ /// The thread the comment is in; a new comment starts its own.
+ pub thread_id: Uuid,
+ /// The posted comment.
+ pub comment_id: Uuid,
+}
+
+impl ToolAnnotated for Comment {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Comment");
+}
+
+#[async_trait]
+impl<ESvc: EntityAccessService> AsyncTool<MessageToolContext<ESvc>> for Comment {
+ type Output = CommentResponse;
+
+ #[tracing::instrument(skip_all, fields(entity_type = ?self.entity_type, entity_id = ?self.entity_id, thread_id = ?self.thread_id), err)]
+ async fn call(
+ &self,
+ ctx: ServiceContext<MessageToolContext<ESvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let target = parse_target(self.entity_type, self.entity_id.as_deref())?;
+ let (kind, parent) = match (target, self.thread_id) {
+ (Some(target), _) => target,
+ (None, Some(thread_id)) => ctx.discussion_of(thread_id).await?,
+ (None, None) => {
+ return Err(ToolCallError {
+ description:
+ "pass entityType and entityId for a new comment, or threadId for a reply"
+ .to_owned(),
+ internal_error: MessageError::Invalid("comment without a target").into(),
+ });
+ }
+ };
+ let access = ctx.discussion_write(&request_context, &parent).await?;
+ let message = ctx
+ .messages
+ .post(
+ access,
+ PostMessage {
+ id: None,
+ 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(CommentResponse {
+ entity_type: kind,
+ entity_id: parent.entity_id(),
+ thread_id: message.root_id(),
+ comment_id: message.id,
+ })
+ }
+}
diff --git a/crates/messages/src/inbound/toolset/delete_comment.rs b/crates/messages/src/inbound/toolset/delete_comment.rs
new file mode 100644
index 0000000000..e7345a41eb
--- /dev/null
+++ b/crates/messages/src/inbound/toolset/delete_comment.rs
@@ -0,0 +1,85 @@
+//! DeleteComment tool for deleting a comment, reply, or whole thread in any
+//! Discussion.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::{DiscussionParentType, MessageToolContext, comment_error};
+use crate::domain::ports::MessageError;
+
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "DeleteComment",
+ description = "Delete a comment or reply in the Discussion of a document, task, Tasks project, CRM company or CRM contact. Deleting the first comment of a thread deletes the whole thread with its replies. Authors can delete their own comments, and the item's owner can delete any comment. This cannot be undone. A comment id is enough to find its item. Comment ids come from ReadDiscussion, or from ReadContent for a document. Use only when the user explicitly asks to delete a comment; use ResolveComment to close a thread instead."
+)]
+/// Delete a comment, or a whole thread by its first comment.
+pub struct DeleteComment {
+ /// The comment to delete; a thread's first comment deletes the thread.
+ #[schemars(
+ description = "The id of the comment or reply to delete. Pass the thread id to delete the whole thread."
+ )]
+ pub comment_id: Uuid,
+}
+
+/// The deleted comment.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DeleteCommentResponse {
+ /// The kind of item the comment was on.
+ pub entity_type: DiscussionParentType,
+ /// The item the comment was on.
+ pub entity_id: String,
+ /// The deleted comment.
+ pub comment_id: Uuid,
+ /// Whether the whole thread was deleted.
+ pub deleted_thread: bool,
+}
+
+impl ToolAnnotated for DeleteComment {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Delete comment").with_idempotent();
+}
+
+#[async_trait]
+impl<ESvc: EntityAccessService> AsyncTool<MessageToolContext<ESvc>> for DeleteComment {
+ type Output = DeleteCommentResponse;
+
+ #[tracing::instrument(skip_all, fields(comment_id = %self.comment_id), err)]
+ async fn call(
+ &self,
+ ctx: ServiceContext<MessageToolContext<ESvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let (kind, parent) = ctx.discussion_of(self.comment_id).await?;
+ let access = ctx
+ .comment_author_write(&request_context, &parent, self.comment_id)
+ .await?;
+ let deleted = ctx
+ .messages
+ .delete(access, self.comment_id, None)
+ .await
+ .map_err(|error| match error {
+ MessageError::Forbidden => ToolCallError {
+ description: format!(
+ "only the comment's author or the {}'s owner can delete it",
+ kind.noun()
+ ),
+ internal_error: error.into(),
+ },
+ error => comment_error("unable to delete the comment")(error),
+ })?;
+
+ Ok(DeleteCommentResponse {
+ entity_type: kind,
+ entity_id: parent.entity_id(),
+ comment_id: self.comment_id,
+ deleted_thread: deleted.thread_id.is_none(),
+ })
+ }
+}
diff --git a/crates/messages/src/inbound/toolset/edit_comment.rs b/crates/messages/src/inbound/toolset/edit_comment.rs
new file mode 100644
index 0000000000..66e1b8b47a
--- /dev/null
+++ b/crates/messages/src/inbound/toolset/edit_comment.rs
@@ -0,0 +1,96 @@
+//! EditComment tool for rewriting a comment or reply in any Discussion.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::{DiscussionParentType, MessageToolContext, comment_error};
+use crate::domain::ports::{MessageError, MessagePatch};
+
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "EditComment",
+ description = "Replace the text of a comment or reply in the Discussion of a document, task, Tasks project, CRM company or CRM contact. Only a comment's author can edit it, so this edits comments the user wrote and comments this assistant wrote for them. A comment id is enough to find its item. Comment ids come from ReadDiscussion, or from ReadContent for a document. Use only when the user asks to edit a comment."
+)]
+/// Replace the text of a comment the user or the tool actor wrote.
+pub struct EditComment {
+ /// The comment to edit.
+ #[schemars(
+ description = "The id of the comment or reply to edit. For the first comment of a thread this is the thread id."
+ )]
+ pub comment_id: Uuid,
+
+ /// The replacement Macro Markdown body.
+ #[schemars(description = "The full replacement text of the comment, in Macro markdown.")]
+ pub content: String,
+}
+
+/// The edited comment.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct EditCommentResponse {
+ /// The kind of item the comment is on.
+ pub entity_type: DiscussionParentType,
+ /// The item the comment is on.
+ pub entity_id: String,
+ /// The edited comment.
+ pub comment_id: Uuid,
+}
+
+impl ToolAnnotated for EditComment {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::destructive("Edit comment").with_idempotent();
+}
+
+#[async_trait]
+impl<ESvc: EntityAccessService> AsyncTool<MessageToolContext<ESvc>> for EditComment {
+ type Output = EditCommentResponse;
+
+ #[tracing::instrument(skip_all, fields(comment_id = %self.comment_id), err)]
+ async fn call(
+ &self,
+ ctx: ServiceContext<MessageToolContext<ESvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ if self.content.trim().is_empty() {
+ return Err(ToolCallError {
+ description:
+ "comment text must not be empty; use DeleteComment to remove a comment"
+ .to_owned(),
+ internal_error: MessageError::Invalid("empty comment edit").into(),
+ });
+ }
+ let (kind, parent) = ctx.discussion_of(self.comment_id).await?;
+ let access = ctx
+ .comment_author_write(&request_context, &parent, self.comment_id)
+ .await?;
+ ctx.messages
+ .patch(
+ access,
+ self.comment_id,
+ MessagePatch {
+ content: Some(self.content.clone()),
+ ..MessagePatch::default()
+ },
+ )
+ .await
+ .map_err(|error| match error {
+ MessageError::Forbidden => ToolCallError {
+ description: "only the comment's author can edit it".to_owned(),
+ internal_error: error.into(),
+ },
+ error => comment_error("unable to edit the comment")(error),
+ })?;
+
+ Ok(EditCommentResponse {
+ entity_type: kind,
+ entity_id: parent.entity_id(),
+ comment_id: self.comment_id,
+ })
+ }
+}
diff --git a/crates/messages/src/inbound/toolset/read_discussion.rs b/crates/messages/src/inbound/toolset/read_discussion.rs
new file mode 100644
index 0000000000..8b342b1810
--- /dev/null
+++ b/crates/messages/src/inbound/toolset/read_discussion.rs
@@ -0,0 +1,153 @@
+//! ReadDiscussion tool for reading the comment threads on any item.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::{DiscussionParentType, MessageToolContext, comment_error};
+use crate::domain::{
+ discussions::live_threads,
+ models::{Message, MessageThread, ThreadAnchor},
+};
+
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ReadDiscussion",
+ description = "Read the comment threads in the Discussion of a document, task, Tasks project (initiative), CRM company or CRM contact: each thread's id, resolved state and comments, with their ids, authors and text, oldest thread first. Thread and comment ids are what Comment, EditComment, DeleteComment and ResolveComment take. For a document, ReadContent returns the same threads alongside the content, with the live text each inline comment is on."
+)]
+/// Read every live thread in an item's Discussion.
+pub struct ReadDiscussion {
+ /// The kind of item.
+ #[schemars(description = "The kind of item whose Discussion to read.")]
+ pub entity_type: DiscussionParentType,
+
+ /// The item.
+ #[schemars(description = "The id of the item.")]
+ pub entity_id: String,
+}
+
+/// A single comment in a thread.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DiscussionComment {
+ /// The comment id.
+ pub id: Uuid,
+ /// The user or bot id of the author.
+ pub author: String,
+ /// The author's display name, for bots and imported comments.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub author_name: Option<String>,
+ /// The comment body in markdown; absent when the comment was deleted.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub content: Option<String>,
+ /// When the comment was written.
+ pub created_at: DateTime<Utc>,
+ /// When the comment was last edited.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub edited_at: Option<DateTime<Utc>>,
+}
+
+/// A comment thread: its first comment followed by the replies.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DiscussionThread {
+ /// The thread id, which is the id of its first comment. Replies and
+ /// resolution address the thread by this id.
+ pub id: Uuid,
+ /// Whether the thread has been resolved.
+ pub resolved: bool,
+ /// For an inline comment on a document, the text it was written on;
+ /// absent for a comment on the item as a whole. ReadContent has the
+ /// text as the document reads now.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub marked_text: Option<String>,
+ /// The comments in order, first comment first.
+ pub comments: Vec<DiscussionComment>,
+}
+
+/// The item's Discussion.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ReadDiscussionResponse {
+ /// The kind of item.
+ pub entity_type: DiscussionParentType,
+ /// The item.
+ pub entity_id: String,
+ /// The live threads, oldest first.
+ pub threads: Vec<DiscussionThread>,
+}
+
+impl ToolAnnotated for ReadDiscussion {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Read discussion");
+}
+
+#[async_trait]
+impl<ESvc: EntityAccessService> AsyncTool<MessageToolContext<ESvc>> for ReadDiscussion {
+ type Output = ReadDiscussionResponse;
+
+ #[tracing::instrument(skip_all, fields(entity_type = ?self.entity_type, entity_id = %self.entity_id), err)]
+ async fn call(
+ &self,
+ ctx: ServiceContext<MessageToolContext<ESvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let parent = self
+ .entity_type
+ .parent(&self.entity_id)
+ .map_err(|error| ToolCallError {
+ description: format!(
+ "{} is not a valid {} id",
+ self.entity_id,
+ self.entity_type.noun()
+ ),
+ internal_error: error.into(),
+ })?;
+ let access = ctx.discussion_view(&request_context, &parent).await?;
+ let threads = live_threads(ctx.messages.as_ref(), &access)
+ .await
+ .map_err(comment_error("unable to read the discussion"))?;
+
+ Ok(ReadDiscussionResponse {
+ entity_type: self.entity_type,
+ entity_id: parent.entity_id(),
+ threads: threads.into_iter().map(thread).collect(),
+ })
+ }
+}
+
+fn thread(thread: MessageThread) -> DiscussionThread {
+ DiscussionThread {
+ id: thread.root.id,
+ resolved: thread.state.resolved,
+ marked_text: match thread.state.anchor {
+ Some(ThreadAnchor::Markdown { marked_text, .. })
+ | Some(ThreadAnchor::PdfHighlight { marked_text, .. }) => marked_text,
+ _ => None,
+ },
+ comments: std::iter::once(thread.root)
+ .chain(thread.replies)
+ .map(comment)
+ .collect(),
+ }
+}
+
+fn comment(message: Message) -> DiscussionComment {
+ let deleted = message.deleted_at.is_some();
+ DiscussionComment {
+ id: message.id,
+ author: message.sender_id.as_ref().to_owned(),
+ author_name: message
+ .imported_author
+ .map(|author| author.name)
+ .or(message.bot_profile.map(|bot| bot.name)),
+ content: (!deleted).then_some(message.content),
+ created_at: message.created_at,
+ edited_at: message.edited_at,
+ }
+}
diff --git a/crates/messages/src/inbound/toolset/resolve_comment.rs b/crates/messages/src/inbound/toolset/resolve_comment.rs
new file mode 100644
index 0000000000..c43ac4ba2c
--- /dev/null
+++ b/crates/messages/src/inbound/toolset/resolve_comment.rs
@@ -0,0 +1,90 @@
+//! ResolveComment tool for resolving and reopening comment threads in any
+//! Discussion.
+
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolResult};
+use ai_toolset::{ToolAnnotated, ToolAnnotations};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::{DiscussionParentType, MessageToolContext, comment_error};
+use crate::domain::models::ThreadPatch;
+
+fn default_resolved() -> bool {
+ true
+}
+
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ResolveComment",
+ description = "Resolve or reopen a comment thread in the Discussion of a document, task, Tasks project, CRM company or CRM contact on behalf of the user. A thread id is enough to find its item. Only use this when explicitly asked to resolve or reopen a comment. Thread ids come from ReadDiscussion, or from ReadContent for a document."
+)]
+/// Resolve or reopen a comment thread.
+pub struct ResolveComment {
+ /// The thread to change.
+ #[schemars(description = "The id of the thread to resolve or reopen.")]
+ pub thread_id: Uuid,
+
+ /// Whether the thread should be resolved; defaults to true.
+ #[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 ResolveCommentResponse {
+ /// The kind of item the thread is on.
+ pub entity_type: DiscussionParentType,
+ /// The item the thread is on.
+ pub entity_id: String,
+ /// The thread that was changed.
+ pub thread_id: Uuid,
+ /// Whether the thread is now resolved.
+ pub resolved: bool,
+}
+
+impl ToolAnnotated for ResolveComment {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Resolve comment");
+}
+
+#[async_trait]
+impl<ESvc: EntityAccessService> AsyncTool<MessageToolContext<ESvc>> for ResolveComment {
+ type Output = ResolveCommentResponse;
+
+ #[tracing::instrument(skip_all, fields(thread_id = %self.thread_id, resolved = self.resolved), err)]
+ async fn call(
+ &self,
+ ctx: ServiceContext<MessageToolContext<ESvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let (kind, parent) = ctx.discussion_of(self.thread_id).await?;
+ let access = ctx.discussion_write(&request_context, &parent).await?;
+ let state = ctx
+ .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(ResolveCommentResponse {
+ entity_type: kind,
+ entity_id: parent.entity_id(),
+ thread_id: state.root_id,
+ resolved: state.resolved,
+ })
+ }
+}
diff --git a/crates/messages/src/inbound/toolset/test.rs b/crates/messages/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..b0779ad758
--- /dev/null
+++ b/crates/messages/src/inbound/toolset/test.rs
@@ -0,0 +1,1045 @@
+use std::sync::{Arc, Mutex};
+
+use ai_toolset::schema::generate_validated_input_schema;
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext};
+use channel_sender::ChannelSender;
+use chrono::{TimeZone, Utc};
+use entity_access::domain::{
+ models::{
+ AccessError, BotAccessScope, BotId, CallChannelInfo, Entity, EntityAccessAuth,
+ EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission, TeamRole,
+ UserTeamInfo,
+ },
+ ports::EntityAccessService,
+};
+use macro_user_id::{
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
+use models_permissions::share_permission::access_level::AccessLevel;
+use uuid::Uuid;
+
+use super::{
+ Comment, DeleteComment, DiscussionParentType, EditComment, MessageToolContext, ReadDiscussion,
+ ResolveComment,
+};
+use crate::domain::{
+ api::{MessageCommands, MessageReader},
+ models::{
+ Message, MessageAttribution, MessageListItem, MessageParent, MessageThread,
+ MessageThreadPreview, PostMessage, PostMessageNotificationPolicy, ThreadAnchor,
+ ThreadPatch, ThreadState,
+ },
+ ports::{MessageError, MessagePage, MessagePatch, MessageTimelinePage, MessageTimelineQuery},
+ service::{MessageView, MessageWrite},
+};
+
+const USER: &str = "macro|[email protected]";
+const INITIATIVE: Uuid = Uuid::from_u128(0x019fd3b9_3c6c_7c05_89c2_a27f0121813b);
+const THREAD: Uuid = Uuid::from_u128(7);
+const REPLY: Uuid = Uuid::from_u128(8);
+const CHANNEL: Uuid = Uuid::from_u128(9);
+const POSTED: Uuid = Uuid::from_u128(99);
+
+fn at() -> chrono::DateTime<Utc> {
+ Utc.with_ymd_and_hms(2026, 9, 23, 12, 0, 0).unwrap()
+}
+
+fn initiative() -> MessageParent {
+ MessageParent::Initiative(INITIATIVE)
+}
+
+fn user_sender() -> ChannelSender<'static> {
+ ChannelSender::try_from(USER.to_owned()).unwrap()
+}
+
+fn bot_sender() -> ChannelSender<'static> {
+ ChannelSender::try_from(bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string()).unwrap()
+}
+
+fn message(id: Uuid, thread_id: Option<Uuid>, sender: ChannelSender<'static>) -> Message {
+ Message {
+ id,
+ parent: initiative(),
+ thread_id,
+ sender_id: sender,
+ guest_name: None,
+ imported_author: None,
+ bot_profile: None,
+ mentions: vec![],
+ triggered_by: None,
+ content: format!("comment {id}"),
+ created_at: at(),
+ updated_at: at(),
+ edited_at: None,
+ deleted_at: None,
+ attachments: vec![],
+ reactions: vec![],
+ }
+}
+
+fn thread(root: Uuid, replies: Vec<Message>, anchor: Option<ThreadAnchor>) -> MessageThread {
+ MessageThread {
+ state: ThreadState {
+ root_id: root,
+ user_id: USER.to_owned(),
+ resolved: false,
+ anchor,
+ created_at: at(),
+ updated_at: at(),
+ deleted_at: None,
+ },
+ root: message(root, None, user_sender()),
+ replies,
+ }
+}
+
+/// Records the writes the tools make. `parent` is what every id resolves
+/// to; `thread_exists` false answers a reply as the message service does
+/// for a thread not on the item.
+#[derive(Clone)]
+struct FakeMessages {
+ parent: Option<MessageParent>,
+ thread_exists: bool,
+ /// Author of the stored comment `get` returns; reads panic when unset.
+ comment_author: Option<ChannelSender<'static>>,
+ /// Whether the stored comment is a reply rather than a thread's first comment.
+ comment_is_reply: bool,
+ /// Refuse every comment edit or delete as the message service refuses a non-author.
+ forbid_changes: bool,
+ /// Threads the timeline lists, newest first. The preview holds one
+ /// reply at most, so longer threads are read in full.
+ threads: Vec<MessageThread>,
+ parent_lookups: Recorded<Uuid>,
+ posts: Recorded<(EntityAccessReceipt<MessageWrite>, PostMessage)>,
+ thread_patches: Recorded<(EntityAccessReceipt<MessageWrite>, Uuid, ThreadPatch)>,
+ comment_patches: Recorded<(EntityAccessReceipt<MessageWrite>, Uuid, MessagePatch)>,
+ comment_deletes: Recorded<(EntityAccessReceipt<MessageWrite>, Uuid)>,
+}
+
+/// The calls a fake records, shared with the test that inspects them.
+type Recorded<T> = Arc<Mutex<Vec<T>>>;
+
+impl Default for FakeMessages {
+ fn default() -> Self {
+ Self {
+ parent: Some(initiative()),
+ thread_exists: true,
+ comment_author: None,
+ comment_is_reply: false,
+ forbid_changes: false,
+ threads: vec![],
+ parent_lookups: Arc::default(),
+ posts: Arc::default(),
+ thread_patches: Arc::default(),
+ comment_patches: Arc::default(),
+ comment_deletes: Arc::default(),
+ }
+ }
+}
+
+impl FakeMessages {
+ fn with_comment_by(author: ChannelSender<'static>) -> Self {
+ Self {
+ comment_author: Some(author),
+ ..Self::default()
+ }
+ }
+
+ fn stored_comment(&self, id: Uuid) -> Message {
+ message(
+ id,
+ self.comment_is_reply.then_some(THREAD),
+ self.comment_author
+ .clone()
+ .expect("test configured a stored comment"),
+ )
+ }
+}
+
+#[async_trait::async_trait]
+impl MessageReader for FakeMessages {
+ async fn get(
+ &self,
+ _access: EntityAccessReceipt<MessageView>,
+ id: Uuid,
+ ) -> Result<Message, MessageError> {
+ Ok(self.stored_comment(id))
+ }
+ async fn get_thread(
+ &self,
+ _access: EntityAccessReceipt<MessageView>,
+ root: Uuid,
+ ) -> Result<MessageThread, MessageError> {
+ self.threads
+ .iter()
+ .find(|thread| thread.root.id == root)
+ .cloned()
+ .ok_or(MessageError::NotFound)
+ }
+ async fn timeline(
+ &self,
+ _access: EntityAccessReceipt<MessageView>,
+ _query: MessageTimelineQuery,
+ ) -> Result<MessagePage, MessageError> {
+ Ok(MessagePage {
+ items: self
+ .threads
+ .iter()
+ .map(|thread| MessageListItem {
+ message: thread.root.clone(),
+ state: thread.state.clone(),
+ thread: MessageThreadPreview {
+ reply_count: thread.replies.len() as i64,
+ latest_reply_at: None,
+ preview: thread.replies.iter().take(1).cloned().collect(),
+ },
+ })
+ .collect(),
+ next_cursor: None,
+ previous_cursor: None,
+ })
+ }
+ async fn timeline_entries(
+ &self,
+ _access: EntityAccessReceipt<MessageView>,
+ _query: MessageTimelineQuery,
+ ) -> Result<MessageTimelinePage, MessageError> {
+ panic!("unexpected timeline_entries 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 fn parent_of(&self, id: Uuid) -> Result<Option<MessageParent>, MessageError> {
+ self.parent_lookups.lock().unwrap().push(id);
+ Ok(self.parent.clone())
+ }
+}
+
+#[async_trait::async_trait]
+impl MessageCommands for FakeMessages {
+ async fn post_from_event(
+ &self,
+ _: EntityAccessReceipt<MessageWrite>,
+ _: Uuid,
+ _: PostMessage,
+ ) -> Result<Message, MessageError> {
+ panic!("discussion tools do not post broker events")
+ }
+ 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 posted = Message {
+ content: input.content.clone(),
+ triggered_by: Some(USER.to_owned()),
+ ..message(POSTED, input.thread_id, bot_sender())
+ };
+ self.posts.lock().unwrap().push((access, input));
+ Ok(posted)
+ }
+ async fn patch(
+ &self,
+ access: EntityAccessReceipt<MessageWrite>,
+ id: Uuid,
+ input: MessagePatch,
+ ) -> Result<Message, MessageError> {
+ if self.forbid_changes {
+ return Err(MessageError::Forbidden);
+ }
+ self.comment_patches
+ .lock()
+ .unwrap()
+ .push((access, id, input));
+ Ok(self.stored_comment(id))
+ }
+ async fn delete(
+ &self,
+ access: EntityAccessReceipt<MessageWrite>,
+ id: Uuid,
+ _nonce: Option<String>,
+ ) -> Result<Message, MessageError> {
+ if self.forbid_changes {
+ return Err(MessageError::Forbidden);
+ }
+ self.comment_deletes.lock().unwrap().push((access, id));
+ Ok(self.stored_comment(id))
+ }
+ 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 state = ThreadState {
+ root_id,
+ user_id: USER.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")
+ }
+}
+
+/// Grants `access_level` on every entity, or finds none of them.
+#[derive(Clone)]
+struct FakeEntityAccessService {
+ access_level: AccessLevel,
+ not_found: bool,
+}
+
+impl EntityAccessService for FakeEntityAccessService {
+ async fn generate_entity_access_receipt<T: RequiredPermission>(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ _user_org_id: Option<i64>,
+ entity_id: &str,
+ entity_type: EntityType,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ if self.not_found {
+ return Err(AccessError::NotFound("entity"));
+ }
+ EntityAccessReceipt::try_new_authenticated_user(
+ MacroUserIdStr::try_from(user_id.as_ref().to_string())
+ .expect("test user id should be valid"),
+ Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ EntityPermission::AccessLevel {
+ 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,
+ ) -> Result<EntityAccessReceipt<T>, AccessError> {
+ if self.not_found {
+ return Err(AccessError::NotFound("entity"));
+ }
+ EntityAccessReceipt::try_new_bot(
+ bot_id.into_storage_id(),
+ (&scope).into(),
+ Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ EntityPermission::AccessLevel {
+ access_level: self.access_level,
+ },
+ )
+ }
+
+ async fn get_access_level(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ panic!("unexpected get_access_level call")
+ }
+
+ async fn check_access(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ panic!("unexpected check_access call")
+ }
+
+ async fn check_public_access(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _required_level: AccessLevel,
+ ) -> Result<AccessLevel, AccessError> {
+ panic!("unexpected check_public_access call")
+ }
+
+ async fn get_entity_permission(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ _user_org_id: Option<i64>,
+ ) -> Result<EntityPermission, AccessError> {
+ panic!("unexpected get_entity_permission call")
+ }
+
+ async fn get_crm_entity_permission_with_team(
+ &self,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {
+ panic!("unexpected get_crm_entity_permission_with_team call")
+ }
+
+ async fn get_users_by_entity(
+ &self,
+ _entity_id: &str,
+ _entity_type: EntityType,
+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
+ panic!("unexpected get_users_by_entity call")
+ }
+
+ async fn get_call_channel(
+ &self,
+ _call_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ panic!("unexpected get_call_channel call")
+ }
+
+ async fn get_call_channel_by_channel_id(
+ &self,
+ _channel_id: &Uuid,
+ ) -> Result<Option<CallChannelInfo>, AccessError> {
+ panic!("unexpected get_call_channel_by_channel_id call")
+ }
+
+ async fn get_user_team(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Option<UserTeamInfo>, AccessError> {
+ panic!("unexpected get_user_team call")
+ }
+}
+
+type TestToolContext = MessageToolContext<FakeEntityAccessService>;
+
+fn context(access_level: AccessLevel, messages: FakeMessages) -> ServiceContext<TestToolContext> {
+ ServiceContext(MessageToolContext::new(
+ Arc::new(messages),
+ Arc::new(FakeEntityAccessService {
+ access_level,
+ not_found: false,
+ }),
+ ))
+}
+
+fn context_without_items(messages: FakeMessages) -> ServiceContext<TestToolContext> {
+ ServiceContext(MessageToolContext::new(
+ Arc::new(messages),
+ Arc::new(FakeEntityAccessService {
+ access_level: AccessLevel::Owner,
+ not_found: true,
+ }),
+ ))
+}
+
+fn request() -> RequestContext {
+ RequestContext::new(MacroUserIdStr::try_from(USER.to_owned()).unwrap())
+}
+
+fn comment_on_initiative(content: &str) -> Comment {
+ Comment {
+ entity_type: Some(DiscussionParentType::Initiative),
+ entity_id: Some(INITIATIVE.to_string()),
+ thread_id: None,
+ content: content.to_owned(),
+ }
+}
+
+fn reply(thread_id: Uuid, content: &str) -> Comment {
+ Comment {
+ entity_type: None,
+ entity_id: None,
+ thread_id: Some(thread_id),
+ content: content.to_owned(),
+ }
+}
+
+/// The write went to the initiative as the tool actor bot on the user's behalf.
+fn assert_bot_on_initiative(access: &EntityAccessReceipt<MessageWrite>) {
+ assert_eq!(access.entity().entity_id, INITIATIVE.to_string());
+ assert_eq!(access.entity().entity_type, EntityType::Initiative);
+ assert!(matches!(access.auth(), EntityAccessAuth::Bot(_)));
+ assert_eq!(
+ access.acting_user_id().map(|user| user.as_ref()),
+ Some(USER)
+ );
+}
+
+fn assert_user_on_initiative(access: &EntityAccessReceipt<MessageWrite>) {
+ assert_eq!(access.entity().entity_id, INITIATIVE.to_string());
+ assert_eq!(access.entity().entity_type, EntityType::Initiative);
+ assert!(matches!(access.auth(), EntityAccessAuth::Authenticated(_)));
+}
+
+#[tokio::test]
+async fn comment_on_a_project_posts_as_the_bot_for_the_user() {
+ let messages = FakeMessages::default();
+ let response = comment_on_initiative("Rollout tracking lives in two docs.")
+ .call(context(AccessLevel::Comment, messages.clone()), request())
+ .await
+ .unwrap();
+
+ assert_eq!(response.entity_type, DiscussionParentType::Initiative);
+ assert_eq!(response.entity_id, INITIATIVE.to_string());
+ assert_eq!(response.thread_id, response.comment_id);
+ assert_eq!(response.comment_id, POSTED);
+ let posts = messages.posts.lock().unwrap();
+ let [(access, post)] = posts.as_slice() else {
+ panic!("expected one post, got {}", posts.len());
+ };
+ assert_bot_on_initiative(access);
+ assert_eq!(post.thread_id, None);
+ assert_eq!(post.content, "Rollout tracking lives in two docs.");
+ assert_eq!(post.attribution, MessageAttribution::ActingUser);
+ assert_eq!(
+ post.notification_policy,
+ PostMessageNotificationPolicy::Default
+ );
+ assert!(post.anchor.is_none());
+ assert!(messages.parent_lookups.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn reply_by_thread_id_alone_finds_its_item() {
+ let messages = FakeMessages::default();
+ let response = reply(THREAD, "Fixed in the latest draft.")
+ .call(context(AccessLevel::Comment, messages.clone()), request())
+ .await
+ .unwrap();
+
+ assert_eq!(response.entity_type, DiscussionParentType::Initiative);
+ assert_eq!(response.entity_id, INITIATIVE.to_string());
+ assert_eq!(response.thread_id, THREAD);
+ assert_eq!(response.comment_id, POSTED);
+ assert_eq!(*messages.parent_lookups.lock().unwrap(), vec![THREAD]);
+ let posts = messages.posts.lock().unwrap();
+ assert_bot_on_initiative(&posts[0].0);
+ assert_eq!(posts[0].1.thread_id, Some(THREAD));
+}
+
+#[tokio::test]
+async fn reply_with_its_item_given_needs_no_lookup() {
+ let messages = FakeMessages {
+ parent: None,
+ ..FakeMessages::default()
+ };
+ let mut tool = comment_on_initiative("Done.");
+ tool.thread_id = Some(THREAD);
+ let response = tool
+ .call(context(AccessLevel::Comment, messages.clone()), request())
+ .await
+ .unwrap();
+
+ assert_eq!(response.thread_id, THREAD);
+ assert!(messages.parent_lookups.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn reply_to_a_thread_not_on_the_item_says_so() {
+ let messages = FakeMessages {
+ thread_exists: false,
+ ..FakeMessages::default()
+ };
+ let mut tool = comment_on_initiative("Done.");
+ tool.thread_id = Some(THREAD);
+ let error = tool
+ .call(context(AccessLevel::Edit, messages), request())
+ .await
+ .unwrap_err();
+
+ assert!(
+ error.description.contains("thread not found"),
+ "{}",
+ error.description
+ );
+}
+
+#[tokio::test]
+async fn comment_needs_a_target() {
+ let messages = FakeMessages::default();
+ let error = Comment {
+ entity_type: None,
+ entity_id: None,
+ thread_id: None,
+ content: "Looks good.".to_owned(),
+ }
+ .call(context(AccessLevel::Comment, messages.clone()), request())
+ .await
+ .unwrap_err();
+
+ assert!(
+ error.description.contains("entityType and entityId"),
+ "{}",
+ error.description
+ );
+ assert!(messages.posts.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn entity_type_without_entity_id_is_refused() {
+ let error = Comment {
+ entity_type: Some(DiscussionParentType::Document),
+ entity_id: None,
+ thread_id: None,
+ content: "Looks good.".to_owned(),
+ }
+ .call(
+ context(AccessLevel::Comment, FakeMessages::default()),
+ request(),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(
+ error.description.contains("go together"),
+ "{}",
+ error.description
+ );
+}
+
+#[tokio::test]
+async fn comment_needs_comment_access() {
+ let messages = FakeMessages::default();
+ let error = comment_on_initiative("Looks good.")
+ .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 comment_on_an_unknown_item_points_at_the_kind() {
+ let error = comment_on_initiative("Looks good.")
+ .call(context_without_items(FakeMessages::default()), request())
+ .await
+ .unwrap_err();
+
+ assert!(
+ error.description.contains("no project with id"),
+ "{}",
+ error.description
+ );
+ assert!(
+ error.description.contains("entityType"),
+ "{}",
+ error.description
+ );
+}
+
+#[tokio::test]
+async fn reply_in_a_channel_thread_is_refused() {
+ let messages = FakeMessages {
+ parent: Some(MessageParent::Channel(CHANNEL)),
+ ..FakeMessages::default()
+ };
+ let error = reply(THREAD, "Looks good.")
+ .call(context(AccessLevel::Comment, messages.clone()), request())
+ .await
+ .unwrap_err();
+
+ assert!(
+ error.description.contains("channel"),
+ "{}",
+ error.description
+ );
+ assert!(messages.posts.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn reply_to_an_unknown_thread_says_so() {
+ let messages = FakeMessages {
+ parent: None,
+ ..FakeMessages::default()
+ };
+ let error = reply(THREAD, "Looks good.")
+ .call(context(AccessLevel::Comment, messages), request())
+ .await
+ .unwrap_err();
+
+ assert!(
+ error.description.contains("no comment or thread"),
+ "{}",
+ error.description
+ );
+}
+
+#[tokio::test]
+async fn read_discussion_lists_threads_oldest_first_with_every_live_reply() {
+ let older = Uuid::from_u128(1);
+ let newer = Uuid::from_u128(2);
+ let deleted_reply = Message {
+ deleted_at: Some(at()),
+ ..message(Uuid::from_u128(12), Some(older), user_sender())
+ };
+ let messages = FakeMessages {
+ threads: vec![
+ thread(
+ newer,
+ vec![message(Uuid::from_u128(21), Some(newer), bot_sender())],
+ Some(ThreadAnchor::Markdown {
+ mark_id: Uuid::from_u128(5),
+ marked_text: Some("ships on Friday".to_owned()),
+ }),
+ ),
+ thread(
+ older,
+ vec![
+ message(Uuid::from_u128(11), Some(older), user_sender()),
+ deleted_reply,
+ message(Uuid::from_u128(13), Some(older), user_sender()),
+ ],
+ None,
+ ),
+ ],
+ ..FakeMessages::default()
+ };
+ let response = ReadDiscussion {
+ entity_type: DiscussionParentType::Initiative,
+ entity_id: INITIATIVE.to_string(),
+ }
+ .call(context(AccessLevel::View, messages), request())
+ .await
+ .unwrap();
+
+ assert_eq!(response.entity_type, DiscussionParentType::Initiative);
+ assert_eq!(response.entity_id, INITIATIVE.to_string());
+ let [first, second] = response.threads.as_slice() else {
+ panic!("expected two threads, got {}", response.threads.len());
+ };
+ assert_eq!(first.id, older);
+ assert!(first.marked_text.is_none());
+ assert_eq!(
+ first
+ .comments
+ .iter()
+ .map(|comment| comment.id)
+ .collect::<Vec<_>>(),
+ vec![older, Uuid::from_u128(11), Uuid::from_u128(13)]
+ );
+ assert_eq!(second.id, newer);
+ assert_eq!(second.marked_text.as_deref(), Some("ships on Friday"));
+ assert_eq!(second.comments.len(), 2);
+ assert_eq!(
+ second.comments[1].author,
+ bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string()
+ );
+}
+
+#[tokio::test]
+async fn read_discussion_on_an_unknown_item_points_at_the_kind() {
+ let error = ReadDiscussion {
+ entity_type: DiscussionParentType::CrmCompany,
+ entity_id: INITIATIVE.to_string(),
+ }
+ .call(context_without_items(FakeMessages::default()), request())
+ .await
+ .unwrap_err();
+
+ assert!(
+ error.description.contains("no company with id"),
+ "{}",
+ error.description
+ );
+}
+
+#[tokio::test]
+async fn read_discussion_rejects_an_invalid_id() {
+ let error = ReadDiscussion {
+ entity_type: DiscussionParentType::Initiative,
+ entity_id: "not-a-uuid".to_owned(),
+ }
+ .call(
+ context(AccessLevel::View, FakeMessages::default()),
+ request(),
+ )
+ .await
+ .unwrap_err();
+
+ assert_eq!(error.description, "not-a-uuid is not a valid project id");
+}
+
+#[tokio::test]
+async fn resolve_resolves_the_thread_as_the_bot_for_the_user() {
+ let messages = FakeMessages::default();
+ let response = ResolveComment {
+ thread_id: THREAD,
+ resolved: true,
+ }
+ .call(context(AccessLevel::Comment, messages.clone()), request())
+ .await
+ .unwrap();
+
+ assert_eq!(response.entity_type, DiscussionParentType::Initiative);
+ assert_eq!(response.entity_id, INITIATIVE.to_string());
+ 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_initiative(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 = ResolveComment {
+ 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: ResolveComment = serde_json::from_value(serde_json::json!({
+ "threadId": THREAD,
+ }))
+ .unwrap();
+
+ assert!(tool.resolved);
+}
+
+#[tokio::test]
+async fn resolve_needs_comment_access() {
+ let messages = FakeMessages::default();
+ let error = ResolveComment {
+ 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());
+}
+
+#[tokio::test]
+async fn edit_comment_rewrites_the_users_own_comment_as_the_user() {
+ let messages = FakeMessages::with_comment_by(user_sender());
+ let patches = messages.comment_patches.clone();
+
+ let response = EditComment {
+ comment_id: THREAD,
+ content: "clearer wording".to_owned(),
+ }
+ .call(context(AccessLevel::Comment, messages), request())
+ .await
+ .expect("the author can edit their comment");
+
+ assert_eq!(response.entity_id, INITIATIVE.to_string());
+ let patches = patches.lock().unwrap();
+ let [(access, id, patch)] = patches.as_slice() else {
+ panic!("expected one edit, got {}", patches.len());
+ };
+ assert_user_on_initiative(access);
+ assert_eq!(*id, THREAD);
+ assert_eq!(patch.content.as_deref(), Some("clearer wording"));
+}
+
+#[tokio::test]
+async fn edit_comment_rewrites_the_assistants_comment_as_the_bot() {
+ let messages = FakeMessages::with_comment_by(bot_sender());
+ let patches = messages.comment_patches.clone();
+
+ EditComment {
+ comment_id: THREAD,
+ content: "corrected".to_owned(),
+ }
+ .call(context(AccessLevel::Comment, messages), request())
+ .await
+ .expect("the assistant can edit its own comment");
+
+ assert_bot_on_initiative(&patches.lock().unwrap()[0].0);
+}
+
+#[tokio::test]
+async fn edit_comment_explains_that_only_the_author_can_edit() {
+ let messages = FakeMessages {
+ forbid_changes: true,
+ ..FakeMessages::with_comment_by(user_sender())
+ };
+
+ let error = EditComment {
+ comment_id: THREAD,
+ content: "rewrite".to_owned(),
+ }
+ .call(context(AccessLevel::Comment, messages), request())
+ .await
+ .expect_err("the message service refused the edit");
+
+ assert!(
+ error.description.contains("author"),
+ "{}",
+ error.description
+ );
+}
+
+#[tokio::test]
+async fn edit_comment_rejects_empty_text() {
+ let error = EditComment {
+ comment_id: THREAD,
+ content: " ".to_owned(),
+ }
+ .call(
+ context(AccessLevel::Comment, FakeMessages::default()),
+ request(),
+ )
+ .await
+ .expect_err("empty edits are refused");
+
+ assert!(error.description.contains("DeleteComment"));
+}
+
+#[tokio::test]
+async fn delete_comment_reports_whether_the_thread_went_with_it() {
+ let root = FakeMessages::with_comment_by(user_sender());
+ let root_deletes = root.comment_deletes.clone();
+ let response = DeleteComment { comment_id: THREAD }
+ .call(context(AccessLevel::Comment, root), request())
+ .await
+ .expect("the author can delete their comment");
+ assert!(response.deleted_thread);
+ assert_eq!(response.entity_id, INITIATIVE.to_string());
+ assert_user_on_initiative(&root_deletes.lock().unwrap()[0].0);
+
+ let reply = FakeMessages {
+ comment_is_reply: true,
+ ..FakeMessages::with_comment_by(user_sender())
+ };
+ let response = DeleteComment { comment_id: REPLY }
+ .call(context(AccessLevel::Comment, reply), request())
+ .await
+ .expect("the author can delete their reply");
+ assert!(!response.deleted_thread);
+}
+
+#[tokio::test]
+async fn delete_comment_explains_who_can_delete() {
+ let messages = FakeMessages {
+ forbid_changes: true,
+ ..FakeMessages::with_comment_by(user_sender())
+ };
+
+ let error = DeleteComment { comment_id: THREAD }
+ .call(context(AccessLevel::Comment, messages), request())
+ .await
+ .expect_err("the message service refused the delete");
+
+ assert!(
+ error.description.contains("project's owner"),
+ "{}",
+ error.description
+ );
+}
+
+#[test]
+fn tool_schemas_are_valid() {
+ for (name, result) in [
+ (
+ "ReadDiscussion",
+ generate_validated_input_schema::<ReadDiscussion>(),
+ ),
+ ("Comment", generate_validated_input_schema::<Comment>()),
+ (
+ "EditComment",
+ generate_validated_input_schema::<EditComment>(),
+ ),
+ (
+ "DeleteComment",
+ generate_validated_input_schema::<DeleteComment>(),
+ ),
+ (
+ "ResolveComment",
+ generate_validated_input_schema::<ResolveComment>(),
+ ),
+ ] {
+ let validated = result.unwrap_or_else(|error| panic!("{name}: {error:?}"));
+ assert_eq!(validated.name, name);
+ }
+
+ let schema = schemars::schema_for!(Comment).to_value();
+ assert_eq!(schema["required"], serde_json::json!(["content"]));
+ let properties = schema["properties"].as_object().unwrap();
+ for name in ["entityType", "entityId", "threadId", "content"] {
+ assert!(properties.contains_key(name), "missing {name}");
+ }
+}
diff --git a/crates/messages/src/lib.rs b/crates/messages/src/lib.rs
index 3d44e24366..80a4c42c4e 100644
--- a/crates/messages/src/lib.rs
+++ b/crates/messages/src/lib.rs
@@ -3,8 +3,8 @@
/// Transport-independent message models, policies, and services.
pub mod domain;
-/// HTTP adapters for the shared message use cases.
-#[cfg(feature = "inbound")]
+/// HTTP and AI tool adapters for the shared message use cases.
+#[cfg(any(feature = "inbound", feature = "ai_tools"))]
pub mod inbound;
/// Database and external delivery adapters.
#[cfg(any(feature = "outbound", feature = "broker"))]
diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.md
index a0feba3427..c0fa44cc96 100644
--- a/docs/agent-guide/ai-chat.md
+++ b/docs/agent-guide/ai-chat.md
@@ -1096,14 +1096,17 @@ list, create, and update projects (initiatives in the API) and move tasks in or
render `displayResults` views). Requests go to `POST /cognition/stream/chat/message`; results
stream over the app's websocket, not the HTTP response.
-When explicitly asked, the agent uses `CommentOnDocument` to reply with `threadId`,
-start an inline markdown comment with `quote`, or start a Discussion comment with
-neither. `threadId` and `quote` cannot be combined; `occurrence` only applies with
-`quote`. Thread ids come from the comments returned by `ReadContent`. 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. Asked to comment on part of a markdown
-document, the agent starts an inline comment on the quoted passage: the row reads
+When explicitly asked, the agent uses `Comment` to start a Discussion comment on an
+item, addressed by `entityType` and `entityId` (a `document`, which includes tasks and
+PDFs, an `initiative`, which is a Tasks project, a `crm_company` or a `crm_contact`),
+or to reply with `threadId` alone: a thread id is enough to find its item. It reads any
+item's threads with `ReadDiscussion`, and edits, deletes and resolves comments by their
+ids with `EditComment`, `DeleteComment` and `ResolveComment`. For a document,
+`ReadContent` returns the same threads with the content. A reply row reads **Replied to
+a comment on** (or **Commented on** for a new Discussion comment) followed by the item,
+and expands to the posted text; a resolve row reads **Resolved** or **Reopened a comment
+on** the item. Asked to comment on part of a markdown document, the agent uses
+`CommentOnText` with `quote` (`occurrence` picks a repeated passage): the row reads
**Commented on text in** the document and expands to the quoted text and the comment,
and the passage is highlighted in the document with the comment floating beside it.
A passage that is missing, spans blocks, or repeats with no occurrence chosen is
diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.md
index 17727594df..351d56b5b6 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -2810,7 +2810,7 @@ updates live and shows each collaborator's caret with their name
the file on download; reply with a Macro comment.
- Threads whose text was deleted are listed under `Comments on text that has
changed`, above the `Discussion` composer.
-- AI `CommentOnDocument` works on DOCX by quote. The editor pins each quote to
+- AI `CommentOnText` works on DOCX by quote. The editor pins each quote to
the first matching text the next time someone opens the file.
- AI `EditWordDocument` can record its edits as tracked changes
(`trackChanges`, or by default when the document tracks changes) and add
diff --git a/services/ai-editing-worker/AI_EDITING.md b/services/ai-editing-worker/AI_EDITING.md
index a90fb4b59a..95a6c562d6 100644
--- a/services/ai-editing-worker/AI_EDITING.md
+++ b/services/ai-editing-worker/AI_EDITING.md
@@ -160,7 +160,7 @@ wraps that exact span in a committed `CommentNode`, and pushes it like any other
edit. Text that is missing, crosses from one block into another, or appears
more than once with no occurrence chosen is refused with a 422 and the
document is left untouched, so a mark is never guessed into place. The
-backend `CommentOnDocument` tool with `quote` places the mark first and then posts the
+backend `CommentOnText` tool places the mark first and then posts the
thread anchored to it, removing the mark again if the post fails.
## Forms
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 8381265d09..29d65d17a0 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -512,6 +512,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
image_generation_tool_context: ai_tools::build_image_generation_tool_context_test(
&document_tool_context,
),
+ message_tool_context: ai_tools::build_message_tool_context(&document_tool_context),
document_tool_context: document_tool_context.clone(),
properties_tool_context: properties_tool_context.clone(),
email_tool_context: email_tool_context.clone(),
diff --git a/services/document_cognition_service/src/server.rs b/services/document_cognition_service/src/server.rs
index ff8987ba4d..6fcdd0c5b1 100644
--- a/services/document_cognition_service/src/server.rs
+++ b/services/document_cognition_service/src/server.rs
@@ -794,6 +794,7 @@ pub async fn run() -> anyhow::Result<()> {
ai_tools::build_image_generator_from_env(),
recorder.clone(),
)?,
+ message_tool_context: ai_tools::build_message_tool_context(&document_tool_context),
document_tool_context: document_tool_context.clone(),
properties_tool_context: properties_tool_context.clone(),
email_tool_context: email_tool_context.clone(),
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index c78212647a..98a96c776b 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -553,6 +553,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
ai_tools::build_image_generator_from_env(),
recorder.clone(),
)?,
+ message_tool_context: ai_tools::build_message_tool_context(&document_tool_context),
document_tool_context,
properties_tool_context,
email_tool_context,