Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(document-comment): thread notifications and comment deep link (#19039)

Rdmclin20c1e4a0f9212
diff --git a/apps/server/src/routers/lambda/__tests__/integration/documentComment.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/documentComment.integration.test.ts
index 661f6820c3f..aaa5462c13b 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/documentComment.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/documentComment.integration.test.ts
@@ -146,6 +146,37 @@ describe('documentCommentRouter integration', () => {
expect((await admin.delete({ id: created.comment.id })).mode).toBe('hard');
});
+ it('serves one comment by id with a live reply count for roots', async () => {
+ const member = documentCommentRouter.createCaller(context(memberId, workspaceId));
+ const viewer = documentCommentRouter.createCaller(context(viewerId, workspaceId));
+ const root = (await member.create({ clientId: 'get-root', content: 'root', documentId }))
+ .comment;
+ const reply = (
+ await member.create({
+ clientId: 'get-reply',
+ content: 'reply',
+ documentId,
+ parentCommentId: root.id,
+ })
+ ).comment;
+ await flushAfterResponse();
+
+ expect(await viewer.get({ id: root.id })).toMatchObject({
+ canEdit: false,
+ content: 'root',
+ replyCount: 1,
+ });
+ expect(await member.get({ id: reply.id })).toMatchObject({
+ canEdit: true,
+ parentCommentId: root.id,
+ replyCount: 0,
+ });
+
+ expect((await member.delete({ id: reply.id })).mode).toBe('hard');
+ await expect(member.get({ id: reply.id })).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(await member.get({ id: root.id })).toMatchObject({ replyCount: 0 });
+ });
+
it('preserves a root tombstone while replies remain and keeps counts consistent', async () => {
const member = documentCommentRouter.createCaller(context(memberId, workspaceId));
const owner = documentCommentRouter.createCaller(context(ownerId, workspaceId));
@@ -318,6 +349,71 @@ describe('documentCommentRouter integration', () => {
expect(notifyDocumentCommentActivity).toHaveBeenCalledTimes(1);
});
+ it('fans a reply out to the direct target and the other thread participants', async () => {
+ const owner = documentCommentRouter.createCaller(context(ownerId, workspaceId));
+ const member = documentCommentRouter.createCaller(context(memberId, workspaceId));
+ const admin = documentCommentRouter.createCaller(context(adminId, workspaceId));
+
+ const root = await owner.create({ clientId: 'owner-root', content: 'root', documentId });
+ const memberReply = await member.create({
+ clientId: 'member-reply',
+ content: 'reply',
+ documentId,
+ parentCommentId: root.comment.id,
+ });
+ await flushAfterResponse();
+ notifyDocumentCommentActivity.mockClear();
+
+ // Admin replies to the member's reply: member is the direct target, the
+ // root author only gets the thread ping.
+ const adminReply = await admin.create({
+ clientId: 'admin-reply',
+ content: 'nested',
+ documentId,
+ parentCommentId: memberReply.comment.id,
+ });
+ await flushAfterResponse();
+ expect(notifyDocumentCommentActivity).toHaveBeenCalledTimes(2);
+ expect(notifyDocumentCommentActivity).toHaveBeenCalledWith(
+ expect.objectContaining({
+ commentId: adminReply.comment.id,
+ kind: 'replied',
+ recipientUserId: memberId,
+ rootCommentId: root.comment.id,
+ }),
+ );
+ expect(notifyDocumentCommentActivity).toHaveBeenCalledWith(
+ expect.objectContaining({
+ commentId: adminReply.comment.id,
+ kind: 'thread',
+ recipientUserId: ownerId,
+ rootCommentId: root.comment.id,
+ }),
+ );
+
+ // Root author replies to their own root: never self-notified, every other
+ // participant hears about the new activity.
+ notifyDocumentCommentActivity.mockClear();
+ await owner.create({
+ clientId: 'owner-reply',
+ content: 'thanks both',
+ documentId,
+ parentCommentId: root.comment.id,
+ });
+ await flushAfterResponse();
+ expect(notifyDocumentCommentActivity).toHaveBeenCalledTimes(2);
+ expect(
+ notifyDocumentCommentActivity.mock.calls
+ .map(([params]) => [params.recipientUserId, params.kind])
+ .sort(),
+ ).toEqual(
+ [
+ [adminId, 'thread'],
+ [memberId, 'thread'],
+ ].sort(),
+ );
+ });
+
it('notifies valid mentions once, prefers mention copy, and only sends newly added mentions', async () => {
const member = documentCommentRouter.createCaller(context(memberId, workspaceId));
const created = await member.create({
diff --git a/apps/server/src/routers/lambda/documentComment.ts b/apps/server/src/routers/lambda/documentComment.ts
index 7217ce3fed0..47358132b17 100644
--- a/apps/server/src/routers/lambda/documentComment.ts
+++ b/apps/server/src/routers/lambda/documentComment.ts
@@ -1,4 +1,7 @@
-import type { DocumentCommentItem as DocumentCommentDTO } from '@lobechat/types';
+import type {
+ DocumentCommentDetail,
+ DocumentCommentItem as DocumentCommentDTO,
+} from '@lobechat/types';
import { toRecord } from '@lobechat/utils/object';
import { TRPCError } from '@trpc/server';
import { and, eq, inArray, isNull } from 'drizzle-orm';
@@ -385,19 +388,23 @@ export const documentCommentRouter = router({
const mentionedUserIds = await validateMentionedUserIds(ctx, input.editorData);
const result = await ctx.documentCommentModel.create({ ...input, mentionedUserIds });
if (!result.isDuplicate) {
+ // Later entries win, so the order encodes precedence:
+ // thread participant < direct target / document author < mention.
const recipientsByUserId = new Map<string, NotifyDocumentCommentActivityParams['kind']>();
- const recipientUserId = input.parentCommentId
- ? result.parentAuthorUserId
- : result.documentAuthorUserId;
- if (recipientUserId && recipientUserId !== ctx.userId) {
- recipientsByUserId.set(
- recipientUserId,
- input.parentCommentId ? 'replied' : 'commented',
- );
+ if (input.parentCommentId) {
+ for (const userId of result.threadParticipantUserIds) {
+ recipientsByUserId.set(userId, 'thread');
+ }
+ if (result.parentAuthorUserId) {
+ recipientsByUserId.set(result.parentAuthorUserId, 'replied');
+ }
+ } else if (result.documentAuthorUserId) {
+ recipientsByUserId.set(result.documentAuthorUserId, 'commented');
}
for (const userId of result.addedMentionUserIds) {
recipientsByUserId.set(userId, 'mentioned');
}
+ recipientsByUserId.delete(ctx.userId);
notifyActivitiesBestEffort(
ctx,
@@ -451,7 +458,12 @@ export const documentCommentRouter = router({
throw new TRPCError({ code: 'NOT_FOUND', message: 'Document comment not found' });
}
await assertDocumentView(ctx, comment.documentId, grantedPermissions);
- return (await enrich(ctx, [comment]))[0];
+ // Roots carry their live reply count so a deep link can render the thread on its own.
+ const [enriched, replyCount] = await Promise.all([
+ enrich(ctx, [comment]),
+ comment.parentCommentId ? 0 : ctx.documentCommentModel.countLiveReplies(comment.id),
+ ]);
+ return { ...enriched[0], replyCount } satisfies DocumentCommentDetail;
}),
listReplies: documentCommentProcedure
diff --git a/locales/ar/file.json b/locales/ar/file.json
index 5cd43d5a8d2..5d3740f1993 100644
--- a/locales/ar/file.json
+++ b/locales/ar/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "عضو سابق",
"pageEditor.comments.cancel": "إلغاء",
"pageEditor.comments.createFailed": "فشل نشر التعليق. لا يزال المسودة موجودة هنا.",
+ "pageEditor.comments.deepLinkLoadFailed": "فشل تحميل التعليق المرتبط. حاول مرة أخرى.",
+ "pageEditor.comments.deepLinkMissing": "هذا التعليق لم يعد متاحًا.",
"pageEditor.comments.delete": "حذف",
"pageEditor.comments.deleteConfirm.content": "هل تريد حذف هذا التعليق؟ ستظل الردود مرئية إذا كان لهذا التعليق سلسلة.",
"pageEditor.comments.deleteConfirm.title": "حذف التعليق",
diff --git a/locales/ar/notification.json b/locales/ar/notification.json
index ea1b8999d0b..b2cbfff2a24 100644
--- a/locales/ar/notification.json
+++ b/locales/ar/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} علق على مستندك \"{{documentTitle}}\".",
"document_comment_activity_replied": "{{actorLabel}} رد على تعليقك في \"{{documentTitle}}\".",
"document_comment_activity_replied_title": "رد جديد على تعليقك",
+ "document_comment_activity_thread": "{{actorLabel}} رد على سلسلة تعليقات تشارك فيها في \"{{documentTitle}}\".",
+ "document_comment_activity_thread_title": "رد جديد في سلسلة تعليقاتك",
"document_comment_activity_title": "تعليق جديد على مستندك",
"document_comment_mentioned": "{{actorLabel}} أشار إليك في تعليق على \"{{documentTitle}}\".",
"document_comment_mentioned_title": "تم الإشارة إليك في تعليق على مستند",
diff --git a/locales/bg-BG/file.json b/locales/bg-BG/file.json
index d8014c12e45..54719a72e0d 100644
--- a/locales/bg-BG/file.json
+++ b/locales/bg-BG/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "Бивш член",
"pageEditor.comments.cancel": "Отказ",
"pageEditor.comments.createFailed": "Неуспешно публикуване на коментар. Вашият чернови все още е тук.",
+ "pageEditor.comments.deepLinkLoadFailed": "Неуспешно зареждане на свързания коментар. Опитайте отново.",
+ "pageEditor.comments.deepLinkMissing": "Този коментар вече не е наличен.",
"pageEditor.comments.delete": "Изтрий",
"pageEditor.comments.deleteConfirm.content": "Да изтрия ли този коментар? Отговорите ще останат видими, ако този коментар има нишка.",
"pageEditor.comments.deleteConfirm.title": "Изтриване на коментар",
diff --git a/locales/bg-BG/notification.json b/locales/bg-BG/notification.json
index cc19d84850a..d7054d57f6d 100644
--- a/locales/bg-BG/notification.json
+++ b/locales/bg-BG/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} коментира вашия документ \"{{documentTitle}}\".",
"document_comment_activity_replied": "{{actorLabel}} отговори на вашия коментар в \"{{documentTitle}}\".",
"document_comment_activity_replied_title": "Нов отговор на вашия коментар",
+ "document_comment_activity_thread": "{{actorLabel}} отговори в нишка с коментари, в която участвате, в \"{{documentTitle}}\".",
+ "document_comment_activity_thread_title": "Нов отговор в нишката с вашите коментари",
"document_comment_activity_title": "Нов коментар във вашия документ",
"document_comment_mentioned": "{{actorLabel}} ви спомена в коментар на \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Бяхте споменати в коментар на документ",
diff --git a/locales/de-DE/file.json b/locales/de-DE/file.json
index ef74ee0a261..4e049f71c4c 100644
--- a/locales/de-DE/file.json
+++ b/locales/de-DE/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "Ehemaliges Mitglied",
"pageEditor.comments.cancel": "Abbrechen",
"pageEditor.comments.createFailed": "Kommentar konnte nicht veröffentlicht werden. Ihr Entwurf ist noch vorhanden.",
+ "pageEditor.comments.deepLinkLoadFailed": "Der verlinkte Kommentar konnte nicht geladen werden. Bitte versuchen Sie es erneut.",
+ "pageEditor.comments.deepLinkMissing": "Dieser Kommentar ist nicht mehr verfügbar.",
"pageEditor.comments.delete": "Löschen",
"pageEditor.comments.deleteConfirm.content": "Diesen Kommentar löschen? Antworten bleiben sichtbar, wenn dieser Kommentar einen Thread hat.",
"pageEditor.comments.deleteConfirm.title": "Kommentar löschen",
diff --git a/locales/de-DE/notification.json b/locales/de-DE/notification.json
index 19e39002a8e..e9648462c3f 100644
--- a/locales/de-DE/notification.json
+++ b/locales/de-DE/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} hat einen Kommentar zu Ihrem Dokument \"{{documentTitle}}\" hinterlassen.",
"document_comment_activity_replied": "{{actorLabel}} hat auf Ihren Kommentar in \"{{documentTitle}}\" geantwortet.",
"document_comment_activity_replied_title": "Neue Antwort auf Ihren Kommentar",
+ "document_comment_activity_thread": "{{actorLabel}} hat in einem Kommentar-Thread geantwortet, an dem Sie in \"{{documentTitle}}\" beteiligt sind.",
+ "document_comment_activity_thread_title": "Neue Antwort in Ihrem Kommentar-Thread",
"document_comment_activity_title": "Neuer Kommentar zu Ihrem Dokument",
"document_comment_mentioned": "{{actorLabel}} hat Sie in einem Kommentar zu \"{{documentTitle}}\" erwähnt.",
"document_comment_mentioned_title": "Sie wurden in einem Dokumentkommentar erwähnt",
diff --git a/locales/en-US/file.json b/locales/en-US/file.json
index 07a1ef55ab1..29e2b1941f2 100644
--- a/locales/en-US/file.json
+++ b/locales/en-US/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "Former member",
"pageEditor.comments.cancel": "Cancel",
"pageEditor.comments.createFailed": "Failed to publish comment. Your draft is still here.",
+ "pageEditor.comments.deepLinkLoadFailed": "Failed to load the linked comment. Try again.",
+ "pageEditor.comments.deepLinkMissing": "This comment is no longer available.",
"pageEditor.comments.delete": "Delete",
"pageEditor.comments.deleteConfirm.content": "Delete this comment? Replies will remain visible if this comment has a thread.",
"pageEditor.comments.deleteConfirm.title": "Delete comment",
diff --git a/locales/en-US/notification.json b/locales/en-US/notification.json
index 4988d176014..a1e81240afd 100644
--- a/locales/en-US/notification.json
+++ b/locales/en-US/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} commented on your document \"{{documentTitle}}\".",
"document_comment_activity_replied": "{{actorLabel}} replied to your comment in \"{{documentTitle}}\".",
"document_comment_activity_replied_title": "New reply to your comment",
+ "document_comment_activity_thread": "{{actorLabel}} replied in a comment thread you're part of in \"{{documentTitle}}\".",
+ "document_comment_activity_thread_title": "New reply in your comment thread",
"document_comment_activity_title": "New comment on your document",
"document_comment_mentioned": "{{actorLabel}} mentioned you in a comment on \"{{documentTitle}}\".",
"document_comment_mentioned_title": "You were mentioned in a document comment",
diff --git a/locales/es-ES/file.json b/locales/es-ES/file.json
index 3852f87a00b..dbdfd2265ed 100644
--- a/locales/es-ES/file.json
+++ b/locales/es-ES/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "Miembro anterior",
"pageEditor.comments.cancel": "Cancelar",
"pageEditor.comments.createFailed": "No se pudo publicar el comentario. Tu borrador sigue aquí.",
+ "pageEditor.comments.deepLinkLoadFailed": "No se pudo cargar el comentario vinculado. Inténtalo de nuevo.",
+ "pageEditor.comments.deepLinkMissing": "Este comentario ya no está disponible.",
"pageEditor.comments.delete": "Eliminar",
"pageEditor.comments.deleteConfirm.content": "¿Eliminar este comentario? Las respuestas seguirán siendo visibles si este comentario tiene un hilo.",
"pageEditor.comments.deleteConfirm.title": "Eliminar comentario",
diff --git a/locales/es-ES/notification.json b/locales/es-ES/notification.json
index a060a69cf47..0ee46fbb714 100644
--- a/locales/es-ES/notification.json
+++ b/locales/es-ES/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} comentó en tu documento \"{{documentTitle}}\".",
"document_comment_activity_replied": "{{actorLabel}} respondió a tu comentario en \"{{documentTitle}}\".",
"document_comment_activity_replied_title": "Nueva respuesta a tu comentario",
+ "document_comment_activity_thread": "{{actorLabel}} respondió en un hilo de comentarios en el que participas en \"{{documentTitle}}\".",
+ "document_comment_activity_thread_title": "Nueva respuesta en tu hilo de comentarios",
"document_comment_activity_title": "Nuevo comentario en tu documento",
"document_comment_mentioned": "{{actorLabel}} te mencionó en un comentario en \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Fuiste mencionado en un comentario de un documento",
diff --git a/locales/fa-IR/file.json b/locales/fa-IR/file.json
index d6929409abd..f769b76fec1 100644
--- a/locales/fa-IR/file.json
+++ b/locales/fa-IR/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "عضو سابق",
"pageEditor.comments.cancel": "لغو",
"pageEditor.comments.createFailed": "انتشار نظر ناموفق بود. پیش‌نویس شما هنوز موجود است.",
+ "pageEditor.comments.deepLinkLoadFailed": "بارگذاری نظر مرتبط انجام نشد. دوباره تلاش کنید.",
+ "pageEditor.comments.deepLinkMissing": "این نظر دیگر در دسترس نیست.",
"pageEditor.comments.delete": "حذف",
"pageEditor.comments.deleteConfirm.content": "آیا این نظر حذف شود؟ پاسخ‌ها همچنان قابل مشاهده خواهند بود اگر این نظر دارای رشته‌ای باشد.",
"pageEditor.comments.deleteConfirm.title": "حذف نظر",
diff --git a/locales/fa-IR/notification.json b/locales/fa-IR/notification.json
index f5f2abcc702..8808fff83d7 100644
--- a/locales/fa-IR/notification.json
+++ b/locales/fa-IR/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} روی سند شما \"{{documentTitle}}\" نظر داد.",
"document_comment_activity_replied": "{{actorLabel}} به نظر شما در \"{{documentTitle}}\" پاسخ داد.",
"document_comment_activity_replied_title": "پاسخ جدید به نظر شما",
+ "document_comment_activity_thread": "{{actorLabel}} در یک رشته نظر که شما بخشی از آن هستید در \"{{documentTitle}}\" پاسخ داد.",
+ "document_comment_activity_thread_title": "پاسخ جدید در رشته نظر شما",
"document_comment_activity_title": "نظر جدید روی سند شما",
"document_comment_mentioned": "{{actorLabel}} شما را در نظری روی \"{{documentTitle}}\" ذکر کرد.",
"document_comment_mentioned_title": "شما در یک نظر سند ذکر شدید",
diff --git a/locales/fr-FR/file.json b/locales/fr-FR/file.json
index f735d263bdc..fd24d3a38ee 100644
--- a/locales/fr-FR/file.json
+++ b/locales/fr-FR/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "Ancien membre",
"pageEditor.comments.cancel": "Annuler",
"pageEditor.comments.createFailed": "Échec de la publication du commentaire. Votre brouillon est toujours là.",
+ "pageEditor.comments.deepLinkLoadFailed": "Échec du chargement du commentaire lié. Veuillez réessayer.",
+ "pageEditor.comments.deepLinkMissing": "Ce commentaire n'est plus disponible.",
"pageEditor.comments.delete": "Supprimer",
"pageEditor.comments.deleteConfirm.content": "Supprimer ce commentaire ? Les réponses resteront visibles si ce commentaire a un fil de discussion.",
"pageEditor.comments.deleteConfirm.title": "Supprimer le commentaire",
diff --git a/locales/fr-FR/notification.json b/locales/fr-FR/notification.json
index 2411a59b78a..0c7caffff3b 100644
--- a/locales/fr-FR/notification.json
+++ b/locales/fr-FR/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} a commenté votre document \"{{documentTitle}}\".",
"document_comment_activity_replied": "{{actorLabel}} a répondu à votre commentaire dans \"{{documentTitle}}\".",
"document_comment_activity_replied_title": "Nouvelle réponse à votre commentaire",
+ "document_comment_activity_thread": "{{actorLabel}} a répondu dans un fil de commentaires auquel vous participez dans \"{{documentTitle}}\".",
+ "document_comment_activity_thread_title": "Nouvelle réponse dans votre fil de commentaires",
"document_comment_activity_title": "Nouveau commentaire sur votre document",
"document_comment_mentioned": "{{actorLabel}} vous a mentionné dans un commentaire sur \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Vous avez été mentionné dans un commentaire de document",
diff --git a/locales/it-IT/file.json b/locales/it-IT/file.json
index fa673cc7be9..5bee72d3373 100644
--- a/locales/it-IT/file.json
+++ b/locales/it-IT/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "Ex membro",
"pageEditor.comments.cancel": "Annulla",
"pageEditor.comments.createFailed": "Impossibile pubblicare il commento. La tua bozza è ancora qui.",
+ "pageEditor.comments.deepLinkLoadFailed": "Impossibile caricare il commento collegato. Riprova.",
+ "pageEditor.comments.deepLinkMissing": "Questo commento non è più disponibile.",
"pageEditor.comments.delete": "Elimina",
"pageEditor.comments.deleteConfirm.content": "Eliminare questo commento? Le risposte rimarranno visibili se questo commento ha un thread.",
"pageEditor.comments.deleteConfirm.title": "Elimina commento",
diff --git a/locales/it-IT/notification.json b/locales/it-IT/notification.json
index 1b2c4278b61..8ce9abcb304 100644
--- a/locales/it-IT/notification.json
+++ b/locales/it-IT/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} ha commentato il tuo documento \"{{documentTitle}}\".",
"document_comment_activity_replied": "{{actorLabel}} ha risposto al tuo commento in \"{{documentTitle}}\".",
"document_comment_activity_replied_title": "Nuova risposta al tuo commento",
+ "document_comment_activity_thread": "{{actorLabel}} ha risposto in un thread di commenti di cui fai parte in \"{{documentTitle}}\".",
+ "document_comment_activity_thread_title": "Nuova risposta nel tuo thread di commenti",
"document_comment_activity_title": "Nuovo commento sul tuo documento",
"document_comment_mentioned": "{{actorLabel}} ti ha menzionato in un commento su \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Sei stato menzionato in un commento sul documento",
diff --git a/locales/ja-JP/file.json b/locales/ja-JP/file.json
index 6a2d97556d5..8d7de5ce106 100644
--- a/locales/ja-JP/file.json
+++ b/locales/ja-JP/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "元メンバー",
"pageEditor.comments.cancel": "キャンセル",
"pageEditor.comments.createFailed": "コメントの投稿に失敗しました。下書きはそのまま残っています。",
+ "pageEditor.comments.deepLinkLoadFailed": "リンクされたコメントの読み込みに失敗しました。再試行してください。",
+ "pageEditor.comments.deepLinkMissing": "このコメントはもう利用できません。",
"pageEditor.comments.delete": "削除",
"pageEditor.comments.deleteConfirm.content": "このコメントを削除しますか?スレッドがある場合、返信は表示されたままになります。",
"pageEditor.comments.deleteConfirm.title": "コメントを削除",
diff --git a/locales/ja-JP/notification.json b/locales/ja-JP/notification.json
index 15b63c79e91..ce1ac9cb3c7 100644
--- a/locales/ja-JP/notification.json
+++ b/locales/ja-JP/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}}があなたのドキュメント「{{documentTitle}}」にコメントしました。",
"document_comment_activity_replied": "{{actorLabel}}が「{{documentTitle}}」内のあなたのコメントに返信しました。",
"document_comment_activity_replied_title": "あなたのコメントへの新しい返信",
+ "document_comment_activity_thread": "{{actorLabel}} があなたが参加しているコメントスレッドで「{{documentTitle}}」に返信しました。",
+ "document_comment_activity_thread_title": "あなたのコメントスレッドに新しい返信があります",
"document_comment_activity_title": "あなたのドキュメントへの新しいコメント",
"document_comment_mentioned": "{{actorLabel}}が「{{documentTitle}}」のコメントであなたに言及しました。",
"document_comment_mentioned_title": "ドキュメントのコメントで言及されました",
diff --git a/locales/ko-KR/file.json b/locales/ko-KR/file.json
index fb8f3da44ff..0a371070be5 100644
--- a/locales/ko-KR/file.json
+++ b/locales/ko-KR/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "이전 멤버",
"pageEditor.comments.cancel": "취소",
"pageEditor.comments.createFailed": "댓글 게시에 실패했습니다. 작성 중인 초안은 여전히 남아 있습니다.",
+ "pageEditor.comments.deepLinkLoadFailed": "연결된 댓글을 불러오지 못했습니다. 다시 시도해 주세요.",
+ "pageEditor.comments.deepLinkMissing": "이 댓글은 더 이상 사용할 수 없습니다.",
"pageEditor.comments.delete": "삭제",
"pageEditor.comments.deleteConfirm.content": "이 댓글을 삭제하시겠습니까? 댓글에 스레드가 있는 경우 답글은 계속 표시됩니다.",
"pageEditor.comments.deleteConfirm.title": "댓글 삭제",
diff --git a/locales/ko-KR/notification.json b/locales/ko-KR/notification.json
index 63ebfb1183a..1c160ad7b3d 100644
--- a/locales/ko-KR/notification.json
+++ b/locales/ko-KR/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}}님이 귀하의 문서 \"{{documentTitle}}\"에 댓글을 남겼습니다.",
"document_comment_activity_replied": "{{actorLabel}}님이 \"{{documentTitle}}\"에서 귀하의 댓글에 답글을 남겼습니다.",
"document_comment_activity_replied_title": "귀하의 댓글에 대한 새 답글",
+ "document_comment_activity_thread": "{{actorLabel}}님이 \"{{documentTitle}}\"에서 참여 중인 댓글 스레드에 답글을 남겼습니다.",
+ "document_comment_activity_thread_title": "댓글 스레드에 새 답글이 있습니다",
"document_comment_activity_title": "귀하의 문서에 대한 새 댓글",
"document_comment_mentioned": "{{actorLabel}}님이 \"{{documentTitle}}\"의 댓글에서 귀하를 언급했습니다.",
"document_comment_mentioned_title": "문서 댓글에서 귀하가 언급되었습니다",
diff --git a/locales/nl-NL/file.json b/locales/nl-NL/file.json
index 33da29f22ee..e72d8d4c091 100644
--- a/locales/nl-NL/file.json
+++ b/locales/nl-NL/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "Voormalig lid",
"pageEditor.comments.cancel": "Annuleren",
"pageEditor.comments.createFailed": "Reactie plaatsen mislukt. Je concept is nog steeds hier.",
+ "pageEditor.comments.deepLinkLoadFailed": "Kan de gekoppelde opmerking niet laden. Probeer het opnieuw.",
+ "pageEditor.comments.deepLinkMissing": "Deze opmerking is niet langer beschikbaar.",
"pageEditor.comments.delete": "Verwijderen",
"pageEditor.comments.deleteConfirm.content": "Deze reactie verwijderen? Antwoorden blijven zichtbaar als deze reactie een thread heeft.",
"pageEditor.comments.deleteConfirm.title": "Reactie verwijderen",
diff --git a/locales/nl-NL/notification.json b/locales/nl-NL/notification.json
index d65b655199c..06f4fc445b4 100644
--- a/locales/nl-NL/notification.json
+++ b/locales/nl-NL/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} heeft een opmerking gemaakt over uw document \"{{documentTitle}}\".",
"document_comment_activity_replied": "{{actorLabel}} heeft gereageerd op uw opmerking in \"{{documentTitle}}\".",
"document_comment_activity_replied_title": "Nieuwe reactie op uw opmerking",
+ "document_comment_activity_thread": "{{actorLabel}} heeft gereageerd in een commentaarthread waar je deel van uitmaakt in \"{{documentTitle}}\".",
+ "document_comment_activity_thread_title": "Nieuwe reactie in jouw commentaarthread",
"document_comment_activity_title": "Nieuwe opmerking over uw document",
"document_comment_mentioned": "{{actorLabel}} heeft u genoemd in een opmerking over \"{{documentTitle}}\".",
"document_comment_mentioned_title": "U bent genoemd in een documentopmerking",
diff --git a/locales/pl-PL/file.json b/locales/pl-PL/file.json
index 15d11b51e19..f5046d5f2ef 100644
--- a/locales/pl-PL/file.json
+++ b/locales/pl-PL/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "Były członek",
"pageEditor.comments.cancel": "Anuluj",
"pageEditor.comments.createFailed": "Nie udało się opublikować komentarza. Twój szkic nadal tutaj jest.",
+ "pageEditor.comments.deepLinkLoadFailed": "Nie udało się załadować powiązanego komentarza. Spróbuj ponownie.",
+ "pageEditor.comments.deepLinkMissing": "Ten komentarz nie jest już dostępny.",
"pageEditor.comments.delete": "Usuń",
"pageEditor.comments.deleteConfirm.content": "Usunąć ten komentarz? Odpowiedzi pozostaną widoczne, jeśli ten komentarz ma wątek.",
"pageEditor.comments.deleteConfirm.title": "Usuń komentarz",
diff --git a/locales/pl-PL/notification.json b/locales/pl-PL/notification.json
index ffd9142737e..f50c723bedf 100644
--- a/locales/pl-PL/notification.json
+++ b/locales/pl-PL/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} skomentował Twój dokument \"{{documentTitle}}\".",
"document_comment_activity_replied": "{{actorLabel}} odpowiedział na Twój komentarz w \"{{documentTitle}}\".",
"document_comment_activity_replied_title": "Nowa odpowiedź na Twój komentarz",
+ "document_comment_activity_thread": "{{actorLabel}} odpowiedział(a) w wątku komentarzy, w którym uczestniczysz, w \"{{documentTitle}}\".",
+ "document_comment_activity_thread_title": "Nowa odpowiedź w Twoim wątku komentarzy",
"document_comment_activity_title": "Nowy komentarz do Twojego dokumentu",
"document_comment_mentioned": "{{actorLabel}} wspomniał Cię w komentarzu do \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Zostałeś wspomniany w komentarzu do dokumentu",
diff --git a/locales/pt-BR/file.json b/locales/pt-BR/file.json
index 3026c28d203..b0ba7d148f1 100644
--- a/locales/pt-BR/file.json
+++ b/locales/pt-BR/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "Ex-membro",
"pageEditor.comments.cancel": "Cancelar",
"pageEditor.comments.createFailed": "Falha ao publicar o comentário. Seu rascunho ainda está aqui.",
+ "pageEditor.comments.deepLinkLoadFailed": "Falha ao carregar o comentário vinculado. Tente novamente.",
+ "pageEditor.comments.deepLinkMissing": "Este comentário não está mais disponível.",
"pageEditor.comments.delete": "Excluir",
"pageEditor.comments.deleteConfirm.content": "Excluir este comentário? As respostas permanecerão visíveis se este comentário tiver um encadeamento.",
"pageEditor.comments.deleteConfirm.title": "Excluir comentário",
diff --git a/locales/pt-BR/notification.json b/locales/pt-BR/notification.json
index 669ffad8adf..a8e68d6aa27 100644
--- a/locales/pt-BR/notification.json
+++ b/locales/pt-BR/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} comentou no seu documento \"{{documentTitle}}\".",
"document_comment_activity_replied": "{{actorLabel}} respondeu ao seu comentário em \"{{documentTitle}}\".",
"document_comment_activity_replied_title": "Nova resposta ao seu comentário",
+ "document_comment_activity_thread": "{{actorLabel}} respondeu em um tópico de comentário do qual você faz parte em \"{{documentTitle}}\".",
+ "document_comment_activity_thread_title": "Nova resposta no seu tópico de comentário",
"document_comment_activity_title": "Novo comentário no seu documento",
"document_comment_mentioned": "{{actorLabel}} mencionou você em um comentário no \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Você foi mencionado em um comentário de documento",
diff --git a/locales/ru-RU/file.json b/locales/ru-RU/file.json
index 2fe8b2578cd..72e760ece8c 100644
--- a/locales/ru-RU/file.json
+++ b/locales/ru-RU/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "Бывший участник",
"pageEditor.comments.cancel": "Отмена",
"pageEditor.comments.createFailed": "Не удалось опубликовать комментарий. Ваш черновик все еще здесь.",
+ "pageEditor.comments.deepLinkLoadFailed": "Не удалось загрузить связанный комментарий. Попробуйте еще раз.",
+ "pageEditor.comments.deepLinkMissing": "Этот комментарий больше недоступен.",
"pageEditor.comments.delete": "Удалить",
"pageEditor.comments.deleteConfirm.content": "Удалить этот комментарий? Ответы останутся видимыми, если у этого комментария есть ветка.",
"pageEditor.comments.deleteConfirm.title": "Удалить комментарий",
diff --git a/locales/ru-RU/notification.json b/locales/ru-RU/notification.json
index aa441a07c3f..e9e6139f612 100644
--- a/locales/ru-RU/notification.json
+++ b/locales/ru-RU/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} оставил комментарий к вашему документу \"{{documentTitle}}\".",
"document_comment_activity_replied": "{{actorLabel}} ответил на ваш комментарий в \"{{documentTitle}}\".",
"document_comment_activity_replied_title": "Новый ответ на ваш комментарий",
+ "document_comment_activity_thread": "{{actorLabel}} ответил в ветке комментариев, в которой вы участвуете, в \"{{documentTitle}}\".",
+ "document_comment_activity_thread_title": "Новый ответ в вашей ветке комментариев",
"document_comment_activity_title": "Новый комментарий к вашему документу",
"document_comment_mentioned": "{{actorLabel}} упомянул вас в комментарии к \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Вы были упомянуты в комментарии к документу",
diff --git a/locales/tr-TR/file.json b/locales/tr-TR/file.json
index d58a12ce849..0319734210b 100644
--- a/locales/tr-TR/file.json
+++ b/locales/tr-TR/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "Eski üye",
"pageEditor.comments.cancel": "İptal",
"pageEditor.comments.createFailed": "Yorum yayınlanamadı. Taslağınız hala burada.",
+ "pageEditor.comments.deepLinkLoadFailed": "Bağlantılı yorumu yükleme başarısız oldu. Tekrar deneyin.",
+ "pageEditor.comments.deepLinkMissing": "Bu yorum artık mevcut değil.",
"pageEditor.comments.delete": "Sil",
"pageEditor.comments.deleteConfirm.content": "Bu yorumu silmek istiyor musunuz? Eğer bu yorumun bir dizisi varsa, yanıtlar görünür kalacaktır.",
"pageEditor.comments.deleteConfirm.title": "Yorumu sil",
diff --git a/locales/tr-TR/notification.json b/locales/tr-TR/notification.json
index 9e8b1604837..319e129d5f3 100644
--- a/locales/tr-TR/notification.json
+++ b/locales/tr-TR/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} belgeniz \"{{documentTitle}}\" üzerinde yorum yaptı.",
"document_comment_activity_replied": "{{actorLabel}} \"{{documentTitle}}\" içindeki yorumunuza yanıt verdi.",
"document_comment_activity_replied_title": "Yorumunuza yeni bir yanıt",
+ "document_comment_activity_thread": "{{actorLabel}}, \"{{documentTitle}}\" adlı belgede bulunduğunuz bir yorum dizisinde yanıt verdi.",
+ "document_comment_activity_thread_title": "Yorum dizinizde yeni bir yanıt",
"document_comment_activity_title": "Belgenizde yeni bir yorum",
"document_comment_mentioned": "{{actorLabel}} \"{{documentTitle}}\" üzerindeki bir yorumda sizi bahsetti.",
"document_comment_mentioned_title": "Bir belge yorumunda bahsedildiniz",
diff --git a/locales/vi-VN/file.json b/locales/vi-VN/file.json
index b2ae66eb983..31e15c84bd4 100644
--- a/locales/vi-VN/file.json
+++ b/locales/vi-VN/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "Thành viên cũ",
"pageEditor.comments.cancel": "Hủy",
"pageEditor.comments.createFailed": "Không thể đăng bình luận. Bản nháp của bạn vẫn còn ở đây.",
+ "pageEditor.comments.deepLinkLoadFailed": "Không thể tải nhận xét được liên kết. Vui lòng thử lại.",
+ "pageEditor.comments.deepLinkMissing": "Bình luận này không còn khả dụng.",
"pageEditor.comments.delete": "Xóa",
"pageEditor.comments.deleteConfirm.content": "Xóa bình luận này? Các phản hồi sẽ vẫn hiển thị nếu bình luận này có chuỗi.",
"pageEditor.comments.deleteConfirm.title": "Xóa bình luận",
diff --git a/locales/vi-VN/notification.json b/locales/vi-VN/notification.json
index 3f382a90e16..f7c3db4fa98 100644
--- a/locales/vi-VN/notification.json
+++ b/locales/vi-VN/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} đã bình luận về tài liệu của bạn \"{{documentTitle}}\".",
"document_comment_activity_replied": "{{actorLabel}} đã trả lời bình luận của bạn trong \"{{documentTitle}}\".",
"document_comment_activity_replied_title": "Phản hồi mới cho bình luận của bạn",
+ "document_comment_activity_thread": "{{actorLabel}} đã trả lời trong một chuỗi bình luận mà bạn tham gia trong \"{{documentTitle}}\".",
+ "document_comment_activity_thread_title": "Phản hồi mới trong chuỗi bình luận của bạn",
"document_comment_activity_title": "Bình luận mới về tài liệu của bạn",
"document_comment_mentioned": "{{actorLabel}} đã nhắc đến bạn trong một bình luận về \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Bạn đã được nhắc đến trong một bình luận tài liệu",
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.json
index f5c8d9c10c6..8dcaf9de73f 100644
--- a/locales/zh-CN/file.json
+++ b/locales/zh-CN/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "前成员",
"pageEditor.comments.cancel": "取消",
"pageEditor.comments.createFailed": "评论发布失败,草稿已为你保留",
+ "pageEditor.comments.deepLinkLoadFailed": "链接的评论加载失败,请重试",
+ "pageEditor.comments.deepLinkMissing": "这条评论已不存在",
"pageEditor.comments.delete": "删除",
"pageEditor.comments.deleteConfirm.content": "确定删除这条评论吗?如果评论下有回复,回复仍会保留。",
"pageEditor.comments.deleteConfirm.title": "删除评论",
diff --git a/locales/zh-CN/notification.json b/locales/zh-CN/notification.json
index 74aa7465099..4757c4a04a5 100644
--- a/locales/zh-CN/notification.json
+++ b/locales/zh-CN/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} 评论了你的文档「{{documentTitle}}」。",
"document_comment_activity_replied": "{{actorLabel}} 在「{{documentTitle}}」中回复了你的评论。",
"document_comment_activity_replied_title": "你的评论有新回复",
+ "document_comment_activity_thread": "{{actorLabel}} 在「{{documentTitle}}」中你参与的评论线程里发表了回复。",
+ "document_comment_activity_thread_title": "你参与的评论线程有新回复",
"document_comment_activity_title": "你的文档有新评论",
"document_comment_mentioned": "{{actorLabel}} 在文档「{{documentTitle}}」的评论中提到了你。",
"document_comment_mentioned_title": "你在文档评论中被提及",
diff --git a/locales/zh-TW/file.json b/locales/zh-TW/file.json
index 6aab5f47ce7..8091e4bdc5e 100644
--- a/locales/zh-TW/file.json
+++ b/locales/zh-TW/file.json
@@ -100,6 +100,8 @@
"pageEditor.comments.author.former": "前成員",
"pageEditor.comments.cancel": "取消",
"pageEditor.comments.createFailed": "發佈評論失敗。您的草稿仍然保留。",
+ "pageEditor.comments.deepLinkLoadFailed": "無法載入連結的評論。請再試一次。",
+ "pageEditor.comments.deepLinkMissing": "此評論已不再可用。",
"pageEditor.comments.delete": "刪除",
"pageEditor.comments.deleteConfirm.content": "確定要刪除此評論嗎?如果此評論有回覆,回覆仍會顯示。",
"pageEditor.comments.deleteConfirm.title": "刪除評論",
diff --git a/locales/zh-TW/notification.json b/locales/zh-TW/notification.json
index 03b63d8671e..0bb0fb16d38 100644
--- a/locales/zh-TW/notification.json
+++ b/locales/zh-TW/notification.json
@@ -37,6 +37,8 @@
"document_comment_activity": "{{actorLabel}} 在您的文件「{{documentTitle}}」中留下了評論。",
"document_comment_activity_replied": "{{actorLabel}} 回覆了您在「{{documentTitle}}」中的評論。",
"document_comment_activity_replied_title": "您的評論有新的回覆",
+ "document_comment_activity_thread": "{{actorLabel}} 在您參與的「{{documentTitle}}」評論串中回覆了。",
+ "document_comment_activity_thread_title": "您的評論串有新回覆",
"document_comment_activity_title": "您的文件有新的評論",
"document_comment_mentioned": "{{actorLabel}} 在「{{documentTitle}}」的評論中提到了您。",
"document_comment_mentioned_title": "您在文件評論中被提及",
diff --git a/packages/database/src/models/__tests__/documentComment.test.ts b/packages/database/src/models/__tests__/documentComment.test.ts
index 5bd769254da..13841d97d5d 100644
--- a/packages/database/src/models/__tests__/documentComment.test.ts
+++ b/packages/database/src/models/__tests__/documentComment.test.ts
@@ -147,6 +147,73 @@ describe('DocumentCommentModel', () => {
});
});
+ it('collects thread participants for replies and skips tombstoned reply targets', async () => {
+ const outsiderInWorkspaceModel = new DocumentCommentModel(serverDB, outsiderId, workspaceId);
+ const root = await authorModel.create({ clientId: 'root', content: 'root', documentId });
+ expect(root.threadParticipantUserIds).toEqual([]);
+
+ const memberReply = await memberModel.create({
+ clientId: 'member-reply',
+ content: 'member',
+ documentId,
+ parentCommentId: root.comment.id,
+ });
+ // First reply: only the root author is in the thread, and they are the
+ // direct target, so nobody else needs the weaker thread ping.
+ expect(memberReply.parentAuthorUserId).toBe(authorId);
+ expect(memberReply.threadParticipantUserIds).toEqual([]);
+
+ const outsiderReply = await outsiderInWorkspaceModel.create({
+ clientId: 'outsider-reply',
+ content: 'outsider',
+ documentId,
+ parentCommentId: memberReply.comment.id,
+ });
+ // Replying to the member's reply: member gets `replied`, root author is a
+ // thread participant, the actor is excluded.
+ expect(outsiderReply.parentAuthorUserId).toBe(memberId);
+ expect(outsiderReply.threadParticipantUserIds).toEqual([authorId]);
+
+ const authorReply = await authorModel.create({
+ clientId: 'author-reply',
+ content: 'author again',
+ documentId,
+ parentCommentId: root.comment.id,
+ });
+ // Root author replying to their own root: no direct target ping, the two
+ // other repliers are participants.
+ expect(authorReply.parentAuthorUserId).toBe(authorId);
+ expect(new Set(authorReply.threadParticipantUserIds)).toEqual(new Set([memberId, outsiderId]));
+
+ // Only roots leave tombstones (replies to replies are flattened). Tombstone
+ // the root and reply to it: the deleted comment's author must not be a
+ // target, and the live repliers are still participants.
+ expect(await authorModel.delete(root.comment.id)).toBe('soft');
+ const replyToTombstone = await memberModel.create({
+ clientId: 'reply-to-tombstone',
+ content: 'still here?',
+ documentId,
+ parentCommentId: root.comment.id,
+ });
+ expect(replyToTombstone.parentAuthorUserId).toBeNull();
+ // The root author stays a participant through their live reply.
+ expect(new Set(replyToTombstone.threadParticipantUserIds)).toEqual(
+ new Set([authorId, outsiderId]),
+ );
+ expect(replyToTombstone.comment).toMatchObject({
+ parentCommentId: root.comment.id,
+ replyToCommentId: null,
+ });
+
+ const duplicate = await memberModel.create({
+ clientId: 'reply-to-tombstone',
+ content: 'still here?',
+ documentId,
+ parentCommentId: root.comment.id,
+ });
+ expect(duplicate).toMatchObject({ isDuplicate: true, threadParticipantUserIds: [] });
+ });
+
it('scopes updates and deletes to the author unless explicitly overridden', async () => {
const created = await authorModel.create({
clientId: 'owned',
@@ -349,5 +416,14 @@ describe('DocumentCommentModel', () => {
.where(eq(documentComments.id, oldRoot.id));
expect(await authorModel.summary(documentId)).toEqual({ total: 3 });
expect(await outsiderModel.summary(foreignDocumentId)).toEqual({ total: 0 });
+
+ // Single-thread lookup for deep links: live replies only, scoped to the workspace.
+ expect(await authorModel.countLiveReplies(oldRoot.id)).toBe(2);
+ expect(await outsiderModel.countLiveReplies(oldRoot.id)).toBe(0);
+ await serverDB
+ .update(documentComments)
+ .set({ deletedAt: new Date() })
+ .where(eq(documentComments.clientId, 'reply-2'));
+ expect(await authorModel.countLiveReplies(oldRoot.id)).toBe(1);
});
});
diff --git a/packages/database/src/models/documentComment.ts b/packages/database/src/models/documentComment.ts
index d89cd564db6..dad815f8df2 100644
--- a/packages/database/src/models/documentComment.ts
+++ b/packages/database/src/models/documentComment.ts
@@ -46,8 +46,17 @@ export interface CreateDocumentCommentResult {
documentAuthorUserId: string;
/** true when the idempotency key already existed and no new activity should be emitted */
isDuplicate: boolean;
- /** Author of the directly targeted comment when creating a reply. */
+ /**
+ * Author of the directly targeted comment when creating a reply. Null when
+ * the target is a tombstone so nobody is pinged about a deleted comment.
+ */
parentAuthorUserId?: string | null;
+ /**
+ * Everyone else already talking in the thread when creating a reply: the
+ * root author plus authors of live replies, minus the actor and the direct
+ * reply target (who receives the stronger `replied` ping instead).
+ */
+ threadParticipantUserIds: string[];
}
export interface UpdateDocumentCommentParams {
@@ -112,10 +121,12 @@ export class DocumentCommentModel {
let parentCommentId: string | null = null;
let parentAuthorUserId: string | null | undefined;
let replyToCommentId: string | null = null;
+ let threadParticipantUserIds: string[] = [];
if (params.parentCommentId) {
const [parent] = await tx
.select({
authorUserId: documentComments.authorUserId,
+ deletedAt: documentComments.deletedAt,
documentId: documentComments.documentId,
id: documentComments.id,
parentCommentId: documentComments.parentCommentId,
@@ -133,9 +144,30 @@ export class DocumentCommentModel {
) {
throw new Error(DOCUMENT_COMMENT_PARENT_NOT_FOUND);
}
- parentAuthorUserId = parent.authorUserId;
+ parentAuthorUserId = parent.deletedAt ? null : parent.authorUserId;
parentCommentId = parent.parentCommentId ?? parent.id;
replyToCommentId = parent.parentCommentId ? parent.id : null;
+
+ const threadMembers = await tx
+ .select({ authorUserId: documentComments.authorUserId })
+ .from(documentComments)
+ .where(
+ and(
+ or(
+ eq(documentComments.id, parentCommentId),
+ eq(documentComments.parentCommentId, parentCommentId),
+ ),
+ eq(documentComments.workspaceId, workspaceId),
+ isNull(documentComments.deletedAt),
+ ),
+ )
+ .groupBy(documentComments.authorUserId);
+ threadParticipantUserIds = threadMembers
+ .map(({ authorUserId }) => authorUserId)
+ .filter(
+ (userId): userId is string =>
+ Boolean(userId) && userId !== this.userId && userId !== parentAuthorUserId,
+ );
}
const [inserted] = await tx
@@ -180,6 +212,7 @@ export class DocumentCommentModel {
documentAuthorUserId: document.userId,
isDuplicate: false,
parentAuthorUserId,
+ threadParticipantUserIds,
};
}
@@ -202,6 +235,7 @@ export class DocumentCommentModel {
documentAuthorUserId: document.userId,
isDuplicate: true,
parentAuthorUserId,
+ threadParticipantUserIds: [],
};
});
}
@@ -361,6 +395,22 @@ export class DocumentCommentModel {
return comment;
}
+ /** Live (non-tombstoned) replies under one root, for a single-thread lookup. */
+ async countLiveReplies(rootCommentId: string) {
+ const workspaceId = this.requireWorkspaceId();
+ const [row] = await this.db
+ .select({ total: count() })
+ .from(documentComments)
+ .where(
+ and(
+ eq(documentComments.workspaceId, workspaceId),
+ eq(documentComments.parentCommentId, rootCommentId),
+ isNull(documentComments.deletedAt),
+ ),
+ );
+ return row?.total ?? 0;
+ }
+
async listThreads(params: ListDocumentCommentThreadsParams) {
const workspaceId = this.requireWorkspaceId();
const { cursor, documentId, limit = 20 } = params;
diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.ts
index 2b9a92f33a7..f7815adb9a6 100644
--- a/packages/locales/src/default/file.ts
+++ b/packages/locales/src/default/file.ts
@@ -112,6 +112,8 @@ export default {
'pageEditor.comments.attachments.chooseLibrary': 'Choose from Library',
'pageEditor.comments.cancel': 'Cancel',
'pageEditor.comments.createFailed': 'Failed to publish comment. Your draft is still here.',
+ 'pageEditor.comments.deepLinkLoadFailed': 'Failed to load the linked comment. Try again.',
+ 'pageEditor.comments.deepLinkMissing': 'This comment is no longer available.',
'pageEditor.comments.delete': 'Delete',
'pageEditor.comments.deleteConfirm.content':
'Delete this comment? Replies will remain visible if this comment has a thread.',
diff --git a/packages/locales/src/default/notification.ts b/packages/locales/src/default/notification.ts
index 1cda8b0d080..c5b33e31366 100644
--- a/packages/locales/src/default/notification.ts
+++ b/packages/locales/src/default/notification.ts
@@ -93,6 +93,9 @@ export default {
'{{actorLabel}} replied to your comment in "{{documentTitle}}".',
'document_comment_activity_replied_title': 'New reply to your comment',
'document_comment_activity_title': 'New comment on your document',
+ 'document_comment_activity_thread':
+ '{{actorLabel}} replied in a comment thread you\'re part of in "{{documentTitle}}".',
+ 'document_comment_activity_thread_title': 'New reply in your comment thread',
'document_comment_mentioned': '{{actorLabel}} mentioned you in a comment on "{{documentTitle}}".',
'document_comment_mentioned_title': 'You were mentioned in a document comment',
'document_liked': '{{actorLabel}} liked your document "{{documentTitle}}".',
diff --git a/packages/types/src/documentComment.ts b/packages/types/src/documentComment.ts
index 937dacd0b24..b842a5094a3 100644
--- a/packages/types/src/documentComment.ts
+++ b/packages/types/src/documentComment.ts
@@ -30,6 +30,11 @@ export interface DocumentCommentItem {
workspaceId: string;
}
+/** One comment fetched by id; roots also carry their live reply count. */
+export interface DocumentCommentDetail extends DocumentCommentItem {
+ replyCount: number;
+}
+
export interface DocumentCommentThread {
replyCount: number;
root: DocumentCommentItem;
diff --git a/src/business/server/document-comment/notifyActivity.ts b/src/business/server/document-comment/notifyActivity.ts
index df845d0f7c1..1aef8778c84 100644
--- a/src/business/server/document-comment/notifyActivity.ts
+++ b/src/business/server/document-comment/notifyActivity.ts
@@ -1,4 +1,10 @@
-export type DocumentCommentActivityKind = 'commented' | 'mentioned' | 'replied';
+/**
+ * - `commented`: a new root comment on a document the recipient authored
+ * - `replied`: a reply whose direct target the recipient authored
+ * - `thread`: a reply in a thread the recipient already participates in
+ * - `mentioned`: the recipient was @-mentioned in the comment
+ */
+export type DocumentCommentActivityKind = 'commented' | 'mentioned' | 'replied' | 'thread';
export interface NotifyDocumentCommentActivityParams {
actorUserId: string;
diff --git a/src/features/ChatInput/useEditorRootLifecycle.test.ts b/src/features/ChatInput/useEditorRootLifecycle.test.ts
index 9ba40b430b3..d411562c368 100644
--- a/src/features/ChatInput/useEditorRootLifecycle.test.ts
+++ b/src/features/ChatInput/useEditorRootLifecycle.test.ts
@@ -86,13 +86,18 @@ const renderRealEditor = ({ lifecycle }: { lifecycle: boolean }) => {
};
describe('useEditorRootLifecycle with a real editor', () => {
- it('leaks the kernel into the global registry when the lifecycle is not applied', async () => {
+ it('leaves the kernel alive when the lifecycle is not applied', async () => {
const { editor, unmount } = renderRealEditor({ lifecycle: false });
await waitFor(() => expect(rootOf(editor())).toBeTruthy());
+ const destroy = vi.spyOn(editor(), 'destroy');
unmount();
await new Promise((resolve) => setTimeout(resolve, 20));
- expect(isRegistered(editor())).toBe(true);
+ // Whether an orphaned kernel lingers in the global registry is the editor
+ // library's concern (>= 4.25.1 unregisters it on root detach); what the
+ // lifecycle adds is destroying it, so that is the observable difference.
+ expect(destroy).not.toHaveBeenCalled();
+ expect(editor().getLexicalEditor()).not.toBeNull();
});
it('destroys the kernel on a direct visible unmount', async () => {
@@ -107,11 +112,17 @@ describe('useEditorRootLifecycle with a real editor', () => {
const { editor, rerender, tree } = renderRealEditor({ lifecycle: true });
await waitFor(() => expect(rootOf(editor())).toBeTruthy());
const root = rootOf(editor());
+ const lexicalEditor = editor().getLexicalEditor();
+ const destroy = vi.spyOn(editor(), 'destroy');
rerender(tree('hidden'));
expect(rootOf(editor())).toBeNull();
expect(root!.isConnected).toBe(true);
- expect(isRegistered(editor())).toBe(true);
+ // Registry membership while hidden depends on the editor version (>= 4.25.1
+ // unregisters until the root is re-attached, see the "revealed" case); the
+ // hook's guarantee is that the kernel itself survives hiding.
+ expect(editor().getLexicalEditor()).toBe(lexicalEditor);
+ expect(destroy).not.toHaveBeenCalled();
});
it('restores the same root to the same kernel when revealed', async () => {
diff --git a/src/features/PageEditor/DocumentComments/CommentCard.tsx b/src/features/PageEditor/DocumentComments/CommentCard.tsx
index 0a2ec98d5c7..0d9cbf2ebb6 100644
--- a/src/features/PageEditor/DocumentComments/CommentCard.tsx
+++ b/src/features/PageEditor/DocumentComments/CommentCard.tsx
@@ -3,7 +3,7 @@ import { ChatInput, ChatInputActionBar, useEditor } from '@lobehub/editor/react'
import { Flexbox, Markdown } from '@lobehub/ui';
import { ActionIcon, Avatar, Button, confirmModal, Text, toast } from '@lobehub/ui/base-ui';
import { ChevronRight, MessageCircle, Pencil, Trash } from 'lucide-react';
-import { memo, useCallback, useRef, useState } from 'react';
+import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AttachmentMenu } from '@/features/AttachmentInput';
@@ -29,6 +29,8 @@ import { COMMENT_INPUT_MAX_HEIGHT, styles } from './styles';
interface CommentCardProps {
comment: DocumentCommentItem;
+ /** Set when a deep link targets this comment; each new token scrolls + highlights again. */
+ focusToken?: number;
onMutated: () => void | Promise<void>;
onReply?: () => void;
onUpdate: DocumentCommentUpdateHandler;
@@ -61,8 +63,9 @@ const CommentContent = memo<Pick<DocumentCommentItem, 'content' | 'editorData'>>
CommentContent.displayName = 'DocumentCommentContent';
const CommentCard = memo<CommentCardProps>(
- ({ comment, onMutated, onReply, onUpdate, replying, variant = 'root' }) => {
+ ({ comment, focusToken, onMutated, onReply, onUpdate, replying, variant = 'root' }) => {
const { t } = useTranslation('file');
+ const cardRef = useRef<HTMLDivElement>(null);
const { text: time, title: timeTitle } = useActivityTime(comment.createdAt);
const shouldSendOnEnter = useEnterToSend();
const [editing, setEditing] = useState(false);
@@ -88,6 +91,20 @@ const CommentCard = memo<CommentCardProps>(
(comment.replyTo ? t('pageEditor.comments.author.deactivated') : null);
const edited = new Date(comment.updatedAt).getTime() > new Date(comment.createdAt).getTime();
+ useEffect(() => {
+ const node = cardRef.current;
+ if (focusToken === undefined || !node) return;
+ // Honor reduced motion: jump instead of gliding; the steady highlight itself stays.
+ const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ node.scrollIntoView({ behavior: reduceMotion ? 'auto' : 'smooth', block: 'center' });
+ node.classList.add(styles.highlighted);
+ const timer = setTimeout(() => node.classList.remove(styles.highlighted), 2400);
+ return () => {
+ clearTimeout(timer);
+ node.classList.remove(styles.highlighted);
+ };
+ }, [focusToken]);
+
const handleUpdate = useCallback(async () => {
const editorValue: DocumentCommentEditorValue = editorRef.current?.getValue() ?? {
content,
@@ -154,6 +171,7 @@ const CommentCard = memo<CommentCardProps>(
<Flexbox
className={`${styles.card} ${variant === 'reply' ? styles.replyCard : ''}`}
data-document-comment-id={comment.id}
+ ref={cardRef}
>
<Flexbox horizontal align={'center'} className={styles.header} gap={8}>
<Avatar
diff --git a/src/features/PageEditor/DocumentComments/Thread.tsx b/src/features/PageEditor/DocumentComments/Thread.tsx
index 94b673524d5..3cc8e69340f 100644
--- a/src/features/PageEditor/DocumentComments/Thread.tsx
+++ b/src/features/PageEditor/DocumentComments/Thread.tsx
@@ -1,7 +1,7 @@
-import type { DocumentCommentThread } from '@lobechat/types';
+import type { DocumentCommentItem, DocumentCommentThread } from '@lobechat/types';
import { Center, Flexbox } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
-import { Fragment, memo, useCallback, useState } from 'react';
+import { Fragment, memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
@@ -10,7 +10,11 @@ import { documentCommentService } from '@/services/documentComment';
import CommentCard from './CommentCard';
import Composer from './Composer';
-import { useDocumentCommentReplies, useOptimisticDocumentComment } from './hooks';
+import {
+ useDocumentCommentDetail,
+ useDocumentCommentReplies,
+ useOptimisticDocumentComment,
+} from './hooks';
import type { DocumentCommentSubmitInput, DocumentCommentUpdateHandler } from './optimistic';
import {
appendOptimisticReply,
@@ -21,9 +25,17 @@ import {
} from './optimistic';
import { styles } from './styles';
import { useAutoLoadReplies } from './useAutoLoadReplies';
+import type {
+ DocumentCommentFocus,
+ DocumentCommentFocusMissReason,
+} from './useDocumentCommentDeepLink';
interface ThreadProps extends DocumentCommentThread {
documentId: string;
+ /** Deep-link target inside this thread; forces replies to load and highlights the card. */
+ focus?: DocumentCommentFocus;
+ /** The deep-linked reply is gone from this thread ('missing') or could not be loaded ('failed'). */
+ onFocusMissing?: (reason: DocumentCommentFocusMissReason) => void;
onMutated: () => void | Promise<void>;
onReplyCountChange: (rootCommentId: string, delta: number) => void | Promise<unknown>;
onRootUpdate: DocumentCommentUpdateHandler;
@@ -33,6 +45,8 @@ interface ThreadProps extends DocumentCommentThread {
const Thread = memo<ThreadProps>(
({
documentId,
+ focus,
+ onFocusMissing,
onMutated,
onReplyCountChange,
onRootUpdate,
@@ -43,19 +57,56 @@ const Thread = memo<ThreadProps>(
const { t } = useTranslation('file');
const [replyTargetId, setReplyTargetId] = useState<string | null>(null);
const { containerRef, shouldLoad } = useAutoLoadReplies(replyCount > 0);
- const replies = useDocumentCommentReplies(root.id, shouldLoad || Boolean(replyTargetId));
+ const focusedReplyId = focus && focus.commentId !== root.id ? focus.commentId : undefined;
+ const replies = useDocumentCommentReplies(
+ root.id,
+ shouldLoad || Boolean(replyTargetId) || Boolean(focusedReplyId),
+ );
const createOptimistic = useOptimisticDocumentComment();
const mutateReplies = replies.mutate;
const reloadReplies = replies.reload;
+ // The linked reply is fetched by id and shown first until it appears on a loaded page
+ // (replies are oldest-first). It lives in its own cache entry, so thread refreshes
+ // revalidate it too — a deleted pinned reply must not linger.
+ const hasFocusedReply =
+ Boolean(focusedReplyId) && replies.items.some((item) => item.id === focusedReplyId);
+ const focusedReply = useDocumentCommentDetail(hasFocusedReply ? undefined : focusedReplyId);
+ const mutateFocusedReply = focusedReply.mutate;
const refreshThread = useCallback(async () => {
- await Promise.all([reloadReplies(), onMutated()]);
- }, [onMutated, reloadReplies]);
+ // A post-delete 404 on the detail entry flows through `isNotFound`; it is not a failure.
+ await Promise.all([
+ reloadReplies(),
+ mutateFocusedReply().catch(() => undefined),
+ onMutated(),
+ ]);
+ }, [mutateFocusedReply, onMutated, reloadReplies]);
+ // Reply edits patch the paginated cache; mirror them into the pinned detail entry too.
+ const patchFocusedReply = useCallback(
+ (next: DocumentCommentItem) =>
+ mutateFocusedReply(
+ (current) => (current && current.id === next.id ? { ...current, ...next } : current),
+ { revalidate: false },
+ ),
+ [mutateFocusedReply],
+ );
+ // The deep-link target while it is not on a loaded page. It renders on its own, so a
+ // pending or failed page request never hides a reply that was already fetched.
+ const pinnedReply = useMemo(() => {
+ const pinned = focusedReply.data;
+ if (!pinned || hasFocusedReply || pinned.parentCommentId !== root.id) return undefined;
+ return pinned;
+ }, [focusedReply.data, hasFocusedReply, root.id]);
+ // Everything a reply action can target: the pinned reply plus the loaded pages.
+ const visibleReplies = useMemo(
+ () => (pinnedReply ? [pinnedReply, ...replies.items] : replies.items),
+ [pinnedReply, replies.items],
+ );
const handleReplySubmit = useCallback(
async ({ clientId, content, editorData }: DocumentCommentSubmitInput) => {
const replyTarget =
replyTargetId === root.id
? root
- : replies.items.find((item) => item.id === replyTargetId);
+ : visibleReplies.find((item) => item.id === replyTargetId);
if (!replyTarget) throw new Error('Document comment reply target is unavailable');
if (isOptimisticDocumentComment(replyTarget)) {
throw new Error('An optimistic document comment cannot be replied to');
@@ -116,56 +167,102 @@ const Thread = memo<ThreadProps>(
onSummaryChange,
refreshThread,
reloadReplies,
- replies.items,
replyTargetId,
root,
+ visibleReplies,
],
);
const handleReplyUpdate: DocumentCommentUpdateHandler = useCallback(
async (comment, value) => {
const optimisticComment = { ...comment, ...value, updatedAt: new Date() };
- await mutateReplies((pages) => replaceReplyComment(pages, optimisticComment), {
- revalidate: false,
- });
+ await Promise.all([
+ mutateReplies((pages) => replaceReplyComment(pages, optimisticComment), {
+ revalidate: false,
+ }),
+ patchFocusedReply(optimisticComment),
+ ]);
let updated: Awaited<ReturnType<typeof documentCommentService.update>>;
try {
updated = await documentCommentService.update({ ...value, id: comment.id });
if (!updated) throw new Error('Document comment reply update returned no result');
} catch (error) {
- await mutateReplies((pages) => replaceReplyComment(pages, comment), {
- revalidate: false,
- });
+ await Promise.all([
+ mutateReplies((pages) => replaceReplyComment(pages, comment), {
+ revalidate: false,
+ }),
+ patchFocusedReply(comment),
+ ]);
throw error;
}
try {
- await mutateReplies((pages) => replaceReplyComment(pages, updated), {
- revalidate: false,
- });
+ await Promise.all([
+ mutateReplies((pages) => replaceReplyComment(pages, updated), {
+ revalidate: false,
+ }),
+ patchFocusedReply(updated),
+ ]);
} catch (error) {
console.error('Failed to reconcile the updated document comment reply', error);
void reloadReplies();
}
},
- [mutateReplies, reloadReplies],
+ [mutateReplies, patchFocusedReply, reloadReplies],
);
+ // NOT_FOUND, or a reply from another thread, means the linked reply is gone; any other
+ // lookup failure is reported so the miss is never silent.
+ const isFocusedReplyMissing =
+ Boolean(focusedReplyId) &&
+ (focusedReply.isNotFound ||
+ Boolean(focusedReply.data && focusedReply.data.parentCommentId !== root.id));
+ const isFocusedReplyFailed =
+ Boolean(focusedReplyId) && Boolean(focusedReply.error) && !focusedReply.isNotFound;
+ useEffect(() => {
+ if (isFocusedReplyMissing) onFocusMissing?.('missing');
+ else if (isFocusedReplyFailed) onFocusMissing?.('failed');
+ }, [isFocusedReplyFailed, isFocusedReplyMissing, onFocusMissing]);
+
const toggleReplyTarget = useCallback((commentId: string) => {
setReplyTargetId((current) => (current === commentId ? null : commentId));
}, []);
+ const renderReply = (reply: DocumentCommentItem) => (
+ <Fragment key={reply.id}>
+ <CommentCard
+ comment={reply}
+ focusToken={focusedReplyId === reply.id ? focus?.token : undefined}
+ replying={replyTargetId === reply.id}
+ variant={'reply'}
+ onMutated={refreshThread}
+ onReply={() => toggleReplyTarget(reply.id)}
+ onUpdate={handleReplyUpdate}
+ />
+ {replyTargetId === reply.id && (
+ <Composer
+ documentId={documentId}
+ key={`reply:${reply.id}`}
+ parentCommentId={reply.id}
+ onSubmit={handleReplySubmit}
+ onSuccess={() => setReplyTargetId(null)}
+ />
+ )}
+ </Fragment>
+ );
+
return (
<Flexbox className={styles.thread} ref={containerRef}>
<CommentCard
comment={root}
+ focusToken={focus && focus.commentId === root.id ? focus.token : undefined}
replying={replyTargetId === root.id}
onMutated={onMutated}
onReply={() => toggleReplyTarget(root.id)}
onUpdate={onRootUpdate}
/>
- {(replyCount > 0 || replyTargetId) && (
+ {(replyCount > 0 || replyTargetId || focusedReplyId) && (
<Flexbox className={styles.replyList}>
{replyTargetId === root.id && (
<Composer
@@ -176,6 +273,7 @@ const Thread = memo<ThreadProps>(
onSuccess={() => setReplyTargetId(null)}
/>
)}
+ {pinnedReply && renderReply(pinnedReply)}
{replies.isLoadingInitial && replyCount > 0 ? (
<SurfaceSkeleton header={false} variant={'list'} />
) : replies.isInitialError ? (
@@ -185,27 +283,7 @@ const Thread = memo<ThreadProps>(
onRetry={() => void replies.reload()}
/>
) : (
- replies.items.map((reply) => (
- <Fragment key={reply.id}>
- <CommentCard
- comment={reply}
- replying={replyTargetId === reply.id}
- variant={'reply'}
- onMutated={refreshThread}
- onReply={() => toggleReplyTarget(reply.id)}
- onUpdate={handleReplyUpdate}
- />
- {replyTargetId === reply.id && (
- <Composer
- documentId={documentId}
- key={`reply:${reply.id}`}
- parentCommentId={reply.id}
- onSubmit={handleReplySubmit}
- onSuccess={() => setReplyTargetId(null)}
- />
- )}
- </Fragment>
- ))
+ replies.items.map(renderReply)
)}
{replies.error && !replies.isInitialError ? (
<AsyncError
diff --git a/src/features/PageEditor/DocumentComments/hooks.ts b/src/features/PageEditor/DocumentComments/hooks.ts
index a9909702513..482cd82ca13 100644
--- a/src/features/PageEditor/DocumentComments/hooks.ts
+++ b/src/features/PageEditor/DocumentComments/hooks.ts
@@ -1,4 +1,5 @@
import type {
+ DocumentCommentDetail,
DocumentCommentItem,
DocumentCommentReplyPage,
DocumentCommentSummary,
@@ -13,6 +14,7 @@ import { documentCommentKeys } from '@/libs/swr/keys';
import { documentCommentService } from '@/services/documentComment';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
+import { isTrpcErrorCode } from '@/utils/trpcError';
import {
createOptimisticComment,
@@ -62,6 +64,21 @@ export const useDocumentCommentSummary = (documentId?: string | null) =>
{ dedupingInterval: 30_000 },
);
+/**
+ * One comment by id. Lists are oldest-first and a notification usually points
+ * at the newest comment, so a deep link fetches its target directly instead of
+ * paging towards it; `isNotFound` means the comment is gone.
+ */
+export const useDocumentCommentDetail = (commentId?: string | null) => {
+ const workspaceId = useActiveWorkspaceId();
+ const response = useClientDataSWR<DocumentCommentDetail>(
+ commentId && workspaceId ? documentCommentKeys.detail(workspaceId, commentId) : null,
+ () => documentCommentService.get(commentId!),
+ );
+
+ return { ...response, isNotFound: isTrpcErrorCode(response.error, 'NOT_FOUND') };
+};
+
export const useOptimisticDocumentComment = () => {
const workspaceId = useActiveWorkspaceId();
const user = useUserStore(userProfileSelectors.userProfile);
diff --git a/src/features/PageEditor/DocumentComments/index.tsx b/src/features/PageEditor/DocumentComments/index.tsx
index 3b182b0d595..a345d4b498b 100644
--- a/src/features/PageEditor/DocumentComments/index.tsx
+++ b/src/features/PageEditor/DocumentComments/index.tsx
@@ -1,8 +1,8 @@
'use client';
import { Center, Flexbox, Skeleton } from '@lobehub/ui';
-import { Button, Text } from '@lobehub/ui/base-ui';
-import { memo, useCallback } from 'react';
+import { Button, Text, toast } from '@lobehub/ui/base-ui';
+import { memo, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
@@ -12,6 +12,7 @@ import { documentCommentService } from '@/services/documentComment';
import Composer from './Composer';
import {
+ useDocumentCommentDetail,
useDocumentCommentSummary,
useDocumentCommentThreads,
useOptimisticDocumentComment,
@@ -26,6 +27,10 @@ import {
} from './optimistic';
import { styles } from './styles';
import Thread from './Thread';
+import {
+ type DocumentCommentFocusMissReason,
+ useDocumentCommentDeepLink,
+} from './useDocumentCommentDeepLink';
const DocumentComments = memo<{ documentId: string }>(({ documentId }) => {
const { t } = useTranslation('file');
@@ -33,6 +38,7 @@ const DocumentComments = memo<{ documentId: string }>(({ documentId }) => {
const summary = useDocumentCommentSummary(workspaceId ? documentId : undefined);
const threads = useDocumentCommentThreads(workspaceId ? documentId : undefined);
const createOptimistic = useOptimisticDocumentComment();
+ const { clearFocus, focus, focusRoot } = useDocumentCommentDeepLink(documentId);
const reloadSummary = summary.mutate;
const reloadThreads = threads.reload;
const mutateThreads = threads.mutate;
@@ -127,6 +133,86 @@ const DocumentComments = memo<{ documentId: string }>(({ documentId }) => {
);
const isHeaderLoading = threads.isLoadingInitial || (summary.isLoading && !summary.data);
+ // Deep-link landing. Lists are oldest-first and a notification usually points at the
+ // newest comment, so the target root is fetched by id and pinned above the list until it
+ // shows up on a loaded page. NOT_FOUND, a non-root id, or a root from another document
+ // means the thread is gone; any other lookup failure is reported, never swallowed.
+ const focusRootCommentId = focus?.rootCommentId;
+ const hasFocusedThread =
+ Boolean(focusRootCommentId) && threads.items.some(({ root }) => root.id === focusRootCommentId);
+ const focusedRoot = useDocumentCommentDetail(hasFocusedThread ? undefined : focusRootCommentId);
+ const focusedRootData = focusedRoot.data;
+ const isFocusedRootUsable =
+ Boolean(focusedRootData) &&
+ !focusedRootData?.parentCommentId &&
+ focusedRootData?.documentId === documentId;
+ const pinnedThread =
+ focus && !hasFocusedThread && focusedRootData && isFocusedRootUsable
+ ? { replyCount: focusedRootData.replyCount, root: focusedRootData }
+ : undefined;
+ const isFocusedRootMissing =
+ Boolean(focusRootCommentId) &&
+ (focusedRoot.isNotFound || (Boolean(focusedRootData) && !isFocusedRootUsable));
+ const isFocusedRootFailed =
+ Boolean(focusRootCommentId) && Boolean(focusedRoot.error) && !focusedRoot.isNotFound;
+ const handleFocusMissing = useCallback(() => {
+ toast.info(t('pageEditor.comments.deepLinkMissing'));
+ clearFocus();
+ }, [clearFocus, t]);
+ const handleFocusFailed = useCallback(() => {
+ toast.error(t('pageEditor.comments.deepLinkLoadFailed'));
+ clearFocus();
+ }, [clearFocus, t]);
+ // The linked reply is gone (or failed to load) but its thread is not: keep the thread and
+ // land on the root.
+ const handleReplyFocusMissing = useCallback(
+ (reason: DocumentCommentFocusMissReason) => {
+ if (reason === 'missing') toast.info(t('pageEditor.comments.deepLinkMissing'));
+ else toast.error(t('pageEditor.comments.deepLinkLoadFailed'));
+ focusRoot();
+ },
+ [focusRoot, t],
+ );
+ useEffect(() => {
+ if (isFocusedRootMissing) handleFocusMissing();
+ else if (isFocusedRootFailed) handleFocusFailed();
+ }, [handleFocusFailed, handleFocusMissing, isFocusedRootFailed, isFocusedRootMissing]);
+ // The pinned root lives in its own detail entry, so the list handlers (which only patch
+ // the paginated caches) are mirrored into it; a post-delete 404 flows through
+ // `isNotFound` and is not a refresh failure.
+ const mutateFocusedRoot = focusedRoot.mutate;
+ const refreshPinned = useCallback(async () => {
+ await Promise.all([mutateFocusedRoot().catch(() => undefined), refresh()]);
+ }, [mutateFocusedRoot, refresh]);
+ const updatePinnedReplyCount = useCallback(
+ async (rootCommentId: string, delta: number) => {
+ await Promise.all([
+ updateReplyCount(rootCommentId, delta),
+ mutateFocusedRoot(
+ (current) =>
+ current && current.id === rootCommentId
+ ? { ...current, replyCount: Math.max(0, current.replyCount + delta) }
+ : current,
+ { revalidate: false },
+ ),
+ ]);
+ },
+ [mutateFocusedRoot, updateReplyCount],
+ );
+ const handlePinnedRootUpdate: DocumentCommentUpdateHandler = useCallback(
+ async (comment, value) => {
+ await handleUpdate(comment, value);
+ await mutateFocusedRoot(
+ (current) =>
+ current && current.id === comment.id
+ ? { ...current, ...value, updatedAt: new Date() }
+ : current,
+ { revalidate: false },
+ );
+ },
+ [handleUpdate, mutateFocusedRoot],
+ );
+
if (!workspaceId) return null;
return (
@@ -156,25 +242,52 @@ const DocumentComments = memo<{ documentId: string }>(({ documentId }) => {
)}
</Flexbox>
- {threads.isInitialError ? (
- <AsyncError error={threads.error} variant={'block'} onRetry={() => void threads.reload()} />
- ) : threads.isLoadingInitial ? (
- <SurfaceSkeleton header={false} variant={'list'} />
- ) : threads.items.length === 0 ? null : (
+ {/* The pinned deep-link thread renders on its own, so a pending or failed list
+ request never hides a target that was already fetched. */}
+ {threads.isInitialError ||
+ threads.isLoadingInitial ||
+ threads.items.length > 0 ||
+ pinnedThread ? (
<Flexbox className={styles.threadList}>
- {threads.items.map(({ replyCount, root }) => (
+ {pinnedThread && (
<Thread
documentId={documentId}
- key={root.id}
- replyCount={replyCount}
- root={root}
- onMutated={refresh}
- onReplyCountChange={updateReplyCount}
- onRootUpdate={handleUpdate}
+ focus={focus}
+ key={pinnedThread.root.id}
+ replyCount={pinnedThread.replyCount}
+ root={pinnedThread.root}
+ onFocusMissing={handleReplyFocusMissing}
+ onMutated={refreshPinned}
+ onReplyCountChange={updatePinnedReplyCount}
+ onRootUpdate={handlePinnedRootUpdate}
onSummaryChange={updateSummaryTotal}
/>
- ))}
- {threads.error ? (
+ )}
+ {threads.isInitialError ? (
+ <AsyncError
+ error={threads.error}
+ variant={'block'}
+ onRetry={() => void threads.reload()}
+ />
+ ) : threads.isLoadingInitial ? (
+ <SurfaceSkeleton header={false} variant={'list'} />
+ ) : (
+ threads.items.map(({ replyCount, root }) => (
+ <Thread
+ documentId={documentId}
+ focus={focus?.rootCommentId === root.id ? focus : undefined}
+ key={root.id}
+ replyCount={replyCount}
+ root={root}
+ onFocusMissing={handleReplyFocusMissing}
+ onMutated={refresh}
+ onReplyCountChange={updateReplyCount}
+ onRootUpdate={handleUpdate}
+ onSummaryChange={updateSummaryTotal}
+ />
+ ))
+ )}
+ {threads.error && !threads.isInitialError ? (
<AsyncError
error={threads.error}
retrying={threads.isRetrying}
@@ -195,7 +308,7 @@ const DocumentComments = memo<{ documentId: string }>(({ documentId }) => {
)
)}
</Flexbox>
- )}
+ ) : null}
{/* While the thread list is still skeleton-loading the composer would
float against placeholder content — reveal it with the real list. */}
diff --git a/src/features/PageEditor/DocumentComments/styles.ts b/src/features/PageEditor/DocumentComments/styles.ts
index 022ab4fd312..bbd910458a1 100644
--- a/src/features/PageEditor/DocumentComments/styles.ts
+++ b/src/features/PageEditor/DocumentComments/styles.ts
@@ -24,7 +24,16 @@ export const styles = createStaticStyles(({ css }) => ({
line-height: 1.7;
`,
card: css`
+ margin-inline: -12px;
padding-block: 20px 12px;
+ padding-inline: 12px;
+ border-radius: ${cssVar.borderRadiusLG};
+
+ transition: background-color 600ms ${cssVar.motionEaseOut};
+
+ @media (prefers-reduced-motion: reduce) {
+ transition: none;
+ }
`,
commentContent: css`
/* Published comments render images as left-aligned thumbnails: the
@@ -107,6 +116,10 @@ export const styles = createStaticStyles(({ css }) => ({
header: css`
min-height: 32px;
`,
+ /* Applied briefly when a notification deep link lands on the card. */
+ highlighted: css`
+ background-color: ${cssVar.colorPrimaryBg};
+ `,
meta: css`
color: ${cssVar.colorTextTertiary};
`,
diff --git a/src/features/PageEditor/DocumentComments/useDocumentCommentDeepLink.test.ts b/src/features/PageEditor/DocumentComments/useDocumentCommentDeepLink.test.ts
new file mode 100644
index 00000000000..5f644de98c0
--- /dev/null
+++ b/src/features/PageEditor/DocumentComments/useDocumentCommentDeepLink.test.ts
@@ -0,0 +1,98 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useDocumentCommentDeepLink } from './useDocumentCommentDeepLink';
+
+const mocks = vi.hoisted(() => ({
+ location: {
+ hash: '#notes',
+ pathname: '/acme/page/document-1',
+ search: '?comment=reply-1&commentThread=root-1&source=inbox',
+ },
+ navigate: vi.fn(),
+}));
+
+vi.mock('react-router', () => ({ useLocation: () => mocks.location }));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => mocks.navigate,
+}));
+
+describe('useDocumentCommentDeepLink', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.location.search = '?comment=reply-1&commentThread=root-1&source=inbox';
+ });
+
+ it('turns the query into a focus target and consumes only its own params', async () => {
+ const { result } = renderHook(() => useDocumentCommentDeepLink('document-1'));
+
+ await waitFor(() =>
+ expect(result.current.focus).toMatchObject({
+ commentId: 'reply-1',
+ rootCommentId: 'root-1',
+ token: 1,
+ }),
+ );
+ expect(mocks.navigate).toHaveBeenCalledWith('/acme/page/document-1?source=inbox#notes', {
+ replace: true,
+ });
+ });
+
+ it('focuses the root itself when only the thread is linked', async () => {
+ mocks.location.search = '?commentThread=root-1';
+
+ const { result } = renderHook(() => useDocumentCommentDeepLink('document-1'));
+
+ await waitFor(() =>
+ expect(result.current.focus).toMatchObject({ commentId: 'root-1', rootCommentId: 'root-1' }),
+ );
+ expect(mocks.navigate).toHaveBeenCalledWith('/acme/page/document-1#notes', { replace: true });
+ });
+
+ it('drops the target once the list reports it missing', async () => {
+ const { result } = renderHook(() => useDocumentCommentDeepLink('document-1'));
+ await waitFor(() => expect(result.current.focus).toBeDefined());
+
+ act(() => result.current.clearFocus());
+
+ expect(result.current.focus).toBeUndefined();
+ // The query was already consumed, so nothing re-arms the focus.
+ expect(mocks.navigate).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to the root when only the linked reply is gone', async () => {
+ const { result } = renderHook(() => useDocumentCommentDeepLink('document-1'));
+ await waitFor(() => expect(result.current.focus?.token).toBe(1));
+
+ act(() => result.current.focusRoot());
+
+ expect(result.current.focus).toMatchObject({
+ commentId: 'root-1',
+ rootCommentId: 'root-1',
+ token: 2,
+ });
+ });
+
+ it('does nothing without a comment thread target', () => {
+ mocks.location.search = '?source=inbox';
+
+ const { result } = renderHook(() => useDocumentCommentDeepLink('document-1'));
+
+ expect(result.current.focus).toBeUndefined();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it('does not hand a focus target to a different document', async () => {
+ const { result } = renderHook(() => useDocumentCommentDeepLink('document-2'));
+
+ await waitFor(() => expect(mocks.navigate).toHaveBeenCalled());
+ expect(result.current.focus).toMatchObject({ rootCommentId: 'root-1' });
+
+ const other = renderHook(() => useDocumentCommentDeepLink('document-1'));
+ // A fresh mount for another document parses its own location; this one still matches.
+ expect(other.result.current.focus?.rootCommentId).toBe('root-1');
+ });
+});
diff --git a/src/features/PageEditor/DocumentComments/useDocumentCommentDeepLink.ts b/src/features/PageEditor/DocumentComments/useDocumentCommentDeepLink.ts
new file mode 100644
index 00000000000..cbb10215b26
--- /dev/null
+++ b/src/features/PageEditor/DocumentComments/useDocumentCommentDeepLink.ts
@@ -0,0 +1,68 @@
+import { useCallback, useEffect, useState } from 'react';
+import { useLocation } from 'react-router';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+
+const COMMENT_QUERY = 'comment';
+const COMMENT_THREAD_QUERY = 'commentThread';
+
+/** Why a deep-link target could not be landed on. */
+export type DocumentCommentFocusMissReason = 'failed' | 'missing';
+
+export interface DocumentCommentFocus {
+ /** The comment to scroll to and highlight; equals `rootCommentId` for roots. */
+ commentId: string;
+ rootCommentId: string;
+ /** Changes on every deep link so the same comment can be focused twice in a row. */
+ token: number;
+}
+
+/**
+ * Turns a notification deep link (`?commentThread=<root>&comment=<id>`) into a
+ * focus target for the comment list and strips the query so a reload or a
+ * shared URL doesn't replay it. The list itself is responsible for paging
+ * for landing on the target — see `DocumentComments` / `Thread` — and calls
+ * `clearFocus` (thread gone) or `focusRoot` (only the reply is gone).
+ */
+export const useDocumentCommentDeepLink = (documentId: string) => {
+ const location = useLocation();
+ const navigate = useWorkspaceAwareNavigate();
+ const [focus, setFocus] = useState<(DocumentCommentFocus & { documentId: string }) | undefined>(
+ undefined,
+ );
+
+ useEffect(() => {
+ const searchParams = new URLSearchParams(location.search);
+ const rootCommentId = searchParams.get(COMMENT_THREAD_QUERY);
+ if (!rootCommentId) return;
+
+ const commentId = searchParams.get(COMMENT_QUERY) ?? rootCommentId;
+ setFocus((current) => ({
+ commentId,
+ documentId,
+ rootCommentId,
+ token: (current?.token ?? 0) + 1,
+ }));
+
+ searchParams.delete(COMMENT_QUERY);
+ searchParams.delete(COMMENT_THREAD_QUERY);
+ const search = searchParams.toString();
+ navigate(`${location.pathname}${search ? `?${search}` : ''}${location.hash}`, {
+ replace: true,
+ });
+ }, [documentId, location.hash, location.pathname, location.search, navigate]);
+
+ const clearFocus = useCallback(() => setFocus(undefined), []);
+ /** Fall back to the thread root when the linked reply itself is gone. */
+ const focusRoot = useCallback(
+ () =>
+ setFocus(
+ (current) =>
+ current && { ...current, commentId: current.rootCommentId, token: current.token + 1 },
+ ),
+ [],
+ );
+
+ // A focus target belongs to the document it was opened on.
+ return { clearFocus, focus: focus?.documentId === documentId ? focus : undefined, focusRoot };
+};
diff --git a/src/features/Portal/TopicComments/ThreadBody.tsx b/src/features/Portal/TopicComments/ThreadBody.tsx
index 794b3c777cb..5a54ecca54b 100644
--- a/src/features/Portal/TopicComments/ThreadBody.tsx
+++ b/src/features/Portal/TopicComments/ThreadBody.tsx
@@ -74,7 +74,11 @@ const ThreadBody = memo(() => {
).find((element) => element.dataset.topicCommentId === view.focusCommentId);
if (!target) return;
- requestAnimationFrame(() => target.scrollIntoView({ behavior: 'smooth', block: 'center' }));
+ // Honor reduced motion: jump to the comment instead of gliding.
+ const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ requestAnimationFrame(() =>
+ target.scrollIntoView({ behavior: reduceMotion ? 'auto' : 'smooth', block: 'center' }),
+ );
}, [focusedReply.data, replies.items, root.data, view?.focusCommentId]);
if (!view) return null;
diff --git a/src/features/ResourceManager/components/ResourceModeToggle/index.tsx b/src/features/ResourceManager/components/ResourceModeToggle/index.tsx
index b156b951780..66fb38e986c 100644
--- a/src/features/ResourceManager/components/ResourceModeToggle/index.tsx
+++ b/src/features/ResourceManager/components/ResourceModeToggle/index.tsx
@@ -1,13 +1,14 @@
'use client';
-import { type DropdownItem, DropdownMenu, Flexbox, Icon, type MenuInfo } from '@lobehub/ui';
-import { Button, Text } from '@lobehub/ui/base-ui';
+import { type DropdownItem, DropdownMenu, Icon, type MenuInfo } from '@lobehub/ui';
+import { ActionIcon } from '@lobehub/ui/base-ui';
import { cssVar } from 'antd-style';
-import { CheckIcon, ChevronDownIcon, LockIcon, UsersIcon } from 'lucide-react';
+import { CheckIcon, LockIcon, UsersIcon } from 'lucide-react';
import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
import type { ResourceListVisibilityFilter } from '@/features/ResourceManager/store/initialState';
@@ -15,24 +16,23 @@ const OPTIONS: Array<{
icon: typeof LockIcon;
key: ResourceListVisibilityFilter;
labelKey: string;
- tooltipKey: string;
}> = [
{
icon: LockIcon,
key: 'private',
labelKey: 'resources.visibility.private',
- tooltipKey: 'resources.mode.privateHint',
},
{
icon: UsersIcon,
key: 'workspace',
labelKey: 'resources.visibility.workspace',
- tooltipKey: 'resources.mode.workspaceHint',
},
];
/**
- * Sidebar-header scope chip, mirroring the task list's visibility filter.
+ * Sidebar-header scope chip, mirroring the task list's visibility filter:
+ * collapsed it is a single icon for the active scope (🔒 private / 👥
+ * workspace); the dropdown lists both scopes with a check on the current one.
*
* Rendered only in team-workspace mode — personal mode has no notion of
* visibility, so the toggle is meaningless there and is deliberately hidden.
@@ -87,20 +87,11 @@ const ResourceModeToggle = memo(() => {
return (
<DropdownMenu items={menuItems} open={open} onOpenChange={setOpen}>
- <Button
- size={'small'}
- style={{ paddingInline: 6 }}
+ <ActionIcon
+ icon={current.icon}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
title={`${t('resources.visibility.label')}: ${currentLabel}`}
- type={'text'}
- >
- <Flexbox horizontal align={'center'} gap={4}>
- <Icon color={cssVar.colorIcon} icon={current.icon} size={14} />
- <Text ellipsis fontSize={12} style={{ maxWidth: 96 }} type={'secondary'}>
- {currentLabel}
- </Text>
- <Icon color={cssVar.colorIcon} icon={ChevronDownIcon} size={12} />
- </Flexbox>
- </Button>
+ />
</DropdownMenu>
);
});
diff --git a/src/features/ResourceManager/store/action.test.ts b/src/features/ResourceManager/store/action.test.ts
index 59049d72235..804a42dd48c 100644
--- a/src/features/ResourceManager/store/action.test.ts
+++ b/src/features/ResourceManager/store/action.test.ts
@@ -26,9 +26,9 @@ describe('resource manager store actions', () => {
useFileStore.setState(fileInitialState);
});
- it('should default workspace resources to private mode when no preference is persisted', () => {
+ it('should default workspace resources to workspace mode when no preference is persisted', () => {
useResourceManagerStore.setState({
- listVisibility: 'workspace',
+ listVisibility: 'private',
selectAllState: 'loaded',
selectedFileIds: ['file-1'],
});
@@ -36,12 +36,21 @@ describe('resource manager store actions', () => {
useResourceManagerStore.getState().hydrateListVisibility('workspace-1');
expect(useResourceManagerStore.getState()).toMatchObject({
- listVisibility: 'private',
+ listVisibility: 'workspace',
selectAllState: 'none',
selectedFileIds: [],
});
});
+ it('should restore the persisted private mode over the workspace default', () => {
+ useResourceManagerStore.getState().setListVisibility('private', 'workspace-1');
+ useResourceManagerStore.setState({ listVisibility: 'workspace' });
+
+ useResourceManagerStore.getState().hydrateListVisibility('workspace-1');
+
+ expect(useResourceManagerStore.getState().listVisibility).toBe('private');
+ });
+
it('should drop the previous source rows when the source filter changes', () => {
// Regression: the pick used to update ResourceManager state only, leaving
// the previous source's rows on screen and interactive until the fetch
diff --git a/src/features/ResourceManager/store/initialState.ts b/src/features/ResourceManager/store/initialState.ts
index 0379e286e38..9c72cdd320c 100644
--- a/src/features/ResourceManager/store/initialState.ts
+++ b/src/features/ResourceManager/store/initialState.ts
@@ -19,7 +19,12 @@ export type SelectAllState = 'all' | 'loaded' | 'none';
*/
export type ResourceListVisibilityFilter = 'private' | 'workspace';
-export const DEFAULT_WORKSPACE_LIST_VISIBILITY: ResourceListVisibilityFilter = 'private';
+/**
+ * Workspace mode opens on the team share, matching the task list's default:
+ * workspace resources are team work by default, and the private drawer stays
+ * one click away in the header scope dropdown.
+ */
+export const DEFAULT_WORKSPACE_LIST_VISIBILITY: ResourceListVisibilityFilter = 'workspace';
export interface State {
/**
diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.ts
index 704062145d7..0e7edfe2287 100644
--- a/src/libs/swr/keys.test.ts
+++ b/src/libs/swr/keys.test.ts
@@ -142,9 +142,16 @@ describe('isDocumentCommentKeyForEvent', () => {
event,
),
).toBe(true);
+ // Pinned deep-link details revalidate on any comment event in the workspace.
+ expect(
+ isDocumentCommentKeyForEvent(documentCommentKeys.detail('workspace-1', 'reply-9'), event),
+ ).toBe(true);
});
it('does not invalidate other documents, workspaces, or reply threads', () => {
+ expect(
+ isDocumentCommentKeyForEvent(documentCommentKeys.detail('workspace-2', 'root-1'), event),
+ ).toBe(false);
expect(
isDocumentCommentKeyForEvent(documentCommentKeys.threads('workspace-2', 'document-1'), event),
).toBe(false);
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index e6a6d8b7a27..f1dab21bd6c 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -174,6 +174,11 @@ export const topicCommentKeys = {
// ---- document comment ---------------------------------------------------
export const documentCommentKeys = {
+ detail: def('documentComment:detail', (workspaceId: string | null, commentId: string) => [
+ 'documentComment:detail',
+ workspaceId ?? '',
+ commentId,
+ ]),
replies: def(
'documentComment:replies',
(workspaceId: string | null, rootCommentId: string, cursor?: string) => [
@@ -215,6 +220,9 @@ export const isDocumentCommentKeyForEvent = (
if (key[0] === documentCommentKeys.summary.root) return key[1] === event.documentId;
if (key[1] !== event.workspaceId) return false;
+ // Deep-link detail entries are few (at most a pinned root and reply) and events do not
+ // carry the comment id, so revalidate them on any comment event in the workspace.
+ if (key[0] === documentCommentKeys.detail.root) return true;
if (key[0] === documentCommentKeys.threads.root) return key[2] === event.documentId;
if (key[0] === documentCommentKeys.replies.root) {
return !event.rootCommentId || key[2] === event.rootCommentId;
diff --git a/src/services/documentComment.ts b/src/services/documentComment.ts
index 979321d3e6b..611d732b9f6 100644
--- a/src/services/documentComment.ts
+++ b/src/services/documentComment.ts
@@ -7,6 +7,8 @@ class DocumentCommentService {
delete = (id: string) => lambdaClient.documentComment.delete.mutate({ id });
+ get = (id: string) => lambdaClient.documentComment.get.query({ id });
+
listReplies = (params: { cursor?: string; limit?: number; rootCommentId: string }) =>
lambdaClient.documentComment.listReplies.query(params);