mirror of
https://github.com/outline/outline.git
synced 2026-11-28 08:14:58 +03:00
Fix attribution of Markdown document mentions (#14123)
Co-authored-by: Tom Moor <380914+tommoor@users.noreply.github.com> Co-authored-by: linear-code[bot] <222613912+linear-code[bot]@users.noreply.github.com>
This commit is contained in:
11 files changed
+376
-12
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
||||
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
|
||||
import {
|
||||
buildUser,
|
||||
@@ -10,6 +11,22 @@ import { withAPIContext } from "@server/test/support";
|
||||
import documentCreator from "./documentCreator";
|
||||
|
||||
describe("documentCreator", () => {
|
||||
it("should attribute Markdown mentions to the authenticated writer", async () => {
|
||||
const user = await buildUser();
|
||||
const mentioned = await buildUser({ teamId: user.teamId });
|
||||
const document = await withAPIContext(user, (ctx) =>
|
||||
documentCreator(ctx, {
|
||||
title: "Mentions",
|
||||
text: `@[${mentioned.name}](mention://user/${mentioned.id})`,
|
||||
})
|
||||
);
|
||||
|
||||
await document.reload();
|
||||
expect(DocumentHelper.parseMentions(document)).toEqual([
|
||||
expect.objectContaining({ modelId: mentioned.id, actorId: user.id }),
|
||||
]);
|
||||
});
|
||||
|
||||
describe("content vs text priority", () => {
|
||||
it("should prioritize content over text when both are provided", async () => {
|
||||
const user = await buildUser();
|
||||
|
||||
@@ -217,7 +217,10 @@ export default async function documentCreator(
|
||||
const contentWithReplacements = content
|
||||
? content
|
||||
: text
|
||||
? ProsemirrorHelper.toProsemirror(text).toJSON()
|
||||
? ProsemirrorHelper.assignMentionActors(
|
||||
ProsemirrorHelper.toProsemirror(text),
|
||||
user.id
|
||||
).toJSON()
|
||||
: template
|
||||
? ProsemirrorHelper.replaceTemplateVariables(
|
||||
await DocumentHelper.toJSON(template),
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import * as Y from "yjs";
|
||||
import { yDocToProsemirrorJSON } from "y-prosemirror";
|
||||
import {
|
||||
TextEditMode,
|
||||
MentionType,
|
||||
type ProsemirrorData,
|
||||
type ProsemirrorMark,
|
||||
} from "@shared/types";
|
||||
import { APIUpdateExtension } from "@server/collaboration/APIUpdateExtension";
|
||||
import { type Document, Event } from "@server/models";
|
||||
import { Document, Event } from "@server/models";
|
||||
import { parser, schema } from "@server/editor";
|
||||
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
||||
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
|
||||
@@ -15,6 +17,76 @@ import { withAPIContext } from "@server/test/support";
|
||||
import documentUpdater from "./documentUpdater";
|
||||
|
||||
describe("documentUpdater", () => {
|
||||
it.each(Object.values(TextEditMode))(
|
||||
"should attribute new mentions and preserve existing actors in %s mode",
|
||||
async (editMode) => {
|
||||
const user = await buildUser();
|
||||
const originalActor = await buildUser({ teamId: user.teamId });
|
||||
const mentionId = randomUUID();
|
||||
const originalMention = `@[Original](mention://${mentionId}/user/${originalActor.id})`;
|
||||
const initialDoc = ProsemirrorHelper.assignMentionActors(
|
||||
parser.parse(`${originalMention} replace me`),
|
||||
originalActor.id
|
||||
);
|
||||
let document = await buildDocument({
|
||||
teamId: user.teamId,
|
||||
content: initialDoc.toJSON(),
|
||||
state: Buffer.from(
|
||||
Y.encodeStateAsUpdate(ProsemirrorHelper.toYDoc(initialDoc.toJSON()))
|
||||
),
|
||||
});
|
||||
const newMention = `@[Writer](mention://user/${user.id})`;
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
documentUpdater(ctx, {
|
||||
document,
|
||||
text:
|
||||
editMode === TextEditMode.Replace
|
||||
? `${originalMention} ${newMention}`
|
||||
: newMention,
|
||||
editMode,
|
||||
findText: editMode === TextEditMode.Patch ? "replace me" : undefined,
|
||||
})
|
||||
);
|
||||
|
||||
document = await Document.findByPk(document.id, {
|
||||
includeState: true,
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
expect(
|
||||
DocumentHelper.parseMentions(document, { type: MentionType.User })
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ id: mentionId, actorId: originalActor.id }),
|
||||
expect.objectContaining({ modelId: user.id, actorId: user.id }),
|
||||
])
|
||||
);
|
||||
if (!document.state) {
|
||||
throw new Error("Expected collaborative state to be persisted");
|
||||
}
|
||||
const ydoc = new Y.Doc();
|
||||
Y.applyUpdate(ydoc, document.state);
|
||||
expect(yDocToProsemirrorJSON(ydoc, "default")).toEqual(document.content);
|
||||
}
|
||||
);
|
||||
|
||||
it("should leave retained mentions without attribution unchanged", async () => {
|
||||
const user = await buildUser();
|
||||
const mention = `@[Writer](mention://${randomUUID()}/user/${user.id})`;
|
||||
let document = await buildDocument({
|
||||
teamId: user.teamId,
|
||||
content: parser.parse(mention).toJSON(),
|
||||
});
|
||||
const originalMentions = DocumentHelper.parseMentions(document);
|
||||
|
||||
document = await withAPIContext(user, (ctx) =>
|
||||
documentUpdater(ctx, { document, text: `${mention} updated` })
|
||||
);
|
||||
|
||||
await document.reload();
|
||||
expect(DocumentHelper.parseMentions(document)).toEqual(originalMentions);
|
||||
});
|
||||
|
||||
it("should change lastModifiedById", async () => {
|
||||
const user = await buildUser();
|
||||
let document = await buildDocument({
|
||||
|
||||
@@ -109,7 +109,8 @@ export default async function documentUpdater(
|
||||
base64Only: true,
|
||||
}),
|
||||
editMode,
|
||||
findText
|
||||
findText,
|
||||
user.id
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
UserMembership,
|
||||
} from "@server/models";
|
||||
import { SearchQuerySource } from "@server/models/SearchQuery";
|
||||
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
||||
import { getTestServer } from "@server/test/support";
|
||||
import {
|
||||
buildOAuthUser,
|
||||
@@ -392,6 +393,28 @@ describe("list_documents", () => {
|
||||
});
|
||||
|
||||
describe("create_document", () => {
|
||||
it("attributes Markdown mentions to the authenticated user", async () => {
|
||||
const { user, accessToken } = await buildOAuthUser();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const mentioned = await buildUser({ teamId: user.teamId });
|
||||
|
||||
const res = await callMcpTool(server, accessToken, "create_document", {
|
||||
title: "Mentions",
|
||||
collectionId: collection.id,
|
||||
text: `@[${mentioned.name}](mention://user/${mentioned.id})`,
|
||||
});
|
||||
const data = JSON.parse(res?.result?.content?.[0]?.text ?? "{}");
|
||||
expect(data.success).toBe(true);
|
||||
|
||||
const document = await Document.findByPk(data.id, { rejectOnEmpty: true });
|
||||
expect(DocumentHelper.parseMentions(document)).toEqual([
|
||||
expect.objectContaining({ modelId: mentioned.id, actorId: user.id }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates in the personal collection", async () => {
|
||||
const { user, accessToken } = await buildOAuthUser();
|
||||
user.team.setPreference(TeamPreference.PersonalDocs, true);
|
||||
@@ -632,6 +655,26 @@ describe("create_document", () => {
|
||||
});
|
||||
|
||||
describe("update_document", () => {
|
||||
it("attributes Markdown mentions to the authenticated editor", async () => {
|
||||
const { user, accessToken } = await buildOAuthUser();
|
||||
const author = await buildUser({ teamId: user.teamId });
|
||||
const document = await buildDocument({
|
||||
teamId: user.teamId,
|
||||
userId: author.id,
|
||||
});
|
||||
|
||||
const res = await callMcpTool(server, accessToken, "update_document", {
|
||||
id: document.id,
|
||||
text: `@[Author](mention://user/${author.id})`,
|
||||
});
|
||||
expect(res?.result?.isError).toBeFalsy();
|
||||
|
||||
await document.reload();
|
||||
expect(DocumentHelper.parseMentions(document)).toEqual([
|
||||
expect.objectContaining({ modelId: author.id, actorId: user.id }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not create the personal collection when it is not used", async () => {
|
||||
const { user, accessToken } = await buildOAuthUser();
|
||||
const collection = await buildCollection({
|
||||
|
||||
@@ -732,14 +732,19 @@ export class DocumentHelper {
|
||||
* @param text The markdown to apply
|
||||
* @param editMode The edit mode to use: "replace" (default), "append", "prepend", or "patch"
|
||||
* @param findText The markdown text to find when using "patch" edit mode
|
||||
* @param actorId the authenticated writer to attribute new mentions to.
|
||||
* @returns The document
|
||||
*/
|
||||
static applyMarkdownToDocument(
|
||||
document: Document,
|
||||
text: string,
|
||||
editMode: TextEditMode = TextEditMode.Replace,
|
||||
findText?: string
|
||||
findText?: string,
|
||||
actorId?: string
|
||||
) {
|
||||
const previousDoc = actorId
|
||||
? DocumentHelper.toProsemirror(document)
|
||||
: undefined;
|
||||
let doc: Node;
|
||||
|
||||
if (editMode === TextEditMode.Patch) {
|
||||
@@ -864,6 +869,10 @@ export class DocumentHelper {
|
||||
doc = parser.parse(text);
|
||||
}
|
||||
|
||||
if (actorId) {
|
||||
doc = ProsemirrorHelper.assignMentionActors(doc, actorId, previousDoc);
|
||||
}
|
||||
|
||||
document.content = doc.toJSON();
|
||||
document.text = serializer.serialize(doc);
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type DecorationSource,
|
||||
} from "prosemirror-view";
|
||||
import { Node, Fragment } from "prosemirror-model";
|
||||
import { Transform } from "prosemirror-transform";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import styled, { ServerStyleSheet, ThemeProvider } from "styled-components";
|
||||
import {
|
||||
@@ -187,6 +188,52 @@ export class ProsemirrorHelper extends SharedProsemirrorHelper {
|
||||
return Node.fromJSON(schema, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attributes new mentions to the writer, preserving the original actor of
|
||||
* mentions retained from an earlier document, including Markdown round trips.
|
||||
*
|
||||
* @param doc the updated document.
|
||||
* @param actorId the authenticated writer's ID.
|
||||
* @param previousDoc the document before the update, if any.
|
||||
* @returns the document with mention attribution restored or assigned.
|
||||
*/
|
||||
static assignMentionActors(doc: Node, actorId: string, previousDoc?: Node) {
|
||||
const previousMentions = new Map(
|
||||
previousDoc
|
||||
? this.parseMentions(previousDoc).map((mention) => [
|
||||
mention.id,
|
||||
mention,
|
||||
])
|
||||
: []
|
||||
);
|
||||
const transform = new Transform(doc);
|
||||
|
||||
doc.descendants((node, pos) => {
|
||||
if (node.type.name !== "mention") {
|
||||
return;
|
||||
}
|
||||
|
||||
const previous = previousMentions.get(node.attrs.id);
|
||||
const retained =
|
||||
previous &&
|
||||
previous.type === node.attrs.type &&
|
||||
previous.modelId === node.attrs.modelId;
|
||||
const mentionActorId = retained
|
||||
? previous.actorId
|
||||
: (node.attrs.actorId ?? actorId);
|
||||
|
||||
if (mentionActorId !== node.attrs.actorId) {
|
||||
transform.setNodeMarkup(pos, undefined, {
|
||||
...node.attrs,
|
||||
actorId: mentionActorId,
|
||||
});
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
return transform.doc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of attributes of all mentions in the node.
|
||||
*
|
||||
|
||||
@@ -22,6 +22,85 @@ beforeEach(async () => {
|
||||
});
|
||||
|
||||
describe("documents.publish", () => {
|
||||
describe.each([MentionType.User, MentionType.Group])(
|
||||
"%s mentions",
|
||||
(type) => {
|
||||
test.each(["missing", "null", "preserved", "self"])(
|
||||
"should use the correct actor for %s attribution",
|
||||
async (scenario) => {
|
||||
const actor = await buildUser();
|
||||
const originalActor = await buildUser({ teamId: actor.teamId });
|
||||
const recipient =
|
||||
scenario === "self"
|
||||
? actor
|
||||
: await buildUser({ teamId: actor.teamId });
|
||||
const group =
|
||||
type === MentionType.Group
|
||||
? await buildGroup({ teamId: actor.teamId })
|
||||
: undefined;
|
||||
if (group) {
|
||||
await buildGroupUser({ groupId: group.id, userId: recipient.id });
|
||||
}
|
||||
const eventType = group
|
||||
? NotificationEventType.GroupMentionedInDocument
|
||||
: NotificationEventType.MentionedInDocument;
|
||||
recipient.setNotificationEventType(eventType);
|
||||
await recipient.save();
|
||||
|
||||
const document = await buildDocument({
|
||||
teamId: actor.teamId,
|
||||
userId: actor.id,
|
||||
});
|
||||
document.content = buildProseMirrorDoc([
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "mention",
|
||||
attrs: {
|
||||
id: "mention-attribution-test",
|
||||
type,
|
||||
modelId: group?.id ?? recipient.id,
|
||||
actorId:
|
||||
scenario === "preserved"
|
||||
? originalActor.id
|
||||
: scenario === "null"
|
||||
? null
|
||||
: undefined,
|
||||
label: "Mention",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]).toJSON();
|
||||
await document.save();
|
||||
const task = new DocumentPublishedNotificationsTask();
|
||||
await task.perform({
|
||||
name: "documents.publish",
|
||||
documentId: document.id,
|
||||
teamId: document.teamId,
|
||||
actorId: actor.id,
|
||||
collectionId: document.collectionId!,
|
||||
ip,
|
||||
});
|
||||
|
||||
const notifications = await Notification.findAll({
|
||||
where: { documentId: document.id, event: eventType },
|
||||
});
|
||||
if (scenario === "self") {
|
||||
expect(notifications).toHaveLength(0);
|
||||
} else {
|
||||
expect(notifications).toHaveLength(1);
|
||||
expect(notifications[0].userId).toBe(recipient.id);
|
||||
expect(notifications[0].actorId).toBe(
|
||||
scenario === "preserved" ? originalActor.id : actor.id
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
test("should not send a notification to author", async () => {
|
||||
const spy = vi.spyOn(Notification, "create");
|
||||
const user = await buildUser();
|
||||
|
||||
@@ -35,11 +35,12 @@ export default class DocumentPublishedNotificationsTask extends BaseTask<Documen
|
||||
}
|
||||
userIdsProcessed.add(mention.modelId);
|
||||
|
||||
const actorId = mention.actorId ?? event.actorId;
|
||||
const recipient = await User.findByPk(mention.modelId);
|
||||
|
||||
if (
|
||||
!recipient ||
|
||||
recipient.id === mention.actorId ||
|
||||
recipient.id === actorId ||
|
||||
!(await canUserAccessDocument(recipient, document.id))
|
||||
) {
|
||||
continue;
|
||||
@@ -55,7 +56,7 @@ export default class DocumentPublishedNotificationsTask extends BaseTask<Documen
|
||||
await Notification.create({
|
||||
event: NotificationEventType.MentionedInDocument,
|
||||
userId: recipient.id,
|
||||
actorId: mention.actorId,
|
||||
actorId,
|
||||
teamId: document.teamId,
|
||||
documentId: document.id,
|
||||
});
|
||||
@@ -75,6 +76,8 @@ export default class DocumentPublishedNotificationsTask extends BaseTask<Documen
|
||||
continue;
|
||||
}
|
||||
|
||||
const actorId = group.actorId ?? event.actorId;
|
||||
|
||||
// Check if the group has mentions disabled
|
||||
const groupModel = await Group.findByPk(group.modelId);
|
||||
if (groupModel?.disableMentions) {
|
||||
@@ -97,7 +100,7 @@ export default class DocumentPublishedNotificationsTask extends BaseTask<Documen
|
||||
const recipient = await User.findByPk(user.userId);
|
||||
if (
|
||||
recipient &&
|
||||
recipient.id !== group.actorId &&
|
||||
recipient.id !== actorId &&
|
||||
recipient.subscribedToEventType(
|
||||
NotificationEventType.GroupMentionedInDocument
|
||||
) &&
|
||||
@@ -107,7 +110,7 @@ export default class DocumentPublishedNotificationsTask extends BaseTask<Documen
|
||||
event: NotificationEventType.GroupMentionedInDocument,
|
||||
groupId: group.modelId,
|
||||
userId: recipient.id,
|
||||
actorId: group.actorId,
|
||||
actorId,
|
||||
teamId: document.teamId,
|
||||
documentId: document.id,
|
||||
});
|
||||
|
||||
@@ -37,6 +37,93 @@ function updateDocumentText(document: Document, text: string) {
|
||||
}
|
||||
|
||||
describe("revisions.create", () => {
|
||||
describe.each([MentionType.User, MentionType.Group])(
|
||||
"%s mentions",
|
||||
(type) => {
|
||||
test.each(["missing", "null", "preserved", "self"])(
|
||||
"should use the correct actor for %s attribution",
|
||||
async (scenario) => {
|
||||
const actor = await buildUser();
|
||||
const originalActor = await buildUser({ teamId: actor.teamId });
|
||||
const recipient =
|
||||
scenario === "self"
|
||||
? actor
|
||||
: await buildUser({ teamId: actor.teamId });
|
||||
const group =
|
||||
type === MentionType.Group
|
||||
? await buildGroup({ teamId: actor.teamId })
|
||||
: undefined;
|
||||
if (group) {
|
||||
await buildGroupUser({ groupId: group.id, userId: recipient.id });
|
||||
}
|
||||
const eventType = group
|
||||
? NotificationEventType.GroupMentionedInDocument
|
||||
: NotificationEventType.MentionedInDocument;
|
||||
recipient.setNotificationEventType(eventType);
|
||||
await recipient.save();
|
||||
|
||||
const document = await buildDocument({
|
||||
teamId: actor.teamId,
|
||||
userId: actor.id,
|
||||
});
|
||||
await Revision.createFromDocument(
|
||||
createContext({ user: actor }),
|
||||
document
|
||||
);
|
||||
document.content = buildProseMirrorDoc([
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "mention",
|
||||
attrs: {
|
||||
id: "mention-attribution-test",
|
||||
type,
|
||||
modelId: group?.id ?? recipient.id,
|
||||
actorId:
|
||||
scenario === "preserved"
|
||||
? originalActor.id
|
||||
: scenario === "null"
|
||||
? null
|
||||
: undefined,
|
||||
label: "Mention",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]).toJSON();
|
||||
await document.save();
|
||||
const revision = await Revision.createFromDocument(
|
||||
createContext({ user: actor }),
|
||||
document
|
||||
);
|
||||
const task = new RevisionCreatedNotificationsTask();
|
||||
await task.perform({
|
||||
name: "revisions.create",
|
||||
documentId: document.id,
|
||||
teamId: document.teamId,
|
||||
actorId: actor.id,
|
||||
modelId: revision.id,
|
||||
ip,
|
||||
});
|
||||
|
||||
const notifications = await Notification.findAll({
|
||||
where: { documentId: document.id, event: eventType },
|
||||
});
|
||||
if (scenario === "self") {
|
||||
expect(notifications).toHaveLength(0);
|
||||
} else {
|
||||
expect(notifications).toHaveLength(1);
|
||||
expect(notifications[0].userId).toBe(recipient.id);
|
||||
expect(notifications[0].actorId).toBe(
|
||||
scenario === "preserved" ? originalActor.id : actor.id
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
test("should send a notification to other collaborators", async () => {
|
||||
const spy = vi.spyOn(Notification, "create");
|
||||
const user = await buildUser();
|
||||
|
||||
@@ -59,11 +59,12 @@ export default class RevisionCreatedNotificationsTask extends BaseTask<RevisionE
|
||||
}
|
||||
userIdsProcessed.add(mention.modelId);
|
||||
|
||||
const actorId = mention.actorId ?? event.actorId;
|
||||
const recipient = await User.findByPk(mention.modelId);
|
||||
|
||||
if (
|
||||
!recipient ||
|
||||
recipient.id === mention.actorId ||
|
||||
recipient.id === actorId ||
|
||||
!(await canUserAccessDocument(recipient, document.id))
|
||||
) {
|
||||
continue;
|
||||
@@ -80,7 +81,7 @@ export default class RevisionCreatedNotificationsTask extends BaseTask<RevisionE
|
||||
event: NotificationEventType.MentionedInDocument,
|
||||
userId: recipient.id,
|
||||
revisionId: event.modelId,
|
||||
actorId: mention.actorId,
|
||||
actorId,
|
||||
teamId: document.teamId,
|
||||
documentId: document.id,
|
||||
});
|
||||
@@ -110,6 +111,8 @@ export default class RevisionCreatedNotificationsTask extends BaseTask<RevisionE
|
||||
continue;
|
||||
}
|
||||
|
||||
const actorId = group.actorId ?? event.actorId;
|
||||
|
||||
// Check if the group has mentions disabled
|
||||
const groupModel = await Group.findByPk(group.modelId);
|
||||
if (groupModel?.disableMentions) {
|
||||
@@ -132,7 +135,7 @@ export default class RevisionCreatedNotificationsTask extends BaseTask<RevisionE
|
||||
const recipient = await User.findByPk(user.userId);
|
||||
if (
|
||||
recipient &&
|
||||
recipient.id !== group.actorId &&
|
||||
recipient.id !== actorId &&
|
||||
recipient.subscribedToEventType(
|
||||
NotificationEventType.GroupMentionedInDocument
|
||||
) &&
|
||||
@@ -143,7 +146,7 @@ export default class RevisionCreatedNotificationsTask extends BaseTask<RevisionE
|
||||
groupId: group.modelId,
|
||||
userId: recipient.id,
|
||||
revisionId: event.modelId,
|
||||
actorId: group.actorId,
|
||||
actorId,
|
||||
teamId: document.teamId,
|
||||
documentId: document.id,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user