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(messages): tell an agent what a comment is anchored to (#6793)

gbirmanfa79b30733b2
diff --git a/apps/web/src/features/block-md/comments/messageCommentOperations.ts b/apps/web/src/features/block-md/comments/messageCommentOperations.ts
index 5900d2fe5b..a954d2a078 100644
--- a/apps/web/src/features/block-md/comments/messageCommentOperations.ts
+++ b/apps/web/src/features/block-md/comments/messageCommentOperations.ts
@@ -5,6 +5,7 @@ import {
type ThreadId,
} from '@core/comments/commentType';
import { COMMIT_COMMENT_MARK_COMMAND } from '@core/component/LexicalMarkdown/plugins/comments/commentPlugin';
+import { $getCommentMarkText } from '@macro-inc/lexical-core';
import { createCallback } from '@solid-primitives/rootless';
import { useMarkdownDocument } from '../context/markdown-document-context';
import { useDeleteNewComments } from './commentOperations';
@@ -44,9 +45,15 @@ export function useCreateMessageComment(): MessageCommentOperations['createComme
return null;
}
+ // Read the mark now rather than when the draft was made: what the comment
+ // is about is whatever it still covers as the comment is posted.
+ const markedText =
+ editor?.read(() => $getCommentMarkText(draft.anchorId)) || undefined;
+
const response = await createMarkedMessage(
message.content,
draft.anchorId,
+ markedText,
message.mentions,
message.attachments
);
diff --git a/apps/web/src/features/block-md/comments/messageCommentsResource.ts b/apps/web/src/features/block-md/comments/messageCommentsResource.ts
index 5b267e3125..346dd220d6 100644
--- a/apps/web/src/features/block-md/comments/messageCommentsResource.ts
+++ b/apps/web/src/features/block-md/comments/messageCommentsResource.ts
@@ -15,12 +15,14 @@ export function useCreateMarkedMessageResource() {
return (
content: string,
markId: string,
+ markedText: string | undefined,
mentions?: PostMessage['mentions'],
attachments?: PostMessage['attachments']
) =>
messages.post({
content,
- anchor: { type: 'markdown', mark_id: markId },
+ // The server trims and bounds the snapshot; it is sent as the mark reads.
+ anchor: { type: 'markdown', mark_id: markId, marked_text: markedText },
mentions,
attachments,
});
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 463576e13c..49b6853c17 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -960,10 +960,11 @@ export * from './newChannelAttachmentHeight';
export * from './newChannelAttachmentWidth';
export * from './newThreadAnchor';
export * from './newThreadAnchorOneOf';
-export * from './newThreadAnchorOneOfFive';
-export * from './newThreadAnchorOneOfFiveType';
-export * from './newThreadAnchorOneOfThree';
-export * from './newThreadAnchorOneOfThreeType';
+export * from './newThreadAnchorOneOfFour';
+export * from './newThreadAnchorOneOfFourType';
+export * from './newThreadAnchorOneOfMarkedText';
+export * from './newThreadAnchorOneOfSix';
+export * from './newThreadAnchorOneOfSixType';
export * from './newThreadAnchorOneOfType';
export * from './notificationFilters';
export * from './notificationState';
@@ -1412,10 +1413,11 @@ export * from './teamRole';
export * from './thread';
export * from './threadAnchor';
export * from './threadAnchorOneOf';
-export * from './threadAnchorOneOfFive';
-export * from './threadAnchorOneOfFiveType';
-export * from './threadAnchorOneOfThree';
-export * from './threadAnchorOneOfThreeType';
+export * from './threadAnchorOneOfFour';
+export * from './threadAnchorOneOfFourType';
+export * from './threadAnchorOneOfMarkedText';
+export * from './threadAnchorOneOfSix';
+export * from './threadAnchorOneOfSixType';
export * from './threadAnchorOneOfType';
export * from './threadCreatedAt';
export * from './threadDeletedAt';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchor.ts
index 1aa45b7df2..21f8a68e1c 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchor.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchor.ts
@@ -5,13 +5,13 @@
* OpenAPI spec version: 0.1.0
*/
import type { NewThreadAnchorOneOf } from './newThreadAnchorOneOf';
-import type { NewThreadAnchorOneOfFive } from './newThreadAnchorOneOfFive';
-import type { NewThreadAnchorOneOfThree } from './newThreadAnchorOneOfThree';
+import type { NewThreadAnchorOneOfFour } from './newThreadAnchorOneOfFour';
+import type { NewThreadAnchorOneOfSix } from './newThreadAnchorOneOfSix';
/**
* Location supplied when creating a document discussion.
*/
export type NewThreadAnchor =
| NewThreadAnchorOneOf
- | NewThreadAnchorOneOfThree
- | NewThreadAnchorOneOfFive;
+ | NewThreadAnchorOneOfFour
+ | NewThreadAnchorOneOfSix;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOf.ts
index 090c93bc9c..b0e0321bf3 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOf.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOf.ts
@@ -4,6 +4,7 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { NewThreadAnchorOneOfMarkedText } from './newThreadAnchorOneOfMarkedText';
import type { NewThreadAnchorOneOfType } from './newThreadAnchorOneOfType';
/**
@@ -12,5 +13,9 @@ import type { NewThreadAnchorOneOfType } from './newThreadAnchorOneOfType';
export type NewThreadAnchorOneOf = {
/** Serialized mark identifier. */
mark_id: string;
+ /** The document text the mark covers, captured by the editor as the
+comment is written. Trimmed and bounded before it is stored, so an
+oversized or whitespace-only claim cannot reach the thread row. */
+ marked_text?: NewThreadAnchorOneOfMarkedText;
type: NewThreadAnchorOneOfType;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfThree.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfFour.ts
similarity index 61%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfThree.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfFour.ts
index b626f25972..f7f0e922e8 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfThree.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfFour.ts
@@ -4,13 +4,13 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { NewThreadAnchorOneOfThreeType } from './newThreadAnchorOneOfThreeType';
+import type { NewThreadAnchorOneOfFourType } from './newThreadAnchorOneOfFourType';
/**
* Attach an independently existing highlight on this document.
*/
-export type NewThreadAnchorOneOfThree = {
+export type NewThreadAnchorOneOfFour = {
/** Highlight annotation identifier. */
anchor_id: string;
- type: NewThreadAnchorOneOfThreeType;
+ type: NewThreadAnchorOneOfFourType;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfThreeType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfFourType.ts
similarity index 57%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfThreeType.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfFourType.ts
index eb8e784ca3..895dd5bd00 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfThreeType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfFourType.ts
@@ -5,10 +5,10 @@
* OpenAPI spec version: 0.1.0
*/
-export type NewThreadAnchorOneOfThreeType =
- (typeof NewThreadAnchorOneOfThreeType)[keyof typeof NewThreadAnchorOneOfThreeType];
+export type NewThreadAnchorOneOfFourType =
+ (typeof NewThreadAnchorOneOfFourType)[keyof typeof NewThreadAnchorOneOfFourType];
// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const NewThreadAnchorOneOfThreeType = {
+export const NewThreadAnchorOneOfFourType = {
pdf_highlight: 'pdf_highlight',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfMarkedText.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfMarkedText.ts
new file mode 100644
index 0000000000..09d77b40a2
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfMarkedText.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The document text the mark covers, captured by the editor as the
+comment is written. Trimmed and bounded before it is stored, so an
+oversized or whitespace-only claim cannot reach the thread row.
+ */
+export type NewThreadAnchorOneOfMarkedText = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfFive.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfSix.ts
similarity index 79%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfFive.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfSix.ts
index 7c50fab875..b41ed63b37 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfFive.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfSix.ts
@@ -4,19 +4,19 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { NewThreadAnchorOneOfFiveType } from './newThreadAnchorOneOfFiveType';
+import type { NewThreadAnchorOneOfSixType } from './newThreadAnchorOneOfSixType';
/**
* Atomically create a placeable annotation with the root message.
*/
-export type NewThreadAnchorOneOfFive = {
+export type NewThreadAnchorOneOfSix = {
/** Client-generated annotation identifier used by optimistic rendering. */
anchor_id: string;
/** Height as a fraction of the page height. */
height_pct: number;
/** PDF page number. */
page: number;
- type: NewThreadAnchorOneOfFiveType;
+ type: NewThreadAnchorOneOfSixType;
/** Width as a fraction of the page width. */
width_pct: number;
/** Horizontal position as a fraction of the page width. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfFiveType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfSixType.ts
similarity index 57%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfFiveType.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfSixType.ts
index c0c4d612f1..3e028c2f29 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfFiveType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/newThreadAnchorOneOfSixType.ts
@@ -5,10 +5,10 @@
* OpenAPI spec version: 0.1.0
*/
-export type NewThreadAnchorOneOfFiveType =
- (typeof NewThreadAnchorOneOfFiveType)[keyof typeof NewThreadAnchorOneOfFiveType];
+export type NewThreadAnchorOneOfSixType =
+ (typeof NewThreadAnchorOneOfSixType)[keyof typeof NewThreadAnchorOneOfSixType];
// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const NewThreadAnchorOneOfFiveType = {
+export const NewThreadAnchorOneOfSixType = {
pdf_placeable: 'pdf_placeable',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchor.ts
index d24c39cdb6..b6b0d9f938 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchor.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchor.ts
@@ -5,13 +5,13 @@
* OpenAPI spec version: 0.1.0
*/
import type { ThreadAnchorOneOf } from './threadAnchorOneOf';
-import type { ThreadAnchorOneOfFive } from './threadAnchorOneOfFive';
-import type { ThreadAnchorOneOfThree } from './threadAnchorOneOfThree';
+import type { ThreadAnchorOneOfFour } from './threadAnchorOneOfFour';
+import type { ThreadAnchorOneOfSix } from './threadAnchorOneOfSix';
/**
* A thread's location within its document. Geometry remains annotation-owned.
*/
export type ThreadAnchor =
| ThreadAnchorOneOf
- | ThreadAnchorOneOfThree
- | ThreadAnchorOneOfFive;
+ | ThreadAnchorOneOfFour
+ | ThreadAnchorOneOfSix;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOf.ts
index 3a3fbba86c..cf5bb796c1 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOf.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOf.ts
@@ -4,6 +4,7 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { ThreadAnchorOneOfMarkedText } from './threadAnchorOneOfMarkedText';
import type { ThreadAnchorOneOfType } from './threadAnchorOneOfType';
/**
@@ -12,5 +13,10 @@ import type { ThreadAnchorOneOfType } from './threadAnchorOneOfType';
export type ThreadAnchorOneOf = {
/** Mark UUID serialized in the document. */
mark_id: string;
+ /** The marked text as it read when the discussion was created, already
+trimmed and bounded. Absent on threads created or imported before
+snapshots were captured: the text a mark covers cannot be recovered
+from the mark id alone. */
+ marked_text?: ThreadAnchorOneOfMarkedText;
type: ThreadAnchorOneOfType;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfThree.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfFour.ts
similarity index 60%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfThree.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfFour.ts
index 5f43013954..9a0eb2a9a4 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfThree.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfFour.ts
@@ -4,13 +4,13 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { ThreadAnchorOneOfThreeType } from './threadAnchorOneOfThreeType';
+import type { ThreadAnchorOneOfFourType } from './threadAnchorOneOfFourType';
/**
* An independently existing PDF highlight.
*/
-export type ThreadAnchorOneOfThree = {
+export type ThreadAnchorOneOfFour = {
/** Highlight annotation UUID. */
anchor_id: string;
- type: ThreadAnchorOneOfThreeType;
+ type: ThreadAnchorOneOfFourType;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfThreeType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfFourType.ts
similarity index 58%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfThreeType.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfFourType.ts
index 8098adf502..3910d4c35a 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfThreeType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfFourType.ts
@@ -5,10 +5,10 @@
* OpenAPI spec version: 0.1.0
*/
-export type ThreadAnchorOneOfThreeType =
- (typeof ThreadAnchorOneOfThreeType)[keyof typeof ThreadAnchorOneOfThreeType];
+export type ThreadAnchorOneOfFourType =
+ (typeof ThreadAnchorOneOfFourType)[keyof typeof ThreadAnchorOneOfFourType];
// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const ThreadAnchorOneOfThreeType = {
+export const ThreadAnchorOneOfFourType = {
pdf_highlight: 'pdf_highlight',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfMarkedText.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfMarkedText.ts
new file mode 100644
index 0000000000..e324c2a37e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfMarkedText.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The marked text as it read when the discussion was created, already
+trimmed and bounded. Absent on threads created or imported before
+snapshots were captured: the text a mark covers cannot be recovered
+from the mark id alone.
+ */
+export type ThreadAnchorOneOfMarkedText = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfFive.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfSix.ts
similarity index 61%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfFive.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfSix.ts
index 64e9d1f266..7a7b021585 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfFive.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfSix.ts
@@ -4,13 +4,13 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { ThreadAnchorOneOfFiveType } from './threadAnchorOneOfFiveType';
+import type { ThreadAnchorOneOfSixType } from './threadAnchorOneOfSixType';
/**
* A comment-only placeable PDF annotation.
*/
-export type ThreadAnchorOneOfFive = {
+export type ThreadAnchorOneOfSix = {
/** Placeable annotation UUID. */
anchor_id: string;
- type: ThreadAnchorOneOfFiveType;
+ type: ThreadAnchorOneOfSixType;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfFiveType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfSixType.ts
similarity index 59%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfFiveType.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfSixType.ts
index a744a7961f..503f622e60 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfFiveType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/threadAnchorOneOfSixType.ts
@@ -5,10 +5,10 @@
* OpenAPI spec version: 0.1.0
*/
-export type ThreadAnchorOneOfFiveType =
- (typeof ThreadAnchorOneOfFiveType)[keyof typeof ThreadAnchorOneOfFiveType];
+export type ThreadAnchorOneOfSixType =
+ (typeof ThreadAnchorOneOfSixType)[keyof typeof ThreadAnchorOneOfSixType];
// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const ThreadAnchorOneOfFiveType = {
+export const ThreadAnchorOneOfSixType = {
pdf_placeable: 'pdf_placeable',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index f8ad5b2f53..602470ba9f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -28610,6 +28610,12 @@ export const messageTimelineResponse = zod
.describe(
'Mark UUID serialized in the document.'
),
+ marked_text: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The marked text as it read when the discussion was created, already\ntrimmed and bounded. Absent on threads created or imported before\nsnapshots were captured: the text a mark covers cannot be recovered\nfrom the mark id alone.'
+ ),
type: zod.enum(['markdown']),
})
.describe(
@@ -28910,6 +28916,12 @@ export const entityMessageCreateBody = zod
zod
.object({
mark_id: zod.uuid().describe('Serialized mark identifier.'),
+ marked_text: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The document text the mark covers, captured by the editor as the\ncomment is written. Trimmed and bounded before it is stored, so an\noversized or whitespace-only claim cannot reach the thread row.'
+ ),
type: zod.enum(['markdown']),
})
.describe('Attach a discussion to a stable Markdown mark.'),
@@ -30137,6 +30149,12 @@ export const entityMessageGetThreadResponse = zod
mark_id: zod
.uuid()
.describe('Mark UUID serialized in the document.'),
+ marked_text: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The marked text as it read when the discussion was created, already\ntrimmed and bounded. Absent on threads created or imported before\nsnapshots were captured: the text a mark covers cannot be recovered\nfrom the mark id alone.'
+ ),
type: zod.enum(['markdown']),
})
.describe(
@@ -30219,6 +30237,12 @@ export const entityMessageDeleteThreadResponse = zod
mark_id: zod
.uuid()
.describe('Mark UUID serialized in the document.'),
+ marked_text: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The marked text as it read when the discussion was created, already\ntrimmed and bounded. Absent on threads created or imported before\nsnapshots were captured: the text a mark covers cannot be recovered\nfrom the mark id alone.'
+ ),
type: zod.enum(['markdown']),
})
.describe(
@@ -30310,6 +30334,12 @@ export const entityMessagePatchThreadResponse = zod
mark_id: zod
.uuid()
.describe('Mark UUID serialized in the document.'),
+ marked_text: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The marked text as it read when the discussion was created, already\ntrimmed and bounded. Absent on threads created or imported before\nsnapshots were captured: the text a mark covers cannot be recovered\nfrom the mark id alone.'
+ ),
type: zod.enum(['markdown']),
})
.describe(
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 996da35f01..05c0e1f925 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -25580,6 +25580,10 @@
"format": "uuid",
"description": "Serialized mark identifier."
},
+ "marked_text": {
+ "type": ["string", "null"],
+ "description": "The document text the mark covers, captured by the editor as the\ncomment is written. Trimmed and bounded before it is stored, so an\noversized or whitespace-only claim cannot reach the thread row."
+ },
"type": {
"type": "string",
"enum": ["markdown"]
@@ -30195,6 +30199,10 @@
"format": "uuid",
"description": "Mark UUID serialized in the document."
},
+ "marked_text": {
+ "type": ["string", "null"],
+ "description": "The marked text as it read when the discussion was created, already\ntrimmed and bounded. Absent on threads created or imported before\nsnapshots were captured: the text a mark covers cannot be recovered\nfrom the mark id alone."
+ },
"type": {
"type": "string",
"enum": ["markdown"]
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index b7b2ce70b5..f954f3718a 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -321,6 +321,27 @@ pub struct PriorMessage {
pub content: String,
}
+/// Where in a document a comment thread sits. The mark id alone names a
+/// location the agent has no way to resolve: the document body it can read
+/// carries no marks, so the text the comment covers travels with the id.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CommentAnchor {
+ /// Lexical mark the thread is attached to.
+ pub mark_id: String,
+ /// The marked text as it read when the comment was posted. Absent on
+ /// threads anchored before snapshots were captured.
+ pub marked_text: Option<String>,
+}
+
+/// What the conversation an agent was summoned from contributes to its prompt.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct ConversationContext {
+ /// The document location, when the prompt came from an anchored comment.
+ pub anchor: Option<CommentAnchor>,
+ /// Untrusted prior messages, oldest first.
+ pub messages: Vec<PriorMessage>,
+}
+
/// Do something in a session that already exists.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DeliverAction {
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index 78f00f056e..ff6b02efeb 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -15,8 +15,8 @@ use macro_user_id::user_id::MacroUserIdStr;
use super::error::{HarnessError, Result};
use super::model::{
- AgentKind, AgentRuntimeConfig, AnnouncedMessage, CommandOutcome, DeclinedMention,
- HarnessCommand, PriorMessage, ProvisionedEgress, ReachableRepository, SandboxEgress,
+ AgentKind, AgentRuntimeConfig, AnnouncedMessage, CommandOutcome, ConversationContext,
+ DeclinedMention, HarnessCommand, ProvisionedEgress, ReachableRepository, SandboxEgress,
SessionAnnouncement, SessionBlocker, SpawnContainer,
};
use super::notifications::PlannedNotification;
@@ -155,23 +155,24 @@ pub trait MessagePromptContext: Send + Sync + 'static {
origin: &super::model::AnnounceOrigin,
) -> impl Future<Output = Result<()>> + Send;
- /// Read up to ten preceding live messages with a fresh access check.
- fn preceding_messages(
+ /// Read up to ten preceding live messages, and the comment anchor the
+ /// prompt sits on, with a fresh access check.
+ fn conversation_context(
&self,
actor: &MacroUserIdStr<'static>,
origin: &super::model::AnnounceOrigin,
- ) -> impl Future<Output = Result<Vec<PriorMessage>>> + Send;
+ ) -> impl Future<Output = Result<ConversationContext>> + Send;
}
-/// Composes an agent prompt from raw markdown and optional channel history.
+/// Composes an agent prompt from raw markdown and optional conversation context.
pub trait AgentPromptComposer: Send + Sync + 'static {
/// Return the markdown that should be delivered to the agent runtime.
- /// `None` sanitizes a prompt without adding a channel-context node.
+ /// `None` sanitizes a prompt without adding a conversation-context node.
fn compose(
&self,
prompt_markdown: &str,
parent: Option<&messages::domain::models::MessageParent>,
- messages: Option<&[PriorMessage]>,
+ context: Option<&ConversationContext>,
) -> impl Future<Output = Result<String>> + Send;
}
diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rs
index edaa8b78e1..d27a374cce 100644
--- a/crates/agent_harness/src/domain/service/deliver.rs
+++ b/crates/agent_harness/src/domain/service/deliver.rs
@@ -157,7 +157,7 @@ where
return Ok(());
};
let raw_prompt = prompt.prompt.clone();
- let prior_messages = if let Some(origin) = announce {
+ let context = if let Some(origin) = announce {
Some(self.load_prompt_context(origin, actor).await?)
} else {
None
@@ -167,21 +167,21 @@ where
.compose(
&raw_prompt,
announce.map(|origin| &origin.parent),
- prior_messages.as_deref(),
+ context.as_ref(),
)
.await?;
prompt.set_name_source(raw_prompt);
Ok(())
}
- /// Recheck the actor's access to the origin, then read the history before
- /// it. Authorization is not optional: a prompt that names an origin was
- /// posted by a user, and one who may no longer write there sends nothing.
+ /// Recheck the actor's access to the origin, then read the conversation
+ /// around it. Authorization is not optional: a prompt that names an origin
+ /// was posted by a user, and one who may no longer write there sends nothing.
pub(super) async fn load_prompt_context(
&self,
origin: &AnnounceOrigin,
actor: Option<&MacroUserIdStr<'static>>,
- ) -> Result<Vec<crate::domain::model::PriorMessage>> {
+ ) -> Result<crate::domain::model::ConversationContext> {
let actor = actor.ok_or_else(|| {
HarnessError::PromptContext(rootcause::report!(
"message prompts require an acting user"
@@ -190,7 +190,7 @@ where
self.prompt_context.authorize_origin(actor, origin).await?;
Ok(self
.prompt_context
- .preceding_messages(actor, origin)
+ .conversation_context(actor, origin)
.await
.inspect_err(|error| {
// Trigger events are admitted at-most-once. Context is useful,
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index c86ef9433b..4d84dc1aa7 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -41,9 +41,10 @@ use super::AgentHarnessService;
use super::into_session_error;
use crate::domain::error::HarnessError;
use crate::domain::model::{
- AgentKind, AgentRuntimeConfig, AnnounceOrigin, CommandOutcome, DeclinedMention, DeliverAction,
- HarnessCommand, HarnessDefaults, MentionOrigin, OpenSession, PriorMessage, SessionBlocker,
- SessionDefaults, SessionRepository, SpawnContainer,
+ AgentKind, AgentRuntimeConfig, AnnounceOrigin, CommandOutcome, CommentAnchor,
+ ConversationContext, DeclinedMention, DeliverAction, HarnessCommand, HarnessDefaults,
+ MentionOrigin, OpenSession, PriorMessage, SessionBlocker, SessionDefaults, SessionRepository,
+ SpawnContainer,
};
use crate::domain::ports::{
AgentPromptComposer, ContainerManager as _, MessagePromptContext, NoPeers,
@@ -120,7 +121,7 @@ fn forward_message(content: &str) -> DeliverAction {
#[derive(Clone, Default)]
struct PromptContextMock {
- messages: Arc<Mutex<Vec<PriorMessage>>>,
+ context: Arc<Mutex<ConversationContext>>,
failure: Arc<Mutex<Option<String>>>,
unauthorized: Arc<Mutex<Option<String>>>,
authorized: Arc<Mutex<Vec<(MacroUserIdStr<'static>, AnnounceOrigin)>>>,
@@ -128,8 +129,15 @@ struct PromptContextMock {
impl PromptContextMock {
fn with_messages(messages: Vec<PriorMessage>) -> Self {
+ Self::with_context(ConversationContext {
+ anchor: None,
+ messages,
+ })
+ }
+
+ fn with_context(context: ConversationContext) -> Self {
Self {
- messages: Arc::new(Mutex::new(messages)),
+ context: Arc::new(Mutex::new(context)),
..Self::default()
}
}
@@ -169,19 +177,19 @@ impl MessagePromptContext for PromptContextMock {
Ok(())
}
- async fn preceding_messages(
+ async fn conversation_context(
&self,
_actor: &MacroUserIdStr<'static>,
_origin: &AnnounceOrigin,
- ) -> crate::domain::error::Result<Vec<PriorMessage>> {
+ ) -> crate::domain::error::Result<ConversationContext> {
if let Some(message) = self.failure.lock().unwrap().clone() {
return Err(HarnessError::PromptContext(rootcause::report!("{message}")));
}
- Ok(self.messages.lock().unwrap().clone())
+ Ok(self.context.lock().unwrap().clone())
}
}
-type PromptCompositionCall = (String, Option<Vec<PriorMessage>>);
+type PromptCompositionCall = (String, Option<ConversationContext>);
#[derive(Clone, Default)]
struct PromptComposerMock {
@@ -207,18 +215,18 @@ impl AgentPromptComposer for PromptComposerMock {
&self,
prompt_markdown: &str,
_parent: Option<&MessageParent>,
- messages: Option<&[PriorMessage]>,
+ context: Option<&ConversationContext>,
) -> crate::domain::error::Result<String> {
- self.calls.lock().unwrap().push((
- prompt_markdown.to_owned(),
- messages.map(|messages| messages.to_vec()),
- ));
+ self.calls
+ .lock()
+ .unwrap()
+ .push((prompt_markdown.to_owned(), context.cloned()));
if let Some(message) = self.failure.lock().unwrap().clone() {
return Err(HarnessError::PromptComposition(rootcause::report!(
"{message}"
)));
}
- Ok(if messages.is_some() {
+ Ok(if context.is_some() {
context_prompt(prompt_markdown)
} else {
prompt_markdown.to_owned()
@@ -797,7 +805,10 @@ async fn context_failure_still_calls_composer_with_empty_messages_and_delivers()
assert_eq!(announcer.announced().len(), 1);
assert_eq!(
composer.calls(),
- [("@claude fix the failing test".to_owned(), Some(Vec::new()))]
+ [(
+ "@claude fix the failing test".to_owned(),
+ Some(ConversationContext::default())
+ )]
);
assert_eq!(
prompts(&container.agent()),
@@ -871,13 +882,61 @@ async fn open_sends_context_but_not_agent_instructions_to_the_agent_prompt() {
result.unwrap();
assert_eq!(announcer.announced()[0].prompted_content, raw);
- assert_eq!(composer.calls(), [(raw.clone(), Some(context))]);
+ assert_eq!(
+ composer.calls(),
+ [(
+ raw.clone(),
+ Some(ConversationContext {
+ anchor: None,
+ messages: context,
+ })
+ )]
+ );
assert_eq!(
prompts(&container.agent()),
[vec![ContentBlock::from(context_prompt(&raw))]]
);
}
+/// A mention in a document comment: the agent is told which mark the comment
+/// sits on and what that mark covered, so it can find the words the comment is
+/// about instead of guessing from the comment body.
+#[tokio::test]
+async fn open_sends_the_comment_anchor_the_prompt_was_posted_on() {
+ let context = ConversationContext {
+ anchor: Some(CommentAnchor {
+ mark_id: "0199f3d4-0000-7000-8000-00000000000a".to_owned(),
+ marked_text: Some("the marked phrase".to_owned()),
+ }),
+ messages: vec![],
+ };
+ let composer = PromptComposerMock::default();
+ let (service, _repo, containers, _announcer, _runtimes) = harness_with_edges(
+ PromptContextMock::with_context(context.clone()),
+ composer.clone(),
+ );
+ let command = open_command();
+ let raw = command.origin.content.clone();
+ let id = AgentSessionId::new();
+
+ let open = service.execute(id, HarnessCommand::Open(command));
+ let drive = async {
+ loop {
+ if containers.spawned() == 1 {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ let container = containers.container(id).unwrap();
+ complete_handshake(&container).await;
+ container
+ };
+ let (result, _container) = tokio::join!(open, drive);
+ result.unwrap();
+
+ assert_eq!(composer.calls(), [(raw, Some(context))]);
+}
+
/// A provider mention from someone missing account setup: the bot answers in
/// the thread with what to connect, and nothing is created for a session
/// that could never spawn - no row, no egress token, no chip.
@@ -1050,7 +1109,10 @@ async fn forward_to_a_live_session_reuses_the_transport() {
assert_eq!(containers.resumed(), 0, "no resume for a live session");
assert_eq!(
composer.calls().last(),
- Some(&("and add a regression test".to_owned(), Some(Vec::new())))
+ Some(&(
+ "and add a regression test".to_owned(),
+ Some(ConversationContext::default())
+ ))
);
assert_eq!(
prompts(&container.agent())[1],
@@ -1102,7 +1164,10 @@ async fn composer_failure_stops_follow_up_announcement_and_delivery() {
assert!(matches!(result, Err(HarnessError::PromptComposition(_))));
assert_eq!(
composer.calls().last(),
- Some(&("do not deliver this".to_owned(), Some(Vec::new())))
+ Some(&(
+ "do not deliver this".to_owned(),
+ Some(ConversationContext::default())
+ ))
);
assert_eq!(prompts(&container.agent()).len(), prompts_before);
assert_eq!(announcer.announced().len(), announcements_before);
diff --git a/crates/agent_harness/src/outbound/agent_prompt_composer.rs b/crates/agent_harness/src/outbound/agent_prompt_composer.rs
index 218def7132..6961474c39 100644
--- a/crates/agent_harness/src/outbound/agent_prompt_composer.rs
+++ b/crates/agent_harness/src/outbound/agent_prompt_composer.rs
@@ -1,10 +1,10 @@
//! Compose channel context for every harness.
use lexical_client::LexicalClient;
-use lexical_client::parse_markdown::AgentContextMessage;
+use lexical_client::parse_markdown::{AgentContextAnchor, AgentContextMessage};
use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::PriorMessage;
+use crate::domain::model::ConversationContext;
use crate::domain::ports::AgentPromptComposer;
/// Lexical-service-backed agent prompt composer.
@@ -24,10 +24,11 @@ impl AgentPromptComposer for LexicalAgentPromptComposer {
&self,
prompt_markdown: &str,
parent: Option<&messages::domain::models::MessageParent>,
- messages: Option<&[PriorMessage]>,
+ context: Option<&ConversationContext>,
) -> Result<String> {
- let messages = messages.map(|messages| {
- messages
+ let messages = context.map(|context| {
+ context
+ .messages
.iter()
.map(|message| AgentContextMessage {
sender: &message.sender,
@@ -35,9 +36,20 @@ impl AgentPromptComposer for LexicalAgentPromptComposer {
})
.collect::<Vec<_>>()
});
+ let anchor = context
+ .and_then(|context| context.anchor.as_ref())
+ .map(|anchor| AgentContextAnchor {
+ mark_id: &anchor.mark_id,
+ marked_text: anchor.marked_text.as_deref(),
+ });
self.lexical
- .compose_agent_context(prompt_markdown, parent, messages.as_deref())
+ .compose_agent_context(
+ prompt_markdown,
+ parent,
+ anchor.as_ref(),
+ messages.as_deref(),
+ )
.await
.map_err(|error| HarnessError::PromptComposition(rootcause::report!(error).into()))
}
diff --git a/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs b/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs
index 3b68c0776d..a6e36c8278 100644
--- a/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs
+++ b/crates/agent_harness/src/outbound/agent_prompt_composer/test.rs
@@ -1,5 +1,7 @@
use super::*;
+use crate::domain::model::{CommentAnchor, PriorMessage};
use axum::{Json, Router, routing::post};
+use std::sync::{Arc, Mutex};
#[tokio::test]
async fn composition_preserves_lexical_output_without_tool_instructions() {
@@ -15,13 +17,77 @@ async fn composition_preserves_lexical_output_without_tool_instructions() {
format!("http://{address}"),
));
- for messages in [None, Some([].as_slice())] {
- let prompt = composer
- .compose("Raw prompt", None, messages)
- .await
- .unwrap();
+ for context in [None, Some(&ConversationContext::default())] {
+ let prompt = composer.compose("Raw prompt", None, context).await.unwrap();
assert_eq!(prompt, "Sanitized prompt and context");
assert!(!prompt.contains("set_pull_request"));
}
server.abort();
}
+
+/// The comment anchor crosses a service boundary, so the shape the lexical
+/// service validates is asserted here rather than only in its own types.
+#[tokio::test]
+async fn the_comment_anchor_reaches_the_lexical_service_beside_the_history() {
+ let received: Arc<Mutex<Option<serde_json::Value>>> = Arc::default();
+ let seen = received.clone();
+ let app = Router::new().route(
+ "/agent-context",
+ post(move |Json(body): Json<serde_json::Value>| {
+ let seen = seen.clone();
+ async move {
+ *seen.lock().unwrap() = Some(body);
+ Json(serde_json::json!({ "markdown": "composed" }))
+ }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let composer = LexicalAgentPromptComposer::new(LexicalClient::new(
+ "test".into(),
+ format!("http://{address}"),
+ ));
+
+ composer
+ .compose(
+ "Raw prompt",
+ None,
+ Some(&ConversationContext {
+ anchor: Some(CommentAnchor {
+ mark_id: "mark-1".to_owned(),
+ marked_text: Some("the marked phrase".to_owned()),
+ }),
+ messages: vec![PriorMessage {
+ sender: "alice".to_owned(),
+ content: "earlier".to_owned(),
+ }],
+ }),
+ )
+ .await
+ .unwrap();
+ let body = received.lock().unwrap().clone().unwrap();
+ assert_eq!(body["anchor"]["markId"], "mark-1");
+ assert_eq!(body["anchor"]["markedText"], "the marked phrase");
+ assert_eq!(body["messages"][0]["sender"], "alice");
+
+ // A thread anchored before snapshots existed still names its mark.
+ composer
+ .compose(
+ "Raw prompt",
+ None,
+ Some(&ConversationContext {
+ anchor: Some(CommentAnchor {
+ mark_id: "mark-2".to_owned(),
+ marked_text: None,
+ }),
+ messages: vec![],
+ }),
+ )
+ .await
+ .unwrap();
+ let body = received.lock().unwrap().clone().unwrap();
+ assert_eq!(body["anchor"]["markId"], "mark-2");
+ assert!(body["anchor"].get("markedText").is_none());
+ server.abort();
+}
diff --git a/crates/agent_harness/src/outbound/channel_prompt_context.rs b/crates/agent_harness/src/outbound/channel_prompt_context.rs
index 9c699ed19c..84cd55cad7 100644
--- a/crates/agent_harness/src/outbound/channel_prompt_context.rs
+++ b/crates/agent_harness/src/outbound/channel_prompt_context.rs
@@ -5,7 +5,7 @@ mod test;
use crate::domain::{
error::{HarnessError, Result},
- model::{AnnounceOrigin, PriorMessage},
+ model::{AnnounceOrigin, CommentAnchor, ConversationContext, PriorMessage},
ports::MessagePromptContext,
};
use entity_access::domain::{
@@ -13,7 +13,11 @@ use entity_access::domain::{
ports::EntityAccessService,
};
use macro_user_id::user_id::MacroUserIdStr;
-use messages::domain::{api::MessageReader, models::MessageParent, service::MessageWrite};
+use messages::domain::{
+ api::MessageReader,
+ models::{MessageParent, ThreadAnchor},
+ service::{MessageView, MessageWrite},
+};
use std::sync::Arc;
trait ContextAuthorizer: Send + Sync + 'static {
@@ -85,19 +89,20 @@ impl<Access: ContextAuthorizer> MessagePromptContext for MessagePromptContextAda
Ok(())
}
- async fn preceding_messages(
+ async fn conversation_context(
&self,
actor: &MacroUserIdStr<'static>,
origin: &AnnounceOrigin,
- ) -> Result<Vec<PriorMessage>> {
+ ) -> Result<ConversationContext> {
let access = self
.access
.capability(actor, &origin.parent)
.await?
.try_into_requirement()
.map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))?;
- self.messages
- .preceding(access, origin.message_id, 10)
+ let messages = self
+ .messages
+ .preceding(access.clone(), origin.message_id, 10)
.await
.map(|messages| {
messages
@@ -108,6 +113,39 @@ impl<Access: ContextAuthorizer> MessagePromptContext for MessagePromptContextAda
})
.collect()
})
- .map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))
+ .map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))?;
+ Ok(ConversationContext {
+ anchor: anchor(self.messages.as_ref(), access, origin).await?,
+ messages,
+ })
}
}
+
+/// Where a document discussion sits, read from the thread the prompt was posted
+/// in. Only documents anchor discussions, so a channel prompt never pays for
+/// the lookup.
+async fn anchor(
+ messages: &dyn MessageReader,
+ access: EntityAccessReceipt<MessageView>,
+ origin: &AnnounceOrigin,
+) -> Result<Option<CommentAnchor>> {
+ if !matches!(origin.parent, MessageParent::Document(_)) {
+ return Ok(None);
+ }
+ let thread = messages
+ .get_thread(access, origin.thread_id)
+ .await
+ .map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))?;
+ Ok(match thread.state.anchor {
+ // PDF anchors name an annotation the agent cannot read either, but
+ // their text is owned by the annotation rather than the thread.
+ Some(ThreadAnchor::Markdown {
+ mark_id,
+ marked_text,
+ }) => Some(CommentAnchor {
+ mark_id: mark_id.to_string(),
+ marked_text,
+ }),
+ _ => None,
+ })
+}
diff --git a/crates/agent_harness/src/outbound/channel_prompt_context/test.rs b/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
index 42abcf6ac8..88ba2fb5ea 100644
--- a/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
+++ b/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
@@ -2,7 +2,10 @@ use super::*;
use chrono::Utc;
use entity_access::domain::models::{AccessLevel, Entity, EntityPermission};
use macro_uuid::Uuid;
-use messages::domain::{api::MockMessageReader, models::Message};
+use messages::domain::{
+ api::MockMessageReader,
+ models::{Message, MessageThread, ThreadState},
+};
struct Authorizer {
allowed: bool,
@@ -91,7 +94,7 @@ async fn revoked_access_never_reads_message_content() {
assert!(adapter.authorize_origin(&actor(), &origin()).await.is_err());
assert!(
adapter
- .preceding_messages(&actor(), &origin())
+ .conversation_context(&actor(), &origin())
.await
.is_err()
);
@@ -120,8 +123,23 @@ async fn a_claimed_root_or_parent_cannot_link_an_unrelated_session() {
}
}
-#[tokio::test]
-async fn history_uses_the_shared_authorized_message_reader() {
+fn thread(anchor: Option<ThreadAnchor>) -> MessageThread {
+ MessageThread {
+ state: ThreadState {
+ root_id: origin().thread_id,
+ user_id: actor().as_ref().to_owned(),
+ resolved: false,
+ anchor,
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ deleted_at: None,
+ },
+ root: message(),
+ replies: vec![],
+ }
+}
+
+fn reader(anchor: Option<ThreadAnchor>) -> MockMessageReader {
let mut source = MockMessageReader::new();
source
.expect_preceding()
@@ -130,13 +148,94 @@ async fn history_uses_the_shared_authorized_message_reader() {
access.entity().entity_id == "doc" && *id == origin().message_id && *limit == 10
})
.return_once(|_, _, _| Ok(vec![message()]));
+ source
+ .expect_get_thread()
+ .once()
+ .withf(|access, root| access.entity().entity_id == "doc" && *root == origin().thread_id)
+ .return_once(move |_, _| Ok(thread(anchor)));
+ source
+}
+
+#[tokio::test]
+async fn history_uses_the_shared_authorized_message_reader() {
+ let adapter = MessagePromptContextAdapter::new(
+ Arc::new(reader(None)),
+ Arc::new(Authorizer { allowed: true }),
+ );
+ let context = adapter
+ .conversation_context(&actor(), &origin())
+ .await
+ .unwrap();
+ assert_eq!(context.messages.len(), 1);
+ assert_eq!(context.messages[0].sender, actor().as_ref());
+ assert_eq!(context.messages[0].content, message().content);
+ // An unanchored discussion names no place in the document.
+ assert_eq!(context.anchor, None);
+}
+
+#[tokio::test]
+async fn a_marked_discussion_names_its_mark_and_the_text_it_covers() {
+ let mark_id = Uuid::from_u128(7);
+ let adapter = MessagePromptContextAdapter::new(
+ Arc::new(reader(Some(ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: Some("the marked phrase".to_owned()),
+ }))),
+ Arc::new(Authorizer { allowed: true }),
+ );
+ let context = adapter
+ .conversation_context(&actor(), &origin())
+ .await
+ .unwrap();
+ assert_eq!(
+ context.anchor,
+ Some(CommentAnchor {
+ mark_id: mark_id.to_string(),
+ marked_text: Some("the marked phrase".to_owned()),
+ })
+ );
+}
+
+#[tokio::test]
+async fn a_discussion_anchored_before_snapshots_still_names_its_mark() {
+ let mark_id = Uuid::from_u128(8);
+ let adapter = MessagePromptContextAdapter::new(
+ Arc::new(reader(Some(ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: None,
+ }))),
+ Arc::new(Authorizer { allowed: true }),
+ );
+ let context = adapter
+ .conversation_context(&actor(), &origin())
+ .await
+ .unwrap();
+ assert_eq!(
+ context.anchor,
+ Some(CommentAnchor {
+ mark_id: mark_id.to_string(),
+ marked_text: None,
+ })
+ );
+}
+
+#[tokio::test]
+async fn a_channel_prompt_never_reads_a_thread_for_an_anchor() {
+ let mut source = MockMessageReader::new();
+ source
+ .expect_preceding()
+ .once()
+ .return_once(|_, _, _| Ok(vec![]));
+ source.expect_get_thread().never();
let adapter =
MessagePromptContextAdapter::new(Arc::new(source), Arc::new(Authorizer { allowed: true }));
- let history = adapter
- .preceding_messages(&actor(), &origin())
+ let channel = AnnounceOrigin {
+ parent: MessageParent::Channel(Uuid::from_u128(3)),
+ ..origin()
+ };
+ let context = adapter
+ .conversation_context(&actor(), &channel)
.await
.unwrap();
- assert_eq!(history.len(), 1);
- assert_eq!(history[0].sender, actor().as_ref());
- assert_eq!(history[0].content, message().content);
+ assert_eq!(context.anchor, None);
}
diff --git a/crates/channel_bots/src/domain/service.rs b/crates/channel_bots/src/domain/service.rs
index 94648636f6..83ebe0dac3 100644
--- a/crates/channel_bots/src/domain/service.rs
+++ b/crates/channel_bots/src/domain/service.rs
@@ -9,7 +9,7 @@ use messages::domain::{
api::MessageServiceApi,
models::{
MessageAttribution, MessageParent, PatchMessageNotificationPolicy, PostMessage,
- PostMessageNotificationPolicy,
+ PostMessageNotificationPolicy, ThreadAnchor,
},
ports::{MessageError, MessagePatch},
service::MessageView,
@@ -46,6 +46,26 @@ triggering message.";
const CHANNEL_CONTEXT_INSTRUCTION: &str = "Recent messages in the channel around the mention \
(oldest to newest).";
+const ANCHOR_INSTRUCTION: &str = "The document text this discussion is attached to. It is what \
+the mark covered when the discussion was started, so the document may have changed since — read \
+the document itself if you need its current wording.";
+
+/// The thread a mention sits in, read once for everything the prompt needs.
+struct ThreadContext {
+ lines: Vec<PromptLine>,
+ ids: HashSet<Uuid>,
+ /// Present only for a document discussion the author anchored to text,
+ /// and only when the anchor carries a snapshot of what it marked.
+ marked: Option<MarkedText>,
+}
+
+/// The text a markdown discussion marks, with the mark that identifies it —
+/// the same id the comment reads carry, so the two can be matched up.
+struct MarkedText {
+ mark_id: Uuid,
+ text: String,
+}
+
/// A single message rendered into the prompt.
struct PromptLine {
sender: String,
@@ -69,6 +89,20 @@ fn trigger_line(event: &BotEvent) -> PromptLine {
}
}
+/// Write the block naming what a document discussion is anchored to, so a
+/// mention that says "this" can be resolved to words rather than to a mark id
+/// the agent has no way to look up.
+fn append_anchor(prompt: &mut String, marked: Option<&MarkedText>) {
+ let Some(marked) = marked else {
+ return;
+ };
+ let _ = write!(
+ prompt,
+ "\n<anchor mark=\"{}\">\n{ANCHOR_INSTRUCTION}\n\n{}\n</anchor>\n",
+ marked.mark_id, marked.text
+ );
+}
+
/// Write a tagged context block: an instruction line followed by one message
/// per line, labeled by sender. Skipped entirely when there are no messages.
fn append_block(
@@ -170,8 +204,15 @@ where
event: &BotEvent,
access: EntityAccessReceipt<MessageView>,
root_id: Uuid,
- ) -> anyhow::Result<(Vec<PromptLine>, HashSet<Uuid>)> {
+ ) -> anyhow::Result<ThreadContext> {
let thread = self.messages.get_thread(access, root_id).await?;
+ let marked = match thread.state.anchor {
+ Some(ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: Some(text),
+ }) => Some(MarkedText { mark_id, text }),
+ _ => None,
+ };
let mut thread_ids = HashSet::new();
let mut lines = Vec::new();
for message in std::iter::once(thread.root).chain(thread.replies) {
@@ -191,7 +232,11 @@ where
if !lines.iter().any(|line| line.is_trigger) {
lines.push(trigger_line(event));
}
- Ok((lines, thread_ids))
+ Ok(ThreadContext {
+ lines,
+ ids: thread_ids,
+ marked,
+ })
}
/// Build the prompt for a mention.
@@ -268,7 +313,12 @@ where
),
};
let _ = writeln!(prompt, "{intro}");
- let (thread, thread_ids) = self.thread_lines(event, view, root_id).await?;
+ let ThreadContext {
+ lines: thread,
+ ids: thread_ids,
+ marked,
+ } = self.thread_lines(event, view, root_id).await?;
+ append_anchor(&mut prompt, marked.as_ref());
append_block(&mut prompt, "thread", thread_instruction, marker, &thread);
let background: Vec<PromptLine> = nearby
diff --git a/crates/channel_bots/src/domain/service/tests.rs b/crates/channel_bots/src/domain/service/tests.rs
index efa55c5d4a..6256d9c0f8 100644
--- a/crates/channel_bots/src/domain/service/tests.rs
+++ b/crates/channel_bots/src/domain/service/tests.rs
@@ -130,6 +130,41 @@ async fn root_comment_is_valid_agent_context_before_any_replies_exist() {
assert!(prompt.contains("<thread>"));
}
+#[tokio::test]
+async fn an_anchored_discussion_names_the_text_it_marks() {
+ let trigger = message(1, None, "@macro what is this anchored to?");
+ let mut api = MockMessageServiceApi::new();
+ configure_reads(
+ &mut api,
+ &trigger,
+ marked_thread(
+ trigger.clone(),
+ Some("backfills the ledger from the archive"),
+ ),
+ );
+ let prompt = handler(api, Arc::new(Access::default()), responder("reply"))
+ .build_prompt(&invocation(&trigger))
+ .await
+ .unwrap();
+ assert!(prompt.contains("<anchor mark=\"00000000-0000-0000-0000-0000000000aa\">"));
+ assert!(prompt.contains("backfills the ledger from the archive"));
+ // The snapshot is dated, and the prompt says so rather than implying it is current.
+ assert!(prompt.contains("the document may have changed since"));
+}
+
+#[tokio::test]
+async fn a_discussion_with_no_marked_text_claims_no_anchor() {
+ let trigger = message(1, None, "@macro help with this document");
+ let mut api = MockMessageServiceApi::new();
+ // Both an unanchored discussion and one anchored before snapshots existed.
+ configure_reads(&mut api, &trigger, marked_thread(trigger.clone(), None));
+ let prompt = handler(api, Arc::new(Access::default()), responder("reply"))
+ .build_prompt(&invocation(&trigger))
+ .await
+ .unwrap();
+ assert!(!prompt.contains("<anchor"));
+}
+
#[tokio::test]
async fn revoked_document_access_prevents_context_reads_and_agent_work() {
let trigger = message(1, None, "@macro help");
diff --git a/crates/channel_bots/src/domain/test.rs b/crates/channel_bots/src/domain/test.rs
index b1f2b8dccf..af04b8c87c 100644
--- a/crates/channel_bots/src/domain/test.rs
+++ b/crates/channel_bots/src/domain/test.rs
@@ -8,7 +8,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use messages::domain::{
api::MockMessageServiceApi,
events::MessagePostedMetadata,
- models::{Message, MessageParent, MessageThread, ThreadState},
+ models::{Message, MessageParent, MessageThread, ThreadAnchor, ThreadState},
service::MessageWrite,
};
use std::sync::{
@@ -60,6 +60,15 @@ pub(super) fn thread(root: Message, replies: Vec<Message>) -> MessageThread {
replies,
}
}
+/// A discussion anchored to marked document text, as the editor records it.
+pub(super) fn marked_thread(root: Message, marked_text: Option<&str>) -> MessageThread {
+ let mut thread = thread(root, vec![]);
+ thread.state.anchor = Some(ThreadAnchor::Markdown {
+ mark_id: Uuid::from_u128(0xaa),
+ marked_text: marked_text.map(ToOwned::to_owned),
+ });
+ thread
+}
pub(super) fn configure_reads(
api: &mut MockMessageServiceApi,
trigger: &Message,
diff --git a/crates/lexical_client/src/parse_markdown.rs b/crates/lexical_client/src/parse_markdown.rs
index 370aeca975..2494d15b2a 100644
--- a/crates/lexical_client/src/parse_markdown.rs
+++ b/crates/lexical_client/src/parse_markdown.rs
@@ -219,6 +219,17 @@ pub struct AgentContextMessage<'a> {
pub content: &'a str,
}
+/// The document location of the comment thread an agent prompt was posted in.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentContextAnchor<'a> {
+ /// Lexical mark the comment is attached to.
+ pub mark_id: &'a str,
+ /// The marked text when the comment was posted, when it was captured.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub marked_text: Option<&'a str>,
+}
+
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct AgentContextRequest<'a> {
@@ -226,6 +237,8 @@ struct AgentContextRequest<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
parent: Option<&'a MessageParent>,
#[serde(skip_serializing_if = "Option::is_none")]
+ anchor: Option<&'a AgentContextAnchor<'a>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
messages: Option<&'a [AgentContextMessage<'a>]>,
}
@@ -482,14 +495,15 @@ impl LexicalClient {
Ok(data.markdown)
}
- /// Sanitizes an agent prompt and optionally composes it with prior-message
- /// context via the lexical service, so internal nodes and escaping are
- /// handled by Lexical rather than assembled manually by the caller.
- #[tracing::instrument(skip(self, prompt_markdown, messages), err)]
+ /// Sanitizes an agent prompt and optionally composes it with the comment
+ /// anchor and prior-message context via the lexical service, so internal
+ /// nodes and escaping are handled by Lexical rather than by the caller.
+ #[tracing::instrument(skip(self, prompt_markdown, anchor, messages), err)]
pub async fn compose_agent_context(
&self,
prompt_markdown: &str,
parent: Option<&MessageParent>,
+ anchor: Option<&AgentContextAnchor<'_>>,
messages: Option<&[AgentContextMessage<'_>]>,
) -> Result<String> {
let url = format!("{}/agent-context", self.url);
@@ -499,6 +513,7 @@ impl LexicalClient {
.json(&AgentContextRequest {
prompt_markdown,
parent,
+ anchor,
messages,
})
.send()
diff --git a/crates/messages/src/domain/models.rs b/crates/messages/src/domain/models.rs
index ca9b15737a..3838c8d80c 100644
--- a/crates/messages/src/domain/models.rs
+++ b/crates/messages/src/domain/models.rs
@@ -98,6 +98,12 @@ pub enum ThreadAnchor {
Markdown {
/// Mark UUID serialized in the document.
mark_id: Uuid,
+ /// The marked text as it read when the discussion was created, already
+ /// trimmed and bounded. Absent on threads created or imported before
+ /// snapshots were captured: the text a mark covers cannot be recovered
+ /// from the mark id alone.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ marked_text: Option<String>,
},
/// An independently existing PDF highlight.
PdfHighlight {
@@ -121,6 +127,11 @@ pub enum NewThreadAnchor {
Markdown {
/// Serialized mark identifier.
mark_id: Uuid,
+ /// The document text the mark covers, captured by the editor as the
+ /// comment is written. Trimmed and bounded before it is stored, so an
+ /// oversized or whitespace-only claim cannot reach the thread row.
+ #[serde(default)]
+ marked_text: Option<String>,
},
/// Attach an independently existing highlight on this document.
PdfHighlight {
@@ -144,13 +155,44 @@ pub enum NewThreadAnchor {
},
}
+/// Longest marked-text snapshot kept with a discussion. A comment marks a
+/// phrase or a paragraph; a longer range is elided so that one highlight
+/// cannot crowd out the rest of an agent prompt.
+pub const MARKED_TEXT_LIMIT: usize = 1000;
+
+/// The storable form of text a mark covers: trimmed, elided at
+/// [`MARKED_TEXT_LIMIT`] characters, and absent when it carries nothing. The
+/// only way a snapshot enters a thread row, so no client claim is stored whole.
+pub fn marked_text_snapshot(text: &str) -> Option<String> {
+ let text = text.trim();
+ if text.is_empty() {
+ return None;
+ }
+ let mut snapshot: String = text.chars().take(MARKED_TEXT_LIMIT).collect();
+ // The ellipsis is the whole truncation signal, on the wire and in the row.
+ if text.chars().nth(MARKED_TEXT_LIMIT).is_some() {
+ snapshot.push('\u{2026}');
+ }
+ Some(snapshot)
+}
+
impl NewThreadAnchor {
/// Thread-owned reference after annotation geometry has been persisted.
pub fn reference(&self) -> ThreadAnchor {
- match *self {
- Self::Markdown { mark_id } => ThreadAnchor::Markdown { mark_id },
- Self::PdfHighlight { anchor_id } => ThreadAnchor::PdfHighlight { anchor_id },
- Self::PdfPlaceable { anchor_id, .. } => ThreadAnchor::PdfPlaceable { anchor_id },
+ match self {
+ Self::Markdown {
+ mark_id,
+ marked_text,
+ } => ThreadAnchor::Markdown {
+ mark_id: *mark_id,
+ marked_text: marked_text.as_deref().and_then(marked_text_snapshot),
+ },
+ Self::PdfHighlight { anchor_id } => ThreadAnchor::PdfHighlight {
+ anchor_id: *anchor_id,
+ },
+ Self::PdfPlaceable { anchor_id, .. } => ThreadAnchor::PdfPlaceable {
+ anchor_id: *anchor_id,
+ },
}
}
}
diff --git a/crates/messages/src/domain/models/test.rs b/crates/messages/src/domain/models/test.rs
index 38aaf706ff..72fa3fbf4d 100644
--- a/crates/messages/src/domain/models/test.rs
+++ b/crates/messages/src/domain/models/test.rs
@@ -46,7 +46,10 @@ fn email_threads_are_not_message_parents() {
#[test]
fn anchors_require_a_known_kind_and_stable_uuid() {
let mark_id = Uuid::from_u128(123);
- let anchor = ThreadAnchor::Markdown { mark_id };
+ let anchor = ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: None,
+ };
assert_eq!(
serde_json::to_value(anchor).unwrap(),
serde_json::json!({ "type": "markdown", "mark_id": mark_id })
@@ -59,3 +62,70 @@ fn anchors_require_a_known_kind_and_stable_uuid() {
assert!(serde_json::from_value::<ThreadAnchor>(invalid).is_err());
}
}
+
+#[test]
+fn a_marked_text_snapshot_is_trimmed_bounded_and_optional() {
+ assert_eq!(
+ marked_text_snapshot(" the exact phrase "),
+ Some("the exact phrase".to_owned())
+ );
+ assert_eq!(marked_text_snapshot(" \n "), None);
+ // A range longer than the limit keeps its first characters and says so.
+ let long = "é".repeat(MARKED_TEXT_LIMIT + 10);
+ let snapshot = marked_text_snapshot(&long).unwrap();
+ assert_eq!(snapshot.chars().count(), MARKED_TEXT_LIMIT + 1);
+ assert!(snapshot.ends_with('\u{2026}'));
+ // A range exactly at the limit is whole, so nothing claims it was cut.
+ let exact = "é".repeat(MARKED_TEXT_LIMIT);
+ assert_eq!(marked_text_snapshot(&exact), Some(exact));
+}
+
+#[test]
+fn a_markdown_anchor_carries_its_normalized_snapshot() {
+ let mark_id = Uuid::from_u128(321);
+ let anchor = NewThreadAnchor::Markdown {
+ mark_id,
+ marked_text: Some(" anchored words ".to_owned()),
+ };
+ assert_eq!(
+ anchor.reference(),
+ ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: Some("anchored words".to_owned()),
+ }
+ );
+ let blank = NewThreadAnchor::Markdown {
+ mark_id,
+ marked_text: Some(" ".to_owned()),
+ };
+ assert_eq!(
+ blank.reference(),
+ ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: None,
+ }
+ );
+}
+
+#[test]
+fn a_stored_anchor_without_a_snapshot_still_reads() {
+ // Threads created or imported before snapshots existed keep only a mark id.
+ let mark_id = Uuid::from_u128(456);
+ let stored = serde_json::json!({ "type": "markdown", "mark_id": mark_id });
+ assert_eq!(
+ serde_json::from_value::<ThreadAnchor>(stored).unwrap(),
+ ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: None,
+ }
+ );
+ let with_text =
+ serde_json::json!({ "type": "markdown", "mark_id": mark_id, "marked_text": "marked" });
+ assert_eq!(
+ serde_json::from_value::<ThreadAnchor>(with_text).unwrap(),
+ ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: Some("marked".to_owned()),
+ }
+ );
+}
diff --git a/crates/messages/src/domain/service/test.rs b/crates/messages/src/domain/service/test.rs
index cb678d5085..0f6f64dc0b 100644
--- a/crates/messages/src/domain/service/test.rs
+++ b/crates/messages/src/domain/service/test.rs
@@ -219,6 +219,7 @@ fn fixture() -> Repo {
resolved: false,
anchor: Some(ThreadAnchor::Markdown {
mark_id: Uuid::from_u128(2),
+ marked_text: None,
}),
created_at: Utc::now(),
updated_at: Utc::now(),
@@ -535,6 +536,7 @@ fn only_root_document_messages_can_have_anchors() {
thread_id: None,
anchor: Some(NewThreadAnchor::Markdown {
mark_id: Uuid::from_u128(1),
+ marked_text: None,
}),
mentions: vec![],
attachments: vec![],
@@ -1205,6 +1207,7 @@ async fn anchors_are_only_accepted_on_document_roots() {
let mut anchored = post_input();
anchored.anchor = Some(NewThreadAnchor::Markdown {
mark_id: Uuid::from_u128(5),
+ marked_text: None,
});
assert!(matches!(
service.post(channel_access(), anchored.clone()).await,
diff --git a/crates/messages/src/outbound/pg_message_repo/test.rs b/crates/messages/src/outbound/pg_message_repo/test.rs
index 14c179cca0..e851225264 100644
--- a/crates/messages/src/outbound/pg_message_repo/test.rs
+++ b/crates/messages/src/outbound/pg_message_repo/test.rs
@@ -192,14 +192,19 @@ async fn deleted_markdown_threads_keep_paged_cleanup_identity(pool: PgPool) {
let repo = PgMessageRepository::new(pool.clone());
let mark_id = Uuid::from_u128(102);
let mut create = command("message-doc-a", None, "removed discussion");
- create.input.anchor = Some(NewThreadAnchor::Markdown { mark_id });
+ create.input.anchor = Some(NewThreadAnchor::Markdown {
+ mark_id,
+ marked_text: None,
+ });
let deleted = repo.create(create).await.unwrap();
let state = repo
.delete_thread(&deleted.parent, deleted.id)
.await
.unwrap();
assert!(state.deleted_at.is_some());
- assert!(matches!(state.anchor, Some(ThreadAnchor::Markdown { mark_id: id }) if id == mark_id));
+ assert!(
+ matches!(state.anchor, Some(ThreadAnchor::Markdown { mark_id: id, .. }) if id == mark_id)
+ );
let live = repo
.create(command("message-doc-a", None, "live discussion"))
.await
@@ -242,7 +247,7 @@ async fn deleted_markdown_threads_keep_paged_cleanup_identity(pool: PgPool) {
assert!(older.items[0].message.content.is_empty());
assert!(older.items[0].state.deleted_at.is_some());
assert!(
- matches!(older.items[0].state.anchor, Some(ThreadAnchor::Markdown { mark_id: id }) if id == mark_id)
+ matches!(older.items[0].state.anchor, Some(ThreadAnchor::Markdown { mark_id: id, .. }) if id == mark_id)
);
assert!(older.next_cursor.is_none());
let other_parent = MessageParent::parse("document", "message-doc-b").unwrap();
@@ -261,6 +266,27 @@ async fn deleted_markdown_threads_keep_paged_cleanup_identity(pool: PgPool) {
);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_markdown_anchor_stores_the_marked_text_beside_its_mark(pool: PgPool) {
+ setup(&pool).await;
+ let repo = PgMessageRepository::new(pool);
+ let mark_id = Uuid::from_u128(150);
+ let mut create = command("message-doc-a", None, "what does this mean?");
+ create.input.anchor = Some(NewThreadAnchor::Markdown {
+ mark_id,
+ marked_text: Some(" the marked phrase ".to_owned()),
+ });
+ let root = repo.create(create).await.unwrap();
+ let state = repo.thread(&root.parent, root.id).await.unwrap().unwrap();
+ assert_eq!(
+ state.anchor,
+ Some(ThreadAnchor::Markdown {
+ mark_id,
+ marked_text: Some("the marked phrase".to_owned()),
+ })
+ );
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn reactions_attachments_and_resolution_use_shared_message_data(pool: PgPool) {
setup(&pool).await;
@@ -268,6 +294,7 @@ async fn reactions_attachments_and_resolution_use_shared_message_data(pool: PgPo
let mut create = command("message-doc-a", None, "message");
create.input.anchor = Some(NewThreadAnchor::Markdown {
mark_id: Uuid::from_u128(100),
+ marked_text: None,
});
create.input.attachments.push(NewAttachment {
entity_type: "document".into(),
@@ -322,6 +349,7 @@ async fn detaching_a_mark_retains_the_complete_thread_and_makes_it_unanchored(po
let mut create = command("message-doc-a", None, "anchored root");
create.input.anchor = Some(NewThreadAnchor::Markdown {
mark_id: Uuid::from_u128(101),
+ marked_text: None,
});
let root = repo.create(create).await.unwrap();
let reply = repo
@@ -555,12 +583,13 @@ async fn roots_get_thread_rows_without_the_bookkeeping_trigger(pool: PgPool) {
let mut create = command("message-doc-a", None, "root without trigger");
create.input.anchor = Some(NewThreadAnchor::Markdown {
mark_id: Uuid::from_u128(202),
+ marked_text: None,
});
let root = repo.create(create).await.unwrap();
let state = repo.thread(&root.parent, root.id).await.unwrap().unwrap();
assert_eq!(state.user_id, USER);
assert!(
- matches!(state.anchor, Some(ThreadAnchor::Markdown { mark_id }) if mark_id == Uuid::from_u128(202))
+ matches!(state.anchor, Some(ThreadAnchor::Markdown { mark_id, .. }) if mark_id == Uuid::from_u128(202))
);
let reply = repo
.create(command("message-doc-a", Some(root.id), "reply"))
@@ -659,6 +688,7 @@ async fn a_mark_identifies_one_live_discussion_per_document(pool: PgPool) {
let mut request = command(document, None, "Anchored");
request.input.anchor = Some(NewThreadAnchor::Markdown {
mark_id: Uuid::from_u128(77),
+ marked_text: None,
});
request
};
diff --git a/packages/lexical-core/nodes/CommentNode.ts b/packages/lexical-core/nodes/CommentNode.ts
index 5a027dc491..34d6ceacc2 100644
--- a/packages/lexical-core/nodes/CommentNode.ts
+++ b/packages/lexical-core/nodes/CommentNode.ts
@@ -1,6 +1,8 @@
import { MarkNode, type SerializedMarkNode } from '@lexical/mark';
+import { $dfs } from '@lexical/utils';
import {
$applyNodeReplacement,
+ $getRoot,
type EditorConfig,
type ElementNode,
type LexicalUpdateJSON,
@@ -33,6 +35,27 @@ export function $isCommentNode(node: any): node is CommentNode {
return node instanceof CommentNode;
}
+/**
+ * The document text a comment mark covers, in reading order. A range spanning
+ * several blocks is wrapped once per block, so the blocks are rejoined on
+ * newlines. Must run inside an editor read or update.
+ */
+export function $getCommentMarkText(markId: string): string {
+ const blocks: string[] = [];
+ let blockKey: NodeKey | undefined;
+ for (const { node } of $dfs($getRoot())) {
+ if (!$isCommentNode(node) || !node.getIDs().includes(markId)) continue;
+ const key = node.getTopLevelElement()?.getKey();
+ if (key !== undefined && key === blockKey) {
+ blocks[blocks.length - 1] += node.getTextContent();
+ continue;
+ }
+ blockKey = key;
+ blocks.push(node.getTextContent());
+ }
+ return blocks.join('\n').trim();
+}
+
export class CommentNode extends MarkNode {
__threadId: number | undefined;
__isDraft: boolean;
diff --git a/packages/lexical-core/tests/agent-context.test.ts b/packages/lexical-core/tests/agent-context.test.ts
index 3de40271f1..76f7f23ff4 100644
--- a/packages/lexical-core/tests/agent-context.test.ts
+++ b/packages/lexical-core/tests/agent-context.test.ts
@@ -174,6 +174,49 @@ describe('composeAgentContextPrompt', () => {
});
});
+ it('names the comment anchor and the text it marked', () => {
+ const composed = composeAgentContextPrompt({
+ promptMarkdown: 'what does this mean?',
+ parent: { type: 'document', id: 'doc-1' },
+ anchor: { markId: 'mark-1', markedText: 'the marked phrase' },
+ });
+ const state = markdownToSerializedEditorStateWithIds(composed);
+
+ expect(state.root.children[0]).toMatchObject({
+ type: 'agent-context',
+ text:
+ 'Conversation parent: {"type":"document","id":"doc-1"}\n\n' +
+ 'Comment anchor: {"markId":"mark-1","markedText":"the marked phrase"}\n' +
+ 'markedText is what the mark covered when the comment was posted; the document may have changed since.',
+ });
+ });
+
+ it('names a mark with no snapshot without claiming one', () => {
+ const composed = composeAgentContextPrompt({
+ promptMarkdown: 'what does this mean?',
+ anchor: { markId: 'mark-1' },
+ });
+ const state = markdownToSerializedEditorStateWithIds(composed);
+
+ expect(state.root.children[0]).toMatchObject({
+ type: 'agent-context',
+ text: 'Comment anchor: {"markId":"mark-1"}',
+ });
+ });
+
+ it('cannot close the context envelope from marked text', () => {
+ const composed = composeAgentContextPrompt({
+ promptMarkdown: 'original',
+ anchor: {
+ markId: 'mark-1',
+ markedText: '</m-agent-context>visible',
+ },
+ });
+
+ expect(composed.match(/<\/m-agent-context>/g)).toHaveLength(1);
+ expect(composed).toContain('\\u003c/m-agent-context>visible');
+ });
+
it('cannot close the context envelope from message content', () => {
const composed = composeAgentContextPrompt({
promptMarkdown: 'original',
diff --git a/packages/lexical-core/tests/comment-mark-text.test.ts b/packages/lexical-core/tests/comment-mark-text.test.ts
new file mode 100644
index 0000000000..cbc3626645
--- /dev/null
+++ b/packages/lexical-core/tests/comment-mark-text.test.ts
@@ -0,0 +1,84 @@
+import { createHeadlessEditor } from '@lexical/headless';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ type LexicalEditor,
+} from 'lexical';
+import { describe, expect, it } from 'vitest';
+import {
+ $createCommentNode,
+ $getCommentMarkText,
+ CommentNode,
+} from '../nodes/CommentNode';
+
+/** A paragraph whose marked range is followed by text no comment covers. */
+function markedParagraph(id: string, marked: string, trailing = '') {
+ const mark = $createCommentNode({ ids: [id], isDraft: false });
+ mark.append($createTextNode(marked));
+ const paragraph = $createParagraphNode().append(mark);
+ if (trailing) paragraph.append($createTextNode(trailing));
+ $getRoot().append(paragraph);
+}
+
+function editorWith(build: () => void): LexicalEditor {
+ const editor = createHeadlessEditor({
+ nodes: [CommentNode],
+ onError: (error) => {
+ throw error;
+ },
+ });
+ editor.update(build, { discrete: true });
+ return editor;
+}
+
+describe('$getCommentMarkText', () => {
+ it('reads only the text the mark covers', () => {
+ const editor = editorWith(() =>
+ markedParagraph('mark', 'the marked phrase', ' and the rest')
+ );
+
+ expect(editor.read(() => $getCommentMarkText('mark'))).toBe(
+ 'the marked phrase'
+ );
+ });
+
+ it('joins a range spanning several blocks in reading order', () => {
+ const editor = editorWith(() => {
+ markedParagraph('mark', 'first half');
+ markedParagraph('mark', 'second half');
+ });
+
+ expect(editor.read(() => $getCommentMarkText('mark'))).toBe(
+ 'first half\nsecond half'
+ );
+ });
+
+ it('reads one mark without picking up its neighbours', () => {
+ const editor = editorWith(() => {
+ markedParagraph('other', 'not this one');
+ markedParagraph('mark', 'this one');
+ });
+
+ expect(editor.read(() => $getCommentMarkText('mark'))).toBe('this one');
+ });
+
+ it('reads an overlapping range that shares a node with another mark', () => {
+ const editor = editorWith(() => {
+ const mark = $createCommentNode({
+ ids: ['mark', 'other'],
+ isDraft: false,
+ });
+ mark.append($createTextNode('shared words'));
+ $getRoot().append($createParagraphNode().append(mark));
+ });
+
+ expect(editor.read(() => $getCommentMarkText('mark'))).toBe('shared words');
+ });
+
+ it('is empty when nothing carries the mark', () => {
+ const editor = editorWith(() => markedParagraph('other', 'unrelated'));
+
+ expect(editor.read(() => $getCommentMarkText('mark'))).toBe('');
+ });
+});
diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.ts
index 55471cc410..16bacbe241 100644
--- a/packages/lexical-core/utils/agent-context.ts
+++ b/packages/lexical-core/utils/agent-context.ts
@@ -20,14 +20,34 @@ export type AgentContextParent = {
id: string;
};
+/** Where in a document the comment thread a prompt was posted in sits. */
+export type AgentContextAnchor = {
+ markId: string;
+ /** Absent on threads anchored before marked text was captured. */
+ markedText?: string;
+};
+
/** Input used to compose an agent prompt with private conversation context. */
export type AgentContextPrompt = {
promptMarkdown: string;
/** Supplied by the message service, never by the prompt's author. */
parent?: AgentContextParent;
+ anchor?: AgentContextAnchor;
messages?: AgentContextMessage[];
};
+/**
+ * Name the document range a comment marks. The mark id identifies it, but
+ * nothing the agent can read maps that id back onto text, so the text the
+ * comment covered travels with it — as a snapshot, since the document is free
+ * to change after the comment is written.
+ */
+function describeAnchor(anchor: AgentContextAnchor): string {
+ const location = `Comment anchor: ${JSON.stringify(anchor)}`;
+ if (anchor.markedText === undefined) return location;
+ return `${location}\nmarkedText is what the mark covered when the comment was posted; the document may have changed since.`;
+}
+
function escapeAgentContextTags(markdown: string): string {
// No user-authored entity may decode into reserved syntax during import.
return markdown
@@ -58,7 +78,7 @@ export function composeAgentContextPrompt(input: AgentContextPrompt): string {
editor.update(
() => {
- if (!input.messages?.length && !input.parent) return;
+ if (!input.messages?.length && !input.parent && !input.anchor) return;
const history = (input.messages ?? [])
.map(
@@ -69,9 +89,10 @@ export function composeAgentContextPrompt(input: AgentContextPrompt): string {
const location = input.parent
? `Conversation parent: ${JSON.stringify(input.parent)}`
: '';
+ const anchor = input.anchor ? describeAnchor(input.anchor) : '';
const context = $createAgentContextNode({
version: 1,
- text: [location, history].filter(Boolean).join('\n\n'),
+ text: [location, anchor, history].filter(Boolean).join('\n\n'),
});
const firstChild = $getRoot().getFirstChild();
if (firstChild) firstChild.insertBefore(context);
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 357f56b27c..2ec12196db 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -7154,6 +7154,12 @@ export type NewThreadAnchor = {
* Serialized mark identifier.
*/
mark_id: string;
+ /**
+ * The document text the mark covers, captured by the editor as the
+ * comment is written. Trimmed and bounded before it is stored, so an
+ * oversized or whitespace-only claim cannot reach the thread row.
+ */
+ marked_text?: string | null;
type: 'markdown';
} | {
/**
@@ -9962,6 +9968,13 @@ export type ThreadAnchor = {
* Mark UUID serialized in the document.
*/
mark_id: string;
+ /**
+ * The marked text as it read when the discussion was created, already
+ * trimmed and bounded. Absent on threads created or imported before
+ * snapshots were captured: the text a mark covers cannot be recovered
+ * from the mark id alone.
+ */
+ marked_text?: string | null;
type: 'markdown';
} | {
/**
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 996da35f01..05c0e1f925 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -25580,6 +25580,10 @@
"format": "uuid",
"description": "Serialized mark identifier."
},
+ "marked_text": {
+ "type": ["string", "null"],
+ "description": "The document text the mark covers, captured by the editor as the\ncomment is written. Trimmed and bounded before it is stored, so an\noversized or whitespace-only claim cannot reach the thread row."
+ },
"type": {
"type": "string",
"enum": ["markdown"]
@@ -30195,6 +30199,10 @@
"format": "uuid",
"description": "Mark UUID serialized in the document."
},
+ "marked_text": {
+ "type": ["string", "null"],
+ "description": "The marked text as it read when the discussion was created, already\ntrimmed and bounded. Absent on threads created or imported before\nsnapshots were captured: the text a mark covers cannot be recovered\nfrom the mark id alone."
+ },
"type": {
"type": "string",
"enum": ["markdown"]
diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.ts
index b62901556e..89c7773f6b 100644
--- a/services/lexical-service/src/endpoints/agent-context.ts
+++ b/services/lexical-service/src/endpoints/agent-context.ts
@@ -10,9 +10,15 @@ const messageParent = z.object({
id: z.string().min(1),
});
+const commentAnchor = z.object({
+ markId: z.string().min(1),
+ markedText: z.string().optional(),
+});
+
const agentContextRequest = z.object({
promptMarkdown: z.string(),
parent: messageParent.optional(),
+ anchor: commentAnchor.optional(),
messages: z
.array(
z.object({
@@ -31,7 +37,7 @@ export class AgentContextEndpoint extends OpenAPIRoute {
schema = {
summary: 'Compose an agent prompt with conversation context',
description:
- 'Builds internal markdown containing the conversation parent, optional untrusted prior messages, and the user prompt.',
+ 'Builds internal markdown containing the conversation parent, the comment anchor it was posted on, optional untrusted prior messages, and the user prompt.',
request: {
body: {
content: {