Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(comments): unify document comment tools into CommentOnDocument (#7144)
gbirman79cad882d3c9
diff --git a/apps/docs/AI/mcp/tools/comment-on-document-text.mdx b/apps/docs/AI/mcp/tools/comment-on-document-text.mdxdeleted file mode 100644index eaaeb4c583..0000000000--- a/apps/docs/AI/mcp/tools/comment-on-document-text.mdx+++ /dev/null@@ -1,17 +0,0 @@-----title: CommentOnDocumentText-description: "Start a new inline comment on a passage of a Macro markdown document, on behalf of the user: the passage is highlighted in the document and the comment floats beside it, as when a person selects text and comments. Only use this when explicitly asked to comment on part of a document. Quote the passage exactly as the document reads, 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; if the text is not found, read the document again rather than guessing. Use ReplyToDocumentComment to reply in an existing thread or to comment on the document as a whole."------# CommentOnDocumentText--Start a new inline comment on a passage of a Macro markdown document, on behalf of the user: the passage is highlighted in the document and the comment floats beside it, as when a person selects text and comments. Only use this when explicitly asked to comment on part of a document. Quote the passage exactly as the document reads, 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; if the text is not found, read the document again rather than guessing. Use ReplyToDocumentComment to reply in an existing thread or to comment on the document as a whole.--## Parameters--| Parameter | Type | Required | Description |-| --- | --- | --- | --- |-| `documentId` | string | Yes | The id of the markdown document to comment on. |-| `text` | 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 passage to comment on, counting from 1 in document order. Only needed when the passage appears more than once. |-| `content` | string | Yes | Comment content in macro markdown format. This uses the same syntax as markdown documents. |diff --git a/apps/docs/AI/mcp/tools/comment-on-document.mdx b/apps/docs/AI/mcp/tools/comment-on-document.mdxnew file mode 100644index 0000000000..732a54e313--- /dev/null+++ b/apps/docs/AI/mcp/tools/comment-on-document.mdx@@ -0,0 +1,18 @@+---+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 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."+---++# 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 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.++## 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 document only. 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/index.mdx b/apps/docs/AI/mcp/tools/index.mdxindex 3e257e9cb8..b5dd32e716 100644--- a/apps/docs/AI/mcp/tools/index.mdx+++ b/apps/docs/AI/mcp/tools/index.mdx@@ -12,7 +12,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [BashCodeExecution](/AI/mcp/tools/bash-code-execution)- [BulkSetEntityPropertyOptions](/AI/mcp/tools/bulk-set-entity-property-options)- [CalculateSpreadsheet](/AI/mcp/tools/calculate-spreadsheet)-- [CommentOnDocumentText](/AI/mcp/tools/comment-on-document-text)+- [CommentOnDocument](/AI/mcp/tools/comment-on-document)- [ConfigureBot](/AI/mcp/tools/configure-bot)- [ContentSearch](/AI/mcp/tools/content-search)- [CreateBot](/AI/mcp/tools/create-bot)@@ -78,7 +78,6 @@ These pages are generated from Macro's Rust MCP tool registry.- [ReadThread](/AI/mcp/tools/read-thread)- [RenameChannel](/AI/mcp/tools/rename-channel)- [RenameDocument](/AI/mcp/tools/rename-document)-- [ReplyToDocumentComment](/AI/mcp/tools/reply-to-document-comment)- [ResolveDocumentComment](/AI/mcp/tools/resolve-document-comment)- [SearchSkills](/AI/mcp/tools/search-skills)- [SearchTools](/AI/mcp/tools/search-tools)diff --git a/apps/docs/AI/mcp/tools/reply-to-document-comment.mdx b/apps/docs/AI/mcp/tools/reply-to-document-comment.mdxdeleted file mode 100644index 4e36b611b6..0000000000--- a/apps/docs/AI/mcp/tools/reply-to-document-comment.mdx+++ /dev/null@@ -1,16 +0,0 @@-----title: ReplyToDocumentComment-description: "Reply in a comment thread on a document, or post a new comment in the document's Discussion panel, on behalf of the user. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. To start a new inline comment on a passage of the document, use CommentOnDocumentText."------# ReplyToDocumentComment--Reply in a comment thread on a document, or post a new comment in the document's Discussion panel, on behalf of the user. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. To start a new inline comment on a passage of the document, use CommentOnDocumentText.--## Parameters--| Parameter | Type | Required | Description |-| --- | --- | --- | --- |-| `documentId` | string | Yes | The id of the document the comment is on. |-| `content` | string | Yes | Comment content in macro markdown format. This uses the same syntax as markdown documents. |-| `threadId` | string | No | The id of the inline or Discussion thread to reply in, from ReadContent. Omit to post a new Discussion comment on the document as a whole. |diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.jsonindex fea7488289..ede47e86a6 100644--- a/apps/docs/config/tool-pages.json+++ b/apps/docs/config/tool-pages.json@@ -3,7 +3,7 @@"AI/mcp/tools/bash-code-execution","AI/mcp/tools/bulk-set-entity-property-options","AI/mcp/tools/calculate-spreadsheet",- "AI/mcp/tools/comment-on-document-text",+ "AI/mcp/tools/comment-on-document","AI/mcp/tools/configure-bot","AI/mcp/tools/content-search","AI/mcp/tools/create-bot",@@ -69,7 +69,6 @@"AI/mcp/tools/read-thread","AI/mcp/tools/rename-channel","AI/mcp/tools/rename-document",- "AI/mcp/tools/reply-to-document-comment","AI/mcp/tools/resolve-document-comment","AI/mcp/tools/search-skills","AI/mcp/tools/search-tools",diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex d624236d59..7e8539bd1c 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -74,7 +74,7 @@"AI/mcp/tools/bash-code-execution","AI/mcp/tools/bulk-set-entity-property-options","AI/mcp/tools/calculate-spreadsheet",- "AI/mcp/tools/comment-on-document-text",+ "AI/mcp/tools/comment-on-document","AI/mcp/tools/configure-bot","AI/mcp/tools/content-search","AI/mcp/tools/create-bot",@@ -140,7 +140,6 @@"AI/mcp/tools/read-thread","AI/mcp/tools/rename-channel","AI/mcp/tools/rename-document",- "AI/mcp/tools/reply-to-document-comment","AI/mcp/tools/resolve-document-comment","AI/mcp/tools/search-skills","AI/mcp/tools/search-tools",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.tsxindex 80fef7651c..9c086a868a 100644--- a/apps/web/src/lib/core/component/AI/component/tool/DocumentComments.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/DocumentComments.tsx@@ -2,7 +2,7 @@ import { ItemPreview } from '@core/component/ItemPreview';import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg';import ChatCircle from '@phosphor-icons/core/regular/chat-circle.svg';import CheckCircle from '@phosphor-icons/core/regular/check-circle.svg';-import { createSignal, Suspense } from 'solid-js';+import { createSignal, Show, Suspense } from 'solid-js';import { BaseTool } from './BaseTool';import { Tool } from './Tool';import { createToolRenderer } from './ToolRenderer';@@ -19,52 +19,23 @@ function DocumentPreview(props: { documentId: string }) {);}-export const replyToDocumentCommentHandler = createToolRenderer({- name: 'ReplyToDocumentComment',+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 = () => {- const reply = ctx.tool.data.threadId != null;- if (ctx.response)- return reply ? 'Replied to a comment on' : 'Commented on';- return reply ? 'Reply to a comment on' : 'Comment on';+ 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() ? (- <p class="whitespace-pre-wrap break-words rounded-lg border border-edge-muted bg-ink/[0.02] p-3 text-xs text-ink">- {ctx.tool.data.content}- </p>- ) : undefined- }- >- <div class="flex min-w-0 flex-1 items-center justify-between gap-3">- <span class="min-w-0">- {verb()} <DocumentPreview documentId={ctx.tool.data.documentId} />- </span>- <Tool.ResultToggle- expanded={expanded()}- onToggle={() => setExpanded((value) => !value)}- showToggle={!!ctx.tool.data.content}- />- </div>- </BaseTool>- );- },-});--export const commentOnDocumentTextHandler = createToolRenderer({- name: 'CommentOnDocumentText',- render: (ctx) => {- const [expanded, setExpanded] = createSignal(false);- const markedText = () =>- ctx.response?.data.markedText ?? ctx.tool.data.text;-return (<BaseToolicon={ChatCircle}@@ -73,9 +44,13 @@ export const commentOnDocumentTextHandler = createToolRenderer({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">- <blockquote class="whitespace-pre-wrap break-words border-l-2 border-edge-muted pl-2 text-ink-muted">- {markedText()}- </blockquote>+ <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>@@ -85,8 +60,7 @@ export const commentOnDocumentTextHandler = createToolRenderer({><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'}{' '}- <DocumentPreview documentId={ctx.tool.data.documentId} />+ {verb()} <DocumentPreview documentId={ctx.tool.data.documentId} /></span><Tool.ResultToggleexpanded={expanded()}diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex bcd14a15bc..5e697c42fc 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@@ -34,8 +34,7 @@ import { getCompanyHandler, listCompaniesHandler } from './Crm';import { deleteTagHandler } from './DeleteTag';import { displayResultsHandler } from './DisplayResults';import {- commentOnDocumentTextHandler,- replyToDocumentCommentHandler,+ commentOnDocumentHandler,resolveDocumentCommentHandler,} from './DocumentComments';import { editDocumentHandler } from './EditDocument';@@ -177,8 +176,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {ReadSkill: readSkillHandler,RenameChannel: renameChannelHandler,RenameDocument: renameDocumentHandler,- CommentOnDocumentText: commentOnDocumentTextHandler,- ReplyToDocumentComment: replyToDocumentCommentHandler,+ CommentOnDocument: commentOnDocumentHandler,ResolveDocumentComment: resolveDocumentCommentHandler,SearchSkills: searchSkillsHandler,SearchTools: searchToolsHandler,diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex facc592f0d..1507012f9d 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@@ -602,18 +602,19 @@ export const SpreadsheetResponse = z.any().superRefine((x, ctx) => {}});-export const CommentOnDocumentText = z.object({+export const CommentOnDocument = z.object({documentId: z.string().uuid(),- text: z.string(),- occurrence: z.union([z.number().int().gte(1), z.null()]).optional(),content: z.string(),+ threadId: z.union([z.string().uuid(), z.null()]).optional(),+ quote: z.union([z.string(), z.null()]).optional(),+ occurrence: z.union([z.number().int().gte(1), z.null()]).optional(),});-export const CommentOnDocumentTextResponse = z.object({+export const CommentOnDocumentResponse = z.object({documentId: z.string().uuid(),threadId: z.string().uuid(),commentId: z.string().uuid(),- markedText: z.string(),+ markedText: z.union([z.string(), z.null()]).optional(),});export const ConfigureBot = z.object({@@ -5291,18 +5292,6 @@ export const RenameDocumentResponse = z.object({message: z.string(),});-export const ReplyToDocumentComment = z.object({- documentId: z.string().uuid(),- content: z.string(),- threadId: z.union([z.string().uuid(), z.null()]).optional(),-});--export const ReplyToDocumentCommentResponse = z.object({- documentId: z.string().uuid(),- threadId: z.string().uuid(),- commentId: z.string().uuid(),-});-export const ResolveDocumentComment = z.object({documentId: z.string().uuid(),threadId: z.string().uuid(),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.tsindex 212a48a527..c14249b893 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@@ -20,9 +20,9 @@ type ToolParserMap = {call: types.CalculateSpreadsheet;response: types.SpreadsheetResponse;};- CommentOnDocumentText: {- call: types.CommentOnDocumentText;- response: types.CommentOnDocumentTextResponse;+ CommentOnDocument: {+ call: types.CommentOnDocument;+ response: types.CommentOnDocumentResponse;};ConfigureBot: {call: types.ConfigureBot;@@ -224,10 +224,6 @@ type ToolParserMap = {call: types.RenameDocument;response: types.RenameDocumentResponse;};- ReplyToDocumentComment: {- call: types.ReplyToDocumentComment;- response: types.ReplyToDocumentCommentResponse;- };ResolveDocumentComment: {call: types.ResolveDocumentComment;response: types.ResolveDocumentCommentResponse;@@ -305,9 +301,9 @@ const toolParserMap = {call: schemas.CalculateSpreadsheet,response: schemas.SpreadsheetResponse,},- CommentOnDocumentText: {- call: schemas.CommentOnDocumentText,- response: schemas.CommentOnDocumentTextResponse,+ CommentOnDocument: {+ call: schemas.CommentOnDocument,+ response: schemas.CommentOnDocumentResponse,},ConfigureBot: {call: schemas.ConfigureBot,@@ -533,10 +529,6 @@ const toolParserMap = {call: schemas.RenameDocument,response: schemas.RenameDocumentResponse,},- ReplyToDocumentComment: {- call: schemas.ReplyToDocumentComment,- response: schemas.ReplyToDocumentCommentResponse,- },ResolveDocumentComment: {call: schemas.ResolveDocumentComment,response: schemas.ResolveDocumentCommentResponse,@@ -631,9 +623,9 @@ type ToolDataMap = {call: types.CalculateSpreadsheet;response: types.SpreadsheetResponse;};- CommentOnDocumentText: {- call: types.CommentOnDocumentText;- response: types.CommentOnDocumentTextResponse;+ CommentOnDocument: {+ call: types.CommentOnDocument;+ response: types.CommentOnDocumentResponse;};ConfigureBot: {call: types.ConfigureBot;@@ -835,10 +827,6 @@ type ToolDataMap = {call: types.RenameDocument;response: types.RenameDocumentResponse;};- ReplyToDocumentComment: {- call: types.ReplyToDocumentComment;- response: types.ReplyToDocumentCommentResponse;- };ResolveDocumentComment: {call: types.ResolveDocumentComment;response: types.ResolveDocumentCommentResponse;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex 305b723b4b..f23642f72d 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@@ -1672,36 +1672,40 @@ export interface SpreadsheetChange {range?: string | null;}/**- * Start a new inline comment on a passage of a Macro markdown document, on behalf of the user: the passage is highlighted in the document and the comment floats beside it, as when a person selects text and comments. Only use this when explicitly asked to comment on part of a document. Quote the passage exactly as the document reads, 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; if the text is not found, read the document again rather than guessing. Use ReplyToDocumentComment to reply in an existing thread or to comment on the document as a whole.+ * 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 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.*/-export interface CommentOnDocumentText {+export interface CommentOnDocument {/**- * The id of the markdown document to comment on.+ * The id of the document to comment on.*/documentId: string;/**- * 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.+ * Comment content in macro markdown format. This uses the same syntax as markdown documents.*/- text: string;+ content: string;/**- * Which appearance of the passage to comment on, counting from 1 in document order. Only needed when the passage appears more than once.+ * 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.*/- occurrence?: number | null;+ threadId?: string | null;/**- * Comment content in macro markdown format. This uses the same syntax as markdown documents.+ * 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 document only. Cannot be combined with threadId.*/- content: string;+ quote?: string | null;+ /**+ * 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.+ */+ occurrence?: number | null;}/**- * The inline comment that was started.+ * The posted comment.*/-export interface CommentOnDocumentTextResponse {+export interface CommentOnDocumentResponse {/*** The document the comment was posted on.*/documentId: string;/**- * The new thread; replies and resolution address it by this id.+ * The thread the comment is in; a new comment starts its own.*/threadId: string;/**@@ -1709,9 +1713,9 @@ export interface CommentOnDocumentTextResponse {*/commentId: string;/**- * The text the comment is anchored to, as the document reads.+ * The text the new inline comment is anchored to, as the document reads.*/- markedText: string;+ markedText?: string | null;}/*** Configure a manageable bot's profile. Provide only fields that should change. Use avatarUrl to set a profile picture from an image already uploaded to Macro static files or another reachable image URL; pass an empty string to clear the current picture. Passing an empty string for description clears it. Confirm handle changes because integrations and mentions may rely on the stable handle.@@ -6054,40 +6058,6 @@ export interface RenameDocumentResponse {*/message: string;}-/**- * Reply in a comment thread on a document, or post a new comment in the document's Discussion panel, on behalf of the user. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. To start a new inline comment on a passage of the document, use CommentOnDocumentText.- */-export interface ReplyToDocumentComment {- /**- * The id of the document the comment is on.- */- documentId: string;- /**- * Comment content in macro markdown format. This uses the same syntax as markdown documents.- */- content: string;- /**- * The id of the inline or Discussion thread to reply in, from ReadContent. Omit to post a new Discussion comment on the document as a whole.- */- threadId?: string | null;-}-/**- * The posted comment.- */-export interface ReplyToDocumentCommentResponse {- /**- * The document the comment was posted on.- */- documentId: string;- /**- * The thread the comment is in; a new Discussion comment starts its own.- */- threadId: string;- /**- * The posted comment.- */- commentId: string;-}/*** Resolve or reopen a comment thread on a document on behalf of the user. Only use this when explicitly asked to resolve or reopen a comment. Thread ids come from the comments ReadContent returns.*/diff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rsindex 26b655d4ef..3542e7164c 100644--- a/crates/ai_tools/src/test.rs+++ b/crates/ai_tools/src/test.rs@@ -45,8 +45,7 @@ fn project_workflows_are_available_in_every_host_alongside_folder_and_property_t"ReadTaskInitiatives","ReadInitiativeActivity","SetEntityProperty",- "ReplyToDocumentComment",- "CommentOnDocumentText",+ "CommentOnDocument","ResolveDocumentComment","CreateProject","ReadProject",diff --git a/crates/documents/src/inbound/toolset.rs b/crates/documents/src/inbound/toolset.rsindex f6793f3576..45fb2013bc 100644--- a/crates/documents/src/inbound/toolset.rs+++ b/crates/documents/src/inbound/toolset.rs@@ -1,12 +1,11 @@//! Toolset inbound adapter for Documents.-mod comment_on_document_text;+mod comment_on_document;mod create_document;mod edit_document;mod read_content;mod read_metadata;mod rename_document;-mod reply_to_document_comment;mod resolve_document_comment;mod spreadsheet;mod upload_file;@@ -24,13 +23,12 @@ use crate::{domain::ports::editing::{EditingWorkerService, EditorName},domain::ports::mentions::NoOpDocumentMentionTracker,inbound::toolset::{- comment_on_document_text::CommentOnDocumentText,+ comment_on_document::CommentOnDocument,create_document::CreateDocument,edit_document::EditDocument,read_content::ReadContent,read_metadata::ReadMetadata,rename_document::RenameDocument,- reply_to_document_comment::ReplyToDocumentComment,resolve_document_comment::ResolveDocumentComment,spreadsheet::{CalculateSpreadsheet, EditSpreadsheet, ReadSpreadsheet},upload_file::UploadFile,@@ -265,8 +263,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::<ReplyToDocumentComment, DocumentToolContext<DSvc, ESvc, EDSvc>>()- .add_tool::<CommentOnDocumentText, DocumentToolContext<DSvc, ESvc, EDSvc>>()+ .add_tool::<CommentOnDocument, DocumentToolContext<DSvc, ESvc, EDSvc>>().add_tool::<ResolveDocumentComment, DocumentToolContext<DSvc, ESvc, EDSvc>>().add_tool::<ReadSpreadsheet, DocumentToolContext<DSvc, ESvc, EDSvc>>().add_tool::<CalculateSpreadsheet, DocumentToolContext<DSvc, ESvc, EDSvc>>()diff --git a/crates/documents/src/inbound/toolset/comment_on_document_text.rs b/crates/documents/src/inbound/toolset/comment_on_document.rssimilarity index 63%rename from crates/documents/src/inbound/toolset/comment_on_document_text.rsrename to crates/documents/src/inbound/toolset/comment_on_document.rsindex 446e84d642..61dbabe3b7 100644--- a/crates/documents/src/inbound/toolset/comment_on_document_text.rs+++ b/crates/documents/src/inbound/toolset/comment_on_document.rs@@ -1,5 +1,4 @@-//! CommentOnDocumentText tool for starting an inline comment on a passage of-//! a markdown document.+//! CommentOnDocument tool for posting document comments and replies.use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use ai_toolset::{ToolAnnotated, ToolAnnotations};@@ -26,56 +25,62 @@ use crate::domain::ports::{#[derive(Debug, Clone, Deserialize, JsonSchema)]#[serde(rename_all = "camelCase")]#[schemars(- title = "CommentOnDocumentText",- description = "Start a new inline comment on a passage of a Macro markdown document, on behalf of the user: the passage is highlighted in the document and the comment floats beside it, as when a person selects text and comments. Only use this when explicitly asked to comment on part of a document. Quote the passage exactly as the document reads, 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; if the text is not found, read the document again rather than guessing. Use ReplyToDocumentComment to reply in an existing thread or to comment on the document as a whole."+ 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 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.")]-pub struct CommentOnDocumentText {- #[schemars(description = "The id of the markdown document to comment on.")]+pub struct CommentOnDocument {+ #[schemars(description = "The id of the document to comment on.")]pub document_id: 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."+ description = "Comment content in macro markdown format. This uses the same syntax as markdown documents.")]- pub text: String,+ pub content: String,#[schemars(- range(min = 1),- description = "Which appearance of the passage to comment on, counting from 1 in document order. Only needed when the passage appears more than once."+ 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.")]- pub occurrence: Option<u32>,+ pub thread_id: Option<Uuid>,#[schemars(- description = "Comment content in macro markdown format. This uses the same syntax as markdown documents."+ 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 document only. Cannot be combined with threadId.")]- pub content: String,+ pub quote: Option<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."+ )]+ pub occurrence: Option<u32>,}-/// The inline comment that was started.+/// The posted comment.#[derive(Debug, Serialize, JsonSchema)]#[serde(rename_all = "camelCase")]-pub struct CommentOnDocumentTextResponse {+pub struct CommentOnDocumentResponse {/// The document the comment was posted on.pub document_id: Uuid,- /// The new thread; replies and resolution address it by this id.+ /// The thread the comment is in; a new comment starts its own.pub thread_id: Uuid,/// The posted comment.pub comment_id: Uuid,- /// The text the comment is anchored to, as the document reads.- pub marked_text: String,+ /// 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>,}-impl ToolAnnotated for CommentOnDocumentText {- const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Comment on document text");+impl ToolAnnotated for CommentOnDocument {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Comment on document");}#[async_trait]-impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for CommentOnDocumentText+impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for CommentOnDocumentwhereDSvc: DocumentService + DocumentCreationService,ESvc: EntityAccessService,EDSvc: EditingWorkerService,{- type Output = CommentOnDocumentTextResponse;+ type Output = CommentOnDocumentResponse;#[tracing::instrument(skip_all, fields(document_id = %self.document_id), err)]async fn call(@@ -83,6 +88,18 @@ wherectx: 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:@@ -94,6 +111,33 @@ wherelet 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@@ -106,7 +150,7 @@ where})?;if document.try_file_type() != Some(FileType::Md) {return Err(ToolCallError {- description: "inline comments anchor to text in Macro markdown documents only; use ReplyToDocumentComment to comment on this document as a whole".to_string(),+ description: "inline comments anchor to text in Macro markdown documents only; omit quote to comment on this document as a whole".to_string(),internal_error: anyhow::anyhow!("document file type {:?} is not markdown",document.file_type@@ -140,7 +184,7 @@ where&document_id,&document_token,mark_id,- &self.text,+ quote,self.occurrence,).await@@ -194,11 +238,11 @@ where}};- Ok(CommentOnDocumentTextResponse {+ Ok(CommentOnDocumentResponse {document_id: self.document_id,thread_id: message.id,comment_id: message.id,- marked_text,+ marked_text: Some(marked_text),})}}diff --git a/crates/documents/src/inbound/toolset/comment_test.rs b/crates/documents/src/inbound/toolset/comment_test.rsindex ba8118f894..47e9619cbf 100644--- a/crates/documents/src/inbound/toolset/comment_test.rs+++ b/crates/documents/src/inbound/toolset/comment_test.rs@@ -23,9 +23,8 @@ use crate::domain::permission_token::decode_permission_token;use super::{DocumentToolContext,- comment_on_document_text::CommentOnDocumentText,+ comment_on_document::CommentOnDocument,edit_document::test::{FakeDocumentService, FakeEditingWorker, FakeEntityAccessService},- reply_to_document_comment::ReplyToDocumentComment,resolve_document_comment::ResolveDocumentComment,};@@ -248,10 +247,12 @@ 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 = ReplyToDocumentComment {+ 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@@ -259,6 +260,12 @@ async fn reply_posts_in_the_thread_as_the_bot_for_the_user() {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 {@@ -276,18 +283,26 @@ async fn reply_posts_in_the_thread_as_the_bot_for_the_user() {}#[tokio::test]-async fn reply_without_a_thread_starts_a_discussion_comment() {+async fn comment_without_a_thread_or_quote_starts_a_discussion_comment() {let messages = FakeMessages::default();- let response = ReplyToDocumentComment {+ 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);@@ -297,10 +312,12 @@ async fn reply_without_a_thread_starts_a_discussion_comment() {#[tokio::test]async fn reply_needs_comment_access() {let messages = FakeMessages::default();- let error = ReplyToDocumentComment {+ 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@@ -320,10 +337,12 @@ async fn reply_to_a_thread_not_on_the_document_says_so() {thread_exists: false,..FakeMessages::default()};- let error = ReplyToDocumentComment {+ 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@@ -409,10 +428,11 @@ async fn resolve_needs_comment_access() {assert!(messages.thread_patches.lock().unwrap().is_empty());}-fn comment_on_text(text: &str, occurrence: Option<u32>) -> CommentOnDocumentText {- CommentOnDocumentText {+fn comment_on_text(text: &str, occurrence: Option<u32>) -> CommentOnDocument {+ CommentOnDocument {document_id: DOCUMENT,- text: text.to_owned(),+ thread_id: None,+ quote: Some(text.to_owned()),occurrence,content: "Is this date still right?".to_owned(),}@@ -467,24 +487,30 @@ 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, "ships on Friday");+ assert_eq!(response.marked_text.as_deref(), Some("ships on Friday"));+ assert_eq!(+ serde_json::to_value(&response).unwrap()["markedText"],+ "ships on Friday"+ );assert!(editing.removed_comment_marks.lock().unwrap().is_empty());}#[tokio::test]async fn comment_on_text_refused_by_the_document_posts_nothing() {- let messages = FakeMessages::default();- let editing = FakeEditingWorker::refusing_comment_marks("The text appears 2 times.");- let error = comment_on_text("TBD", None)- .call(- context_with(AccessLevel::Edit, messages.clone(), "md", editing),- request(),- )- .await- .unwrap_err();+ for reason in ["The text appears 2 times.", "The text was not found."] {+ let messages = FakeMessages::default();+ let editing = FakeEditingWorker::refusing_comment_marks(reason);+ let error = comment_on_text("TBD", None)+ .call(+ context_with(AccessLevel::Edit, messages.clone(), "md", editing),+ request(),+ )+ .await+ .unwrap_err();- assert_eq!(error.description, "The text appears 2 times.");- assert!(messages.posts.lock().unwrap().is_empty());+ assert_eq!(error.description, reason);+ assert!(messages.posts.lock().unwrap().is_empty());+ }}#[tokio::test]@@ -607,3 +633,112 @@ 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());+}diff --git a/crates/documents/src/inbound/toolset/reply_to_document_comment.rs b/crates/documents/src/inbound/toolset/reply_to_document_comment.rsdeleted file mode 100644index ea3e7d42cf..0000000000--- a/crates/documents/src/inbound/toolset/reply_to_document_comment.rs+++ /dev/null@@ -1,97 +0,0 @@-//! ReplyToDocumentComment tool for answering document comments in place.--use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolResult};-use ai_toolset::{ToolAnnotated, ToolAnnotations};-use async_trait::async_trait;-use entity_access::domain::ports::EntityAccessService;-use messages::domain::models::{MessageAttribution, PostMessage, PostMessageNotificationPolicy};-use schemars::JsonSchema;-use serde::{Deserialize, Serialize};-use uuid::Uuid;--use super::{DocumentToolContext, comment_error};-use crate::domain::ports::{- DocumentService, create::DocumentCreationService, editing::EditingWorkerService,-};--#[derive(Debug, Clone, Deserialize, JsonSchema)]-#[serde(rename_all = "camelCase")]-#[schemars(- title = "ReplyToDocumentComment",- description = "Reply in a comment thread on a document, or post a new comment in the document's Discussion panel, on behalf of the user. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. To start a new inline comment on a passage of the document, use CommentOnDocumentText."-)]-pub struct ReplyToDocumentComment {- #[schemars(description = "The id of the document the comment is on.")]- pub document_id: Uuid,-- #[schemars(- description = "Comment content in macro markdown format. This uses the same syntax as markdown documents."- )]- pub content: String,-- #[schemars(- description = "The id of the inline or Discussion thread to reply in, from ReadContent. Omit to post a new Discussion comment on the document as a whole."- )]- pub thread_id: Option<Uuid>,-}--/// The posted comment.-#[derive(Debug, Serialize, JsonSchema)]-#[serde(rename_all = "camelCase")]-pub struct ReplyToDocumentCommentResponse {- /// The document the comment was posted on.- pub document_id: Uuid,- /// The thread the comment is in; a new Discussion comment starts its own.- pub thread_id: Uuid,- /// The posted comment.- pub comment_id: Uuid,-}--impl ToolAnnotated for ReplyToDocumentComment {- const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Reply to document comment");-}--#[async_trait]-impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for ReplyToDocumentComment-where- DSvc: DocumentService + DocumentCreationService,- ESvc: EntityAccessService,- EDSvc: EditingWorkerService,-{- type Output = ReplyToDocumentCommentResponse;-- async fn call(- &self,- service_context: ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,- request_context: RequestContext,- ) -> ToolResult<Self::Output> {- let access = service_context- .require_comment_write(&request_context, self.document_id)- .await?;-- let message = service_context- .messages- .post(- access,- PostMessage {- 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(ReplyToDocumentCommentResponse {- document_id: self.document_id,- thread_id: message.thread_id.unwrap_or(message.id),- comment_id: message.id,- })- }-}diff --git a/crates/documents/src/inbound/toolset/test.rs b/crates/documents/src/inbound/toolset/test.rsindex 628af62e1f..97aa4f0256 100644--- a/crates/documents/src/inbound/toolset/test.rs+++ b/crates/documents/src/inbound/toolset/test.rs@@ -66,55 +66,59 @@ fn test_rename_document_schema_validation() {}#[test]-fn test_reply_to_document_comment_schema_validation() {- let result = generate_validated_input_schema::<ReplyToDocumentComment>();+fn test_resolve_document_comment_schema_validation() {+ let result = generate_validated_input_schema::<ResolveDocumentComment>();assert!(result.is_ok(), "{:?}", result);let validated = result.unwrap();assert_eq!(- validated.name, "ReplyToDocumentComment",+ 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 posts"+ "Description should limit when the tool resolves");}#[test]-fn test_resolve_document_comment_schema_validation() {- let result = generate_validated_input_schema::<ResolveDocumentComment>();+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, "ResolveDocumentComment",+ validated.name, "CommentOnDocument","Tool name should match the schemars title");assert!(validated.description.contains("Only use this when explicitly asked"),- "Description should limit when the tool resolves"+ "Description should limit when the tool posts");}#[test]-fn test_comment_on_document_text_schema_validation() {- let result = generate_validated_input_schema::<CommentOnDocumentText>();- assert!(result.is_ok(), "{:?}", result);-- let validated = result.unwrap();+fn test_comment_on_document_schema_fields() {+ let schema = schemars::schema_for!(CommentOnDocument).to_value();assert_eq!(- validated.name, "CommentOnDocumentText",- "Tool name should match the schemars title"+ schema["required"],+ serde_json::json!(["documentId", "content"]));- assert!(- validated- .description- .contains("Only use this when explicitly asked"),- "Description should limit when the tool posts"+ let properties = schema["properties"].as_object().unwrap();+ assert_eq!(properties.len(), 5);+ for name in ["documentId", "content", "threadId", "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();+ assert_eq!(+ response["required"],+ serde_json::json!(["documentId", "threadId", "commentId"]));+ assert!(response["properties"].get("markedText").is_some());}diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex 9eb1a7a37d..a30f2acd29 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -452,7 +452,10 @@ The agent has workspace tools (it can list your documents, read channels, createrender `displayResults` views). Requests go to `POST /cognition/stream/chat/message`; resultsstream over the app's websocket, not the HTTP response.-When asked, the agent also answers document comments in place. A reply row reads+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) followedby 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 markdowndiff --git a/services/ai-editing-worker/AI_EDITING.md b/services/ai-editing-worker/AI_EDITING.mdindex 3433808a01..58e04c57e6 100644--- a/services/ai-editing-worker/AI_EDITING.md+++ b/services/ai-editing-worker/AI_EDITING.md@@ -160,5 +160,5 @@ wraps that exact span in a committed `CommentNode`, and pushes it like any otheredit. Text that is missing, crosses from one block into another, or appearsmore than once with no occurrence chosen is refused with a 422 and thedocument is left untouched, so a mark is never guessed into place. The-backend `CommentOnDocumentText` tool places the mark first and then posts the+backend `CommentOnDocument` tool with `quote` places the mark first and then posts thethread anchored to it, removing the mark again if the post fails.