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(comments): let agents start inline comments anchored to markdown text (#6926)

gbirman1da812503e58
diff --git a/apps/docs/AI/mcp/tools/comment-on-document-text.mdx b/apps/docs/AI/mcp/tools/comment-on-document-text.mdx
new file mode 100644
index 0000000000..eaaeb4c583
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/comment-on-document-text.mdx
@@ -0,0 +1,17 @@
+---
+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/index.mdx b/apps/docs/AI/mcp/tools/index.mdx
index c8110d180f..91272cd607 100644
--- a/apps/docs/AI/mcp/tools/index.mdx
+++ b/apps/docs/AI/mcp/tools/index.mdx
@@ -12,6 +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)
- [ConfigureBot](/AI/mcp/tools/configure-bot)
- [ContentSearch](/AI/mcp/tools/content-search)
- [CreateBot](/AI/mcp/tools/create-bot)
diff --git a/apps/docs/AI/mcp/tools/reply-to-document-comment.mdx b/apps/docs/AI/mcp/tools/reply-to-document-comment.mdx
index a782124d5b..4e36b611b6 100644
--- a/apps/docs/AI/mcp/tools/reply-to-document-comment.mdx
+++ b/apps/docs/AI/mcp/tools/reply-to-document-comment.mdx
@@ -1,11 +1,11 @@
---
title: ReplyToDocumentComment
-description: "Reply in a comment thread on a document, or post a new comment in the document's Discussion panel, on behalf of the user. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. Cannot start a new inline comment on selected text."
+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. Cannot start a new inline comment on selected text.
+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
diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.json
index 04b8f88eeb..80eced8922 100644
--- a/apps/docs/config/tool-pages.json
+++ b/apps/docs/config/tool-pages.json
@@ -3,6 +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/configure-bot",
"AI/mcp/tools/content-search",
"AI/mcp/tools/create-bot",
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index 6502b490e8..dfdb62a164 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -74,6 +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/configure-bot",
"AI/mcp/tools/content-search",
"AI/mcp/tools/create-bot",
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
index dc4b33a37d..80fef7651c 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
@@ -58,6 +58,47 @@ export const replyToDocumentCommentHandler = createToolRenderer({
},
});
+export const commentOnDocumentTextHandler = createToolRenderer({
+ name: 'CommentOnDocumentText',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const markedText = () =>
+ ctx.response?.data.markedText ?? ctx.tool.data.text;
+
+ 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">
+ <blockquote class="whitespace-pre-wrap break-words border-l-2 border-edge-muted pl-2 text-ink-muted">
+ {markedText()}
+ </blockquote>
+ <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">
+ {ctx.response ? 'Commented on text in' : 'Comment on text in'}{' '}
+ <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) => {
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 eea7b41446..c36ea7526d 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,6 +34,7 @@ import { getCompanyHandler, listCompaniesHandler } from './Crm';
import { deleteTagHandler } from './DeleteTag';
import { displayResultsHandler } from './DisplayResults';
import {
+ commentOnDocumentTextHandler,
replyToDocumentCommentHandler,
resolveDocumentCommentHandler,
} from './DocumentComments';
@@ -171,6 +172,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
ReadProject: readProjectHandler,
RenameChannel: renameChannelHandler,
RenameDocument: renameDocumentHandler,
+ CommentOnDocumentText: commentOnDocumentTextHandler,
ReplyToDocumentComment: replyToDocumentCommentHandler,
ResolveDocumentComment: resolveDocumentCommentHandler,
SearchSkills: searchSkillsHandler,
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 c479a93f27..d28c6f05c4 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
@@ -601,6 +601,20 @@ export const SpreadsheetResponse = z.any().superRefine((x, ctx) => {
}
});
+export const CommentOnDocumentText = z.object({
+ documentId: z.string().uuid(),
+ text: z.string(),
+ occurrence: z.union([z.number().int().gte(1), z.null()]).optional(),
+ content: z.string(),
+});
+
+export const CommentOnDocumentTextResponse = z.object({
+ documentId: z.string().uuid(),
+ threadId: z.string().uuid(),
+ commentId: z.string().uuid(),
+ markedText: z.string(),
+});
+
export const ConfigureBot = z.object({
botId: z.string().uuid(),
name: z.union([z.string(), z.null()]).optional(),
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 aba3672502..bb724c3cb8 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,6 +20,10 @@ type ToolParserMap = {
call: types.CalculateSpreadsheet;
response: types.SpreadsheetResponse;
};
+ CommentOnDocumentText: {
+ call: types.CommentOnDocumentText;
+ response: types.CommentOnDocumentTextResponse;
+ };
ConfigureBot: {
call: types.ConfigureBot;
response: types.ConfigureBotResponse;
@@ -260,6 +264,10 @@ const toolParserMap = {
call: schemas.CalculateSpreadsheet,
response: schemas.SpreadsheetResponse,
},
+ CommentOnDocumentText: {
+ call: schemas.CommentOnDocumentText,
+ response: schemas.CommentOnDocumentTextResponse,
+ },
ConfigureBot: {
call: schemas.ConfigureBot,
response: schemas.ConfigureBotResponse,
@@ -541,6 +549,10 @@ type ToolDataMap = {
call: types.CalculateSpreadsheet;
response: types.SpreadsheetResponse;
};
+ CommentOnDocumentText: {
+ call: types.CommentOnDocumentText;
+ response: types.CommentOnDocumentTextResponse;
+ };
ConfigureBot: {
call: types.ConfigureBot;
response: types.ConfigureBotResponse;
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 ac9207bf07..e403df0365 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
@@ -1620,6 +1620,48 @@ 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.
+ */
+export interface CommentOnDocumentText {
+ /**
+ * The id of the markdown 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.
+ */
+ text: string;
+ /**
+ * Which appearance of the passage to comment on, counting from 1 in document order. Only needed when the passage appears more than once.
+ */
+ occurrence?: number | null;
+ /**
+ * Comment content in macro markdown format. This uses the same syntax as markdown documents.
+ */
+ content: string;
+}
+/**
+ * The inline comment that was started.
+ */
+export interface CommentOnDocumentTextResponse {
+ /**
+ * The document the comment was posted on.
+ */
+ documentId: string;
+ /**
+ * The new thread; replies and resolution address it by this id.
+ */
+ threadId: string;
+ /**
+ * The posted comment.
+ */
+ commentId: string;
+ /**
+ * The text the comment is anchored to, as the document reads.
+ */
+ markedText: string;
+}
/**
* 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.
*/
@@ -5586,7 +5628,7 @@ export interface RenameDocumentResponse {
message: string;
}
/**
- * Reply in a comment thread on a document, or post a new comment in the document's Discussion panel, on behalf of the user. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. Cannot start a new inline comment on selected text.
+ * 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 {
/**
diff --git a/crates/documents/src/domain/permission_token.rs b/crates/documents/src/domain/permission_token.rs
index 6a58da9d0c..20007ad502 100644
--- a/crates/documents/src/domain/permission_token.rs
+++ b/crates/documents/src/domain/permission_token.rs
@@ -14,7 +14,7 @@ pub(crate) struct PermissionTokenClaims {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) user_id: Option<MacroUserIdStr<'static>>,
document_id: String,
- access_level: AccessLevel,
+ pub(crate) access_level: AccessLevel,
exp: usize,
iss: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
diff --git a/crates/documents/src/domain/ports/editing.rs b/crates/documents/src/domain/ports/editing.rs
index 1f3a7ad94b..2f44166f6d 100644
--- a/crates/documents/src/domain/ports/editing.rs
+++ b/crates/documents/src/domain/ports/editing.rs
@@ -36,6 +36,20 @@ pub enum EditMode {
Fast,
}
+/// What became of a request to place a comment mark.
+#[cfg(feature = "ai_tools")]
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum CommentMarkPlacement {
+ /// The mark now wraps the requested text.
+ Placed {
+ /// The text the mark covers, as the document reads.
+ marked_text: String,
+ },
+ /// The text could not be anchored exactly, so the document was left
+ /// untouched; the reason is written for the agent that asked.
+ Refused(String),
+}
+
/// Port for applying AI-driven edits to a document via the editing worker.
#[cfg_attr(test, mockall::automock)]
pub trait EditingWorkerService: Send + Sync + 'static {
@@ -48,6 +62,27 @@ pub trait EditingWorkerService: Send + Sync + 'static {
request: &crate::domain::spreadsheet::SpreadsheetRequest,
) -> impl Future<Output = anyhow::Result<crate::domain::spreadsheet::SpreadsheetResponse>> + Send;
+ /// Wrap the `occurrence`th (1-based) appearance of `text` in `document_id`
+ /// in comment mark `mark_id`, merged into the live collaborative document.
+ #[cfg(feature = "ai_tools")]
+ fn add_comment_mark(
+ &self,
+ document_id: &str,
+ document_token: &DocumentPermissionToken,
+ mark_id: uuid::Uuid,
+ text: &str,
+ occurrence: Option<u32>,
+ ) -> impl Future<Output = anyhow::Result<CommentMarkPlacement>> + Send;
+
+ /// Take comment mark `mark_id` out of `document_id`, keeping its text.
+ #[cfg(feature = "ai_tools")]
+ fn remove_comment_mark(
+ &self,
+ document_id: &str,
+ document_token: &DocumentPermissionToken,
+ mark_id: uuid::Uuid,
+ ) -> impl Future<Output = anyhow::Result<()>> + Send;
+
/// Apply AI-driven edits to `document_id` using a pre-minted `document_token`.
fn edit(
&self,
diff --git a/crates/documents/src/inbound/toolset.rs b/crates/documents/src/inbound/toolset.rs
index 92945a75a6..8c68305269 100644
--- a/crates/documents/src/inbound/toolset.rs
+++ b/crates/documents/src/inbound/toolset.rs
@@ -1,5 +1,6 @@
//! Toolset inbound adapter for Documents.
+mod comment_on_document_text;
mod create_document;
mod edit_document;
mod read_content;
@@ -23,6 +24,7 @@ use crate::{
domain::ports::editing::EditingWorkerService,
domain::ports::mentions::NoOpDocumentMentionTracker,
inbound::toolset::{
+ comment_on_document_text::CommentOnDocumentText,
create_document::CreateDocument,
edit_document::EditDocument,
read_content::ReadContent,
@@ -235,6 +237,7 @@ where
.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::<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_text.rs
new file mode 100644
index 0000000000..446e84d642
--- /dev/null
+++ b/crates/documents/src/inbound/toolset/comment_on_document_text.rs
@@ -0,0 +1,220 @@
+//! CommentOnDocumentText tool for starting an inline comment on a passage of
+//! a markdown 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 macro_sync_service_jwt::DocumentPermissionToken;
+use messages::domain::models::{
+ MessageAttribution, NewThreadAnchor, PostMessage, PostMessageNotificationPolicy,
+};
+use model::document::FileType;
+use models_permissions::share_permission::access_level::AccessLevel;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::{DocumentToolContext, comment_error};
+use crate::domain::permission_token::encode_permission_token;
+use crate::domain::ports::{
+ DocumentService,
+ create::DocumentCreationService,
+ editing::{CommentMarkPlacement, EditingWorkerService},
+};
+
+#[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."
+)]
+pub struct CommentOnDocumentText {
+ #[schemars(description = "The id of the markdown 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."
+ )]
+ pub text: 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."
+ )]
+ pub occurrence: Option<u32>,
+
+ #[schemars(
+ description = "Comment content in macro markdown format. This uses the same syntax as markdown documents."
+ )]
+ pub content: String,
+}
+
+/// The inline comment that was started.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CommentOnDocumentTextResponse {
+ /// The document the comment was posted on.
+ pub document_id: Uuid,
+ /// The new thread; replies and resolution address it by this id.
+ 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,
+}
+
+impl ToolAnnotated for CommentOnDocumentText {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Comment on document text");
+}
+
+#[async_trait]
+impl<DSvc, ESvc, EDSvc> AsyncTool<DocumentToolContext<DSvc, ESvc, EDSvc>> for CommentOnDocumentText
+where
+ DSvc: DocumentService + DocumentCreationService,
+ ESvc: EntityAccessService,
+ EDSvc: EditingWorkerService,
+{
+ type Output = CommentOnDocumentTextResponse;
+
+ #[tracing::instrument(skip_all, fields(document_id = %self.document_id), err)]
+ async fn call(
+ &self,
+ ctx: ServiceContext<DocumentToolContext<DSvc, ESvc, EDSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ if self.occurrence == Some(0) {
+ return Err(ToolCallError {
+ description:
+ "occurrence counts from 1: pass 1 for the first appearance of the text"
+ .to_string(),
+ internal_error: anyhow::anyhow!("occurrence 0"),
+ });
+ }
+ let access = ctx
+ .require_comment_write(&request_context, self.document_id)
+ .await?;
+ let document_id = self.document_id.to_string();
+
+ let document = ctx
+ .service
+ .internal_get_basic_document(&document_id)
+ .await
+ .map_err(|e| ToolCallError {
+ description: "unable to look up this document".to_string(),
+ internal_error: e.into(),
+ })?;
+ 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(),
+ internal_error: anyhow::anyhow!(
+ "document file type {:?} is not markdown",
+ document.file_type
+ ),
+ });
+ }
+
+ // Placing the mark is a content change, but the one a commenter makes
+ // whenever they comment on a selection, so comment access suffices, as
+ // it does for the web composer and the sync service.
+ let document_token = encode_permission_token(
+ Some(request_context.user_id.to_string()),
+ document_id.clone(),
+ AccessLevel::Comment,
+ &ctx.document_permission_jwt_secret,
+ Some(ctx.actor.into_storage_id().to_string()),
+ )
+ .map_err(|e| ToolCallError {
+ description: "failed to mint document token".to_string(),
+ internal_error: e.into(),
+ })?;
+
+ // The mark goes in first: refusing an ambiguous or missing passage is
+ // the likely failure, and it then leaves nothing behind, where a thread
+ // posted first would already have notified people of a comment that
+ // cannot be placed.
+ let mark_id = Uuid::now_v7();
+ let placement = match ctx
+ .editing
+ .add_comment_mark(
+ &document_id,
+ &document_token,
+ mark_id,
+ &self.text,
+ self.occurrence,
+ )
+ .await
+ {
+ Ok(placement) => placement,
+ Err(err) => {
+ // The worker may have pushed the mark before the failure reached
+ // us, as when the sync service never acknowledged it.
+ remove_mark(ctx.editing.as_ref(), &document_id, &document_token, mark_id).await;
+ return Err(ToolCallError {
+ description: "unable to anchor the comment to the text".to_string(),
+ internal_error: err,
+ });
+ }
+ };
+ let marked_text = match placement {
+ CommentMarkPlacement::Placed { marked_text } => marked_text,
+ CommentMarkPlacement::Refused(reason) => {
+ return Err(ToolCallError {
+ description: reason.clone(),
+ internal_error: anyhow::anyhow!("comment mark refused: {reason}"),
+ });
+ }
+ };
+
+ let posted = ctx
+ .messages
+ .post(
+ access,
+ PostMessage {
+ id: None,
+ attribution: MessageAttribution::ActingUser,
+ notification_policy: PostMessageNotificationPolicy::Default,
+ content: self.content.clone(),
+ thread_id: None,
+ anchor: Some(NewThreadAnchor::Markdown {
+ mark_id,
+ marked_text: Some(marked_text.clone()),
+ }),
+ mentions: vec![],
+ attachments: vec![],
+ nonce: None,
+ },
+ )
+ .await;
+ let message = match posted {
+ Ok(message) => message,
+ Err(err) => {
+ remove_mark(ctx.editing.as_ref(), &document_id, &document_token, mark_id).await;
+ return Err(comment_error("unable to post the comment")(err));
+ }
+ };
+
+ Ok(CommentOnDocumentTextResponse {
+ document_id: self.document_id,
+ thread_id: message.id,
+ comment_id: message.id,
+ marked_text,
+ })
+ }
+}
+
+/// Best-effort removal of a mark whose thread was never posted: left in place
+/// it would highlight text nobody commented on.
+async fn remove_mark<EDSvc: EditingWorkerService>(
+ editing: &EDSvc,
+ document_id: &str,
+ document_token: &DocumentPermissionToken,
+ mark_id: Uuid,
+) {
+ if let Err(error) = editing
+ .remove_comment_mark(document_id, document_token, mark_id)
+ .await
+ {
+ tracing::error!(error = ?error, %mark_id, "comment mark left without its thread");
+ }
+}
diff --git a/crates/documents/src/inbound/toolset/comment_test.rs b/crates/documents/src/inbound/toolset/comment_test.rs
index 00562b4059..01eae698c5 100644
--- a/crates/documents/src/inbound/toolset/comment_test.rs
+++ b/crates/documents/src/inbound/toolset/comment_test.rs
@@ -9,7 +9,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use messages::domain::{
api::{MessageCommands, MessageReader},
models::{
- Message, MessageAttribution, MessageParent, MessageThread, PostMessage,
+ Message, MessageAttribution, MessageParent, MessageThread, NewThreadAnchor, PostMessage,
PostMessageNotificationPolicy, ThreadPatch, ThreadState,
},
ports::{MessageError, MessagePage, MessagePatch, MessageTimelineQuery},
@@ -19,8 +19,11 @@ use models_permissions::share_permission::access_level::AccessLevel;
use sync_service_client::SyncServiceClient;
use uuid::Uuid;
+use crate::domain::permission_token::decode_permission_token;
+
use super::{
DocumentToolContext,
+ comment_on_document_text::CommentOnDocumentText,
edit_document::test::{FakeDocumentService, FakeEditingWorker, FakeEntityAccessService},
reply_to_document_comment::ReplyToDocumentComment,
resolve_document_comment::ResolveDocumentComment,
@@ -35,6 +38,8 @@ const THREAD: Uuid = Uuid::from_u128(7);
#[derive(Clone)]
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)>>>,
}
@@ -43,6 +48,7 @@ impl Default for FakeMessages {
fn default() -> Self {
Self {
thread_exists: true,
+ fail_posts: false,
posts: Arc::default(),
thread_patches: Arc::default(),
}
@@ -100,6 +106,9 @@ impl MessageCommands for FakeMessages {
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"));
+ }
let at = Utc.with_ymd_and_hms(2026, 9, 23, 12, 0, 0).unwrap();
let message = Message {
id: Uuid::from_u128(99),
@@ -198,12 +207,21 @@ 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,
+ file_type: &str,
+ editing: FakeEditingWorker,
+) -> ServiceContext<TestToolContext> {
ServiceContext(DocumentToolContext::new(
- FakeDocumentService::new("md"),
+ FakeDocumentService::new(file_type),
FakeEntityAccessService { access_level },
LexicalClient::new("unused".to_owned(), "http://localhost/lexical".to_owned()),
SyncServiceClient::new("unused".to_owned(), "http://localhost/sync".to_owned()),
- FakeEditingWorker::default(),
+ editing,
"unused-jwt-secret".to_owned(),
Arc::new(messages),
))
@@ -387,3 +405,202 @@ 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 {
+ document_id: DOCUMENT,
+ text: text.to_owned(),
+ occurrence,
+ content: "Is this date still right?".to_owned(),
+ }
+}
+
+#[tokio::test]
+async fn comment_on_text_places_the_mark_then_posts_a_thread_anchored_to_it() {
+ let messages = FakeMessages::default();
+ let editing = FakeEditingWorker::default();
+ let response = comment_on_text("ships on Friday", Some(2))
+ .call(
+ context_with(
+ AccessLevel::Comment,
+ messages.clone(),
+ "md",
+ editing.clone(),
+ ),
+ request(),
+ )
+ .await
+ .unwrap();
+
+ let marks = editing.added_comment_marks.lock().unwrap();
+ let [mark] = marks.as_slice() else {
+ panic!("expected one mark, got {}", marks.len());
+ };
+ assert_eq!(mark.document_id, DOCUMENT.to_string());
+ assert_eq!(mark.text, "ships on Friday");
+ assert_eq!(mark.occurrence, Some(2));
+ let token = decode_permission_token(&mark.token, "unused-jwt-secret").unwrap();
+ assert_eq!(token.access_level, AccessLevel::Comment);
+ assert_eq!(token.user_id.as_ref().map(|user| user.as_ref()), Some(USER));
+
+ 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, None);
+ assert_eq!(post.content, "Is this date still right?");
+ assert_eq!(post.attribution, MessageAttribution::ActingUser);
+ let Some(NewThreadAnchor::Markdown {
+ mark_id,
+ marked_text,
+ }) = &post.anchor
+ else {
+ panic!("expected a markdown anchor, got {:?}", post.anchor);
+ };
+ assert_eq!(*mark_id, mark.mark_id);
+ assert_eq!(marked_text.as_deref(), Some("ships on Friday"));
+
+ 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!(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();
+
+ assert_eq!(error.description, "The text appears 2 times.");
+ assert!(messages.posts.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn comment_on_text_removes_the_mark_when_the_thread_cannot_be_posted() {
+ let messages = FakeMessages {
+ fail_posts: true,
+ ..FakeMessages::default()
+ };
+ let editing = FakeEditingWorker::default();
+ let error = comment_on_text("ships on Friday", None)
+ .call(
+ context_with(AccessLevel::Comment, messages, "md", editing.clone()),
+ request(),
+ )
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.description,
+ "unable to post the comment: anchor already in use"
+ );
+ let placed = editing.added_comment_marks.lock().unwrap()[0].mark_id;
+ assert_eq!(*editing.removed_comment_marks.lock().unwrap(), vec![placed]);
+}
+
+#[tokio::test]
+async fn comment_on_text_needs_comment_access() {
+ let editing = FakeEditingWorker::default();
+ let error = comment_on_text("ships on Friday", None)
+ .call(
+ context_with(
+ AccessLevel::View,
+ FakeMessages::default(),
+ "md",
+ editing.clone(),
+ ),
+ request(),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(
+ error.description.contains("comment access"),
+ "{}",
+ error.description
+ );
+ assert!(editing.added_comment_marks.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn comment_on_text_rejects_documents_that_are_not_markdown() {
+ let editing = FakeEditingWorker::default();
+ let error = comment_on_text("ships on Friday", None)
+ .call(
+ context_with(
+ AccessLevel::Edit,
+ FakeMessages::default(),
+ "pdf",
+ editing.clone(),
+ ),
+ request(),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(
+ error.description.contains("markdown documents only"),
+ "{}",
+ error.description
+ );
+ assert!(editing.added_comment_marks.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn comment_on_text_removes_the_mark_when_placing_it_fails() {
+ let messages = FakeMessages::default();
+ let editing = FakeEditingWorker::failing_comment_marks();
+ let error = comment_on_text("ships on Friday", None)
+ .call(
+ context_with(
+ AccessLevel::Comment,
+ messages.clone(),
+ "md",
+ editing.clone(),
+ ),
+ request(),
+ )
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.description,
+ "unable to anchor the comment to the text"
+ );
+ let placed = editing.added_comment_marks.lock().unwrap()[0].mark_id;
+ assert_eq!(*editing.removed_comment_marks.lock().unwrap(), vec![placed]);
+ assert!(messages.posts.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn comment_on_text_rejects_occurrence_zero() {
+ let editing = FakeEditingWorker::default();
+ let error = comment_on_text("ships on Friday", Some(0))
+ .call(
+ context_with(
+ AccessLevel::Comment,
+ FakeMessages::default(),
+ "md",
+ editing.clone(),
+ ),
+ request(),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(
+ error.description.contains("counts from 1"),
+ "{}",
+ error.description
+ );
+ assert!(editing.added_comment_marks.lock().unwrap().is_empty());
+}
diff --git a/crates/documents/src/inbound/toolset/edit_document/test.rs b/crates/documents/src/inbound/toolset/edit_document/test.rs
index 01bbf02afe..dcf6ef4718 100644
--- a/crates/documents/src/inbound/toolset/edit_document/test.rs
+++ b/crates/documents/src/inbound/toolset/edit_document/test.rs
@@ -10,7 +10,9 @@ use crate::domain::models::{
LocationQueryParams, TaskBranchName,
};
use crate::domain::permission_token::decode_permission_token;
-use crate::domain::ports::editing::{EditMode, EditResult, EditingWorkerService};
+use crate::domain::ports::editing::{
+ CommentMarkPlacement, EditMode, EditResult, EditingWorkerService,
+};
use crate::domain::response::{
CreateDocumentResponseData, DocumentResponse, GetDocumentResponseData, LocationResponseV3,
};
@@ -410,6 +412,37 @@ pub(in crate::inbound::toolset) struct FakeEditingWorker {
edit_calls: Arc<Mutex<Vec<String>>>,
modes: Arc<Mutex<Vec<EditMode>>>,
tokens: Arc<Mutex<Vec<DocumentPermissionToken>>>,
+ /// Answer every comment mark placement with this refusal.
+ comment_mark_refusal: Option<String>,
+ /// Fail every comment mark placement as a worker whose push was never acked.
+ comment_mark_fails: bool,
+ pub(in crate::inbound::toolset) added_comment_marks: Arc<Mutex<Vec<AddedCommentMark>>>,
+ pub(in crate::inbound::toolset) removed_comment_marks: Arc<Mutex<Vec<Uuid>>>,
+}
+
+impl FakeEditingWorker {
+ pub(in crate::inbound::toolset) fn failing_comment_marks() -> Self {
+ Self {
+ comment_mark_fails: true,
+ ..Self::default()
+ }
+ }
+
+ pub(in crate::inbound::toolset) fn refusing_comment_marks(reason: &str) -> Self {
+ Self {
+ comment_mark_refusal: Some(reason.to_owned()),
+ ..Self::default()
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub(in crate::inbound::toolset) struct AddedCommentMark {
+ pub document_id: String,
+ pub token: DocumentPermissionToken,
+ pub mark_id: Uuid,
+ pub text: String,
+ pub occurrence: Option<u32>,
}
impl EditingWorkerService for FakeEditingWorker {
@@ -422,6 +455,48 @@ impl EditingWorkerService for FakeEditingWorker {
panic!("unexpected spreadsheet call")
}
+ async fn add_comment_mark(
+ &self,
+ document_id: &str,
+ document_token: &DocumentPermissionToken,
+ mark_id: Uuid,
+ text: &str,
+ occurrence: Option<u32>,
+ ) -> anyhow::Result<CommentMarkPlacement> {
+ self.added_comment_marks
+ .lock()
+ .expect("comment marks lock poisoned")
+ .push(AddedCommentMark {
+ document_id: document_id.to_owned(),
+ token: document_token.clone(),
+ mark_id,
+ text: text.to_owned(),
+ occurrence,
+ });
+ if self.comment_mark_fails {
+ anyhow::bail!("sync service did not acknowledge 1 comment mark update(s)");
+ }
+ Ok(match &self.comment_mark_refusal {
+ Some(reason) => CommentMarkPlacement::Refused(reason.clone()),
+ None => CommentMarkPlacement::Placed {
+ marked_text: text.trim().to_owned(),
+ },
+ })
+ }
+
+ async fn remove_comment_mark(
+ &self,
+ _document_id: &str,
+ _document_token: &DocumentPermissionToken,
+ mark_id: Uuid,
+ ) -> anyhow::Result<()> {
+ self.removed_comment_marks
+ .lock()
+ .expect("comment marks lock poisoned")
+ .push(mark_id);
+ Ok(())
+ }
+
async fn edit(
&self,
document_id: &str,
diff --git a/crates/documents/src/inbound/toolset/reply_to_document_comment.rs b/crates/documents/src/inbound/toolset/reply_to_document_comment.rs
index 560a60a16a..ea3e7d42cf 100644
--- a/crates/documents/src/inbound/toolset/reply_to_document_comment.rs
+++ b/crates/documents/src/inbound/toolset/reply_to_document_comment.rs
@@ -18,7 +18,7 @@ use crate::domain::ports::{
#[serde(rename_all = "camelCase")]
#[schemars(
title = "ReplyToDocumentComment",
- description = "Reply in a comment thread on a document, or post a new comment in the document's Discussion panel, on behalf of the user. Only use this when explicitly asked to reply to or comment on a document. Thread ids come from the comments ReadContent returns. Cannot start a new inline comment on selected text."
+ 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.")]
diff --git a/crates/documents/src/inbound/toolset/test.rs b/crates/documents/src/inbound/toolset/test.rs
index 0ace903af6..628af62e1f 100644
--- a/crates/documents/src/inbound/toolset/test.rs
+++ b/crates/documents/src/inbound/toolset/test.rs
@@ -100,3 +100,21 @@ fn test_resolve_document_comment_schema_validation() {
"Description should limit when the tool resolves"
);
}
+
+#[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();
+ assert_eq!(
+ validated.name, "CommentOnDocumentText",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ validated
+ .description
+ .contains("Only use this when explicitly asked"),
+ "Description should limit when the tool posts"
+ );
+}
diff --git a/crates/documents/src/outbound/editing_worker_client.rs b/crates/documents/src/outbound/editing_worker_client.rs
index 8d7a1b4cdf..a1eb633584 100644
--- a/crates/documents/src/outbound/editing_worker_client.rs
+++ b/crates/documents/src/outbound/editing_worker_client.rs
@@ -35,6 +35,31 @@ impl ReqwestEditingWorkerClient {
}
}
+impl ReqwestEditingWorkerClient {
+ #[cfg(feature = "ai_tools")]
+ async fn comment_mark(
+ &self,
+ document_id: &str,
+ document_token: &DocumentPermissionToken,
+ change: serde_json::Value,
+ ) -> anyhow::Result<reqwest::Response> {
+ let mut headers = reqwest::header::HeaderMap::new();
+ macro_tower_layers::inject_trace_headers(&mut headers);
+ Ok(self
+ .client
+ .post(format!("{}/comment-mark", self.worker_url))
+ .headers(headers)
+ .timeout(std::time::Duration::from_secs(30))
+ .json(&serde_json::json!({
+ "documentId": document_id,
+ "documentToken": document_token.as_str(),
+ "change": change,
+ }))
+ .send()
+ .await?)
+ }
+}
+
impl EditingWorkerService for ReqwestEditingWorkerClient {
#[cfg(feature = "ai_tools")]
#[tracing::instrument(skip_all, fields(document_id), err)]
@@ -71,6 +96,70 @@ impl EditingWorkerService for ReqwestEditingWorkerClient {
Ok(response.json().await?)
}
+ #[cfg(feature = "ai_tools")]
+ #[tracing::instrument(skip_all, fields(document_id, %mark_id), err)]
+ async fn add_comment_mark(
+ &self,
+ document_id: &str,
+ document_token: &DocumentPermissionToken,
+ mark_id: uuid::Uuid,
+ text: &str,
+ occurrence: Option<u32>,
+ ) -> anyhow::Result<crate::domain::ports::editing::CommentMarkPlacement> {
+ use crate::domain::ports::editing::CommentMarkPlacement;
+
+ let mut change = serde_json::json!({
+ "action": "add",
+ "markId": mark_id,
+ "text": text,
+ });
+ if let Some(occurrence) = occurrence {
+ change["occurrence"] = occurrence.into();
+ }
+ let response = self
+ .comment_mark(document_id, document_token, change)
+ .await?;
+ let status = response.status();
+ let body = response
+ .json::<serde_json::Value>()
+ .await
+ .unwrap_or_default();
+ if status == reqwest::StatusCode::UNPROCESSABLE_ENTITY
+ && let Some(reason) = body.get("error").and_then(serde_json::Value::as_str)
+ {
+ return Ok(CommentMarkPlacement::Refused(reason.to_owned()));
+ }
+ if !status.is_success() {
+ anyhow::bail!("editing worker returned {status}: {body}");
+ }
+ Ok(CommentMarkPlacement::Placed {
+ marked_text: body["markedText"].as_str().unwrap_or_default().to_owned(),
+ })
+ }
+
+ #[cfg(feature = "ai_tools")]
+ #[tracing::instrument(skip_all, fields(document_id, %mark_id), err)]
+ async fn remove_comment_mark(
+ &self,
+ document_id: &str,
+ document_token: &DocumentPermissionToken,
+ mark_id: uuid::Uuid,
+ ) -> anyhow::Result<()> {
+ let response = self
+ .comment_mark(
+ document_id,
+ document_token,
+ serde_json::json!({ "action": "remove", "markId": mark_id }),
+ )
+ .await?;
+ let status = response.status();
+ if !status.is_success() {
+ let body = response.text().await.unwrap_or_default();
+ anyhow::bail!("editing worker returned {status}: {body}");
+ }
+ Ok(())
+ }
+
#[tracing::instrument(skip_all, fields(document_id), err)]
async fn edit(
&self,
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 40fdc61e97..b0d61f0e94 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -387,7 +387,12 @@ stream over the app's websocket, not the HTTP response.
When asked, the agent also answers document comments in place. A reply row reads
**Replied to a comment on** (or **Commented on** for a new Discussion comment) followed
by the document, and expands to the posted text; a resolve row reads **Resolved** or
-**Reopened a comment on** the document. The comment is posted as the agent with a
+**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
+**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
+refused with no highlight left behind. The comment is posted as the agent with a
**from <user>** pill, and needs the user's comment access to the document.
## Agent sessions asking a question
diff --git a/services/ai-editing-worker/AI_EDITING.md b/services/ai-editing-worker/AI_EDITING.md
index 9b44859968..bd616a5dcc 100644
--- a/services/ai-editing-worker/AI_EDITING.md
+++ b/services/ai-editing-worker/AI_EDITING.md
@@ -145,3 +145,15 @@ it so that AI commits use a small reserved range in
(`999999999999999000`–`999999999999999999`). This makes AI authorship easy to
detect (`isAiPeer`) which history will be able to use to group together all AI
edits.
+
+## Comment marks
+
+`POST /comment-mark` places or removes the comment mark an inline comment is
+anchored to (`src/comment-mark`). No model runs: the caller quotes the text and
+an optional 1-based occurrence, and the worker joins the document as a peer,
+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 `CommentOnDocumentText` tool places the mark first and then posts the
+thread anchored to it, removing the mark again if the post fails.
diff --git a/services/ai-editing-worker/src/comment-mark/anchor.test.ts b/services/ai-editing-worker/src/comment-mark/anchor.test.ts
new file mode 100644
index 0000000000..3298b8c3c1
--- /dev/null
+++ b/services/ai-editing-worker/src/comment-mark/anchor.test.ts
@@ -0,0 +1,197 @@
+import { $convertToMarkdownString } from '@lexical/markdown';
+import { $dfs } from '@lexical/utils';
+import {
+ $getCommentMarkText,
+ $isCommentNode,
+ type CommentNode,
+} from '@macro-inc/lexical-core';
+import { INTERNAL_TRANSFORMERS } from '@macro-inc/lexical-core/transformers';
+import { $getRoot } from 'lexical';
+import { describe, expect, it } from 'vitest';
+import { edit, read, setup } from '../ai-editing/ai-toolkit/_test-helpers';
+import type { LexicalSession } from '../ai-editing/ai-toolkit/session';
+import { $addCommentMark, $removeCommentMark } from './anchor';
+
+const MARK = '0199a1b2-0000-7000-8000-000000000001';
+const OTHER = '0199a1b2-0000-7000-8000-000000000002';
+
+function marks(session: LexicalSession): CommentNode[] {
+ return read(session, () =>
+ $dfs($getRoot())
+ .map(({ node }) => node)
+ .filter($isCommentNode)
+ );
+}
+
+function markedText(session: LexicalSession, id = MARK): string {
+ return read(session, () => $getCommentMarkText(id));
+}
+
+function text(session: LexicalSession): string {
+ return read(session, () => $getRoot().getTextContent());
+}
+
+function markdown(session: LexicalSession): string {
+ return read(session, () => $convertToMarkdownString(INTERNAL_TRANSFORMERS));
+}
+
+describe('$addCommentMark', () => {
+ it('wraps the quoted text in a committed comment mark', () => {
+ const { session } = setup('The quick brown fox jumps.');
+ const result = edit(session, () => $addCommentMark(MARK, 'brown fox'));
+
+ expect(result).toEqual({
+ ok: true,
+ markedText: 'brown fox',
+ surroundingText: 'The quick brown fox jumps.',
+ });
+ const [mark] = marks(session);
+ read(session, () => {
+ expect(mark.getIDs()).toEqual([MARK]);
+ expect(mark.getIsDraft()).toBe(false);
+ expect(mark.getThreadId()).toBeUndefined();
+ });
+ expect(text(session)).toBe('The quick brown fox jumps.');
+ });
+
+ it('crosses formatting and link boundaries within a block', () => {
+ const { session } = setup(
+ 'Ship **the new** [pricing page](https://example.com) today.'
+ );
+ const result = edit(session, () =>
+ $addCommentMark(MARK, 'new pricing page today')
+ );
+
+ expect(result.ok).toBe(true);
+ expect(markedText(session)).toBe('new pricing page today');
+ expect(text(session)).toBe('Ship the new pricing page today.');
+ expect(markdown(session)).toContain('"url":"https://example.com"');
+ });
+
+ it('trims the quote before matching', () => {
+ const { session } = setup('Alpha beta gamma.');
+ edit(session, () => $addCommentMark(MARK, ' beta '));
+ expect(markedText(session)).toBe('beta');
+ });
+
+ it('refuses text that is not in the document', () => {
+ const { session } = setup('Alpha beta gamma.');
+ const result = edit(session, () => $addCommentMark(MARK, 'delta'));
+ expect(result).toMatchObject({ ok: false, reason: 'not_found' });
+ expect(marks(session)).toHaveLength(0);
+ });
+
+ it('refuses markdown syntax the reader does not see', () => {
+ const { session } = setup('Alpha **beta** gamma.');
+ const result = edit(session, () => $addCommentMark(MARK, '**beta**'));
+ expect(result).toMatchObject({ ok: false, reason: 'not_found' });
+ });
+
+ it('refuses text crossing from one block into the next', () => {
+ const { session } = setup('First paragraph ends.\n\nSecond starts here.');
+ const result = edit(session, () =>
+ $addCommentMark(MARK, 'ends. Second starts')
+ );
+ expect(result).toMatchObject({ ok: false, reason: 'spans_blocks' });
+ expect(marks(session)).toHaveLength(0);
+ });
+
+ it('spots a cross-block quote when a block ends in a space', () => {
+ const { session } = setup('First paragraph ends. \n\nSecond starts here.');
+ const result = edit(session, () =>
+ $addCommentMark(MARK, 'ends. Second starts')
+ );
+ expect(result).toMatchObject({ ok: false, reason: 'spans_blocks' });
+ });
+
+ it('does not call a spacing slip inside one block a cross-block quote', () => {
+ const { session } = setup('Alpha beta gamma.');
+ const result = edit(session, () => $addCommentMark(MARK, 'beta gamma'));
+ expect(result).toMatchObject({ ok: false, reason: 'not_found' });
+ });
+
+ it('refuses repeated text with no occurrence and lists each one', () => {
+ const { session } = setup('Owner: TBD.\n\nDeadline: TBD.');
+ const result = edit(session, () => $addCommentMark(MARK, 'TBD'));
+ expect(result.ok).toBe(false);
+ if (!('reason' in result)) return;
+ expect(result.reason).toBe('ambiguous');
+ expect(result.message).toContain('appears 2 times');
+ expect(result.message).toContain('1: "Owner: TBD."');
+ expect(result.message).toContain('2: "Deadline: TBD."');
+ expect(marks(session)).toHaveLength(0);
+ });
+
+ it('marks the chosen occurrence in document order', () => {
+ const { session } = setup('Owner: TBD.\n\nDeadline: TBD.');
+ const result = edit(session, () => $addCommentMark(MARK, 'TBD', 2));
+ expect(result).toMatchObject({
+ ok: true,
+ markedText: 'TBD',
+ surroundingText: 'Deadline: TBD.',
+ });
+ });
+
+ it('refuses an occurrence past the last one', () => {
+ const { session } = setup('Owner: TBD.');
+ const result = edit(session, () => $addCommentMark(MARK, 'TBD', 2));
+ expect(result).toMatchObject({
+ ok: false,
+ reason: 'occurrence_out_of_range',
+ });
+ });
+
+ it('finds text in list items and headings', () => {
+ const { session } = setup('# Launch plan\n\n- ship the beta\n- tell sales');
+ edit(session, () => $addCommentMark(MARK, 'the beta'));
+ edit(session, () => $addCommentMark(OTHER, 'Launch'));
+ expect(markedText(session)).toBe('the beta');
+ expect(markedText(session, OTHER)).toBe('Launch');
+ });
+
+ it('does not mark inside code blocks', () => {
+ const { session } = setup('```\nconst secret = 1;\n```');
+ const result = edit(session, () => $addCommentMark(MARK, 'secret'));
+ expect(result).toMatchObject({ ok: false, reason: 'not_found' });
+ });
+
+ it('leaves a mark it already placed alone when asked again', () => {
+ const { session } = setup('Alpha beta gamma.');
+ edit(session, () => $addCommentMark(MARK, 'beta'));
+ const again = edit(session, () => $addCommentMark(MARK, 'beta'));
+ expect(again).toMatchObject({ ok: true, markedText: 'beta' });
+ expect(marks(session)).toHaveLength(1);
+ });
+
+ it('overlaps an existing comment mark without disturbing it', () => {
+ const { session } = setup('Alpha beta gamma delta.');
+ edit(session, () => $addCommentMark(OTHER, 'beta gamma'));
+ edit(session, () => $addCommentMark(MARK, 'gamma delta'));
+ expect(markedText(session, OTHER)).toBe('beta gamma');
+ expect(markedText(session)).toBe('gamma delta');
+ });
+});
+
+describe('$removeCommentMark', () => {
+ it('unwraps the mark and keeps its text', () => {
+ const { session } = setup('Alpha **beta** gamma.');
+ edit(session, () => $addCommentMark(MARK, 'beta gamma'));
+ expect(edit(session, () => $removeCommentMark(MARK))).toBe(true);
+ expect(marks(session)).toHaveLength(0);
+ expect(markdown(session)).toBe('Alpha **beta** gamma.');
+ });
+
+ it('leaves another comment sharing the text in place', () => {
+ const { session } = setup('Alpha beta gamma.');
+ edit(session, () => $addCommentMark(OTHER, 'beta'));
+ edit(session, () => $addCommentMark(MARK, 'beta'));
+ edit(session, () => $removeCommentMark(MARK));
+ expect(markedText(session)).toBe('');
+ expect(markedText(session, OTHER)).toBe('beta');
+ });
+
+ it('reports a mark the document does not carry', () => {
+ const { session } = setup('Alpha.');
+ expect(edit(session, () => $removeCommentMark(MARK))).toBe(false);
+ });
+});
diff --git a/services/ai-editing-worker/src/comment-mark/anchor.ts b/services/ai-editing-worker/src/comment-mark/anchor.ts
new file mode 100644
index 0000000000..5f6c99a5e0
--- /dev/null
+++ b/services/ai-editing-worker/src/comment-mark/anchor.ts
@@ -0,0 +1,259 @@
+/**
+ * Placing and removing the comment mark an inline comment is anchored to.
+ * Unlike `/edit`, nothing here is model-driven: the caller names the text and
+ * the mark goes exactly there or nowhere, so a mark is never guessed into
+ * place.
+ */
+
+import { $isCodeNode } from '@lexical/code';
+import { $wrapSelectionInMarkNode } from '@lexical/mark';
+import { $dfs } from '@lexical/utils';
+import {
+ $createCommentNode,
+ $getCommentMarkContext,
+ $isCommentNode,
+ type CommentNode,
+} from '@macro-inc/lexical-core';
+import {
+ $createRangeSelection,
+ $getRoot,
+ $isDecoratorNode,
+ $isElementNode,
+ $isLineBreakNode,
+ $isTextNode,
+ type ElementNode,
+ type LexicalNode,
+ type TextNode,
+} from 'lexical';
+
+/** Why a mark could not be placed; each is reported to the agent as is. */
+export type AnchorRefusal =
+ | 'not_found'
+ | 'spans_blocks'
+ | 'ambiguous'
+ | 'occurrence_out_of_range';
+
+export type AnchorResult =
+ | { ok: true; markedText: string; surroundingText: string }
+ | { ok: false; reason: AnchorRefusal; message: string };
+
+type Segment =
+ | { kind: 'text'; node: TextNode; start: number; end: number }
+ | { kind: 'atom'; start: number; end: number };
+
+type Occurrence = {
+ block: ElementNode;
+ start: { node: TextNode; offset: number };
+ end: { node: TextNode; offset: number };
+ context: string;
+};
+
+const CONTEXT_CHARS = 40;
+const MAX_LISTED_OCCURRENCES = 5;
+
+function $isTextBlock(node: LexicalNode): node is ElementNode {
+ return (
+ $isElementNode(node) &&
+ !node.isInline() &&
+ !$isCodeNode(node) &&
+ node
+ .getChildren()
+ .some((child) => !$isElementNode(child) || child.isInline())
+ );
+}
+
+/** The block's text as a reader sees it, with where each text node sits in it. */
+function $blockText(block: ElementNode): { text: string; segments: Segment[] } {
+ const segments: Segment[] = [];
+ let text = '';
+ const visit = (node: LexicalNode) => {
+ if ($isTextNode(node)) {
+ const content = node.getTextContent();
+ segments.push({
+ kind: 'text',
+ node,
+ start: text.length,
+ end: text.length + content.length,
+ });
+ text += content;
+ } else if ($isLineBreakNode(node)) {
+ text += '\n';
+ } else if ($isElementNode(node) && node.isInline()) {
+ for (const child of node.getChildren()) visit(child);
+ } else if ($isDecoratorNode(node)) {
+ const content = node.getTextContent();
+ segments.push({
+ kind: 'atom',
+ start: text.length,
+ end: text.length + content.length,
+ });
+ text += content;
+ }
+ };
+ for (const child of block.getChildren()) visit(child);
+ return { text, segments };
+}
+
+/** A text point at `offset`, `edge` saying which side of a node boundary it prefers. */
+function pointAt(
+ segments: Segment[],
+ offset: number,
+ edge: 'start' | 'end'
+): { node: TextNode; offset: number } | null {
+ for (const segment of segments) {
+ if (segment.kind !== 'text') continue;
+ const inside =
+ edge === 'start'
+ ? offset >= segment.start && offset < segment.end
+ : offset > segment.start && offset <= segment.end;
+ if (inside) return { node: segment.node, offset: offset - segment.start };
+ }
+ return null;
+}
+
+function contextAround(text: string, start: number, end: number): string {
+ const from = Math.max(0, start - CONTEXT_CHARS);
+ const to = Math.min(text.length, end + CONTEXT_CHARS);
+ return (
+ (from > 0 ? '…' : '') + text.slice(from, to) + (to < text.length ? '…' : '')
+ );
+}
+
+function $occurrences(needle: string): Occurrence[] {
+ const out: Occurrence[] = [];
+ for (const { node } of $dfs($getRoot())) {
+ if (!$isTextBlock(node)) continue;
+ const { text, segments } = $blockText(node);
+ for (
+ let index = text.indexOf(needle);
+ index !== -1;
+ index = text.indexOf(needle, index + needle.length)
+ ) {
+ const start = pointAt(segments, index, 'start');
+ const end = pointAt(segments, index + needle.length, 'end');
+ // A match that begins or ends inside a mention or other atom cannot be
+ // wrapped exactly, so it is not a place the mark can go.
+ if (!start || !end) continue;
+ out.push({
+ block: node,
+ start,
+ end,
+ context: contextAround(text, index, index + needle.length),
+ });
+ }
+ }
+ return out;
+}
+
+function $blockTexts(): string[] {
+ const blocks: string[] = [];
+ for (const { node } of $dfs($getRoot())) {
+ if ($isTextBlock(node)) blocks.push($blockText(node).text);
+ }
+ return blocks;
+}
+
+/**
+ * Wrap the `occurrence`th (1-based) appearance of `text` in a committed comment
+ * mark `markId`. Refuses rather than guesses: text that is not in the
+ * document, that crosses from one block into another, or that appears more
+ * than once with no occurrence chosen leaves the document untouched, as does
+ * a mark `markId` the document already carries. Must run
+ * inside an editor update.
+ */
+export function $addCommentMark(
+ markId: string,
+ text: string,
+ occurrence?: number
+): AnchorResult {
+ // A retried request finds its mark already placed; wrapping again would
+ // nest the mark inside itself.
+ const placed = $getCommentMarkContext(markId);
+ if (placed) return { ok: true, ...placed };
+
+ const needle = text.trim();
+ const found = needle ? $occurrences(needle) : [];
+
+ if (found.length === 0) {
+ // Only text that is in no single block but runs across the join of two is
+ // reported as crossing blocks; a whitespace slip inside one block is not.
+ const collapse = (value: string) => value.replace(/\s+/g, ' ');
+ const quote = collapse(needle);
+ const blocks = $blockTexts().map(collapse);
+ if (
+ needle &&
+ !blocks.some((block) => block.includes(quote)) &&
+ collapse(blocks.join(' ')).includes(quote)
+ )
+ return {
+ ok: false,
+ reason: 'spans_blocks',
+ message:
+ 'The text runs across more than one paragraph, heading, list item or table cell. An inline comment covers text within one of them: choose a passage inside a single block.',
+ };
+ return {
+ ok: false,
+ reason: 'not_found',
+ message:
+ 'The text was not found in the document. Quote it exactly as the document reads, including its spacing and line breaks, without markdown syntax such as ** or links, and read the document again if it may have changed.',
+ };
+ }
+
+ if (occurrence !== undefined && (occurrence < 1 || occurrence > found.length))
+ return {
+ ok: false,
+ reason: 'occurrence_out_of_range',
+ message: `The text appears ${found.length} time(s); occurrence ${occurrence} does not exist.`,
+ };
+
+ if (occurrence === undefined && found.length > 1) {
+ const listed = found
+ .slice(0, MAX_LISTED_OCCURRENCES)
+ .map((match, index) => `${index + 1}: "${match.context}"`)
+ .join('\n');
+ const more =
+ found.length > MAX_LISTED_OCCURRENCES
+ ? `\n(and ${found.length - MAX_LISTED_OCCURRENCES} more)`
+ : '';
+ return {
+ ok: false,
+ reason: 'ambiguous',
+ message: `The text appears ${found.length} times. Pass the occurrence to comment on, or quote a longer, unique passage:\n${listed}${more}`,
+ };
+ }
+
+ const target = found[(occurrence ?? 1) - 1];
+ const selection = $createRangeSelection();
+ selection.anchor.set(target.start.node.getKey(), target.start.offset, 'text');
+ selection.focus.set(target.end.node.getKey(), target.end.offset, 'text');
+ $wrapSelectionInMarkNode(selection, false, markId, (ids) =>
+ $createCommentNode({ ids, isDraft: false })
+ );
+
+ const context = $getCommentMarkContext(markId);
+ if (!context)
+ throw new Error(`comment mark ${markId} missing right after it was placed`);
+ return { ok: true, ...context };
+}
+
+/**
+ * Take comment mark `markId` out of the document, keeping the text it
+ * covered. Returns whether the document carried it. Must run inside an editor
+ * update.
+ */
+export function $removeCommentMark(markId: string): boolean {
+ const marks: CommentNode[] = [];
+ for (const { node } of $dfs($getRoot())) {
+ if ($isCommentNode(node) && node.getIDs().includes(markId))
+ marks.push(node);
+ }
+ for (const mark of marks) {
+ if (mark.getIDs().length > 1) {
+ mark.deleteID(markId);
+ continue;
+ }
+ for (const child of mark.getChildren()) mark.insertBefore(child);
+ mark.remove();
+ }
+ return marks.length > 0;
+}
diff --git a/services/ai-editing-worker/src/comment-mark/run.test.ts b/services/ai-editing-worker/src/comment-mark/run.test.ts
new file mode 100644
index 0000000000..8e0c57de0e
--- /dev/null
+++ b/services/ai-editing-worker/src/comment-mark/run.test.ts
@@ -0,0 +1,136 @@
+import { LoroManager } from '@macro-inc/collaboration/collab/manager';
+import { createNoopLiveSyncSource } from '@macro-inc/collaboration/collab/source';
+import { MARKDOWN_LORO_SCHEMA } from '@macro-inc/lexical-core/markdown-loro-schema';
+import { markdownToLoroSnapshot } from '@macro-inc/lexical-core/markdown-loro-snapshot';
+import {
+ LoroDoc,
+ type LoroMap,
+ type LoroMovableList,
+ type LoroText,
+} from 'loro-crdt';
+import { describe, expect, it } from 'vitest';
+import { applyCommentMarkChange } from './run';
+
+const DOC = 'doc-1';
+const MARK = '0199a1b2-0000-7000-8000-000000000001';
+
+type Node = {
+ type?: string;
+ ids?: string[];
+ text?: string;
+ children?: Node[];
+};
+
+async function worker(snapshot: Uint8Array) {
+ const manager = new LoroManager(MARKDOWN_LORO_SCHEMA, { documentId: DOC });
+ (await manager.initializeFromSnapshot(snapshot))._unsafeUnwrap();
+ return manager;
+}
+
+function human(snapshot: Uint8Array): LoroDoc {
+ const doc = new LoroDoc();
+ doc.import(snapshot);
+ return doc;
+}
+
+/** The LoroText of the first paragraph's first text node, as a typist edits it. */
+function firstText(doc: LoroDoc): LoroText {
+ const paragraph = (doc.getMap('root').get('children') as LoroMovableList).get(
+ 0
+ ) as LoroMap;
+ const text = (paragraph.get('children') as LoroMovableList).get(0) as LoroMap;
+ return text.get('text') as LoroText;
+}
+
+function exchange(a: LoroDoc, b: LoroDoc) {
+ const fromA = a.export({ mode: 'update', from: b.oplogVersion() });
+ const fromB = b.export({ mode: 'update', from: a.oplogVersion() });
+ a.import(fromB);
+ b.import(fromA);
+}
+
+function walk(node: Node, out: Node[] = []): Node[] {
+ out.push(node);
+ for (const child of node.children ?? []) walk(child, out);
+ return out;
+}
+
+function textOf(node: Node): string {
+ return (node.text ?? '') + (node.children ?? []).map(textOf).join('');
+}
+
+function tree(doc: LoroDoc): Node {
+ return (doc.toJSON() as { root: Node }).root;
+}
+
+describe('applyCommentMarkChange', () => {
+ it('reaches other peers as a comment mark around the quoted text', async () => {
+ const snapshot = (await markdownToLoroSnapshot('The quick brown fox.'))!;
+ const manager = await worker(snapshot);
+ const peer = human(snapshot);
+
+ const result = await applyCommentMarkChange(
+ manager,
+ createNoopLiveSyncSource(DOC),
+ { action: 'add', markId: MARK, text: 'brown fox' }
+ );
+ expect(result).toMatchObject({ ok: true, markedText: 'brown fox' });
+
+ exchange(manager.doc, peer);
+ const marks = walk(tree(peer)).filter((n) => n.type === 'comment-mark');
+ expect(marks).toHaveLength(1);
+ expect(marks[0].ids).toEqual([MARK]);
+ expect(textOf(marks[0])).toBe('brown fox');
+ expect(textOf(tree(peer))).toBe('The quick brown fox.');
+ manager.dispose();
+ });
+
+ it('merges with typing that lands while the mark is placed', async () => {
+ const snapshot = (await markdownToLoroSnapshot('The quick brown fox.'))!;
+ const manager = await worker(snapshot);
+ const peer = human(snapshot);
+
+ // Typed before the worker's change reaches this peer, into the very text
+ // run the mark splits. Loro keeps every keystroke and both peers converge
+ // on one mark, though typing in a run the split removed can surface
+ // elsewhere in the paragraph, as it does when a person places a comment.
+ const typed = firstText(peer);
+ typed.insert('The quick brown fox.'.length - 1, ' ran');
+ typed.insert('The quick '.length, 'big ');
+ peer.commit();
+
+ await applyCommentMarkChange(manager, createNoopLiveSyncSource(DOC), {
+ action: 'add',
+ markId: MARK,
+ text: 'quick brown',
+ });
+ exchange(manager.doc, peer);
+
+ expect(manager.doc.toJSON()).toEqual(peer.toJSON());
+ const text = textOf(tree(peer));
+ expect(text).toContain('big ');
+ expect(text).toContain(' ran');
+ expect(text.replace('big ', '').replace(' ran', '')).toBe(
+ 'The quick brown fox.'
+ );
+ const marks = walk(tree(peer)).filter((n) => n.type === 'comment-mark');
+ expect(marks).toHaveLength(1);
+ expect(textOf(marks[0])).toBe('quick brown');
+ manager.dispose();
+ });
+
+ it('pushes nothing when the text cannot be anchored', async () => {
+ const snapshot = (await markdownToLoroSnapshot('The quick brown fox.'))!;
+ const manager = await worker(snapshot);
+ const before = manager.doc.oplogVersion();
+
+ const result = await applyCommentMarkChange(
+ manager,
+ createNoopLiveSyncSource(DOC),
+ { action: 'add', markId: MARK, text: 'lazy dog' }
+ );
+ expect(result).toMatchObject({ ok: false, reason: 'not_found' });
+ expect(manager.doc.oplogVersion().compare(before)).toBe(0);
+ manager.dispose();
+ });
+});
diff --git a/services/ai-editing-worker/src/comment-mark/run.ts b/services/ai-editing-worker/src/comment-mark/run.ts
new file mode 100644
index 0000000000..bb7191cb4c
--- /dev/null
+++ b/services/ai-editing-worker/src/comment-mark/run.ts
@@ -0,0 +1,100 @@
+import { LoroManager } from '@macro-inc/collaboration/collab/manager';
+import type { RawUpdate } from '@macro-inc/collaboration/collab/shared';
+import type { LiveSyncSource } from '@macro-inc/collaboration/collab/source';
+import {
+ InMemoryWALStore,
+ WALSyncer,
+} from '@macro-inc/collaboration/collab/wal';
+import type { SyncServiceSource } from '@macro-inc/collaboration/sync-service/source';
+import { MARKDOWN_LORO_SCHEMA } from '@macro-inc/lexical-core/markdown-loro-schema';
+import { EditingWorkspace } from '../editing-workspace';
+import type { AnchorResult } from './anchor';
+import { $addCommentMark, $removeCommentMark } from './anchor';
+
+export type CommentMarkChange =
+ | {
+ action: 'add';
+ markId: string;
+ text: string;
+ occurrence?: number | null;
+ }
+ | { action: 'remove'; markId: string };
+
+export type CommentMarkChangeResult =
+ | AnchorResult
+ | { ok: true; removed: boolean };
+
+/**
+ * Join the document as a Loro peer, apply one comment mark change and push it
+ * to everyone. The change is made on the state merged from the server a
+ * moment before, and lands as ordinary CRDT operations, so edits people make
+ * meanwhile merge with it rather than being overwritten.
+ */
+export async function runCommentMarkChange(
+ source: SyncServiceSource,
+ documentId: string,
+ change: CommentMarkChange
+): Promise<CommentMarkChangeResult> {
+ const manager = new LoroManager(MARKDOWN_LORO_SCHEMA, { documentId });
+ try {
+ const initial = await source.doInitialSync();
+ if (initial.isErr())
+ throw new Error(
+ `initial sync failed: ${initial.error.type} (${initial.error.duration}ms)`
+ );
+ const loaded = await manager.initializeFromSnapshot(initial.value.snapshot);
+ if (loaded.isErr())
+ throw new Error(
+ `failed to initialize from snapshot: ${loaded.error[0]?.message}`
+ );
+
+ return await applyCommentMarkChange(manager, source, change);
+ } finally {
+ manager.dispose();
+ source.cleanup();
+ }
+}
+
+/** Apply `change` to the doc `manager` holds and push it out through `source`. */
+export async function applyCommentMarkChange(
+ manager: LoroManager<typeof MARKDOWN_LORO_SCHEMA>,
+ source: LiveSyncSource,
+ change: CommentMarkChange
+): Promise<CommentMarkChangeResult> {
+ const wal = new WALSyncer<RawUpdate>(
+ new InMemoryWALStore<RawUpdate>(),
+ (updates) => source.pushUpdate(updates)
+ );
+ const workspace = new EditingWorkspace(manager, source, wal);
+ try {
+ let result!: CommentMarkChangeResult;
+ workspace.session.editor.update(
+ () => {
+ result =
+ change.action === 'add'
+ ? $addCommentMark(
+ change.markId,
+ change.text,
+ change.occurrence ?? undefined
+ )
+ : { ok: true, removed: $removeCommentMark(change.markId) };
+ },
+ { discrete: true }
+ );
+ if (result.ok) {
+ await workspace.flush();
+ await wal.flush();
+ // A flush the server never acknowledged resolves all the same; the
+ // caller must not be told a mark landed that nobody else has.
+ const { dirty } = await wal.summary();
+ if (dirty > 0)
+ throw new Error(
+ `sync service did not acknowledge ${dirty} comment mark update(s)`
+ );
+ }
+ return result;
+ } finally {
+ workspace.dispose();
+ wal.destroy();
+ }
+}
diff --git a/services/ai-editing-worker/src/endpoints/comment-mark.ts b/services/ai-editing-worker/src/endpoints/comment-mark.ts
new file mode 100644
index 0000000000..0520426c03
--- /dev/null
+++ b/services/ai-editing-worker/src/endpoints/comment-mark.ts
@@ -0,0 +1,61 @@
+import { zValidator } from '@hono/zod-validator';
+import { Telemetry } from '@macro-inc/observability';
+import { Hono } from 'hono';
+import * as z from 'zod';
+import { runCommentMarkChange } from '../comment-mark/run';
+import { type Bindings, getEnv } from '../env';
+import { createWorkerSyncSource } from '../sources';
+
+const CommentMarkBody = z.object({
+ documentToken: z.string(),
+ documentId: z.string(),
+ change: z.discriminatedUnion('action', [
+ z.object({
+ action: z.literal('add'),
+ markId: z.uuid(),
+ text: z.string().min(1).max(10_000),
+ occurrence: z.number().int().min(1).nullish(),
+ }),
+ z.object({ action: z.literal('remove'), markId: z.uuid() }),
+ ]),
+});
+
+const commentMark = new Hono<{ Bindings: Bindings }>();
+
+/**
+ * Place or remove the comment mark an inline comment is anchored to. A mark
+ * that cannot be placed exactly answers 422 with the reason and leaves the
+ * document untouched.
+ */
+commentMark.post('/', zValidator('json', CommentMarkBody), async (c) => {
+ const env = getEnv(c.env);
+ const { documentToken, documentId, change } = c.req.valid('json');
+ const signal = AbortSignal.any([
+ c.req.raw.signal,
+ AbortSignal.timeout(20_000),
+ ]);
+ try {
+ const wsUrl = `${env.SYNC_WS_BASE}/document/${documentId}/connect?token=${documentToken}`;
+ const result = await Telemetry.span('comment_mark.change', async (span) => {
+ span.setAttr('document.id', documentId);
+ span.setAttr('comment_mark.action', change.action);
+ const result = await runCommentMarkChange(
+ createWorkerSyncSource(wsUrl, documentId, signal),
+ documentId,
+ change
+ );
+ if ('reason' in result)
+ span.setAttr('comment_mark.refused', result.reason);
+ return result;
+ });
+ if ('reason' in result)
+ return c.json({ error: result.message, reason: result.reason }, 422);
+ return c.json(result);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ console.error('comment mark change failed:', message);
+ return c.json({ error: message }, signal.aborted ? 504 : 502);
+ }
+});
+
+export default commentMark;
diff --git a/services/ai-editing-worker/src/endpoints/index.ts b/services/ai-editing-worker/src/endpoints/index.ts
index 08096a36d9..f2d7abead2 100644
--- a/services/ai-editing-worker/src/endpoints/index.ts
+++ b/services/ai-editing-worker/src/endpoints/index.ts
@@ -1,5 +1,6 @@
import { Hono } from 'hono';
import type { Bindings } from '../env';
+import commentMark from './comment-mark';
import edit from './edit';
import spreadsheet from './spreadsheet';
import traces from './traces';
@@ -7,6 +8,7 @@ import traces from './traces';
const endpoints = new Hono<{ Bindings: Bindings }>();
endpoints.route('/edit', edit);
+endpoints.route('/comment-mark', commentMark);
endpoints.route('/traces', traces);
endpoints.route('/spreadsheet', spreadsheet);
diff --git a/services/scheduled_action/src/outbound/pg_event_run_repo.rs b/services/scheduled_action/src/outbound/pg_event_run_repo.rs
index 90217e71ab..33af79c0b2 100644
--- a/services/scheduled_action/src/outbound/pg_event_run_repo.rs
+++ b/services/scheduled_action/src/outbound/pg_event_run_repo.rs
@@ -392,6 +392,9 @@ impl EventRunRepository for PgEventRunRepo {
.fetch_optional(&mut *tx)
.await?;
let Some(action) = action else {
+ // Drop only queues rollback. Release the action lock before returning
+ // so an immediate SKIP LOCKED reconciliation can observe this action.
+ tx.rollback().await?;
return Ok(FinalizationResult::StaleClaim);
};
let stored = sqlx::query!(
@@ -405,17 +408,21 @@ impl EventRunRepository for PgEventRunRepo {
.fetch_optional(&mut *tx)
.await?;
let Some(stored) = stored else {
+ tx.rollback().await?;
return Ok(FinalizationResult::StaleClaim);
};
if stored.claim_token != Some(run.token.as_uuid()) {
+ tx.rollback().await?;
return Ok(FinalizationResult::StaleClaim);
}
if stored.state == "finished" {
+ tx.rollback().await?;
return Ok(FinalizationResult::AlreadyFinalized);
}
// Delayed bookkeeping may still finish its own claim. Reconciliation
// uses the same lock: whichever terminal transition commits first wins.
if stored.state != "started" || action.claim_token != stored.claim_token {
+ tx.rollback().await?;
return Ok(FinalizationResult::StaleClaim);
}
let mut execution_record_id = None;