🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(page-editor): align document comments beside their source text (#19659)
Rdmclin2ebe586289d55
diff --git a/apps/server/src/routers/lambda/documentComment.ts b/apps/server/src/routers/lambda/documentComment.tsindex 5109052da02..d0e827234d0 100644--- a/apps/server/src/routers/lambda/documentComment.ts+++ b/apps/server/src/routers/lambda/documentComment.ts@@ -517,7 +517,7 @@ export const documentCommentRouter = router({}),listThreads: documentCommentProcedure- .input(pageSchema.extend({ documentId: idSchema }))+ .input(pageSchema.extend({ anchored: z.boolean().optional(), documentId: idSchema })).query(async ({ ctx, input }) => {const { grantedPermissions } = await assertPermission(ctx, 'DOCUMENT_COMMENT_READ');await assertDocumentView(ctx, input.documentId, grantedPermissions);diff --git a/locales/ar/agent.json b/locales/ar/agent.jsonindex e65233181f3..c148ef8ec61 100644--- a/locales/ar/agent.json+++ b/locales/ar/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "معرّف حساب WeChat الذي يتم إرجاعه من خلال عملية التفويض.","share.entry": "شارك هذا الوكيل","share.settings.limits.desc": "كل تشغيل للزائر يتم احتسابه على حسابك، لذا فإن هذه الحدود هي ما يمنع رابط المشاركة من زيادة فاتورتك. تنطبق دائمًا — يمكنك تغيير الأرقام، ولكن لا يمكنك إيقافها.",+ "share.settings.limits.maxFileStorage": "حد تخزين الملفات (ميغابايت)",+ "share.settings.limits.maxFileStorageHint": "يتم تخزين الملفات التي يرفقها الزوار في حسابك. تتوقف التحميلات بمجرد الوصول إلى هذا الحد؛ قم بتعيين 0 لإيقاف المرفقات.","share.settings.limits.maxTopicsPerVisitor": "المحادثات لكل زائر","share.settings.limits.maxTopicsPerVisitorHint": "عدد المحادثات المنفصلة التي يمكن لكل زائر مسجل الدخول أن يبدأها.","share.settings.limits.maxTurnsPerTopic": "عدد الرسائل لكل محادثة",@@ -363,6 +365,9 @@"share.settings.updateError": "تعذر حفظ التغيير. يرجى المحاولة مرة أخرى.","share.settings.usage.conversations": "المحادثات","share.settings.usage.desc": "ما جذبته هذه المشاركة، وما كلفك.",+ "share.settings.usage.fileStorage": "تخزين الملفات",+ "share.settings.usage.fileStorageOfLimit": "{{used}} من {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · المرفقات معطلة","share.settings.usage.loadFailed": "تعذر تحميل الاستخدام","share.settings.usage.monthlySpend": "إنفاق هذا الشهر","share.settings.usage.spendOfLimit": "${{spend}} من ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "تسجيل الدخول","share.visitor.access.signInDesc": "سجل الدخول لبدء الدردشة مع هذا الوكيل المشترك. تظل محادثاتك مرتبطة بحسابك.","share.visitor.access.signInTitle": "سجل الدخول للمتابعة",+ "share.visitor.errors.fileUnavailable": "أحد المرفقات لم يعد متاحًا. قم بإزالته وحاول مرة أخرى.","share.visitor.errors.generic": "فشل في إرسال الرسالة. يرجى المحاولة مرة أخرى.","share.visitor.errors.heterogeneousUnsupported": "هذا الوكيل المشترك غير متاح للدردشة مع الزوار بعد. يرجى الاتصال بمالكه.","share.visitor.errors.insufficientBudget": "نفد ميزانية هذا الوكيل المشترك. يرجى الاتصال بمالكه.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} أدوات مفتوحة للزوار.","share.visitor.profile.terms.topics": "يمكنك فتح ما يصل إلى {{count}} محادثات.","share.visitor.profile.terms.turns": "تسمح كل محادثة بما يصل إلى {{count}} أدوار.",+ "share.visitor.profile.terms.uploads": "يمكنك إرفاق ملفات؛ يحتوي هذا الوكيل على {{size}} لتخزين الملفات للزوار.",+ "share.visitor.profile.terms.uploadsOff": "تم تعطيل المرفقات.","share.visitor.profile.terms.visibilityCreator": "قام المنشئ بتفعيل مراجعة الجلسة، لذا يمكنه قراءة هذه المحادثة.","share.visitor.profile.terms.visibilityPrivate": "يمكنك فقط رؤية محادثاتك.","share.visitor.topBar.home": "اذهب إلى LobeHub الخاص بي",@@ -421,6 +429,9 @@"share.visitor.topics.new": "محادثة جديدة","share.visitor.topics.title": "المحادثات","share.visitor.topics.untitled": "محادثة بدون عنوان",+ "share.visitor.upload.creatorStorageBlocked": "مساحة التحميل الخاصة بهذا الوكيل ممتلئة. اطلب من منشئه تحرير مساحة أو زيادة الحد.",+ "share.visitor.upload.fileTooLarge": "يجب أن تكون الملفات أقل من {{max}}.",+ "share.visitor.upload.tooManyFiles": "يمكنك إرفاق ما يصل إلى {{max}} ملفًا لكل رسالة.","transfer.button": "نقل","transfer.confirm.botChannels": "قد تحتاج اتصالات قنوات الروبوت إلى التحديث بعد النقل","transfer.confirm.chatGroups": "سيتم إزالة ارتباطات المجموعات متعددة الوكلاء",diff --git a/locales/ar/chat.json b/locales/ar/chat.jsonindex 3ca05a9f071..c0b52f7b07b 100644--- a/locales/ar/chat.json+++ b/locales/ar/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "نتيجة","goalProcess.kind.problem": "سؤال","goalProcess.kind.task": "مهمة",+ "goalProcess.linked.open": "افتح تقدم الهدف","goalProcess.manager.pending": "في انتظار التشغيل الأول","goalProcess.manager.title": "الوكيل الرئيسي","goalProcess.manager.turns": "جولات التخطيط: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "تم الإيقاف المؤقت — لن يبدأ أي عمل جديد","goalProcess.planning.description": "يقوم المنسق بتقسيم الهدف إلى مهام قابلة للتنفيذ — ستظهر هنا قريبًا.","goalProcess.planning.title": "تخطيط الاستكشاف",+ "goalProcess.portal.openPage": "افتح صفحة الهدف",+ "goalProcess.portal.title": "الهدف","goalProcess.requirementPlaceholder": "وصف ما يعتبر مكتملًا…","goalProcess.requirementSaveFailed": "فشل في حفظ المتطلبات — سيتم إعادة المحاولة عند التعديل التالي","goalProcess.resume": "استئناف",diff --git a/locales/ar/file.json b/locales/ar/file.jsonindex 7796c0bdc6d..19066262f0c 100644--- a/locales/ar/file.json+++ b/locales/ar/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "يتم حفظ صفحتك تلقائيًا. لا حاجة للحفظ يدويًا.","pageEditor.chooseIcon": "اختر أيقونة","pageEditor.comments.anchor.add": "تعليق",+ "pageEditor.comments.anchor.addToLine": "علق على هذا السطر","pageEditor.comments.anchor.label": "النص المقتبس:","pageEditor.comments.anchor.missing": "تمت إزالة الأصل","pageEditor.comments.anchor.remove": "إزالة الاقتباس",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "تم حذف هذا التعليق.","pageEditor.comments.edit": "تعديل","pageEditor.comments.edited": "(تم التعديل)",+ "pageEditor.comments.gutterEmpty": "حدد نصًا في المستند للتعليق عليه.",+ "pageEditor.comments.gutterEmptyReadOnly": "لا توجد تعليقات حتى الآن.","pageEditor.comments.hideReplies": "إخفاء الردود","pageEditor.comments.loadMore": "تحميل المزيد من التعليقات","pageEditor.comments.loadMoreReplies": "تحميل المزيد من الردود",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "اكتب ردًا...","pageEditor.comments.save": "حفظ","pageEditor.comments.title": "التعليقات",+ "pageEditor.comments.toggle": "التعليقات","pageEditor.comments.updateFailed": "فشل تحديث التعليق. حاول مرة أخرى.",+ "pageEditor.copilot.toggle": "اسأل Lobe AI","pageEditor.deleteConfirm.content": "سيتم حذف هذه الصفحة ولا يمكن استعادتها. يرجى المتابعة بحذر.","pageEditor.deleteConfirm.title": "حذف الصفحة","pageEditor.deleteError": "فشل في حذف الصفحة",diff --git a/locales/ar/pageShare.json b/locales/ar/pageShare.jsonindex 2c65430cdce..5e31435df9e 100644--- a/locales/ar/pageShare.json+++ b/locales/ar/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "هل أعجبتك هذه الصفحة؟ <strong>أنشئ صفحتك الخاصة باستخدام {{appName}}</strong> — مساحة عمل مجانية للمستندات المعتمدة على الذكاء الاصطناعي.","banner.signIn": "تسجيل الدخول","banner.signUp": "اشترك مجانًا",+ "error.invalidFormat.desc": "لا يزال بإمكانك قراءته. قد يختلف التنسيق عن الأصل.",+ "error.invalidFormat.ownerHint": "أعد حفظه في المحرر لاستعادة التنسيق الأصلي.",+ "error.invalidFormat.title": "تعذر عرض هذه الصفحة بتنسيقها الأصلي","error.notFound.desc": "هذه الصفحة لم تعد موجودة أو تم حذفها.","error.notFound.title": "الصفحة غير موجودة","error.private.action": "تسجيل الدخول",diff --git a/locales/bg-BG/agent.json b/locales/bg-BG/agent.jsonindex 6e754530264..65fd267f888 100644--- a/locales/bg-BG/agent.json+++ b/locales/bg-BG/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "Идентификатор на WeChat акаунт, върнат от процеса на оторизация.","share.entry": "Сподели този агент","share.settings.limits.desc": "Всяко използване от посетител се таксува към вашия акаунт, така че тези ограничения предпазват споделената връзка от прекомерни разходи. Те винаги са активни — можете да промените числата, но не и да ги изключите.",+ "share.settings.limits.maxFileStorage": "Лимит за съхранение на файлове (MB)",+ "share.settings.limits.maxFileStorageHint": "Файловете, които посетителите прикачват, се съхраняват във вашия акаунт. Качването спира, когато достигне този лимит; задайте 0, за да изключите прикачените файлове.","share.settings.limits.maxTopicsPerVisitor": "Разговори на посетител","share.settings.limits.maxTopicsPerVisitorHint": "Колко отделни разговора може да започне всеки влязъл посетител.","share.settings.limits.maxTurnsPerTopic": "Ходове на разговор",@@ -363,6 +365,9 @@"share.settings.updateError": "Неуспешно запазване на промяната. Моля, опитайте отново.","share.settings.usage.conversations": "Разговори","share.settings.usage.desc": "Какво е привлякло това споделяне и какво ви е струвало.",+ "share.settings.usage.fileStorage": "Съхранение на файлове",+ "share.settings.usage.fileStorageOfLimit": "{{used}} от {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · прикачените файлове са изключени","share.settings.usage.loadFailed": "Неуспешно зареждане на използването","share.settings.usage.monthlySpend": "Разходи за този месец","share.settings.usage.spendOfLimit": "${{spend}} от ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "Влезте","share.visitor.access.signInDesc": "Влезте, за да започнете разговор с този споделен агент. Вашите разговори остават свързани с вашия акаунт.","share.visitor.access.signInTitle": "Влезте, за да продължите",+ "share.visitor.errors.fileUnavailable": "Един от прикачените файлове вече не е наличен. Премахнете го и опитайте отново.","share.visitor.errors.generic": "Неуспешно изпращане на съобщението. Моля, опитайте отново.","share.visitor.errors.heterogeneousUnsupported": "Този споделен агент все още не е наличен за чат с посетители. Моля, свържете се със собственика му.","share.visitor.errors.insufficientBudget": "Този споделен агент е изчерпал бюджета си. Моля, свържете се със собственика му.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} инструменти са отворени за посетители.","share.visitor.profile.terms.topics": "Можете да отворите до {{count}} разговора.","share.visitor.profile.terms.turns": "Всеки разговор позволява до {{count}} хода.",+ "share.visitor.profile.terms.uploads": "Можете да прикачвате файлове; този Аджент има {{size}} за съхранение на файлове за посетители.",+ "share.visitor.profile.terms.uploadsOff": "Прикачените файлове са изключени.","share.visitor.profile.terms.visibilityCreator": "Създателят е включил преглед на сесията, така че може да прочете този разговор.","share.visitor.profile.terms.visibilityPrivate": "Само вие можете да видите вашите разговори.","share.visitor.topBar.home": "Отидете в моя LobeHub",@@ -421,6 +429,9 @@"share.visitor.topics.new": "Нов разговор","share.visitor.topics.title": "Разговори","share.visitor.topics.untitled": "Без заглавие",+ "share.visitor.upload.creatorStorageBlocked": "Пространството за качване на този Аджент е запълнено. Помолете създателя му да освободи място или да увеличи лимита.",+ "share.visitor.upload.fileTooLarge": "Файловете трябва да са под {{max}}.",+ "share.visitor.upload.tooManyFiles": "Можете да прикачите до {{max}} файла на съобщение.","transfer.button": "Прехвърляне","transfer.confirm.botChannels": "Връзките с каналите на бота може да се наложи да бъдат обновени след прехвърляне","transfer.confirm.chatGroups": "Асоциациите на групите с много агенти ще бъдат премахнати",diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.jsonindex 400e5d43bc6..1a627236ba4 100644--- a/locales/bg-BG/chat.json+++ b/locales/bg-BG/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "Находка","goalProcess.kind.problem": "Въпрос","goalProcess.kind.task": "Задача",+ "goalProcess.linked.open": "Отвори напредъка на целта","goalProcess.manager.pending": "Изчакване за първото изпълнение","goalProcess.manager.title": "Главен агент","goalProcess.manager.turns": "Кръгове на планиране: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "На пауза — няма да започват нови задачи","goalProcess.planning.description": "Координаторът разделя целта на изпълними задачи — те скоро ще се появят тук.","goalProcess.planning.title": "Планиране на изследването",+ "goalProcess.portal.openPage": "Отвори страницата на целта",+ "goalProcess.portal.title": "Цел","goalProcess.requirementPlaceholder": "Опишете какво се счита за изпълнено…","goalProcess.requirementSaveFailed": "Неуспешно запазване на изискването — ще се опита отново при следващата ви редакция","goalProcess.resume": "Възобновяване",diff --git a/locales/bg-BG/file.json b/locales/bg-BG/file.jsonindex 3553b04c7ed..9b1a91e5d06 100644--- a/locales/bg-BG/file.json+++ b/locales/bg-BG/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "Страницата се запазва автоматично. Не е нужно ръчно запазване.","pageEditor.chooseIcon": "Избери икона","pageEditor.comments.anchor.add": "Коментар",+ "pageEditor.comments.anchor.addToLine": "Коментар за този ред","pageEditor.comments.anchor.label": "Цитиран текст:","pageEditor.comments.anchor.missing": "Оригиналът е премахнат","pageEditor.comments.anchor.remove": "Премахване на цитата",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "Този коментар беше изтрит.","pageEditor.comments.edit": "Редактирай","pageEditor.comments.edited": "(редактирано)",+ "pageEditor.comments.gutterEmpty": "Изберете текст в документа, за да добавите коментар.",+ "pageEditor.comments.gutterEmptyReadOnly": "Все още няма коментари.","pageEditor.comments.hideReplies": "Скрий отговорите","pageEditor.comments.loadMore": "Зареди още коментари","pageEditor.comments.loadMoreReplies": "Зареди още отговори",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "Напишете отговор…","pageEditor.comments.save": "Запази","pageEditor.comments.title": "Коментари",+ "pageEditor.comments.toggle": "Коментари","pageEditor.comments.updateFailed": "Неуспешно обновяване на коментар. Опитайте отново.",+ "pageEditor.copilot.toggle": "Попитай Lobe AI","pageEditor.deleteConfirm.content": "Тази страница ще бъде изтрита и не може да бъде възстановена. Моля, бъдете внимателни.","pageEditor.deleteConfirm.title": "Изтриване на страница","pageEditor.deleteError": "Неуспешно изтриване на страницата",diff --git a/locales/bg-BG/pageShare.json b/locales/bg-BG/pageShare.jsonindex 2df50b1653d..ac69d3ca876 100644--- a/locales/bg-BG/pageShare.json+++ b/locales/bg-BG/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "Харесвате тази страница? <strong>Създайте своя собствена с {{appName}}</strong> — безплатно пространство за AI-ориентирани документи.","banner.signIn": "Вход","banner.signUp": "Регистрация безплатно",+ "error.invalidFormat.desc": "Все още можете да го прочетете. Оформлението може да се различава от оригинала.",+ "error.invalidFormat.ownerHint": "Запазете го отново в редактора, за да възстановите оригиналното оформление.",+ "error.invalidFormat.title": "Тази страница не може да бъде показана в оригиналния си формат","error.notFound.desc": "Тази страница вече не съществува или е била премахната.","error.notFound.title": "Страницата не е намерена","error.private.action": "Вход",diff --git a/locales/de-DE/agent.json b/locales/de-DE/agent.jsonindex 32dba8695a4..20f26956943 100644--- a/locales/de-DE/agent.json+++ b/locales/de-DE/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "WeChat-Konto-Kennung, die durch den Autorisierungsprozess zurückgegeben wurde.","share.entry": "Diesen Agenten teilen","share.settings.limits.desc": "Jeder Besuch wird Ihrem Konto in Rechnung gestellt, daher verhindern diese Begrenzungen, dass ein freigegebener Link Ihre Kosten in die Höhe treibt. Sie gelten immer – Sie können die Zahlen ändern, aber nicht deaktivieren.",+ "share.settings.limits.maxFileStorage": "Dateispeicherlimit (MB)",+ "share.settings.limits.maxFileStorageHint": "Dateien, die Besucher anhängen, werden in Ihrem Konto gespeichert. Uploads stoppen, sobald sie dieses Gesamtlimit erreichen; setzen Sie 0, um Anhänge zu deaktivieren.","share.settings.limits.maxTopicsPerVisitor": "Gespräche pro Besucher","share.settings.limits.maxTopicsPerVisitorHint": "Wie viele separate Gespräche jeder angemeldete Besucher starten kann.","share.settings.limits.maxTurnsPerTopic": "Beiträge pro Gespräch",@@ -363,6 +365,9 @@"share.settings.updateError": "Die Änderung konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.","share.settings.usage.conversations": "Gespräche","share.settings.usage.desc": "Was diese Freigabe angezogen hat und was es Sie gekostet hat.",+ "share.settings.usage.fileStorage": "Dateispeicher",+ "share.settings.usage.fileStorageOfLimit": "{{used}} von {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · Anhänge deaktiviert","share.settings.usage.loadFailed": "Nutzung konnte nicht geladen werden","share.settings.usage.monthlySpend": "Ausgaben dieses Monats","share.settings.usage.spendOfLimit": "${{spend}} von ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "Anmelden","share.visitor.access.signInDesc": "Melden Sie sich an, um mit diesem freigegebenen Agenten zu chatten. Ihre Gespräche bleiben mit Ihrem Konto verknüpft.","share.visitor.access.signInTitle": "Melden Sie sich an, um fortzufahren",+ "share.visitor.errors.fileUnavailable": "Einer der Anhänge ist nicht mehr verfügbar. Entfernen Sie ihn und versuchen Sie es erneut.","share.visitor.errors.generic": "Die Nachricht konnte nicht gesendet werden. Bitte versuchen Sie es erneut.","share.visitor.errors.heterogeneousUnsupported": "Dieser freigegebene Agent ist für Besucherchat noch nicht verfügbar. Bitte kontaktieren Sie den Besitzer.","share.visitor.errors.insufficientBudget": "Dieser freigegebene Agent hat kein Budget mehr. Bitte kontaktieren Sie den Besitzer.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} Werkzeuge sind für Besucher geöffnet.","share.visitor.profile.terms.topics": "Sie können bis zu {{count}} Gespräche eröffnen.","share.visitor.profile.terms.turns": "Jedes Gespräch erlaubt bis zu {{count}} Züge.",+ "share.visitor.profile.terms.uploads": "Sie können Dateien anhängen; dieser Ajan hat {{size}} Dateispeicher für Besucher.",+ "share.visitor.profile.terms.uploadsOff": "Anhänge sind deaktiviert.","share.visitor.profile.terms.visibilityCreator": "Der Ersteller hat die Sitzungsüberprüfung aktiviert, sodass er dieses Gespräch lesen kann.","share.visitor.profile.terms.visibilityPrivate": "Nur Sie können Ihre Gespräche sehen.","share.visitor.topBar.home": "Gehe zu meinem LobeHub",@@ -421,6 +429,9 @@"share.visitor.topics.new": "Neues Gespräch","share.visitor.topics.title": "Gespräche","share.visitor.topics.untitled": "Unbenanntes Gespräch",+ "share.visitor.upload.creatorStorageBlocked": "Der Upload-Speicherplatz dieses Ajans ist voll. Bitten Sie den Ersteller, Platz freizugeben oder das Limit zu erhöhen.",+ "share.visitor.upload.fileTooLarge": "Dateien müssen unter {{max}} sein.",+ "share.visitor.upload.tooManyFiles": "Sie können bis zu {{max}} Dateien pro Nachricht anhängen.","transfer.button": "Übertragen","transfer.confirm.botChannels": "Bot-Kanalverbindungen müssen möglicherweise nach der Übertragung aktualisiert werden","transfer.confirm.chatGroups": "Multi-Agent-Gruppenassoziationen werden entfernt",diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.jsonindex f4d25fb6bd8..5478ff0af88 100644--- a/locales/de-DE/chat.json+++ b/locales/de-DE/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "Ergebnis","goalProcess.kind.problem": "Frage","goalProcess.kind.task": "Aufgabe",+ "goalProcess.linked.open": "Zielverlauf öffnen","goalProcess.manager.pending": "Warten auf den ersten Lauf","goalProcess.manager.title": "Hauptagent","goalProcess.manager.turns": "Planungsrunden: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "Pausiert — keine neuen Aufgaben werden gestartet","goalProcess.planning.description": "Der Koordinator zerlegt das Ziel in ausführbare Aufgaben — sie werden in Kürze hier erscheinen.","goalProcess.planning.title": "Planung der Erkundung",+ "goalProcess.portal.openPage": "Zielseite öffnen",+ "goalProcess.portal.title": "Ziel","goalProcess.requirementPlaceholder": "Beschreiben Sie, was als erledigt gilt…","goalProcess.requirementSaveFailed": "Anforderung konnte nicht gespeichert werden — sie wird bei Ihrer nächsten Bearbeitung erneut versucht","goalProcess.resume": "Fortsetzen",diff --git a/locales/de-DE/file.json b/locales/de-DE/file.jsonindex f769eb7e009..fe46ed0a178 100644--- a/locales/de-DE/file.json+++ b/locales/de-DE/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "Ihre Seite wird automatisch gespeichert. Ein manuelles Speichern ist nicht erforderlich.","pageEditor.chooseIcon": "Symbol auswählen","pageEditor.comments.anchor.add": "Kommentar",+ "pageEditor.comments.anchor.addToLine": "Kommentar zu dieser Zeile","pageEditor.comments.anchor.label": "Zitierter Text:","pageEditor.comments.anchor.missing": "Original entfernt","pageEditor.comments.anchor.remove": "Zitat entfernen",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "Dieser Kommentar wurde gelöscht.","pageEditor.comments.edit": "Bearbeiten","pageEditor.comments.edited": "(bearbeitet)",+ "pageEditor.comments.gutterEmpty": "Markieren Sie Text im Dokument, um ihn zu kommentieren.",+ "pageEditor.comments.gutterEmptyReadOnly": "Noch keine Kommentare.","pageEditor.comments.hideReplies": "Antworten ausblenden","pageEditor.comments.loadMore": "Mehr Kommentare laden","pageEditor.comments.loadMoreReplies": "Mehr Antworten laden",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "Eine Antwort schreiben…","pageEditor.comments.save": "Speichern","pageEditor.comments.title": "Kommentare",+ "pageEditor.comments.toggle": "Kommentare","pageEditor.comments.updateFailed": "Kommentar konnte nicht aktualisiert werden. Versuchen Sie es erneut.",+ "pageEditor.copilot.toggle": "Lobe AI fragen","pageEditor.deleteConfirm.content": "Diese Seite wird gelöscht und kann nicht wiederhergestellt werden. Bitte seien Sie vorsichtig.","pageEditor.deleteConfirm.title": "Seite löschen","pageEditor.deleteError": "Fehler beim Löschen der Seite",diff --git a/locales/de-DE/pageShare.json b/locales/de-DE/pageShare.jsonindex 4ad1835e926..a7b940e3d24 100644--- a/locales/de-DE/pageShare.json+++ b/locales/de-DE/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "Gefällt dir diese Seite? <strong>Erstelle deine eigene mit {{appName}}</strong> — kostenloser Arbeitsbereich für KI-native Dokumente.","banner.signIn": "Anmelden","banner.signUp": "Kostenlos registrieren",+ "error.invalidFormat.desc": "Sie können es trotzdem lesen. Das Layout kann vom Original abweichen.",+ "error.invalidFormat.ownerHint": "Speichern Sie es im Editor erneut, um das ursprüngliche Layout wiederherzustellen.",+ "error.invalidFormat.title": "Diese Seite konnte nicht im ursprünglichen Format angezeigt werden.","error.notFound.desc": "Diese Seite existiert nicht mehr oder wurde entfernt.","error.notFound.title": "Seite nicht gefunden","error.private.action": "Anmelden",diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex 4ea4948c535..c4f050b92cd 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "Your page is saved automatically. No need to save manually.","pageEditor.chooseIcon": "Choose Icon","pageEditor.comments.anchor.add": "Comment",+ "pageEditor.comments.anchor.addToLine": "Comment on this line","pageEditor.comments.anchor.label": "Quoted text:","pageEditor.comments.anchor.missing": "Original removed","pageEditor.comments.anchor.remove": "Remove quote",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "This comment was deleted.","pageEditor.comments.edit": "Edit","pageEditor.comments.edited": "(edited)",+ "pageEditor.comments.gutterEmpty": "Select text in the document to comment on it.",+ "pageEditor.comments.gutterEmptyReadOnly": "No comments yet.","pageEditor.comments.hideReplies": "Hide replies","pageEditor.comments.loadMore": "Load more comments","pageEditor.comments.loadMoreReplies": "Load more replies",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "Write a reply…","pageEditor.comments.save": "Save","pageEditor.comments.title": "Comments",+ "pageEditor.comments.toggle": "Comments","pageEditor.comments.updateFailed": "Failed to update comment. Try again.",+ "pageEditor.copilot.toggle": "Ask Lobe AI","pageEditor.deleteConfirm.content": "This page will be deleted and cannot be recovered. Please proceed with caution.","pageEditor.deleteConfirm.title": "Delete Page","pageEditor.deleteError": "Failed to delete the page",diff --git a/locales/es-ES/agent.json b/locales/es-ES/agent.jsonindex 231a33ff288..eaa475f55a2 100644--- a/locales/es-ES/agent.json+++ b/locales/es-ES/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "Identificador de la cuenta de WeChat devuelto por el flujo de autorización.","share.entry": "Compartir este Agente","share.settings.limits.desc": "Cada ejecución de visitante se factura a tu cuenta, por lo que estos límites evitan que un enlace compartido aumente tu factura. Siempre se aplican: puedes cambiar los números, pero no desactivarlos.",+ "share.settings.limits.maxFileStorage": "Límite de almacenamiento de archivos (MB)",+ "share.settings.limits.maxFileStorageHint": "Los archivos que los visitantes adjuntan se almacenan en tu cuenta. Las cargas se detienen una vez que alcanzan este total; establece 0 para desactivar los adjuntos.","share.settings.limits.maxTopicsPerVisitor": "Conversaciones por visitante","share.settings.limits.maxTopicsPerVisitorHint": "Cuántas conversaciones separadas puede iniciar cada visitante registrado.","share.settings.limits.maxTurnsPerTopic": "Interacciones por conversación",@@ -363,6 +365,9 @@"share.settings.updateError": "No se pudo guardar el cambio. Por favor, inténtalo de nuevo.","share.settings.usage.conversations": "Conversaciones","share.settings.usage.desc": "Lo que ha atraído este enlace compartido y lo que te ha costado.",+ "share.settings.usage.fileStorage": "Almacenamiento de archivos",+ "share.settings.usage.fileStorageOfLimit": "{{used}} de {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · adjuntos desactivados","share.settings.usage.loadFailed": "No se pudo cargar el uso","share.settings.usage.monthlySpend": "Gasto de este mes","share.settings.usage.spendOfLimit": "${{spend}} de ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "Iniciar sesión","share.visitor.access.signInDesc": "Inicia sesión para comenzar a chatear con este agente compartido. Tus conversaciones permanecerán vinculadas a tu cuenta.","share.visitor.access.signInTitle": "Inicia sesión para continuar",+ "share.visitor.errors.fileUnavailable": "Uno de los adjuntos ya no está disponible. Elimínalo e inténtalo de nuevo.","share.visitor.errors.generic": "No se pudo enviar el mensaje. Por favor, inténtalo de nuevo.","share.visitor.errors.heterogeneousUnsupported": "Este agente compartido aún no está disponible para el chat de visitantes. Por favor, contacta a su propietario.","share.visitor.errors.insufficientBudget": "Este agente compartido se ha quedado sin presupuesto. Por favor, contacta a su propietario.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} herramientas están abiertas a los visitantes.","share.visitor.profile.terms.topics": "Puedes abrir hasta {{count}} conversaciones.","share.visitor.profile.terms.turns": "Cada conversación permite hasta {{count}} turnos.",+ "share.visitor.profile.terms.uploads": "Puedes adjuntar archivos; este Ajan tiene {{size}} de almacenamiento de archivos para visitantes.",+ "share.visitor.profile.terms.uploadsOff": "Los adjuntos están desactivados.","share.visitor.profile.terms.visibilityCreator": "El creador ha activado la revisión de sesiones, por lo que puede leer esta conversación.","share.visitor.profile.terms.visibilityPrivate": "Solo tú puedes ver tus conversaciones.","share.visitor.topBar.home": "Ir a mi LobeHub",@@ -421,6 +429,9 @@"share.visitor.topics.new": "Nueva conversación","share.visitor.topics.title": "Conversaciones","share.visitor.topics.untitled": "Conversación sin título",+ "share.visitor.upload.creatorStorageBlocked": "El espacio de carga de este Ajan está lleno. Pide a su creador que libere espacio o aumente el límite.",+ "share.visitor.upload.fileTooLarge": "Los archivos deben ser menores de {{max}}.",+ "share.visitor.upload.tooManyFiles": "Puedes adjuntar hasta {{max}} archivos por mensaje.","transfer.button": "Transferir","transfer.confirm.botChannels": "Es posible que las conexiones de los canales de bots necesiten ser actualizadas después de la transferencia","transfer.confirm.chatGroups": "Se eliminarán las asociaciones de grupos con múltiples agentes",diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.jsonindex a0598c9f3be..6b06566288e 100644--- a/locales/es-ES/chat.json+++ b/locales/es-ES/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "Hallazgo","goalProcess.kind.problem": "Pregunta","goalProcess.kind.task": "Tarea",+ "goalProcess.linked.open": "Abrir progreso del objetivo","goalProcess.manager.pending": "Esperando la primera ejecución","goalProcess.manager.title": "Agente principal","goalProcess.manager.turns": "Rondas de planificación: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "Pausado — no se iniciará nuevo trabajo","goalProcess.planning.description": "El coordinador está dividiendo el objetivo en tareas ejecutables — aparecerán aquí en breve.","goalProcess.planning.title": "Planificación de la exploración",+ "goalProcess.portal.openPage": "Abrir página del objetivo",+ "goalProcess.portal.title": "Objetivo","goalProcess.requirementPlaceholder": "Describe qué se considera como completado…","goalProcess.requirementSaveFailed": "No se pudo guardar el requisito — se intentará nuevamente en tu próxima edición","goalProcess.resume": "Reanudar",diff --git a/locales/es-ES/file.json b/locales/es-ES/file.jsonindex c9f3af60cc9..5fcc972ff53 100644--- a/locales/es-ES/file.json+++ b/locales/es-ES/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "Tu página se guarda automáticamente. No es necesario guardar manualmente.","pageEditor.chooseIcon": "Elegir ícono","pageEditor.comments.anchor.add": "Comentario",+ "pageEditor.comments.anchor.addToLine": "Comentar en esta línea","pageEditor.comments.anchor.label": "Texto citado:","pageEditor.comments.anchor.missing": "Original eliminado","pageEditor.comments.anchor.remove": "Eliminar cita",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "Este comentario fue eliminado.","pageEditor.comments.edit": "Editar","pageEditor.comments.edited": "(editado)",+ "pageEditor.comments.gutterEmpty": "Selecciona texto en el documento para comentarlo.",+ "pageEditor.comments.gutterEmptyReadOnly": "Aún no hay comentarios.","pageEditor.comments.hideReplies": "Ocultar respuestas","pageEditor.comments.loadMore": "Cargar más comentarios","pageEditor.comments.loadMoreReplies": "Cargar más respuestas",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "Escribe una respuesta…","pageEditor.comments.save": "Guardar","pageEditor.comments.title": "Comentarios",+ "pageEditor.comments.toggle": "Comentarios","pageEditor.comments.updateFailed": "No se pudo actualizar el comentario. Inténtalo de nuevo.",+ "pageEditor.copilot.toggle": "Preguntar a Lobe AI","pageEditor.deleteConfirm.content": "Esta página se eliminará y no se podrá recuperar. Procede con precaución.","pageEditor.deleteConfirm.title": "Eliminar página","pageEditor.deleteError": "Error al eliminar la página",diff --git a/locales/es-ES/pageShare.json b/locales/es-ES/pageShare.jsonindex 5dd6aeb08b4..a145e88bfa0 100644--- a/locales/es-ES/pageShare.json+++ b/locales/es-ES/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "¿Te gusta esta página? <strong>Crea la tuya con {{appName}}</strong> — espacio de trabajo gratuito para documentos nativos de IA.","banner.signIn": "Iniciar sesión","banner.signUp": "Regístrate gratis",+ "error.invalidFormat.desc": "Aún puedes leerlo. El diseño puede diferir del original.",+ "error.invalidFormat.ownerHint": "Vuelve a guardarlo en el editor para restaurar el diseño original.",+ "error.invalidFormat.title": "Esta página no se pudo mostrar en su formato original","error.notFound.desc": "Esta página ya no existe o ha sido eliminada.","error.notFound.title": "Página no encontrada","error.private.action": "Iniciar sesión",diff --git a/locales/fa-IR/agent.json b/locales/fa-IR/agent.jsonindex b85b5590430..a698909b1b1 100644--- a/locales/fa-IR/agent.json+++ b/locales/fa-IR/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "شناسه حساب ویچت که توسط جریان تأیید بازگردانده شده است.","share.entry": "اشتراکگذاری این عامل","share.settings.limits.desc": "هر اجرای بازدیدکننده به حساب شما صورت میگیرد، بنابراین این محدودیتها از افزایش هزینههای شما جلوگیری میکنند. این محدودیتها همیشه اعمال میشوند — شما میتوانید اعداد را تغییر دهید، اما نمیتوانید آنها را غیرفعال کنید.",+ "share.settings.limits.maxFileStorage": "حد ذخیرهسازی فایل (مگابایت)",+ "share.settings.limits.maxFileStorageHint": "فایلهایی که بازدیدکنندگان پیوست میکنند در حساب شما ذخیره میشوند. آپلودها زمانی متوقف میشوند که به این مقدار برسند؛ برای غیرفعال کردن پیوستها مقدار 0 را تنظیم کنید.","share.settings.limits.maxTopicsPerVisitor": "مکالمات به ازای هر بازدیدکننده","share.settings.limits.maxTopicsPerVisitorHint": "تعداد مکالمات جداگانهای که هر بازدیدکننده وارد شده میتواند شروع کند.","share.settings.limits.maxTurnsPerTopic": "تعداد پیامها در هر مکالمه",@@ -363,6 +365,9 @@"share.settings.updateError": "تغییر ذخیره نشد. لطفاً دوباره تلاش کنید.","share.settings.usage.conversations": "مکالمات","share.settings.usage.desc": "آنچه این اشتراک جذب کرده و هزینهای که برای شما داشته است.",+ "share.settings.usage.fileStorage": "ذخیرهسازی فایل",+ "share.settings.usage.fileStorageOfLimit": "{{used}} از {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · پیوستها غیرفعال هستند","share.settings.usage.loadFailed": "استفاده بارگذاری نشد","share.settings.usage.monthlySpend": "هزینه این ماه","share.settings.usage.spendOfLimit": "${{spend}} از ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "ورود","share.visitor.access.signInDesc": "وارد شوید تا گفتگو با این عامل مشترک را شروع کنید. مکالمات شما به حساب شما مرتبط میمانند.","share.visitor.access.signInTitle": "برای ادامه وارد شوید",+ "share.visitor.errors.fileUnavailable": "یکی از پیوستها دیگر در دسترس نیست. آن را حذف کنید و دوباره تلاش کنید.","share.visitor.errors.generic": "ارسال پیام شکست خورد. لطفاً دوباره تلاش کنید.","share.visitor.errors.heterogeneousUnsupported": "این عامل مشترک هنوز برای چت بازدیدکنندگان در دسترس نیست. لطفاً با مالک آن تماس بگیرید.","share.visitor.errors.insufficientBudget": "این عامل مشترک بودجه خود را تمام کرده است. لطفاً با مالک آن تماس بگیرید.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} ابزار برای بازدیدکنندگان باز است.","share.visitor.profile.terms.topics": "میتوانید تا {{count}} گفتگو را باز کنید.","share.visitor.profile.terms.turns": "هر گفتگو حداکثر {{count}} نوبت دارد.",+ "share.visitor.profile.terms.uploads": "میتوانید فایلها را پیوست کنید؛ این Ajan دارای {{size}} فضای ذخیرهسازی فایل برای بازدیدکنندگان است.",+ "share.visitor.profile.terms.uploadsOff": "پیوستها غیرفعال هستند.","share.visitor.profile.terms.visibilityCreator": "سازنده بازبینی جلسه را فعال کرده است، بنابراین میتواند این گفتگو را بخواند.","share.visitor.profile.terms.visibilityPrivate": "فقط شما میتوانید گفتگوهای خود را ببینید.","share.visitor.topBar.home": "رفتن به LobeHub من",@@ -421,6 +429,9 @@"share.visitor.topics.new": "مکالمه جدید","share.visitor.topics.title": "مکالمات","share.visitor.topics.untitled": "مکالمه بدون عنوان",+ "share.visitor.upload.creatorStorageBlocked": "فضای آپلود این Ajan پر است. از سازنده آن بخواهید فضا را آزاد کند یا محدودیت را افزایش دهد.",+ "share.visitor.upload.fileTooLarge": "فایلها باید کمتر از {{max}} باشند.",+ "share.visitor.upload.tooManyFiles": "میتوانید حداکثر {{max}} فایل در هر پیام پیوست کنید.","transfer.button": "انتقال","transfer.confirm.botChannels": "اتصالات کانالهای ربات ممکن است پس از انتقال نیاز به تازهسازی داشته باشند","transfer.confirm.chatGroups": "ارتباطات گروههای چندعاملی حذف خواهد شد",diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.jsonindex 640dda625d7..94e9051a392 100644--- a/locales/fa-IR/chat.json+++ b/locales/fa-IR/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "یافته","goalProcess.kind.problem": "سؤال","goalProcess.kind.task": "وظیفه",+ "goalProcess.linked.open": "باز کردن پیشرفت هدف","goalProcess.manager.pending": "در انتظار اجرای اول","goalProcess.manager.title": "عامل اصلی","goalProcess.manager.turns": "دورهای برنامهریزی: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "متوقف شد — هیچ کار جدیدی شروع نخواهد شد","goalProcess.planning.description": "هماهنگکننده در حال تقسیم هدف به وظایف قابل اجرا است — این وظایف به زودی اینجا ظاهر خواهند شد.","goalProcess.planning.title": "برنامهریزی اکتشاف",+ "goalProcess.portal.openPage": "باز کردن صفحه هدف",+ "goalProcess.portal.title": "هدف","goalProcess.requirementPlaceholder": "توضیح دهید چه چیزی به عنوان انجامشده محسوب میشود…","goalProcess.requirementSaveFailed": "ذخیره الزامات ناموفق بود — در ویرایش بعدی شما دوباره تلاش خواهد کرد","goalProcess.resume": "ادامه",diff --git a/locales/fa-IR/file.json b/locales/fa-IR/file.jsonindex 70c1fa783d5..fd537b902d8 100644--- a/locales/fa-IR/file.json+++ b/locales/fa-IR/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "صفحه شما بهصورت خودکار ذخیره میشود. نیازی به ذخیره دستی نیست.","pageEditor.chooseIcon": "انتخاب آیکون","pageEditor.comments.anchor.add": "نظر",+ "pageEditor.comments.anchor.addToLine": "نظر در این خط","pageEditor.comments.anchor.label": "متن نقلشده:","pageEditor.comments.anchor.missing": "متن اصلی حذف شده است","pageEditor.comments.anchor.remove": "حذف نقلقول",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "این نظر حذف شده است.","pageEditor.comments.edit": "ویرایش","pageEditor.comments.edited": "(ویرایش شده)",+ "pageEditor.comments.gutterEmpty": "برای نظر دادن، متنی را در سند انتخاب کنید.",+ "pageEditor.comments.gutterEmptyReadOnly": "هنوز نظری وجود ندارد.","pageEditor.comments.hideReplies": "پنهان کردن پاسخها","pageEditor.comments.loadMore": "بارگذاری نظرات بیشتر","pageEditor.comments.loadMoreReplies": "بارگذاری پاسخهای بیشتر",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "یک پاسخ بنویسید...","pageEditor.comments.save": "ذخیره","pageEditor.comments.title": "نظرات",+ "pageEditor.comments.toggle": "نظرات","pageEditor.comments.updateFailed": "بهروزرسانی نظر ناموفق بود. دوباره تلاش کنید.",+ "pageEditor.copilot.toggle": "از Lobe AI بپرسید","pageEditor.deleteConfirm.content": "این صفحه حذف خواهد شد و قابل بازیابی نیست. لطفاً با احتیاط ادامه دهید.","pageEditor.deleteConfirm.title": "حذف صفحه","pageEditor.deleteError": "حذف صفحه ناموفق بود",diff --git a/locales/fa-IR/pageShare.json b/locales/fa-IR/pageShare.jsonindex e2f250c18d4..e2c22b69aaa 100644--- a/locales/fa-IR/pageShare.json+++ b/locales/fa-IR/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "از این صفحه خوشتان آمده؟ <strong>صفحه خود را با {{appName}} ایجاد کنید</strong> — فضای کاری رایگان برای مستندات مبتنی بر هوش مصنوعی.","banner.signIn": "ورود","banner.signUp": "ثبتنام رایگان",+ "error.invalidFormat.desc": "شما هنوز میتوانید آن را بخوانید. طرحبندی ممکن است با نسخه اصلی متفاوت باشد.",+ "error.invalidFormat.ownerHint": "آن را در ویرایشگر دوباره ذخیره کنید تا طرحبندی اصلی بازیابی شود.",+ "error.invalidFormat.title": "این صفحه نمیتواند در قالب اصلی خود نمایش داده شود","error.notFound.desc": "این صفحه دیگر وجود ندارد یا حذف شده است.","error.notFound.title": "صفحه پیدا نشد","error.private.action": "ورود",diff --git a/locales/fr-FR/agent.json b/locales/fr-FR/agent.jsonindex 2cd7ebe4c29..616ba84a260 100644--- a/locales/fr-FR/agent.json+++ b/locales/fr-FR/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "Identifiant du compte WeChat renvoyé par le processus d'autorisation.","share.entry": "Partager cet Agent","share.settings.limits.desc": "Chaque exécution par un visiteur est facturée sur votre compte, donc ces limites empêchent un lien partagé de générer des coûts excessifs. Elles s'appliquent toujours — vous pouvez modifier les chiffres, mais pas les désactiver.",+ "share.settings.limits.maxFileStorage": "Limite de stockage de fichiers (Mo)",+ "share.settings.limits.maxFileStorageHint": "Les fichiers que les visiteurs joignent sont stockés sur votre compte. Les téléchargements s'arrêtent une fois ce total atteint ; définissez 0 pour désactiver les pièces jointes.","share.settings.limits.maxTopicsPerVisitor": "Conversations par visiteur","share.settings.limits.maxTopicsPerVisitorHint": "Nombre de conversations distinctes que chaque visiteur connecté peut démarrer.","share.settings.limits.maxTurnsPerTopic": "Tours par conversation",@@ -363,6 +365,9 @@"share.settings.updateError": "Impossible de sauvegarder la modification. Veuillez réessayer.","share.settings.usage.conversations": "Conversations","share.settings.usage.desc": "Ce que ce partage a attiré, et ce qu'il vous a coûté.",+ "share.settings.usage.fileStorage": "Stockage de fichiers",+ "share.settings.usage.fileStorageOfLimit": "{{used}} sur {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · pièces jointes désactivées","share.settings.usage.loadFailed": "Impossible de charger l'utilisation","share.settings.usage.monthlySpend": "Dépenses de ce mois","share.settings.usage.spendOfLimit": "${{spend}} sur ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "Se connecter","share.visitor.access.signInDesc": "Connectez-vous pour commencer à discuter avec cet agent partagé. Vos conversations restent liées à votre compte.","share.visitor.access.signInTitle": "Connectez-vous pour continuer",+ "share.visitor.errors.fileUnavailable": "Une des pièces jointes n'est plus disponible. Supprimez-la et réessayez.","share.visitor.errors.generic": "Échec de l'envoi du message. Veuillez réessayer.","share.visitor.errors.heterogeneousUnsupported": "Cet agent partagé n'est pas encore disponible pour le chat des visiteurs. Veuillez contacter son propriétaire.","share.visitor.errors.insufficientBudget": "Cet agent partagé a épuisé son budget. Veuillez contacter son propriétaire.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} outils sont ouverts aux visiteurs.","share.visitor.profile.terms.topics": "Vous pouvez ouvrir jusqu'à {{count}} conversations.","share.visitor.profile.terms.turns": "Chaque conversation permet jusqu'à {{count}} tours.",+ "share.visitor.profile.terms.uploads": "Vous pouvez joindre des fichiers ; cet Ajan dispose de {{size}} de stockage de fichiers pour les visiteurs.",+ "share.visitor.profile.terms.uploadsOff": "Les pièces jointes sont désactivées.","share.visitor.profile.terms.visibilityCreator": "Le créateur a activé la révision de session, il peut donc lire cette conversation.","share.visitor.profile.terms.visibilityPrivate": "Seul vous pouvez voir vos conversations.","share.visitor.topBar.home": "Aller à mon LobeHub",@@ -421,6 +429,9 @@"share.visitor.topics.new": "Nouvelle conversation","share.visitor.topics.title": "Conversations","share.visitor.topics.untitled": "Conversation sans titre",+ "share.visitor.upload.creatorStorageBlocked": "L'espace de téléchargement de cet Ajan est plein. Demandez à son créateur de libérer de l'espace ou d'augmenter la limite.",+ "share.visitor.upload.fileTooLarge": "Les fichiers doivent être inférieurs à {{max}}.",+ "share.visitor.upload.tooManyFiles": "Vous pouvez joindre jusqu'à {{max}} fichiers par message.","transfer.button": "Transférer","transfer.confirm.botChannels": "Les connexions des canaux de bot peuvent nécessiter une actualisation après le transfert","transfer.confirm.chatGroups": "Les associations de groupes multi-agents seront supprimées",diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.jsonindex b00085ea679..5fdb87aff46 100644--- a/locales/fr-FR/chat.json+++ b/locales/fr-FR/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "Résultat","goalProcess.kind.problem": "Question","goalProcess.kind.task": "Tâche",+ "goalProcess.linked.open": "Ouvrir la progression de l'objectif","goalProcess.manager.pending": "En attente de la première exécution","goalProcess.manager.title": "Agent principal","goalProcess.manager.turns": "Tours de planification : {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "En pause — aucune nouvelle tâche ne commencera","goalProcess.planning.description": "Le coordinateur décompose l'objectif en tâches exécutables — elles apparaîtront ici sous peu.","goalProcess.planning.title": "Planification de l'exploration",+ "goalProcess.portal.openPage": "Ouvrir la page de l'objectif",+ "goalProcess.portal.title": "Objectif","goalProcess.requirementPlaceholder": "Décrivez ce qui est considéré comme terminé…","goalProcess.requirementSaveFailed": "Échec de l'enregistrement de l'exigence — cela sera réessayé lors de votre prochaine modification","goalProcess.resume": "Reprendre",diff --git a/locales/fr-FR/file.json b/locales/fr-FR/file.jsonindex fe1388dbfb2..0446c8aff2b 100644--- a/locales/fr-FR/file.json+++ b/locales/fr-FR/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "Votre page est enregistrée automatiquement. Aucun enregistrement manuel nécessaire.","pageEditor.chooseIcon": "Choisir une icône","pageEditor.comments.anchor.add": "Commentaire",+ "pageEditor.comments.anchor.addToLine": "Commenter cette ligne","pageEditor.comments.anchor.label": "Texte cité :","pageEditor.comments.anchor.missing": "Original supprimé","pageEditor.comments.anchor.remove": "Supprimer la citation",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "Ce commentaire a été supprimé.","pageEditor.comments.edit": "Modifier","pageEditor.comments.edited": "(modifié)",+ "pageEditor.comments.gutterEmpty": "Sélectionnez du texte dans le document pour le commenter.",+ "pageEditor.comments.gutterEmptyReadOnly": "Pas encore de commentaires.","pageEditor.comments.hideReplies": "Masquer les réponses","pageEditor.comments.loadMore": "Charger plus de commentaires","pageEditor.comments.loadMoreReplies": "Charger plus de réponses",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "Écrire une réponse…","pageEditor.comments.save": "Enregistrer","pageEditor.comments.title": "Commentaires",+ "pageEditor.comments.toggle": "Commentaires","pageEditor.comments.updateFailed": "Échec de la mise à jour du commentaire. Réessayez.",+ "pageEditor.copilot.toggle": "Demander à Lobe AI","pageEditor.deleteConfirm.content": "Cette page sera supprimée de façon définitive. Veuillez confirmer.","pageEditor.deleteConfirm.title": "Supprimer la page","pageEditor.deleteError": "Échec de la suppression de la page",diff --git a/locales/fr-FR/pageShare.json b/locales/fr-FR/pageShare.jsonindex 3840ad8b6b6..9a07f5be42f 100644--- a/locales/fr-FR/pageShare.json+++ b/locales/fr-FR/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "Vous aimez cette page ? <strong>Créez la vôtre avec {{appName}}</strong> — espace de travail gratuit pour des documents natifs IA.","banner.signIn": "Se connecter","banner.signUp": "Inscrivez-vous gratuitement",+ "error.invalidFormat.desc": "Vous pouvez toujours le lire. La mise en page peut différer de l'original.",+ "error.invalidFormat.ownerHint": "Réenregistrez-le dans l'éditeur pour restaurer la mise en page originale.",+ "error.invalidFormat.title": "Cette page n'a pas pu être affichée dans son format original","error.notFound.desc": "Cette page n'existe plus ou a été supprimée.","error.notFound.title": "Page introuvable","error.private.action": "Se connecter",diff --git a/locales/it-IT/agent.json b/locales/it-IT/agent.jsonindex c1f8eb867d2..96124c94593 100644--- a/locales/it-IT/agent.json+++ b/locales/it-IT/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "Identificativo dell'account WeChat restituito dal flusso di autorizzazione.","share.entry": "Condividi questo Agente","share.settings.limits.desc": "Ogni esecuzione da parte dei visitatori viene addebitata sul tuo account, quindi questi limiti servono a evitare che un link condiviso faccia aumentare troppo il tuo costo. Si applicano sempre — puoi modificare i numeri, ma non disattivarli.",+ "share.settings.limits.maxFileStorage": "Limite di archiviazione file (MB)",+ "share.settings.limits.maxFileStorageHint": "I file allegati dai visitatori sono archiviati nel tuo account. I caricamenti si interrompono una volta raggiunto questo totale; imposta 0 per disattivare gli allegati.","share.settings.limits.maxTopicsPerVisitor": "Conversazioni per visitatore","share.settings.limits.maxTopicsPerVisitorHint": "Quante conversazioni separate ogni visitatore registrato può avviare.","share.settings.limits.maxTurnsPerTopic": "Messaggi per conversazione",@@ -363,6 +365,9 @@"share.settings.updateError": "Impossibile salvare la modifica. Riprova.","share.settings.usage.conversations": "Conversazioni","share.settings.usage.desc": "Cosa ha attirato questa condivisione e quanto ti è costata.",+ "share.settings.usage.fileStorage": "Archiviazione file",+ "share.settings.usage.fileStorageOfLimit": "{{used}} di {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · allegati disattivati","share.settings.usage.loadFailed": "Impossibile caricare l'utilizzo","share.settings.usage.monthlySpend": "Spesa di questo mese","share.settings.usage.spendOfLimit": "${{spend}} di ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "Accedi","share.visitor.access.signInDesc": "Accedi per iniziare a chattare con questo agente condiviso. Le tue conversazioni rimangono legate al tuo account.","share.visitor.access.signInTitle": "Accedi per continuare",+ "share.visitor.errors.fileUnavailable": "Uno degli allegati non è più disponibile. Rimuovilo e riprova.","share.visitor.errors.generic": "Impossibile inviare il messaggio. Riprova.","share.visitor.errors.heterogeneousUnsupported": "Questo agente condiviso non è ancora disponibile per la chat dei visitatori. Contatta il proprietario.","share.visitor.errors.insufficientBudget": "Questo agente condiviso ha esaurito il budget. Contatta il proprietario.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} strumenti sono aperti ai visitatori.","share.visitor.profile.terms.topics": "Puoi aprire fino a {{count}} conversazioni.","share.visitor.profile.terms.turns": "Ogni conversazione consente fino a {{count}} turni.",+ "share.visitor.profile.terms.uploads": "Puoi allegare file; questo Ajan ha {{size}} di spazio di archiviazione file per i visitatori.",+ "share.visitor.profile.terms.uploadsOff": "Gli allegati sono disattivati.","share.visitor.profile.terms.visibilityCreator": "Il creatore ha attivato la revisione della sessione, quindi può leggere questa conversazione.","share.visitor.profile.terms.visibilityPrivate": "Solo tu puoi vedere le tue conversazioni.","share.visitor.topBar.home": "Vai al mio LobeHub",@@ -421,6 +429,9 @@"share.visitor.topics.new": "Nuova conversazione","share.visitor.topics.title": "Conversazioni","share.visitor.topics.untitled": "Conversazione senza titolo",+ "share.visitor.upload.creatorStorageBlocked": "Lo spazio di caricamento di questo Ajan è pieno. Chiedi al suo creatore di liberare spazio o aumentare il limite.",+ "share.visitor.upload.fileTooLarge": "I file devono essere inferiori a {{max}}.",+ "share.visitor.upload.tooManyFiles": "Puoi allegare fino a {{max}} file per messaggio.","transfer.button": "Trasferisci","transfer.confirm.botChannels": "Le connessioni ai canali bot potrebbero dover essere aggiornate dopo il trasferimento","transfer.confirm.chatGroups": "Le associazioni ai gruppi multi-agente saranno rimosse",diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.jsonindex e7a6e3cdf0e..095adaae082 100644--- a/locales/it-IT/chat.json+++ b/locales/it-IT/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "Risultato","goalProcess.kind.problem": "Domanda","goalProcess.kind.task": "Compito",+ "goalProcess.linked.open": "Apri il progresso dell'obiettivo","goalProcess.manager.pending": "In attesa della prima esecuzione","goalProcess.manager.title": "Agente principale","goalProcess.manager.turns": "Turni di pianificazione: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "In pausa — non inizierà nuovo lavoro","goalProcess.planning.description": "Il coordinatore sta suddividendo l'obiettivo in attività eseguibili — appariranno qui a breve.","goalProcess.planning.title": "Pianificazione dell'esplorazione",+ "goalProcess.portal.openPage": "Apri la pagina dell'obiettivo",+ "goalProcess.portal.title": "Obiettivo","goalProcess.requirementPlaceholder": "Descrivi cosa si intende per completato…","goalProcess.requirementSaveFailed": "Impossibile salvare il requisito — verrà ritentato alla tua prossima modifica","goalProcess.resume": "Riprendi",diff --git a/locales/it-IT/file.json b/locales/it-IT/file.jsonindex 5440759e2be..bdc3e77086d 100644--- a/locales/it-IT/file.json+++ b/locales/it-IT/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "La tua pagina viene salvata automaticamente. Non è necessario salvare manualmente.","pageEditor.chooseIcon": "Scegli icona","pageEditor.comments.anchor.add": "Commento",+ "pageEditor.comments.anchor.addToLine": "Commenta questa riga","pageEditor.comments.anchor.label": "Testo citato:","pageEditor.comments.anchor.missing": "Originale rimosso","pageEditor.comments.anchor.remove": "Rimuovi citazione",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "Questo commento è stato eliminato.","pageEditor.comments.edit": "Modifica","pageEditor.comments.edited": "(modificato)",+ "pageEditor.comments.gutterEmpty": "Seleziona il testo nel documento per commentarlo.",+ "pageEditor.comments.gutterEmptyReadOnly": "Nessun commento ancora.","pageEditor.comments.hideReplies": "Nascondi risposte","pageEditor.comments.loadMore": "Carica più commenti","pageEditor.comments.loadMoreReplies": "Carica più risposte",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "Scrivi una risposta…","pageEditor.comments.save": "Salva","pageEditor.comments.title": "Commenti",+ "pageEditor.comments.toggle": "Commenti","pageEditor.comments.updateFailed": "Impossibile aggiornare il commento. Riprova.",+ "pageEditor.copilot.toggle": "Chiedi a Lobe AI","pageEditor.deleteConfirm.content": "Questa pagina verrà eliminata e non potrà essere recuperata. Procedi con cautela.","pageEditor.deleteConfirm.title": "Elimina pagina","pageEditor.deleteError": "Eliminazione della pagina non riuscita",diff --git a/locales/it-IT/pageShare.json b/locales/it-IT/pageShare.jsonindex a5ab9494d9b..68ed7fa13de 100644--- a/locales/it-IT/pageShare.json+++ b/locales/it-IT/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "Ti piace questa pagina? <strong>Crea la tua con {{appName}}</strong> — spazio di lavoro gratuito per documenti nativi AI.","banner.signIn": "Accedi","banner.signUp": "Registrati gratis",+ "error.invalidFormat.desc": "Puoi ancora leggerlo. Il layout potrebbe differire dall'originale.",+ "error.invalidFormat.ownerHint": "Salvalo nuovamente nell'editor per ripristinare il layout originale.",+ "error.invalidFormat.title": "Questa pagina non può essere mostrata nel suo formato originale","error.notFound.desc": "Questa pagina non esiste più o è stata rimossa.","error.notFound.title": "Pagina non trovata","error.private.action": "Accedi",diff --git a/locales/ja-JP/agent.json b/locales/ja-JP/agent.jsonindex 567a045b65d..be8cf1044fb 100644--- a/locales/ja-JP/agent.json+++ b/locales/ja-JP/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "認証フローによって返されるWeChatアカウント識別子。","share.entry": "このエージェントを共有","share.settings.limits.desc": "訪問者の実行はすべてあなたのアカウントに請求されます。そのため、これらの制限は共有リンクが請求を増やしすぎるのを防ぎます。これらは常に適用されます — 数値を変更することはできますが、オフにすることはできません。",+ "share.settings.limits.maxFileStorage": "ファイルストレージ制限 (MB)",+ "share.settings.limits.maxFileStorageHint": "訪問者が添付するファイルはあなたのアカウントに保存されます。アップロードはこの合計に達すると停止します。添付ファイルを無効にするには0を設定してください。","share.settings.limits.maxTopicsPerVisitor": "訪問者ごとの会話数","share.settings.limits.maxTopicsPerVisitorHint": "サインインした訪問者が開始できる個別の会話の数。","share.settings.limits.maxTurnsPerTopic": "会話ごとのターン数",@@ -363,6 +365,9 @@"share.settings.updateError": "変更を保存できませんでした。再試行してください。","share.settings.usage.conversations": "会話","share.settings.usage.desc": "この共有が引き付けたものと、それにかかった費用。",+ "share.settings.usage.fileStorage": "ファイルストレージ",+ "share.settings.usage.fileStorageOfLimit": "{{used}} / {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · 添付ファイル無効","share.settings.usage.loadFailed": "使用状況を読み込めませんでした","share.settings.usage.monthlySpend": "今月の支出","share.settings.usage.spendOfLimit": "${{spend}} / ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "サインイン","share.visitor.access.signInDesc": "サインインしてこの共有エージェントとチャットを開始してください。会話はあなたのアカウントに紐づけられます。","share.visitor.access.signInTitle": "続行するにはサインインしてください",+ "share.visitor.errors.fileUnavailable": "添付ファイルの1つが利用できなくなっています。削除して再試行してください。","share.visitor.errors.generic": "メッセージの送信に失敗しました。再試行してください。","share.visitor.errors.heterogeneousUnsupported": "この共有エージェントはまだ訪問者チャットに対応していません。所有者に連絡してください。","share.visitor.errors.insufficientBudget": "この共有エージェントの予算が尽きました。所有者に連絡してください。",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} つのツールが訪問者に公開されています。","share.visitor.profile.terms.topics": "最大 {{count}} 件の会話を開くことができます。","share.visitor.profile.terms.turns": "各会話で最大 {{count}} ターンが可能です。",+ "share.visitor.profile.terms.uploads": "ファイルを添付できます。このエージェントには訪問者用に{{size}}のファイルストレージがあります。",+ "share.visitor.profile.terms.uploadsOff": "添付ファイルは無効になっています。","share.visitor.profile.terms.visibilityCreator": "作成者がセッションレビューを有効にしているため、この会話を読むことができます。","share.visitor.profile.terms.visibilityPrivate": "自分だけが自分の会話を見ることができます。","share.visitor.topBar.home": "私のLobeHubに移動",@@ -421,6 +429,9 @@"share.visitor.topics.new": "新しい会話","share.visitor.topics.title": "会話","share.visitor.topics.untitled": "無題の会話",+ "share.visitor.upload.creatorStorageBlocked": "このエージェントのアップロードスペースがいっぱいです。作成者に空き容量を確保するか、制限を引き上げるよう依頼してください。",+ "share.visitor.upload.fileTooLarge": "ファイルは{{max}}以下である必要があります。",+ "share.visitor.upload.tooManyFiles": "1メッセージにつき最大{{max}}ファイルを添付できます。","transfer.button": "転送","transfer.confirm.botChannels": "転送後、ボットチャンネル接続を更新する必要がある場合があります","transfer.confirm.chatGroups": "マルチエージェントグループの関連付けは削除されます",diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.jsonindex 3c410a86fa8..f9ab396a30d 100644--- a/locales/ja-JP/chat.json+++ b/locales/ja-JP/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "発見","goalProcess.kind.problem": "質問","goalProcess.kind.task": "タスク",+ "goalProcess.linked.open": "目標進捗を開く","goalProcess.manager.pending": "最初の実行を待機中","goalProcess.manager.title": "メインエージェント","goalProcess.manager.turns": "計画ラウンド: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "一時停止中 — 新しい作業は開始されません","goalProcess.planning.description": "コーディネーターが目標を実行可能なタスクに分解しています — まもなくここに表示されます。","goalProcess.planning.title": "探索の計画",+ "goalProcess.portal.openPage": "目標ページを開く",+ "goalProcess.portal.title": "目標","goalProcess.requirementPlaceholder": "完了の基準を記述してください…","goalProcess.requirementSaveFailed": "要件の保存に失敗しました — 次回の編集時に再試行されます","goalProcess.resume": "再開",diff --git a/locales/ja-JP/file.json b/locales/ja-JP/file.jsonindex 6581910a4e4..da56198a0c0 100644--- a/locales/ja-JP/file.json+++ b/locales/ja-JP/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "ドキュメントは自動的に保存されます。手動で保存する必要はありません。","pageEditor.chooseIcon": "アイコンを選択","pageEditor.comments.anchor.add": "コメント",+ "pageEditor.comments.anchor.addToLine": "この行にコメントする","pageEditor.comments.anchor.label": "引用テキスト:","pageEditor.comments.anchor.missing": "元のテキストが削除されました","pageEditor.comments.anchor.remove": "引用を削除",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "このコメントは削除されました。","pageEditor.comments.edit": "編集","pageEditor.comments.edited": "(編集済み)",+ "pageEditor.comments.gutterEmpty": "ドキュメント内のテキストを選択してコメントしてください。",+ "pageEditor.comments.gutterEmptyReadOnly": "まだコメントがありません。","pageEditor.comments.hideReplies": "返信を非表示","pageEditor.comments.loadMore": "さらにコメントを読み込む","pageEditor.comments.loadMoreReplies": "さらに返信を読み込む",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "返信を書く…","pageEditor.comments.save": "保存","pageEditor.comments.title": "コメント",+ "pageEditor.comments.toggle": "コメント","pageEditor.comments.updateFailed": "コメントの更新に失敗しました。再試行してください。",+ "pageEditor.copilot.toggle": "Lobe AIに尋ねる","pageEditor.deleteConfirm.content": "このドキュメントを削除しようとしています。削除後は元に戻せませんので、慎重に操作してください。","pageEditor.deleteConfirm.title": "ドキュメントの削除","pageEditor.deleteError": "ドキュメントの削除に失敗しました",diff --git a/locales/ja-JP/pageShare.json b/locales/ja-JP/pageShare.jsonindex acd14049697..69488348e1d 100644--- a/locales/ja-JP/pageShare.json+++ b/locales/ja-JP/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "このページが気に入りましたか?<strong>{{appName}}で自分のページを作成しましょう</strong> — AIネイティブドキュメントの無料ワークスペース。","banner.signIn": "ログイン","banner.signUp": "無料登録",+ "error.invalidFormat.desc": "まだ読むことはできます。レイアウトが元の形式と異なる場合があります。",+ "error.invalidFormat.ownerHint": "エディターで再保存して、元のレイアウトを復元してください。",+ "error.invalidFormat.title": "このページは元の形式で表示できませんでした","error.notFound.desc": "このページは存在しないか、削除されました。","error.notFound.title": "ページが見つかりません","error.private.action": "ログイン",diff --git a/locales/ko-KR/agent.json b/locales/ko-KR/agent.jsonindex 096d4925008..593426872f5 100644--- a/locales/ko-KR/agent.json+++ b/locales/ko-KR/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "인증 흐름에서 반환된 WeChat 계정 식별자입니다.","share.entry": "이 에이전트를 공유하기","share.settings.limits.desc": "방문자 실행은 귀하의 계정에 청구되므로 이러한 제한은 공유 링크가 청구서를 과도하게 증가시키는 것을 방지합니다. 항상 적용되며 숫자를 변경할 수 있지만 끌 수는 없습니다.",+ "share.settings.limits.maxFileStorage": "파일 저장 한도 (MB)",+ "share.settings.limits.maxFileStorageHint": "방문자가 첨부한 파일은 귀하의 계정에 저장됩니다. 업로드는 총 한도에 도달하면 중지됩니다. 첨부 파일을 비활성화하려면 0으로 설정하세요.","share.settings.limits.maxTopicsPerVisitor": "방문자당 대화 수","share.settings.limits.maxTopicsPerVisitorHint": "로그인한 각 방문자가 시작할 수 있는 별도의 대화 수입니다.","share.settings.limits.maxTurnsPerTopic": "대화당 메시지 수",@@ -363,6 +365,9 @@"share.settings.updateError": "변경 사항을 저장할 수 없습니다. 다시 시도하십시오.","share.settings.usage.conversations": "대화","share.settings.usage.desc": "이 공유가 끌어온 것과 귀하에게 비용이 든 것.",+ "share.settings.usage.fileStorage": "파일 저장소",+ "share.settings.usage.fileStorageOfLimit": "{{used}} / {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · 첨부 파일 비활성화됨","share.settings.usage.loadFailed": "사용량을 로드할 수 없습니다","share.settings.usage.monthlySpend": "이번 달 지출","share.settings.usage.spendOfLimit": "${{spend}} / ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "로그인","share.visitor.access.signInDesc": "로그인하여 이 공유 에이전트와 채팅을 시작하십시오. 대화는 귀하의 계정에 연결됩니다.","share.visitor.access.signInTitle": "계속하려면 로그인하십시오",+ "share.visitor.errors.fileUnavailable": "첨부 파일 중 하나를 더 이상 사용할 수 없습니다. 제거하고 다시 시도하세요.","share.visitor.errors.generic": "메시지를 보내는 데 실패했습니다. 다시 시도하십시오.","share.visitor.errors.heterogeneousUnsupported": "이 공유 에이전트는 아직 방문자 채팅에 사용할 수 없습니다. 소유자에게 문의하십시오.","share.visitor.errors.insufficientBudget": "이 공유 에이전트의 예산이 소진되었습니다. 소유자에게 문의하십시오.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "방문자에게 {{count}}개의 도구가 열려 있습니다.","share.visitor.profile.terms.topics": "최대 {{count}}개의 대화를 열 수 있습니다.","share.visitor.profile.terms.turns": "각 대화는 최대 {{count}} 턴까지 가능합니다.",+ "share.visitor.profile.terms.uploads": "파일을 첨부할 수 있습니다. 이 Ajan은 방문자를 위해 {{size}}의 파일 저장 공간을 제공합니다.",+ "share.visitor.profile.terms.uploadsOff": "첨부 파일이 비활성화되었습니다.","share.visitor.profile.terms.visibilityCreator": "제작자가 세션 검토를 활성화했으므로 이 대화를 읽을 수 있습니다.","share.visitor.profile.terms.visibilityPrivate": "오직 본인만 대화를 볼 수 있습니다.","share.visitor.topBar.home": "내 LobeHub로 이동",@@ -421,6 +429,9 @@"share.visitor.topics.new": "새 대화","share.visitor.topics.title": "대화","share.visitor.topics.untitled": "제목 없는 대화",+ "share.visitor.upload.creatorStorageBlocked": "이 Ajan의 업로드 공간이 가득 찼습니다. 생성자에게 공간을 확보하거나 한도를 늘려달라고 요청하세요.",+ "share.visitor.upload.fileTooLarge": "파일은 {{max}} 이하이어야 합니다.",+ "share.visitor.upload.tooManyFiles": "메시지당 최대 {{max}}개의 파일을 첨부할 수 있습니다.","transfer.button": "전송","transfer.confirm.botChannels": "전송 후 봇 채널 연결을 새로 고침해야 할 수 있습니다.","transfer.confirm.chatGroups": "다중 에이전트 그룹 연결이 제거됩니다.",diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.jsonindex b1edcaa1803..15317b80f73 100644--- a/locales/ko-KR/chat.json+++ b/locales/ko-KR/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "발견","goalProcess.kind.problem": "질문","goalProcess.kind.task": "작업",+ "goalProcess.linked.open": "목표 진행 상황 열기","goalProcess.manager.pending": "첫 실행을 기다리는 중","goalProcess.manager.title": "주요 에이전트","goalProcess.manager.turns": "계획 라운드: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "일시 중지됨 — 새로운 작업이 시작되지 않습니다","goalProcess.planning.description": "조정자가 목표를 실행 가능한 작업으로 나누고 있습니다 — 곧 여기에 표시될 것입니다.","goalProcess.planning.title": "탐색 계획 중",+ "goalProcess.portal.openPage": "목표 페이지 열기",+ "goalProcess.portal.title": "목표","goalProcess.requirementPlaceholder": "완료 기준을 설명하세요…","goalProcess.requirementSaveFailed": "요구 사항 저장에 실패했습니다 — 다음 편집 시 다시 시도됩니다","goalProcess.resume": "다시 시작",diff --git a/locales/ko-KR/file.json b/locales/ko-KR/file.jsonindex af11812016c..d53f9e9c4fe 100644--- a/locales/ko-KR/file.json+++ b/locales/ko-KR/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "문서는 자동으로 저장되며, 수동 저장이 필요하지 않습니다","pageEditor.chooseIcon": "아이콘 선택","pageEditor.comments.anchor.add": "댓글",+ "pageEditor.comments.anchor.addToLine": "이 줄에 댓글 달기","pageEditor.comments.anchor.label": "인용된 텍스트:","pageEditor.comments.anchor.missing": "원본이 삭제됨","pageEditor.comments.anchor.remove": "인용 삭제",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "이 댓글은 삭제되었습니다.","pageEditor.comments.edit": "편집","pageEditor.comments.edited": "(편집됨)",+ "pageEditor.comments.gutterEmpty": "문서에서 텍스트를 선택하여 댓글을 달아보세요.",+ "pageEditor.comments.gutterEmptyReadOnly": "아직 댓글이 없습니다.","pageEditor.comments.hideReplies": "답글 숨기기","pageEditor.comments.loadMore": "댓글 더 보기","pageEditor.comments.loadMoreReplies": "답글 더 보기",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "답글 작성…","pageEditor.comments.save": "저장","pageEditor.comments.title": "댓글",+ "pageEditor.comments.toggle": "댓글","pageEditor.comments.updateFailed": "댓글 업데이트에 실패했습니다. 다시 시도하세요.",+ "pageEditor.copilot.toggle": "Lobe AI에게 요청하기","pageEditor.deleteConfirm.content": "이 문서를 삭제하려고 합니다. 삭제 후에는 복구할 수 없으니 신중히 진행해 주세요.","pageEditor.deleteConfirm.title": "문서 삭제","pageEditor.deleteError": "문서 삭제에 실패했습니다",diff --git a/locales/ko-KR/pageShare.json b/locales/ko-KR/pageShare.jsonindex 8ec15a68100..47d9e59b49e 100644--- a/locales/ko-KR/pageShare.json+++ b/locales/ko-KR/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "이 페이지가 마음에 드시나요? <strong>{{appName}}으로 직접 만들어보세요</strong> — AI 기반 문서를 위한 무료 작업 공간.","banner.signIn": "로그인","banner.signUp": "무료 가입",+ "error.invalidFormat.desc": "여전히 읽을 수 있습니다. 레이아웃이 원본과 다를 수 있습니다.",+ "error.invalidFormat.ownerHint": "원본 레이아웃을 복원하려면 편집기에서 다시 저장하세요.",+ "error.invalidFormat.title": "이 페이지를 원본 형식으로 표시할 수 없습니다.","error.notFound.desc": "이 페이지는 더 이상 존재하지 않거나 삭제되었습니다.","error.notFound.title": "페이지를 찾을 수 없습니다","error.private.action": "로그인",diff --git a/locales/nl-NL/agent.json b/locales/nl-NL/agent.jsonindex 47e19ce2bbc..c1b5fd3e452 100644--- a/locales/nl-NL/agent.json+++ b/locales/nl-NL/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "WeChat-accountidentificatie geretourneerd door de autorisatiestroom.","share.entry": "Deel deze Agent","share.settings.limits.desc": "Elke bezoekeractie wordt in rekening gebracht op uw account, dus deze limieten voorkomen dat een gedeelde link uw kosten opdrijft. Ze zijn altijd van toepassing — u kunt de aantallen aanpassen, maar niet uitschakelen.",+ "share.settings.limits.maxFileStorage": "Bestandsopslaglimiet (MB)",+ "share.settings.limits.maxFileStorageHint": "Bestanden die bezoekers bijvoegen worden opgeslagen op uw account. Uploads stoppen zodra ze deze limiet bereiken; stel in op 0 om bijlagen uit te schakelen.","share.settings.limits.maxTopicsPerVisitor": "Gesprekken per bezoeker","share.settings.limits.maxTopicsPerVisitorHint": "Hoeveel afzonderlijke gesprekken elke ingelogde bezoeker kan starten.","share.settings.limits.maxTurnsPerTopic": "Beurten per gesprek",@@ -363,6 +365,9 @@"share.settings.updateError": "De wijziging kon niet worden opgeslagen. Probeer het opnieuw.","share.settings.usage.conversations": "Gesprekken","share.settings.usage.desc": "Wat deze gedeelde link heeft aangetrokken en wat het u heeft gekost.",+ "share.settings.usage.fileStorage": "Bestandsopslag",+ "share.settings.usage.fileStorageOfLimit": "{{used}} van {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · bijlagen uitgeschakeld","share.settings.usage.loadFailed": "Gebruik kon niet worden geladen","share.settings.usage.monthlySpend": "Uitgaven deze maand","share.settings.usage.spendOfLimit": "${{spend}} van ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "Inloggen","share.visitor.access.signInDesc": "Log in om te beginnen met chatten met deze gedeelde agent. Uw gesprekken blijven gekoppeld aan uw account.","share.visitor.access.signInTitle": "Log in om door te gaan",+ "share.visitor.errors.fileUnavailable": "Een van de bijlagen is niet langer beschikbaar. Verwijder deze en probeer opnieuw.","share.visitor.errors.generic": "Het verzenden van het bericht is mislukt. Probeer het opnieuw.","share.visitor.errors.heterogeneousUnsupported": "Deze gedeelde agent is nog niet beschikbaar voor bezoekerschat. Neem contact op met de eigenaar.","share.visitor.errors.insufficientBudget": "Deze gedeelde agent heeft geen budget meer. Neem contact op met de eigenaar.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} tools zijn open voor bezoekers.","share.visitor.profile.terms.topics": "Je kunt maximaal {{count}} gesprekken openen.","share.visitor.profile.terms.turns": "Elk gesprek staat maximaal {{count}} beurten toe.",+ "share.visitor.profile.terms.uploads": "U kunt bestanden bijvoegen; deze Ajan heeft {{size}} aan bestandsopslag voor bezoekers.",+ "share.visitor.profile.terms.uploadsOff": "Bijlagen zijn uitgeschakeld.","share.visitor.profile.terms.visibilityCreator": "De maker heeft sessiebeoordeling ingeschakeld, zodat ze dit gesprek kunnen lezen.","share.visitor.profile.terms.visibilityPrivate": "Alleen jij kunt je gesprekken zien.","share.visitor.topBar.home": "Ga naar mijn LobeHub",@@ -421,6 +429,9 @@"share.visitor.topics.new": "Nieuw gesprek","share.visitor.topics.title": "Gesprekken","share.visitor.topics.untitled": "Naamloos gesprek",+ "share.visitor.upload.creatorStorageBlocked": "De uploadruimte van deze Ajan is vol. Vraag de maker om ruimte vrij te maken of de limiet te verhogen.",+ "share.visitor.upload.fileTooLarge": "Bestanden moeten kleiner zijn dan {{max}}.",+ "share.visitor.upload.tooManyFiles": "U kunt maximaal {{max}} bestanden per bericht bijvoegen.","transfer.button": "Overdragen","transfer.confirm.botChannels": "Botkanaalverbindingen moeten mogelijk worden vernieuwd na overdracht","transfer.confirm.chatGroups": "Associaties met multi-agentgroepen worden verwijderd",diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.jsonindex 8172a4711e7..67b3be54f9c 100644--- a/locales/nl-NL/chat.json+++ b/locales/nl-NL/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "Bevinding","goalProcess.kind.problem": "Vraag","goalProcess.kind.task": "Taak",+ "goalProcess.linked.open": "Doelvoortgang openen","goalProcess.manager.pending": "Wachten op de eerste uitvoering","goalProcess.manager.title": "Hoofdagent","goalProcess.manager.turns": "Planningsrondes: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "Gepauzeerd — er start geen nieuw werk","goalProcess.planning.description": "De coördinator is bezig het doel op te splitsen in uitvoerbare taken — deze verschijnen hier binnenkort.","goalProcess.planning.title": "De verkenning plannen",+ "goalProcess.portal.openPage": "Doelpagina openen",+ "goalProcess.portal.title": "Doel","goalProcess.requirementPlaceholder": "Beschrijf wat als voltooid wordt beschouwd…","goalProcess.requirementSaveFailed": "Het opslaan van de vereiste is mislukt — dit wordt opnieuw geprobeerd bij je volgende bewerking","goalProcess.resume": "Hervatten",diff --git a/locales/nl-NL/file.json b/locales/nl-NL/file.jsonindex 034f2ed9e15..629c21fbfac 100644--- a/locales/nl-NL/file.json+++ b/locales/nl-NL/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "Je pagina wordt automatisch opgeslagen. Handmatig opslaan is niet nodig.","pageEditor.chooseIcon": "Icoon kiezen","pageEditor.comments.anchor.add": "Opmerking",+ "pageEditor.comments.anchor.addToLine": "Opmerking bij deze regel","pageEditor.comments.anchor.label": "Geciteerde tekst:","pageEditor.comments.anchor.missing": "Oorspronkelijke verwijderd","pageEditor.comments.anchor.remove": "Citaat verwijderen",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "Deze reactie is verwijderd.","pageEditor.comments.edit": "Bewerken","pageEditor.comments.edited": "(bewerkt)",+ "pageEditor.comments.gutterEmpty": "Selecteer tekst in het document om erop te reageren.",+ "pageEditor.comments.gutterEmptyReadOnly": "Nog geen opmerkingen.","pageEditor.comments.hideReplies": "Antwoorden verbergen","pageEditor.comments.loadMore": "Meer reacties laden","pageEditor.comments.loadMoreReplies": "Meer antwoorden laden",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "Schrijf een antwoord…","pageEditor.comments.save": "Opslaan","pageEditor.comments.title": "Reacties",+ "pageEditor.comments.toggle": "Opmerkingen","pageEditor.comments.updateFailed": "Reactie bijwerken mislukt. Probeer opnieuw.",+ "pageEditor.copilot.toggle": "Vraag Lobe AI","pageEditor.deleteConfirm.content": "Deze pagina wordt verwijderd en kan niet worden hersteld. Wees voorzichtig.","pageEditor.deleteConfirm.title": "Pagina verwijderen","pageEditor.deleteError": "Verwijderen van pagina mislukt",diff --git a/locales/nl-NL/pageShare.json b/locales/nl-NL/pageShare.jsonindex cb35ff1d6b3..971845e45a6 100644--- a/locales/nl-NL/pageShare.json+++ b/locales/nl-NL/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "Vind je deze pagina leuk? <strong>Maak je eigen met {{appName}}</strong> — gratis werkruimte voor AI-native documenten.","banner.signIn": "Inloggen","banner.signUp": "Gratis aanmelden",+ "error.invalidFormat.desc": "Je kunt het nog steeds lezen. De lay-out kan afwijken van het origineel.",+ "error.invalidFormat.ownerHint": "Sla het opnieuw op in de editor om de originele lay-out te herstellen.",+ "error.invalidFormat.title": "Deze pagina kon niet in het originele formaat worden weergegeven","error.notFound.desc": "Deze pagina bestaat niet meer of is verwijderd.","error.notFound.title": "Pagina niet gevonden","error.private.action": "Inloggen",diff --git a/locales/pl-PL/agent.json b/locales/pl-PL/agent.jsonindex 7a60462eb7e..b0077089656 100644--- a/locales/pl-PL/agent.json+++ b/locales/pl-PL/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "Identyfikator konta WeChat zwrócony przez proces autoryzacji.","share.entry": "Udostępnij tego Agenta","share.settings.limits.desc": "Każde uruchomienie przez odwiedzającego jest rozliczane na Twoim koncie, więc te limity zapobiegają nadmiernym kosztom. Zawsze obowiązują — możesz zmienić liczby, ale nie możesz ich wyłączyć.",+ "share.settings.limits.maxFileStorage": "Limit przechowywania plików (MB)",+ "share.settings.limits.maxFileStorageHint": "Pliki dołączane przez odwiedzających są przechowywane na Twoim koncie. Przesyłanie zostaje zatrzymane po osiągnięciu tego limitu; ustaw 0, aby wyłączyć załączniki.","share.settings.limits.maxTopicsPerVisitor": "Rozmowy na odwiedzającego","share.settings.limits.maxTopicsPerVisitorHint": "Ile oddzielnych rozmów może rozpocząć każdy zalogowany odwiedzający.","share.settings.limits.maxTurnsPerTopic": "Wymiany w rozmowie",@@ -363,6 +365,9 @@"share.settings.updateError": "Nie udało się zapisać zmiany. Spróbuj ponownie.","share.settings.usage.conversations": "Rozmowy","share.settings.usage.desc": "Co przyciągnęło to udostępnienie i ile Cię to kosztowało.",+ "share.settings.usage.fileStorage": "Przechowywanie plików",+ "share.settings.usage.fileStorageOfLimit": "{{used}} z {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · załączniki wyłączone","share.settings.usage.loadFailed": "Nie udało się załadować danych o użyciu","share.settings.usage.monthlySpend": "Wydatki w tym miesiącu","share.settings.usage.spendOfLimit": "${{spend}} z ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "Zaloguj się","share.visitor.access.signInDesc": "Zaloguj się, aby rozpocząć rozmowę z tym udostępnionym agentem. Twoje rozmowy pozostaną powiązane z Twoim kontem.","share.visitor.access.signInTitle": "Zaloguj się, aby kontynuować",+ "share.visitor.errors.fileUnavailable": "Jeden z załączników nie jest już dostępny. Usuń go i spróbuj ponownie.","share.visitor.errors.generic": "Nie udało się wysłać wiadomości. Spróbuj ponownie.","share.visitor.errors.heterogeneousUnsupported": "Ten udostępniony agent nie jest jeszcze dostępny do rozmów odwiedzających. Skontaktuj się z jego właścicielem.","share.visitor.errors.insufficientBudget": "Ten udostępniony agent wyczerpał budżet. Skontaktuj się z jego właścicielem.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} narzędzia są dostępne dla odwiedzających.","share.visitor.profile.terms.topics": "Możesz otworzyć do {{count}} rozmów.","share.visitor.profile.terms.turns": "Każda rozmowa pozwala na maksymalnie {{count}} tur.",+ "share.visitor.profile.terms.uploads": "Możesz dołączać pliki; ten Ajan ma {{size}} miejsca na pliki dla odwiedzających.",+ "share.visitor.profile.terms.uploadsOff": "Załączniki są wyłączone.","share.visitor.profile.terms.visibilityCreator": "Twórca włączył przegląd sesji, więc może przeczytać tę rozmowę.","share.visitor.profile.terms.visibilityPrivate": "Tylko Ty możesz zobaczyć swoje rozmowy.","share.visitor.topBar.home": "Przejdź do mojego LobeHub",@@ -421,6 +429,9 @@"share.visitor.topics.new": "Nowa rozmowa","share.visitor.topics.title": "Rozmowy","share.visitor.topics.untitled": "Rozmowa bez tytułu",+ "share.visitor.upload.creatorStorageBlocked": "Przestrzeń na przesyłanie plików tego Ajana jest pełna. Poproś jego twórcę o zwolnienie miejsca lub zwiększenie limitu.",+ "share.visitor.upload.fileTooLarge": "Pliki muszą być mniejsze niż {{max}}.",+ "share.visitor.upload.tooManyFiles": "Możesz dołączyć maksymalnie {{max}} plików na wiadomość.","transfer.button": "Przenieś","transfer.confirm.botChannels": "Połączenia kanałów botów mogą wymagać odświeżenia po przeniesieniu","transfer.confirm.chatGroups": "Powiązania grup wieloagentowych zostaną usunięte",diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.jsonindex 55fa7c61d3d..ca40a531acb 100644--- a/locales/pl-PL/chat.json+++ b/locales/pl-PL/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "Ustalenie","goalProcess.kind.problem": "Pytanie","goalProcess.kind.task": "Zadanie",+ "goalProcess.linked.open": "Otwórz postęp celu","goalProcess.manager.pending": "Oczekiwanie na pierwsze uruchomienie","goalProcess.manager.title": "Główny agent","goalProcess.manager.turns": "Rundy planowania: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "Wstrzymane — nowe zadania nie będą rozpoczynane","goalProcess.planning.description": "Koordynator dzieli cel na wykonalne zadania — wkrótce pojawią się tutaj.","goalProcess.planning.title": "Planowanie eksploracji",+ "goalProcess.portal.openPage": "Otwórz stronę celu",+ "goalProcess.portal.title": "Cel","goalProcess.requirementPlaceholder": "Opisz, co oznacza ukończenie…","goalProcess.requirementSaveFailed": "Nie udało się zapisać wymagania — zostanie ponowione przy następnej edycji","goalProcess.resume": "Wznów",diff --git a/locales/pl-PL/file.json b/locales/pl-PL/file.jsonindex 9de97f1664e..1f1b9648b44 100644--- a/locales/pl-PL/file.json+++ b/locales/pl-PL/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "Twoja strona jest zapisywana automatycznie. Nie musisz zapisywać ręcznie.","pageEditor.chooseIcon": "Wybierz ikonę","pageEditor.comments.anchor.add": "Komentarz",+ "pageEditor.comments.anchor.addToLine": "Skomentuj tę linię","pageEditor.comments.anchor.label": "Cytowany tekst:","pageEditor.comments.anchor.missing": "Oryginał usunięty","pageEditor.comments.anchor.remove": "Usuń cytat",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "Ten komentarz został usunięty.","pageEditor.comments.edit": "Edytuj","pageEditor.comments.edited": "(edytowano)",+ "pageEditor.comments.gutterEmpty": "Zaznacz tekst w dokumencie, aby go skomentować.",+ "pageEditor.comments.gutterEmptyReadOnly": "Brak komentarzy.","pageEditor.comments.hideReplies": "Ukryj odpowiedzi","pageEditor.comments.loadMore": "Załaduj więcej komentarzy","pageEditor.comments.loadMoreReplies": "Załaduj więcej odpowiedzi",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "Napisz odpowiedź…","pageEditor.comments.save": "Zapisz","pageEditor.comments.title": "Komentarze",+ "pageEditor.comments.toggle": "Komentarze","pageEditor.comments.updateFailed": "Nie udało się zaktualizować komentarza. Spróbuj ponownie.",+ "pageEditor.copilot.toggle": "Zapytaj Lobe AI","pageEditor.deleteConfirm.content": "Ta strona zostanie usunięta i nie będzie można jej odzyskać. Proszę zachować ostrożność.","pageEditor.deleteConfirm.title": "Usuń stronę","pageEditor.deleteError": "Nie udało się usunąć strony",diff --git a/locales/pl-PL/pageShare.json b/locales/pl-PL/pageShare.jsonindex 0f231d68c6f..9b0bcad7282 100644--- a/locales/pl-PL/pageShare.json+++ b/locales/pl-PL/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "Podoba Ci się ta strona? <strong>Stwórz własną z {{appName}}</strong> — darmowe środowisko pracy dla dokumentów opartych na AI.","banner.signIn": "Zaloguj się","banner.signUp": "Zarejestruj się za darmo",+ "error.invalidFormat.desc": "Możesz nadal to przeczytać. Układ może różnić się od oryginału.",+ "error.invalidFormat.ownerHint": "Zapisz ponownie w edytorze, aby przywrócić oryginalny układ.",+ "error.invalidFormat.title": "Nie można wyświetlić tej strony w jej oryginalnym formacie","error.notFound.desc": "Ta strona już nie istnieje lub została usunięta.","error.notFound.title": "Strona nie znaleziona","error.private.action": "Zaloguj się",diff --git a/locales/pt-BR/agent.json b/locales/pt-BR/agent.jsonindex 58b708c93db..db72b62235c 100644--- a/locales/pt-BR/agent.json+++ b/locales/pt-BR/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "Identificador da conta do WeChat retornado pelo fluxo de autorização.","share.entry": "Compartilhar este Agente","share.settings.limits.desc": "Cada execução de visitante é cobrada na sua conta, então esses limites são o que impedem que um link compartilhado aumente sua conta. Eles sempre se aplicam — você pode alterar os números, mas não desativá-los.",+ "share.settings.limits.maxFileStorage": "Limite de armazenamento de arquivos (MB)",+ "share.settings.limits.maxFileStorageHint": "Os arquivos anexados pelos visitantes são armazenados na sua conta. Os uploads param quando atingem esse total; defina 0 para desativar anexos.","share.settings.limits.maxTopicsPerVisitor": "Conversas por visitante","share.settings.limits.maxTopicsPerVisitorHint": "Quantas conversas separadas cada visitante autenticado pode iniciar.","share.settings.limits.maxTurnsPerTopic": "Interações por conversa",@@ -363,6 +365,9 @@"share.settings.updateError": "Não foi possível salvar a alteração. Por favor, tente novamente.","share.settings.usage.conversations": "Conversas","share.settings.usage.desc": "O que este compartilhamento atraiu e o que custou a você.",+ "share.settings.usage.fileStorage": "Armazenamento de arquivos",+ "share.settings.usage.fileStorageOfLimit": "{{used}} de {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · anexos desativados","share.settings.usage.loadFailed": "Não foi possível carregar o uso","share.settings.usage.monthlySpend": "Gastos deste mês","share.settings.usage.spendOfLimit": "${{spend}} de ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "Entrar","share.visitor.access.signInDesc": "Entre para começar a conversar com este agente compartilhado. Suas conversas permanecem vinculadas à sua conta.","share.visitor.access.signInTitle": "Entre para continuar",+ "share.visitor.errors.fileUnavailable": "Um dos anexos não está mais disponível. Remova-o e tente novamente.","share.visitor.errors.generic": "Falha ao enviar a mensagem. Por favor, tente novamente.","share.visitor.errors.heterogeneousUnsupported": "Este agente compartilhado ainda não está disponível para chat de visitantes. Por favor, entre em contato com o proprietário.","share.visitor.errors.insufficientBudget": "Este agente compartilhado ficou sem orçamento. Por favor, entre em contato com o proprietário.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} ferramentas estão abertas para visitantes.","share.visitor.profile.terms.topics": "Você pode abrir até {{count}} conversas.","share.visitor.profile.terms.turns": "Cada conversa permite até {{count}} turnos.",+ "share.visitor.profile.terms.uploads": "Você pode anexar arquivos; este Ajan tem {{size}} de armazenamento de arquivos para visitantes.",+ "share.visitor.profile.terms.uploadsOff": "Anexos estão desativados.","share.visitor.profile.terms.visibilityCreator": "O criador ativou a revisão de sessão, então ele pode ler esta conversa.","share.visitor.profile.terms.visibilityPrivate": "Somente você pode ver suas conversas.","share.visitor.topBar.home": "Ir para meu LobeHub",@@ -421,6 +429,9 @@"share.visitor.topics.new": "Nova conversa","share.visitor.topics.title": "Conversas","share.visitor.topics.untitled": "Conversa sem título",+ "share.visitor.upload.creatorStorageBlocked": "O espaço de upload deste Ajan está cheio. Peça ao criador para liberar espaço ou aumentar o limite.",+ "share.visitor.upload.fileTooLarge": "Os arquivos devem ter menos de {{max}}.",+ "share.visitor.upload.tooManyFiles": "Você pode anexar até {{max}} arquivos por mensagem.","transfer.button": "Transferir","transfer.confirm.botChannels": "As conexões de canais de bot podem precisar ser atualizadas após a transferência","transfer.confirm.chatGroups": "Associações de grupos multiagente serão removidas",diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.jsonindex 271e50bb6ba..7e9c883232f 100644--- a/locales/pt-BR/chat.json+++ b/locales/pt-BR/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "Descoberta","goalProcess.kind.problem": "Pergunta","goalProcess.kind.task": "Tarefa",+ "goalProcess.linked.open": "Abrir progresso da meta","goalProcess.manager.pending": "Aguardando a primeira execução","goalProcess.manager.title": "Agente principal","goalProcess.manager.turns": "Rodadas de planejamento: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "Pausado — nenhum novo trabalho será iniciado","goalProcess.planning.description": "O coordenador está dividindo o objetivo em tarefas executáveis — elas aparecerão aqui em breve.","goalProcess.planning.title": "Planejando a exploração",+ "goalProcess.portal.openPage": "Abrir página da meta",+ "goalProcess.portal.title": "Meta","goalProcess.requirementPlaceholder": "Descreva o que conta como concluído…","goalProcess.requirementSaveFailed": "Falha ao salvar o requisito — será tentado novamente na sua próxima edição","goalProcess.resume": "Retomar",diff --git a/locales/pt-BR/file.json b/locales/pt-BR/file.jsonindex 2530d89a8a2..3d43038a550 100644--- a/locales/pt-BR/file.json+++ b/locales/pt-BR/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "Sua página é salva automaticamente. Não é necessário salvar manualmente.","pageEditor.chooseIcon": "Escolher Ícone","pageEditor.comments.anchor.add": "Comentário",+ "pageEditor.comments.anchor.addToLine": "Comentar nesta linha","pageEditor.comments.anchor.label": "Texto citado:","pageEditor.comments.anchor.missing": "Original removido","pageEditor.comments.anchor.remove": "Remover citação",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "Este comentário foi excluído.","pageEditor.comments.edit": "Editar","pageEditor.comments.edited": "(editado)",+ "pageEditor.comments.gutterEmpty": "Selecione o texto no documento para comentar sobre ele.",+ "pageEditor.comments.gutterEmptyReadOnly": "Ainda não há comentários.","pageEditor.comments.hideReplies": "Ocultar respostas","pageEditor.comments.loadMore": "Carregar mais comentários","pageEditor.comments.loadMoreReplies": "Carregar mais respostas",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "Escreva uma resposta…","pageEditor.comments.save": "Salvar","pageEditor.comments.title": "Comentários",+ "pageEditor.comments.toggle": "Comentários","pageEditor.comments.updateFailed": "Falha ao atualizar o comentário. Tente novamente.",+ "pageEditor.copilot.toggle": "Perguntar ao Lobe AI","pageEditor.deleteConfirm.content": "Esta página será excluída e não poderá ser recuperada. Prossiga com cautela.","pageEditor.deleteConfirm.title": "Excluir Página","pageEditor.deleteError": "Falha ao excluir a página",diff --git a/locales/pt-BR/pageShare.json b/locales/pt-BR/pageShare.jsonindex ecf8ecdc7e3..8bb55736b40 100644--- a/locales/pt-BR/pageShare.json+++ b/locales/pt-BR/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "Gostou desta página? <strong>Crie a sua com {{appName}}</strong> — espaço gratuito para documentos nativos de IA.","banner.signIn": "Entrar","banner.signUp": "Cadastre-se grátis",+ "error.invalidFormat.desc": "Você ainda pode lê-lo. O layout pode diferir do original.",+ "error.invalidFormat.ownerHint": "Re-salve no editor para restaurar o layout original.",+ "error.invalidFormat.title": "Esta página não pôde ser exibida em seu formato original","error.notFound.desc": "Esta página não existe mais ou foi removida.","error.notFound.title": "Página não encontrada","error.private.action": "Entrar",diff --git a/locales/ru-RU/agent.json b/locales/ru-RU/agent.jsonindex 1ec22ecb47f..abc6957b25e 100644--- a/locales/ru-RU/agent.json+++ b/locales/ru-RU/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "Идентификатор аккаунта WeChat, возвращаемый в процессе авторизации.","share.entry": "Поделиться этим агентом","share.settings.limits.desc": "Каждый запуск посетителя оплачивается с вашего аккаунта, поэтому эти ограничения помогают избежать чрезмерных расходов. Они всегда действуют — вы можете изменить числа, но не отключить их.",+ "share.settings.limits.maxFileStorage": "Лимит хранения файлов (МБ)",+ "share.settings.limits.maxFileStorageHint": "Файлы, которые прикрепляют посетители, хранятся в вашей учетной записи. Загрузка прекращается, когда они достигают этого лимита; установите 0, чтобы отключить вложения.","share.settings.limits.maxTopicsPerVisitor": "Беседы на одного посетителя","share.settings.limits.maxTopicsPerVisitorHint": "Сколько отдельных бесед может начать каждый авторизованный посетитель.","share.settings.limits.maxTurnsPerTopic": "Сообщений на беседу",@@ -363,6 +365,9 @@"share.settings.updateError": "Не удалось сохранить изменения. Пожалуйста, попробуйте снова.","share.settings.usage.conversations": "Беседы","share.settings.usage.desc": "Что привлек этот общий доступ и сколько это вам стоило.",+ "share.settings.usage.fileStorage": "Хранилище файлов",+ "share.settings.usage.fileStorageOfLimit": "{{used}} из {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · вложения отключены","share.settings.usage.loadFailed": "Не удалось загрузить данные об использовании","share.settings.usage.monthlySpend": "Расходы за этот месяц","share.settings.usage.spendOfLimit": "${{spend}} из ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "Войти","share.visitor.access.signInDesc": "Войдите, чтобы начать общение с этим общим агентом. Ваши беседы будут связаны с вашим аккаунтом.","share.visitor.access.signInTitle": "Войдите, чтобы продолжить",+ "share.visitor.errors.fileUnavailable": "Одно из вложений больше недоступно. Удалите его и попробуйте снова.","share.visitor.errors.generic": "Не удалось отправить сообщение. Пожалуйста, попробуйте снова.","share.visitor.errors.heterogeneousUnsupported": "Этот общий агент пока недоступен для общения посетителей. Пожалуйста, свяжитесь с его владельцем.","share.visitor.errors.insufficientBudget": "У этого общего агента закончился бюджет. Пожалуйста, свяжитесь с его владельцем.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} инструментов доступны для посетителей.","share.visitor.profile.terms.topics": "Вы можете открыть до {{count}} разговоров.","share.visitor.profile.terms.turns": "Каждый разговор допускает до {{count}} ходов.",+ "share.visitor.profile.terms.uploads": "Вы можете прикреплять файлы; у этого Агента есть {{size}} для хранения файлов посетителей.",+ "share.visitor.profile.terms.uploadsOff": "Вложения отключены.","share.visitor.profile.terms.visibilityCreator": "Создатель включил обзор сессии, поэтому он может читать этот разговор.","share.visitor.profile.terms.visibilityPrivate": "Только вы можете видеть свои разговоры.","share.visitor.topBar.home": "Перейти в мой LobeHub",@@ -421,6 +429,9 @@"share.visitor.topics.new": "Новая беседа","share.visitor.topics.title": "Беседы","share.visitor.topics.untitled": "Без названия",+ "share.visitor.upload.creatorStorageBlocked": "Место для загрузки этого Агента заполнено. Попросите его создателя освободить место или увеличить лимит.",+ "share.visitor.upload.fileTooLarge": "Файлы должны быть меньше {{max}}.",+ "share.visitor.upload.tooManyFiles": "Вы можете прикрепить до {{max}} файлов за сообщение.","transfer.button": "Перенести","transfer.confirm.botChannels": "Подключения каналов бота могут потребовать обновления после переноса","transfer.confirm.chatGroups": "Ассоциации многопользовательских групп будут удалены",diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.jsonindex 44fdcb3e17b..dc9eafcbdb5 100644--- a/locales/ru-RU/chat.json+++ b/locales/ru-RU/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "Находка","goalProcess.kind.problem": "Вопрос","goalProcess.kind.task": "Задача",+ "goalProcess.linked.open": "Открыть прогресс цели","goalProcess.manager.pending": "Ожидание первого запуска","goalProcess.manager.title": "Главный агент","goalProcess.manager.turns": "Раунды планирования: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "Приостановлено — новые задачи не будут начинаться","goalProcess.planning.description": "Координатор разбивает цель на выполнимые задачи — они скоро появятся здесь.","goalProcess.planning.title": "Планирование исследования",+ "goalProcess.portal.openPage": "Открыть страницу цели",+ "goalProcess.portal.title": "Цель","goalProcess.requirementPlaceholder": "Опишите, что считается выполненным…","goalProcess.requirementSaveFailed": "Не удалось сохранить требование — оно будет повторно сохранено при следующем редактировании","goalProcess.resume": "Возобновить",diff --git a/locales/ru-RU/file.json b/locales/ru-RU/file.jsonindex 6bd4eb829ea..343a8c979f2 100644--- a/locales/ru-RU/file.json+++ b/locales/ru-RU/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "Страница сохраняется автоматически. Сохранять вручную не требуется.","pageEditor.chooseIcon": "Выбрать иконку","pageEditor.comments.anchor.add": "Комментарий",+ "pageEditor.comments.anchor.addToLine": "Комментировать эту строку","pageEditor.comments.anchor.label": "Цитируемый текст:","pageEditor.comments.anchor.missing": "Оригинал удален","pageEditor.comments.anchor.remove": "Удалить цитату",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "Этот комментарий был удален.","pageEditor.comments.edit": "Редактировать","pageEditor.comments.edited": "(отредактировано)",+ "pageEditor.comments.gutterEmpty": "Выберите текст в документе, чтобы прокомментировать его.",+ "pageEditor.comments.gutterEmptyReadOnly": "Комментариев пока нет.","pageEditor.comments.hideReplies": "Скрыть ответы","pageEditor.comments.loadMore": "Загрузить больше комментариев","pageEditor.comments.loadMoreReplies": "Загрузить больше ответов",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "Написать ответ…","pageEditor.comments.save": "Сохранить","pageEditor.comments.title": "Комментарии",+ "pageEditor.comments.toggle": "Комментарии","pageEditor.comments.updateFailed": "Не удалось обновить комментарий. Попробуйте снова.",+ "pageEditor.copilot.toggle": "Спросить Lobe AI","pageEditor.deleteConfirm.content": "Эта страница будет удалена без возможности восстановления. Пожалуйста, будьте осторожны.","pageEditor.deleteConfirm.title": "Удалить страницу","pageEditor.deleteError": "Не удалось удалить страницу",diff --git a/locales/ru-RU/pageShare.json b/locales/ru-RU/pageShare.jsonindex 726c9f8c041..5724aee0c6d 100644--- a/locales/ru-RU/pageShare.json+++ b/locales/ru-RU/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "Нравится эта страница? <strong>Создайте свою с помощью {{appName}}</strong> — бесплатное пространство для AI-ориентированных документов.","banner.signIn": "Войти","banner.signUp": "Зарегистрироваться бесплатно",+ "error.invalidFormat.desc": "Вы все еще можете это прочитать. Макет может отличаться от оригинала.",+ "error.invalidFormat.ownerHint": "Сохраните его заново в редакторе, чтобы восстановить оригинальный макет.",+ "error.invalidFormat.title": "Эта страница не может быть показана в ее оригинальном формате","error.notFound.desc": "Эта страница больше не существует или была удалена.","error.notFound.title": "Страница не найдена","error.private.action": "Войти",diff --git a/locales/tr-TR/agent.json b/locales/tr-TR/agent.jsonindex 721e5caaa87..c190051a046 100644--- a/locales/tr-TR/agent.json+++ b/locales/tr-TR/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "Yetkilendirme akışı tarafından döndürülen WeChat hesap tanımlayıcısı.","share.entry": "Bu Ajanı Paylaş","share.settings.limits.desc": "Her ziyaretçi çalıştırması hesabınıza faturalandırılır, bu nedenle bu sınırlar, paylaşılan bir bağlantının faturanızın kabarmasını önler. Her zaman geçerlidir — sayıları değiştirebilirsiniz, ancak kapatamazsınız.",+ "share.settings.limits.maxFileStorage": "Dosya depolama limiti (MB)",+ "share.settings.limits.maxFileStorageHint": "Ziyaretçilerin eklediği dosyalar hesabınızda depolanır. Yüklemeler bu toplam değere ulaştığında durur; ekleri kapatmak için 0 olarak ayarlayın.","share.settings.limits.maxTopicsPerVisitor": "Ziyaretçi başına konuşma","share.settings.limits.maxTopicsPerVisitorHint": "Her oturum açmış ziyaretçinin başlatabileceği ayrı konuşma sayısı.","share.settings.limits.maxTurnsPerTopic": "Konuşma başına mesaj",@@ -363,6 +365,9 @@"share.settings.updateError": "Değişiklik kaydedilemedi. Lütfen tekrar deneyin.","share.settings.usage.conversations": "Konuşmalar","share.settings.usage.desc": "Bu paylaşımın çektiği ilgi ve size maliyeti.",+ "share.settings.usage.fileStorage": "Dosya depolama",+ "share.settings.usage.fileStorageOfLimit": "{{used}} / {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · ekler kapalı","share.settings.usage.loadFailed": "Kullanım yüklenemedi","share.settings.usage.monthlySpend": "Bu ayın harcaması","share.settings.usage.spendOfLimit": "${{spend}} / ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "Giriş yap","share.visitor.access.signInDesc": "Bu paylaşılan ajanla sohbet etmeye başlamak için giriş yapın. Konuşmalarınız hesabınıza bağlı kalır.","share.visitor.access.signInTitle": "Devam etmek için giriş yapın",+ "share.visitor.errors.fileUnavailable": "Eklerden biri artık mevcut değil. Kaldırın ve tekrar deneyin.","share.visitor.errors.generic": "Mesaj gönderilemedi. Lütfen tekrar deneyin.","share.visitor.errors.heterogeneousUnsupported": "Bu paylaşılan ajan henüz ziyaretçi sohbeti için kullanılamıyor. Lütfen sahibine başvurun.","share.visitor.errors.insufficientBudget": "Bu paylaşılan ajanın bütçesi tükendi. Lütfen sahibine başvurun.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} araç ziyaretçilere açık.","share.visitor.profile.terms.topics": "En fazla {{count}} konuşma başlatabilirsiniz.","share.visitor.profile.terms.turns": "Her konuşma en fazla {{count}} dönüşe izin verir.",+ "share.visitor.profile.terms.uploads": "Dosya ekleyebilirsiniz; bu Ajan ziyaretçiler için {{size}} dosya depolama alanına sahiptir.",+ "share.visitor.profile.terms.uploadsOff": "Ekler kapalı.","share.visitor.profile.terms.visibilityCreator": "Oluşturucu oturum incelemesini açtı, bu nedenle bu konuşmayı okuyabilirler.","share.visitor.profile.terms.visibilityPrivate": "Yalnızca siz konuşmalarınızı görebilirsiniz.","share.visitor.topBar.home": "LobeHub'ıma git",@@ -421,6 +429,9 @@"share.visitor.topics.new": "Yeni konuşma","share.visitor.topics.title": "Konuşmalar","share.visitor.topics.untitled": "Başlıksız konuşma",+ "share.visitor.upload.creatorStorageBlocked": "Bu Ajanın yükleme alanı dolu. Yaratıcısından alanı boşaltmasını veya limiti artırmasını isteyin.",+ "share.visitor.upload.fileTooLarge": "Dosyalar {{max}} boyutundan küçük olmalıdır.",+ "share.visitor.upload.tooManyFiles": "Bir mesajda en fazla {{max}} dosya ekleyebilirsiniz.","transfer.button": "Aktar","transfer.confirm.botChannels": "Bot kanal bağlantılarının aktarım sonrası yenilenmesi gerekebilir","transfer.confirm.chatGroups": "Çoklu ajan grup ilişkileri kaldırılacak",diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.jsonindex 6867bd43365..ec18ef593aa 100644--- a/locales/tr-TR/chat.json+++ b/locales/tr-TR/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "Bulgu","goalProcess.kind.problem": "Soru","goalProcess.kind.task": "Görev",+ "goalProcess.linked.open": "Hedef ilerlemesini aç","goalProcess.manager.pending": "İlk çalıştırma bekleniyor","goalProcess.manager.title": "Ana ajan","goalProcess.manager.turns": "Planlama turları: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "Durduruldu — yeni bir iş başlamayacak","goalProcess.planning.description": "Koordinatör, hedefi uygulanabilir görevlere ayırıyor — bunlar kısa süre içinde burada görünecek.","goalProcess.planning.title": "Keşif planlanıyor",+ "goalProcess.portal.openPage": "Hedef sayfasını aç",+ "goalProcess.portal.title": "Hedef","goalProcess.requirementPlaceholder": "Tamamlanmış sayılacak durumu tanımlayın…","goalProcess.requirementSaveFailed": "Gereksinim kaydedilemedi — bir sonraki düzenlemenizde tekrar denenecek","goalProcess.resume": "Devam et",diff --git a/locales/tr-TR/file.json b/locales/tr-TR/file.jsonindex 47f74a1fa39..3b679d9451c 100644--- a/locales/tr-TR/file.json+++ b/locales/tr-TR/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "Sayfanız otomatik olarak kaydedilir. Manuel kaydetmenize gerek yok.","pageEditor.chooseIcon": "Simge Seç","pageEditor.comments.anchor.add": "Yorum",+ "pageEditor.comments.anchor.addToLine": "Bu satıra yorum yap","pageEditor.comments.anchor.label": "Alıntılanan metin:","pageEditor.comments.anchor.missing": "Orijinal kaldırıldı","pageEditor.comments.anchor.remove": "Alıntıyı kaldır",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "Bu yorum silindi.","pageEditor.comments.edit": "Düzenle","pageEditor.comments.edited": "(düzenlendi)",+ "pageEditor.comments.gutterEmpty": "Belgede metni seçerek yorum yapabilirsiniz.",+ "pageEditor.comments.gutterEmptyReadOnly": "Henüz yorum yok.","pageEditor.comments.hideReplies": "Yanıtları gizle","pageEditor.comments.loadMore": "Daha fazla yorum yükle","pageEditor.comments.loadMoreReplies": "Daha fazla yanıt yükle",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "Bir yanıt yazın…","pageEditor.comments.save": "Kaydet","pageEditor.comments.title": "Yorumlar",+ "pageEditor.comments.toggle": "Yorumlar","pageEditor.comments.updateFailed": "Yorum güncellenemedi. Tekrar deneyin.",+ "pageEditor.copilot.toggle": "Lobe AI'ye Sor","pageEditor.deleteConfirm.content": "Bu sayfa silinecek ve geri alınamayacak. Lütfen dikkatli olun.","pageEditor.deleteConfirm.title": "Sayfayı Sil","pageEditor.deleteError": "Sayfa silinemedi",diff --git a/locales/tr-TR/pageShare.json b/locales/tr-TR/pageShare.jsonindex 54040f8a8e4..eb9a7211f2d 100644--- a/locales/tr-TR/pageShare.json+++ b/locales/tr-TR/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "Bu sayfayı beğendiniz mi? <strong>{{appName}} ile kendi sayfanızı oluşturun</strong> — AI tabanlı belgeler için ücretsiz çalışma alanı.","banner.signIn": "Giriş yap","banner.signUp": "Ücretsiz kaydol",+ "error.invalidFormat.desc": "Hâlâ okuyabilirsiniz. Düzen orijinalinden farklı olabilir.",+ "error.invalidFormat.ownerHint": "Orijinal düzeni geri yüklemek için düzenleyicide yeniden kaydedin.",+ "error.invalidFormat.title": "Bu sayfa orijinal formatında gösterilemedi","error.notFound.desc": "Bu sayfa artık mevcut değil veya kaldırılmış.","error.notFound.title": "Sayfa bulunamadı","error.private.action": "Giriş yap",diff --git a/locales/vi-VN/agent.json b/locales/vi-VN/agent.jsonindex 49ed939e5f3..6d0976a683c 100644--- a/locales/vi-VN/agent.json+++ b/locales/vi-VN/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "Định danh tài khoản WeChat được trả về bởi quy trình ủy quyền.","share.entry": "Chia sẻ Agent này","share.settings.limits.desc": "Mỗi lần chạy của khách truy cập đều được tính vào tài khoản của bạn, vì vậy các giới hạn này giúp ngăn một liên kết chia sẻ làm tăng chi phí của bạn. Chúng luôn được áp dụng — bạn có thể thay đổi số lượng, nhưng không thể tắt chúng.",+ "share.settings.limits.maxFileStorage": "Giới hạn lưu trữ tệp (MB)",+ "share.settings.limits.maxFileStorageHint": "Các tệp mà khách truy cập đính kèm sẽ được lưu trữ trên tài khoản của bạn. Việc tải lên sẽ dừng lại khi đạt đến tổng số này; đặt 0 để tắt đính kèm.","share.settings.limits.maxTopicsPerVisitor": "Cuộc trò chuyện mỗi khách truy cập","share.settings.limits.maxTopicsPerVisitorHint": "Số lượng cuộc trò chuyện riêng biệt mà mỗi khách truy cập đã đăng nhập có thể bắt đầu.","share.settings.limits.maxTurnsPerTopic": "Lượt mỗi cuộc trò chuyện",@@ -363,6 +365,9 @@"share.settings.updateError": "Không thể lưu thay đổi. Vui lòng thử lại.","share.settings.usage.conversations": "Cuộc trò chuyện","share.settings.usage.desc": "Những gì chia sẻ này đã thu hút, và chi phí của nó đối với bạn.",+ "share.settings.usage.fileStorage": "Lưu trữ tệp",+ "share.settings.usage.fileStorageOfLimit": "{{used}} trên {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · đính kèm đã tắt","share.settings.usage.loadFailed": "Không thể tải dữ liệu sử dụng","share.settings.usage.monthlySpend": "Chi tiêu tháng này","share.settings.usage.spendOfLimit": "${{spend}} trong ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "Đăng nhập","share.visitor.access.signInDesc": "Đăng nhập để bắt đầu trò chuyện với Agent được chia sẻ này. Các cuộc trò chuyện của bạn sẽ được liên kết với tài khoản của bạn.","share.visitor.access.signInTitle": "Đăng nhập để tiếp tục",+ "share.visitor.errors.fileUnavailable": "Một trong các tệp đính kèm không còn khả dụng. Hãy xóa nó và thử lại.","share.visitor.errors.generic": "Không thể gửi tin nhắn. Vui lòng thử lại.","share.visitor.errors.heterogeneousUnsupported": "Agent được chia sẻ này chưa khả dụng cho trò chuyện của khách truy cập. Vui lòng liên hệ với chủ sở hữu.","share.visitor.errors.insufficientBudget": "Agent được chia sẻ này đã hết ngân sách. Vui lòng liên hệ với chủ sở hữu.",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} công cụ được mở cho khách truy cập.","share.visitor.profile.terms.topics": "Bạn có thể mở tối đa {{count}} cuộc trò chuyện.","share.visitor.profile.terms.turns": "Mỗi cuộc trò chuyện cho phép tối đa {{count}} lượt.",+ "share.visitor.profile.terms.uploads": "Bạn có thể đính kèm tệp; Ajan này có {{size}} dung lượng lưu trữ tệp cho khách truy cập.",+ "share.visitor.profile.terms.uploadsOff": "Đính kèm đã bị tắt.","share.visitor.profile.terms.visibilityCreator": "Người tạo đã bật chế độ xem lại phiên, vì vậy họ có thể đọc cuộc trò chuyện này.","share.visitor.profile.terms.visibilityPrivate": "Chỉ bạn có thể xem các cuộc trò chuyện của mình.","share.visitor.topBar.home": "Đi đến LobeHub của tôi",@@ -421,6 +429,9 @@"share.visitor.topics.new": "Cuộc trò chuyện mới","share.visitor.topics.title": "Cuộc trò chuyện","share.visitor.topics.untitled": "Cuộc trò chuyện chưa đặt tên",+ "share.visitor.upload.creatorStorageBlocked": "Dung lượng tải lên của Ajan này đã đầy. Hãy yêu cầu người tạo giải phóng dung lượng hoặc tăng giới hạn.",+ "share.visitor.upload.fileTooLarge": "Các tệp phải nhỏ hơn {{max}}.",+ "share.visitor.upload.tooManyFiles": "Bạn có thể đính kèm tối đa {{max}} tệp mỗi tin nhắn.","transfer.button": "Chuyển","transfer.confirm.botChannels": "Kết nối kênh bot có thể cần được làm mới sau khi chuyển","transfer.confirm.chatGroups": "Liên kết nhóm nhiều tác nhân sẽ bị xóa",diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.jsonindex efbb407a848..d35253ef7a6 100644--- a/locales/vi-VN/chat.json+++ b/locales/vi-VN/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "Phát hiện","goalProcess.kind.problem": "Câu hỏi","goalProcess.kind.task": "Nhiệm vụ",+ "goalProcess.linked.open": "Mở tiến trình mục tiêu","goalProcess.manager.pending": "Đang chờ lần chạy đầu tiên","goalProcess.manager.title": "Đại lý chính","goalProcess.manager.turns": "Các vòng lập kế hoạch: {{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "Đã tạm dừng — không có công việc mới sẽ bắt đầu","goalProcess.planning.description": "Người điều phối đang chia nhỏ mục tiêu thành các nhiệm vụ có thể thực hiện — chúng sẽ sớm xuất hiện ở đây.","goalProcess.planning.title": "Lập kế hoạch khám phá",+ "goalProcess.portal.openPage": "Mở trang mục tiêu",+ "goalProcess.portal.title": "Mục tiêu","goalProcess.requirementPlaceholder": "Mô tả điều kiện hoàn thành…","goalProcess.requirementSaveFailed": "Không thể lưu yêu cầu — hệ thống sẽ thử lại khi bạn chỉnh sửa lần tới","goalProcess.resume": "Tiếp tục",diff --git a/locales/vi-VN/file.json b/locales/vi-VN/file.jsonindex 1146209034b..5a66727aada 100644--- a/locales/vi-VN/file.json+++ b/locales/vi-VN/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "Trang của bạn được lưu tự động. Không cần lưu thủ công.","pageEditor.chooseIcon": "Chọn Biểu Tượng","pageEditor.comments.anchor.add": "Bình luận",+ "pageEditor.comments.anchor.addToLine": "Bình luận về dòng này","pageEditor.comments.anchor.label": "Văn bản trích dẫn:","pageEditor.comments.anchor.missing": "Đã xóa bản gốc","pageEditor.comments.anchor.remove": "Xóa trích dẫn",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "Bình luận này đã bị xóa.","pageEditor.comments.edit": "Chỉnh sửa","pageEditor.comments.edited": "(đã chỉnh sửa)",+ "pageEditor.comments.gutterEmpty": "Chọn văn bản trong tài liệu để bình luận về nó.",+ "pageEditor.comments.gutterEmptyReadOnly": "Chưa có bình luận nào.","pageEditor.comments.hideReplies": "Ẩn phản hồi","pageEditor.comments.loadMore": "Tải thêm bình luận","pageEditor.comments.loadMoreReplies": "Tải thêm phản hồi",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "Viết phản hồi…","pageEditor.comments.save": "Lưu","pageEditor.comments.title": "Bình luận",+ "pageEditor.comments.toggle": "Bình luận","pageEditor.comments.updateFailed": "Không thể cập nhật bình luận. Vui lòng thử lại.",+ "pageEditor.copilot.toggle": "Hỏi Lobe AI","pageEditor.deleteConfirm.content": "Trang này sẽ bị xóa và không thể khôi phục. Vui lòng cẩn thận.","pageEditor.deleteConfirm.title": "Xóa Trang","pageEditor.deleteError": "Không thể xóa trang",diff --git a/locales/vi-VN/pageShare.json b/locales/vi-VN/pageShare.jsonindex 2cd91b101ae..8e353bfa321 100644--- a/locales/vi-VN/pageShare.json+++ b/locales/vi-VN/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "Thích trang này? <strong>Tạo trang của riêng bạn với {{appName}}</strong> — không gian làm việc miễn phí cho tài liệu AI-native.","banner.signIn": "Đăng nhập","banner.signUp": "Đăng ký miễn phí",+ "error.invalidFormat.desc": "Bạn vẫn có thể đọc nó. Bố cục có thể khác so với bản gốc.",+ "error.invalidFormat.ownerHint": "Lưu lại trong trình chỉnh sửa để khôi phục bố cục ban đầu.",+ "error.invalidFormat.title": "Trang này không thể hiển thị theo định dạng ban đầu","error.notFound.desc": "Trang này không còn tồn tại hoặc đã bị xóa.","error.notFound.title": "Không tìm thấy trang","error.private.action": "Đăng nhập",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex 7149234daff..75a0f9fec16 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "文稿会自动保存,无需手动保存","pageEditor.chooseIcon": "选择图标","pageEditor.comments.anchor.add": "评论",+ "pageEditor.comments.anchor.addToLine": "评论这一行","pageEditor.comments.anchor.label": "引用原文:","pageEditor.comments.anchor.missing": "原文已删除","pageEditor.comments.anchor.remove": "移除引用",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "这条评论已被删除","pageEditor.comments.edit": "编辑","pageEditor.comments.edited": "(已编辑)",+ "pageEditor.comments.gutterEmpty": "在正文中划选文字即可评论。",+ "pageEditor.comments.gutterEmptyReadOnly": "暂无评论。","pageEditor.comments.hideReplies": "收起回复","pageEditor.comments.loadMore": "加载更多评论","pageEditor.comments.loadMoreReplies": "加载更多回复",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "写下回复…","pageEditor.comments.save": "保存","pageEditor.comments.title": "评论",+ "pageEditor.comments.toggle": "评论","pageEditor.comments.updateFailed": "评论更新失败,请重试",+ "pageEditor.copilot.toggle": "问 Lobe AI","pageEditor.deleteConfirm.content": "确认删除该文稿吗?删除后不可恢复。建议先导出或复制重要内容","pageEditor.deleteConfirm.title": "删除文稿","pageEditor.deleteError": "删除遇到了问题。你可以重试",diff --git a/locales/zh-TW/agent.json b/locales/zh-TW/agent.jsonindex 50fc6de860d..7d41e2ff68f 100644--- a/locales/zh-TW/agent.json+++ b/locales/zh-TW/agent.json@@ -309,6 +309,8 @@"channel.wechatUserIdHint": "授權流程返回的微信帳號標識符。","share.entry": "分享此代理","share.settings.limits.desc": "每次訪客執行都會計入您的帳戶,因此這些限制是為了防止共享連結導致您的帳單激增。這些限制始終適用——您可以更改數字,但無法關閉它們。",+ "share.settings.limits.maxFileStorage": "檔案儲存限制(MB)",+ "share.settings.limits.maxFileStorageHint": "訪客附加的檔案會儲存在您的帳戶中。一旦上傳達到此總量,將停止上傳;設為 0 可關閉附件功能。","share.settings.limits.maxTopicsPerVisitor": "每位訪客的對話數","share.settings.limits.maxTopicsPerVisitorHint": "每位已登入訪客可以開始的獨立對話數量。","share.settings.limits.maxTurnsPerTopic": "每次對話的回合數",@@ -363,6 +365,9 @@"share.settings.updateError": "無法保存更改。請重試。","share.settings.usage.conversations": "對話","share.settings.usage.desc": "此共享吸引了什麼,以及它的成本。",+ "share.settings.usage.fileStorage": "檔案儲存",+ "share.settings.usage.fileStorageOfLimit": "{{used}} / {{limit}}",+ "share.settings.usage.fileStorageOff": "{{used}} · 附件已關閉","share.settings.usage.loadFailed": "無法加載使用情況","share.settings.usage.monthlySpend": "本月支出","share.settings.usage.spendOfLimit": "${{spend}} / ${{limit}}",@@ -375,6 +380,7 @@"share.visitor.access.signInCta": "登入","share.visitor.access.signInDesc": "登入以開始與此共享代理聊天。您的對話將與您的帳戶綁定。","share.visitor.access.signInTitle": "登入以繼續",+ "share.visitor.errors.fileUnavailable": "其中一個附件已無法使用。請移除後再試一次。","share.visitor.errors.generic": "無法發送訊息。請重試。","share.visitor.errors.heterogeneousUnsupported": "此共享代理尚未開放訪客聊天。請聯繫其擁有者。","share.visitor.errors.insufficientBudget": "此共享代理的預算已用完。請聯繫其擁有者。",@@ -414,6 +420,8 @@"share.visitor.profile.terms.tools_other": "{{count}} 個工具對訪客開放。","share.visitor.profile.terms.topics": "您最多可以開啟 {{count}} 個對話。","share.visitor.profile.terms.turns": "每次對話最多允許 {{count}} 回合。",+ "share.visitor.profile.terms.uploads": "您可以附加檔案;此 Agent 為訪客提供 {{size}} 的檔案儲存空間。",+ "share.visitor.profile.terms.uploadsOff": "附件功能已關閉。","share.visitor.profile.terms.visibilityCreator": "創建者已開啟會話審查,因此他們可以閱讀此對話。","share.visitor.profile.terms.visibilityPrivate": "只有您可以看到您的對話。","share.visitor.topBar.home": "前往我的 LobeHub",@@ -421,6 +429,9 @@"share.visitor.topics.new": "新對話","share.visitor.topics.title": "對話","share.visitor.topics.untitled": "未命名對話",+ "share.visitor.upload.creatorStorageBlocked": "此 Agent 的上傳空間已滿。請要求其創建者釋放空間或提高上限。",+ "share.visitor.upload.fileTooLarge": "檔案大小必須小於 {{max}}。",+ "share.visitor.upload.tooManyFiles": "每則訊息最多可附加 {{max}} 個檔案。","transfer.button": "轉移","transfer.confirm.botChannels": "轉移後可能需要重新刷新機器人頻道連接","transfer.confirm.chatGroups": "多代理群組關聯將被移除",diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.jsonindex ebb7a8efbec..1d37602e16b 100644--- a/locales/zh-TW/chat.json+++ b/locales/zh-TW/chat.json@@ -637,6 +637,7 @@"goalProcess.kind.finding": "發現","goalProcess.kind.problem": "問題","goalProcess.kind.task": "任務",+ "goalProcess.linked.open": "開啟目標進度","goalProcess.manager.pending": "等待第一次運行","goalProcess.manager.title": "主代理","goalProcess.manager.turns": "規劃回合:{{count}}",@@ -727,6 +728,8 @@"goalProcess.paused": "已暫停 — 不會啟動新工作","goalProcess.planning.description": "協調者正在將目標分解為可執行的任務 — 它們將很快出現在這裡。","goalProcess.planning.title": "探索規劃中",+ "goalProcess.portal.openPage": "開啟目標頁面",+ "goalProcess.portal.title": "目標","goalProcess.requirementPlaceholder": "描述完成的標準…","goalProcess.requirementSaveFailed": "儲存需求失敗 — 它將在您下次編輯時重試","goalProcess.resume": "繼續",diff --git a/locales/zh-TW/file.json b/locales/zh-TW/file.jsonindex efe329d2b0e..febec0ce01a 100644--- a/locales/zh-TW/file.json+++ b/locales/zh-TW/file.json@@ -95,6 +95,7 @@"pageEditor.autoSaveMessage": "文稿會自動儲存,無需手動儲存","pageEditor.chooseIcon": "選擇圖示","pageEditor.comments.anchor.add": "評論",+ "pageEditor.comments.anchor.addToLine": "對此行評論","pageEditor.comments.anchor.label": "引用文字:","pageEditor.comments.anchor.missing": "原文已移除","pageEditor.comments.anchor.remove": "移除引用",@@ -113,6 +114,8 @@"pageEditor.comments.deleted": "此評論已被刪除。","pageEditor.comments.edit": "編輯","pageEditor.comments.edited": "(已編輯)",+ "pageEditor.comments.gutterEmpty": "選取文件中的文字以進行評論。",+ "pageEditor.comments.gutterEmptyReadOnly": "尚無評論。","pageEditor.comments.hideReplies": "隱藏回覆","pageEditor.comments.loadMore": "載入更多評論","pageEditor.comments.loadMoreReplies": "載入更多回覆",@@ -125,7 +128,9 @@"pageEditor.comments.replyPlaceholder": "撰寫回覆…","pageEditor.comments.save": "儲存","pageEditor.comments.title": "評論",+ "pageEditor.comments.toggle": "評論","pageEditor.comments.updateFailed": "更新評論失敗。請再試一次。",+ "pageEditor.copilot.toggle": "詢問 Lobe AI","pageEditor.deleteConfirm.content": "即將刪除此文稿,刪除後將無法恢復,請謹慎操作。","pageEditor.deleteConfirm.title": "刪除文稿","pageEditor.deleteError": "刪除文稿失敗",diff --git a/locales/zh-TW/pageShare.json b/locales/zh-TW/pageShare.jsonindex a88616d463f..30357a7cf66 100644--- a/locales/zh-TW/pageShare.json+++ b/locales/zh-TW/pageShare.json@@ -2,6 +2,9 @@"banner.copy": "喜歡這個頁面嗎?<strong>使用 {{appName}} 創建自己的頁面</strong> — 免費的 AI 原生文檔工作空間。","banner.signIn": "登入","banner.signUp": "免費註冊",+ "error.invalidFormat.desc": "您仍然可以閱讀它。版面配置可能與原始版本不同。",+ "error.invalidFormat.ownerHint": "在編輯器中重新儲存以恢復原始版面配置。",+ "error.invalidFormat.title": "此頁面無法以原始格式顯示","error.notFound.desc": "此頁面已不存在或已被移除。","error.notFound.title": "找不到頁面","error.private.action": "登入",diff --git a/packages/database/src/models/__tests__/documentComment.test.ts b/packages/database/src/models/__tests__/documentComment.test.tsindex cb234d7e65a..af5201fb426 100644--- a/packages/database/src/models/__tests__/documentComment.test.ts+++ b/packages/database/src/models/__tests__/documentComment.test.ts@@ -138,6 +138,17 @@ describe('DocumentCommentModel', () => {]);expect(await authorModel.listAnchors(secondDocumentId)).toEqual([]);expect(await outsiderModel.listAnchors(documentId)).toEqual([]);++ // Each surface pages its own subset: the gutter takes anchored roots, the+ // list below the body takes document-level ones; no filter keeps them mixed.+ const anchoredThreads = await authorModel.listThreads({ anchored: true, documentId });+ expect(anchoredThreads.items.map(({ root: { clientId } }) => clientId)).toEqual([+ 'anchored-root',+ ]);+ const documentThreads = await authorModel.listThreads({ anchored: false, documentId });+ expect(documentThreads.items.map(({ root: { clientId } }) => clientId)).toEqual(['plain-root']);+ const allThreads = await authorModel.listThreads({ documentId });+ expect(allThreads.items).toHaveLength(2);});it('leaves a comment made without a selection unanchored', async () => {diff --git a/packages/database/src/models/documentComment.ts b/packages/database/src/models/documentComment.tsindex f2e4362b489..81e644b60fa 100644--- a/packages/database/src/models/documentComment.ts+++ b/packages/database/src/models/documentComment.ts@@ -94,6 +94,12 @@ export interface UpdateDocumentCommentResult {}export interface ListDocumentCommentThreadsParams {+ /**+ * Restrict to roots with (`true`) or without (`false`) a selection anchor.+ * Anchored threads render beside the text, document-level ones below it, so+ * each surface pages its own subset instead of filtering a mixed list.+ */+ anchored?: boolean;cursor?: string;documentId: string;limit?: number;@@ -435,12 +441,14 @@ export class DocumentCommentModel {async listThreads(params: ListDocumentCommentThreadsParams) {const workspaceId = this.requireWorkspaceId();- const { cursor, documentId, limit = 20 } = params;+ const { anchored, cursor, documentId, limit = 20 } = params;const conditions = [eq(documentComments.documentId, documentId),eq(documentComments.workspaceId, workspaceId),isNull(documentComments.parentCommentId),];+ if (anchored === true) conditions.push(isNotNull(documentComments.selectionAnchor));+ if (anchored === false) conditions.push(isNull(documentComments.selectionAnchor));const decodedCursor = decodeCursor(cursor);if (decodedCursor) {const createdAt = sql`${decodedCursor.createdAt}::timestamptz`;diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.tsindex 03e22e28a15..d0331e85aff 100644--- a/packages/locales/src/default/file.ts+++ b/packages/locales/src/default/file.ts@@ -107,6 +107,7 @@ export default {'pageEditor.autoSaveMessage': 'Your page is saved automatically. No need to save manually.','pageEditor.chooseIcon': 'Choose Icon','pageEditor.comments.anchor.add': 'Comment',+ 'pageEditor.comments.anchor.addToLine': 'Comment on this line','pageEditor.comments.anchor.label': 'Quoted text:','pageEditor.comments.anchor.missing': 'Original removed','pageEditor.comments.anchor.remove': 'Remove quote',@@ -126,6 +127,8 @@ export default {'pageEditor.comments.deleted': 'This comment was deleted.','pageEditor.comments.edit': 'Edit','pageEditor.comments.edited': '(edited)',+ 'pageEditor.comments.gutterEmpty': 'Select text in the document to comment on it.',+ 'pageEditor.comments.gutterEmptyReadOnly': 'No comments yet.','pageEditor.comments.hideReplies': 'Hide replies','pageEditor.comments.loadMore': 'Load more comments','pageEditor.comments.loadMoreReplies': 'Load more replies',@@ -138,7 +141,9 @@ export default {'pageEditor.comments.replyPlaceholder': 'Write a reply…','pageEditor.comments.save': 'Save','pageEditor.comments.title': 'Comments',+ 'pageEditor.comments.toggle': 'Comments','pageEditor.comments.updateFailed': 'Failed to update comment. Try again.',+ 'pageEditor.copilot.toggle': 'Ask Lobe AI','pageEditor.likes.failed': 'Failed to update your like. Try again.','pageEditor.likes.like': 'Find this page helpful? Give it a like','pageEditor.likes.liked': 'Liked',diff --git a/src/features/PageEditor/DocumentComments/BlockCommentMarker.test.ts b/src/features/PageEditor/DocumentComments/BlockCommentMarker.test.tsnew file mode 100644index 00000000000..32b87dcb0ae--- /dev/null+++ b/src/features/PageEditor/DocumentComments/BlockCommentMarker.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from 'vitest';++import { blockAt, inMarkerBridge, lineAt } from './BlockCommentMarker';++const rect = (partial: Partial<DOMRect>): DOMRect =>+ ({ bottom: 0, left: 0, right: 0, top: 0, ...partial }) as DOMRect;++const mount = (text: string, dir: 'ltr' | 'rtl' = 'ltr') => {+ const block = document.createElement('p');+ block.dir = dir;+ block.textContent = text;+ document.body.append(block);+ block.getBoundingClientRect = () => ({ left: 0, right: 100 }) as DOMRect;+ return block;+};++/** Simulate `caretPositionFromPoint` returning a fixed offset per x-coordinate side. */+const stubCaretPositions = (node: Node, leftOffset: number, rightOffset: number) => {+ (+ document as unknown as { caretPositionFromPoint: (x: number) => unknown }+ ).caretPositionFromPoint = (x: number) => ({+ offset: x < 50 ? leftOffset : rightOffset,+ offsetNode: node,+ });+};++describe('lineAt', () => {+ it('selects the hovered line for LTR text, where the left edge is the earlier point', () => {+ const block = mount('hello world, this is a longer paragraph');+ const text = block.firstChild!;+ stubCaretPositions(text, 6, 11);++ const range = lineAt(block, 0);++ expect(range?.collapsed).toBe(false);+ expect(range?.toString()).toBe('world');+ });++ it('orders RTL caret points by document position instead of visual left/right', () => {+ // RTL reads right to left, so the visual left edge of a line is the+ // *later* point in document order and the right edge is the earlier one —+ // the opposite of the LTR case above.+ const block = mount('مرحبا بالعالم في السطر الثاني', 'rtl');+ const text = block.firstChild!;+ stubCaretPositions(text, 12, 6);++ const range = lineAt(block, 0);++ expect(range?.collapsed).toBe(false);+ // Selects just the run between the two points, not the whole paragraph —+ // the bug this guards against falls back to selecting the entire block.+ expect(range?.toString()).toBe(block.textContent!.slice(6, 12));+ expect(range?.toString()).not.toBe(block.textContent);+ });+});++describe('inMarkerBridge', () => {+ // LTR: body on the left, marker on the right, with a gap between them.+ const bodyRect = rect({ bottom: 40, left: 0, right: 100, top: 20 });+ const markerRect = rect({ bottom: 32, left: 120, right: 140, top: 20 });++ it('treats the gap between body and marker, at the marker row, as hoverable', () => {+ // x=110 sits in the gap (past body's right edge, before the marker).+ expect(inMarkerBridge(110, 24, bodyRect, markerRect)).toBe(true);+ });++ it("treats the same gap as hoverable when the marker sits to the body's left (RTL)", () => {+ const rtlBody = rect({ bottom: 40, left: 120, right: 220, top: 20 });+ const rtlMarker = rect({ bottom: 32, left: 80, right: 100, top: 20 });++ expect(inMarkerBridge(110, 24, rtlBody, rtlMarker)).toBe(true);+ });++ it("rejects a point in the gap column but outside the marker's row", () => {+ // Same x as the hoverable case, but well below the marker's row.+ expect(inMarkerBridge(110, 200, bodyRect, markerRect)).toBe(false);+ });++ it('rejects a point entirely outside the combined body+marker span', () => {+ expect(inMarkerBridge(500, 24, bodyRect, markerRect)).toBe(false);+ });+});++describe('blockAt', () => {+ const body = document.createElement('div');+ const block = document.createElement('p');+ const inline = document.createElement('strong');+ block.append(inline);+ body.append(block);+ document.body.append(body);++ it('resolves a nested target to its top-level block', () => {+ expect(blockAt(body, inline)).toBe(block);+ expect(blockAt(body, block)).toBe(block);+ });++ it('returns null over the root-owned whitespace between blocks (the body itself)', () => {+ expect(blockAt(body, body)).toBeNull();+ });++ it('returns null outside the body', () => {+ expect(blockAt(body, document.body)).toBeNull();+ expect(blockAt(body, null)).toBeNull();+ });+});diff --git a/src/features/PageEditor/DocumentComments/BlockCommentMarker.tsx b/src/features/PageEditor/DocumentComments/BlockCommentMarker.tsxnew file mode 100644index 00000000000..5c0fdd1ec0a--- /dev/null+++ b/src/features/PageEditor/DocumentComments/BlockCommentMarker.tsx@@ -0,0 +1,238 @@+'use client';++import { HIDE_TOOLBAR_COMMAND } from '@lobehub/editor';+import { ActionIcon } from '@lobehub/ui/base-ui';+import { MessageSquarePlus } from 'lucide-react';+import { memo, useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { usePermission } from '@/hooks/usePermission';++import { usePageEditorStore } from '../store';+import { useCommentAnchors } from './anchor/context';+import { captureRangeAnchor } from './anchor/textAnchor';+import { useDocumentComments } from './context';+import { styles } from './styles';++interface MarkerTarget {+ /** The visual line under the pointer, as a live DOM range. */+ range: Range;+ top: number;+}++interface CaretPoint {+ node: Node;+ offset: number;+}++/** The DOM point under a viewport coordinate, or `null` outside any text. */+const caretAt = (doc: Document, x: number, y: number): CaretPoint | null => {+ const d = doc as Document & {+ caretPositionFromPoint?: (x: number, y: number) => { offset: number; offsetNode: Node } | null;+ caretRangeFromPoint?: (x: number, y: number) => Range | null;+ };+ const position = d.caretPositionFromPoint?.(x, y);+ if (position?.offsetNode) return { node: position.offsetNode, offset: position.offset };+ const range = d.caretRangeFromPoint?.(x, y);+ return range ? { node: range.startContainer, offset: range.startOffset } : null;+};++/**+ * Two caret points ordered by document position. On an RTL line the visual+ * left edge is the *later* point in the DOM (RTL reads right to left), so the+ * left/right caret pair can't be assigned to start/end by which is which —+ * only by which comes first in the document.+ */+const orderPoints = (doc: Document, a: CaretPoint, b: CaretPoint): [CaretPoint, CaretPoint] => {+ const probe = doc.createRange();+ probe.setStart(a.node, a.offset);+ probe.collapse(true);+ return probe.comparePoint(b.node, b.offset) < 0 ? [b, a] : [a, b];+};++/**+ * The visual line of `block` at viewport height `y`: the run between the+ * caret positions at the block's left and right edges on that line. Falls+ * back to the whole block when the edges cannot be resolved (an image, an+ * embed), so the marker still offers something to comment on.+ */+export const lineAt = (block: HTMLElement, y: number): Range | null => {+ const doc = block.ownerDocument;+ const rect = block.getBoundingClientRect();+ const left = caretAt(doc, rect.left + 1, y);+ const right = caretAt(doc, rect.right - 1, y);+ const range = doc.createRange();+ if (left && right && block.contains(left.node) && block.contains(right.node)) {+ try {+ const [from, to] = orderPoints(doc, left, right);+ range.setStart(from.node, from.offset);+ range.setEnd(to.node, to.offset);+ if (!range.collapsed && range.toString().trim()) return range;+ } catch {+ /* fall through to the whole block */+ }+ }+ range.selectNodeContents(block);+ return range.toString().trim() ? range : null;+};++/** Two ranges over the same run are the same target; the marker need not move. */+const sameRange = (left: Range | undefined, right: Range) =>+ Boolean(left) &&+ left!.startContainer === right.startContainer &&+ left!.startOffset === right.startOffset &&+ left!.endContainer === right.endContainer &&+ left!.endOffset === right.endOffset;++/**+ * The body's top-level block the pointer is over, or `null` over the body's+ * own (root-owned) whitespace between and after blocks, and outside it.+ */+export const blockAt = (body: HTMLElement, target: EventTarget | null): HTMLElement | null => {+ if (!(target instanceof Node)) return null;+ let node: Node | null = target;+ while (node && node.parentNode !== body) node = node.parentNode;+ return node instanceof HTMLElement ? node : null;+};++/**+ * Whether a point sits in the corridor bridging the body and the marker, at+ * the marker's own row height — the natural path from a highlighted line to+ * its (not directly adjoining) marker. Direction-agnostic: works whether the+ * marker sits to the body's physical left or right (RTL vs LTR).+ */+export const inMarkerBridge = (+ x: number,+ y: number,+ bodyRect: DOMRect,+ markerRect: DOMRect,+): boolean => {+ const left = Math.min(bodyRect.left, markerRect.left);+ const right = Math.max(bodyRect.right, markerRect.right);+ return x >= left && x <= right && y >= markerRect.top && y <= markerRect.bottom;+};++/**+ * The comment marker that appears in the body's right margin next to the+ * line under the pointer. Clicking it comments on that visual line, so a+ * reader can annotate a sentence without selecting it first.+ *+ * Mounted inside the editor column, absolutely positioned, so the marker+ * moves with the text it stands beside.+ */+const BlockCommentMarker = memo<{ hostRef: React.RefObject<HTMLElement | null> }>(({ hostRef }) => {+ const { t } = useTranslation('file');+ const state = useDocumentComments();+ const { bodyElement } = useCommentAnchors();+ const { allowed: canComment } = usePermission('create_content');+ const setPendingCommentAnchor = usePageEditorStore((s) => s.setPendingCommentAnchor);+ const editor = usePageEditorStore((s) => s.editor);+ const [target, setTarget] = useState<MarkerTarget | null>(null);+ const targetRef = useRef(target);+ targetRef.current = target;+ const markerRef = useRef<HTMLDivElement>(null);+ const documentId = state?.documentId;+ const enabled = Boolean(documentId) && canComment && Boolean(bodyElement);++ useEffect(() => {+ const host = hostRef.current;+ if (!enabled || !bodyElement || !host) return;++ // The marker sits outside the body's DOM subtree, past the column's own+ // padding — neither a body-only `pointerleave` (old approach) nor a+ // target-containment check on host `pointermove` (still real, but the+ // pointer visiting the gap between body and marker generates its own+ // `pointermove` there too) survives the crossing: both clear the target+ // the instant the pointer is over the gap itself, before it ever reaches+ // the marker. Treat the rectangle spanning body and marker, at the+ // marker's own row height, as one continuous hoverable bridge — the+ // natural path from a highlighted line to its marker never leaves it.+ const pointerStaysWithMarker = (event: PointerEvent) => {+ const marker = markerRef.current;+ if (!marker) return false;+ if (event.target instanceof Node && marker.contains(event.target)) return true;+ return inMarkerBridge(+ event.clientX,+ event.clientY,+ bodyElement.getBoundingClientRect(),+ marker.getBoundingClientRect(),+ );+ };+ const handleMove = (event: PointerEvent) => {+ const block = blockAt(bodyElement, event.target);+ // Root-owned whitespace between or after blocks is no line at all; the+ // marker for the last line the pointer crossed must not stay actionable+ // there — unless the pointer is on the bridge to that very marker, the+ // one path it is meant to survive (the bridge's row is inside the body+ // too, so the host-level handler never sees these moves).+ if (!block) {+ if (!pointerStaysWithMarker(event)) setTarget(null);+ return;+ }+ // A line with nothing to quote (an empty paragraph, a divider) has no+ // marker: the anchor it would produce is empty.+ const range = lineAt(block, event.clientY);+ if (!range) {+ setTarget(null);+ return;+ }+ if (sameRange(targetRef.current?.range, range)) return;+ const lineRect = range.getClientRects()[0] ?? range.getBoundingClientRect();+ const top = lineRect.top - host.getBoundingClientRect().top;+ setTarget({ range, top });+ };+ const handleLeave = () => setTarget(null);+ const handleHostMove = (event: PointerEvent) => {+ const target = event.target;+ if (target instanceof Node && bodyElement.contains(target)) return;+ if (!pointerStaysWithMarker(event)) setTarget(null);+ };++ bodyElement.addEventListener('pointermove', handleMove);+ host.addEventListener('pointermove', handleHostMove);+ host.addEventListener('pointerleave', handleLeave);+ return () => {+ bodyElement.removeEventListener('pointermove', handleMove);+ host.removeEventListener('pointermove', handleHostMove);+ host.removeEventListener('pointerleave', handleLeave);+ setTarget(null);+ };+ }, [bodyElement, enabled, hostRef]);++ const handleClick = useCallback(() => {+ const range = targetRef.current?.range;+ if (!range || !documentId) return;+ const anchor = captureRangeAnchor(bodyElement, range);+ if (!anchor) return;+ setPendingCommentAnchor({ anchor, documentId });+ setTarget(null);+ // Same hand-off as the toolbar's Comment action: the composer takes+ // focus, so the body's selection toolbar must not linger over the text.+ editor?.dispatchCommand(HIDE_TOOLBAR_COMMAND, undefined);+ editor?.blur();+ }, [bodyElement, documentId, editor, setPendingCommentAnchor]);++ if (!enabled || !target) return null;++ return (+ // Leaving the marker for anywhere else in the host, including the gap+ // back to the body, is covered by the host-level pointermove above; no+ // listener of its own needed here.+ <div className={styles.blockMarker} ref={markerRef} style={{ top: target.top }}>+ <ActionIcon+ aria-label={t('pageEditor.comments.anchor.addToLine')}+ icon={MessageSquarePlus}+ size={'small'}+ title={t('pageEditor.comments.anchor.addToLine')}+ onClick={handleClick}+ // The body's selection toolbar reads the selection on pointer-down;+ // pressing this must neither collapse a selection nor move focus.+ onPointerDown={(event) => event.preventDefault()}+ />+ </div>+ );+});++BlockCommentMarker.displayName = 'DocumentCommentBlockMarker';++export default BlockCommentMarker;diff --git a/src/features/PageEditor/DocumentComments/CommentCard.tsx b/src/features/PageEditor/DocumentComments/CommentCard.tsxindex d57e1cf9a1d..fe1b4f33e76 100644--- a/src/features/PageEditor/DocumentComments/CommentCard.tsx+++ b/src/features/PageEditor/DocumentComments/CommentCard.tsx@@ -2,6 +2,7 @@ import type { DocumentCommentItem } from '@lobechat/types';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 { cx } from 'antd-style';import { ChevronRight, MessageCircle, Pencil, Trash } from 'lucide-react';import { memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -31,6 +32,8 @@ import { COMMENT_INPUT_MAX_HEIGHT, styles } from './styles';interface CommentCardProps {comment: DocumentCommentItem;+ /** Narrow-column layout for a card in the gutter: no avatar gutter, tighter spacing. */+ compact?: boolean;/** Whether a focus also scrolls the card into view. Defaults to true; a pick in the body passes false. */focusScroll?: boolean;/** Set when a deep link targets this comment; each new token highlights (and by default scrolls) again. */@@ -39,6 +42,12 @@ interface CommentCardProps {onReply?: () => void;onUpdate: DocumentCommentUpdateHandler;replying?: boolean;+ /**+ * Who a reply answers when it carries no explicit target — the thread's+ * root author. A flat (compact) list has no indentation to imply it, so+ * the card names the target itself.+ */+ threadAuthor?: DocumentCommentItem['author'];variant?: 'reply' | 'root';}@@ -50,31 +59,33 @@ const hasDocumentCommentEditorData = (editorData: DocumentCommentItem['editorDatObject.keys(editorData).length > 0,);-const CommentContent = memo<Pick<DocumentCommentItem, 'content' | 'editorData'>>(- ({ content, editorData }) => (- <div className={styles.commentContent}>- {hasDocumentCommentEditorData(editorData) ? (- <RichTextMessage editorState={editorData} variant={'default'} />- ) : (- <Markdown fontSize={16} variant={'chat'}>- {content}- </Markdown>- )}- </div>- ),-);+const CommentContent = memo<+ Pick<DocumentCommentItem, 'content' | 'editorData'> & { compact?: boolean }+>(({ compact, content, editorData }) => (+ <div className={styles.commentContent}>+ {hasDocumentCommentEditorData(editorData) ? (+ <RichTextMessage editorState={editorData} variant={'default'} />+ ) : (+ <Markdown fontSize={compact ? 14 : 16} variant={'chat'}>+ {content}+ </Markdown>+ )}+ </div>+));CommentContent.displayName = 'DocumentCommentContent';const CommentCard = memo<CommentCardProps>(({comment,+ compact = false,focusScroll = true,focusToken,onMutated,onReply,onUpdate,replying,+ threadAuthor,variant = 'root',}) => {const { t } = useTranslation('file');@@ -101,10 +112,12 @@ const CommentCard = memo<CommentCardProps>(comment.author.fullName ||comment.author.username ||t('pageEditor.comments.author.deactivated');+ const replyTarget =+ comment.replyTo?.author ?? (compact && variant === 'reply' ? threadAuthor : undefined);const replyToName =- comment.replyTo?.author.fullName ||- comment.replyTo?.author.username ||- (comment.replyTo ? t('pageEditor.comments.author.deactivated') : null);+ replyTarget?.fullName ||+ replyTarget?.username ||+ (replyTarget ? t('pageEditor.comments.author.deactivated') : null);const edited = new Date(comment.updatedAt).getTime() > new Date(comment.createdAt).getTime();useEffect(() => {@@ -115,13 +128,15 @@ const CommentCard = memo<CommentCardProps>(const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;node.scrollIntoView({ behavior: reduceMotion ? 'auto' : 'smooth', block: 'center' });}+ // Panel cards are placed level with their run instead of being tinted.+ if (compact) return;node.classList.add(styles.highlighted);const timer = setTimeout(() => node.classList.remove(styles.highlighted), 2400);return () => {clearTimeout(timer);node.classList.remove(styles.highlighted);};- }, [focusScroll, focusToken]);+ }, [compact, focusScroll, focusToken]);const handleUpdate = useCallback(async () => {const editorValue: DocumentCommentEditorValue = editorRef.current?.getValue() ?? {@@ -187,9 +202,13 @@ const CommentCard = memo<CommentCardProps>(return (<Flexbox- className={`${styles.card} ${variant === 'reply' ? styles.replyCard : ''}`}data-document-comment-id={comment.id}ref={cardRef}+ className={cx(+ styles.card,+ variant === 'reply' && styles.replyCard,+ compact && styles.cardCompact,+ )}onMouseEnter={anchor && !anchorOrphaned ? () => setHoveredRootId(comment.id) : undefined}onMouseLeave={anchor && !anchorOrphaned@@ -197,15 +216,57 @@ const CommentCard = memo<CommentCardProps>(: undefined}>- <Flexbox horizontal align={'center'} className={styles.header} gap={8}>+ {/* In the gutter the quote heads the card: it is what the card is about. */}+ {anchor && compact && (+ <AnchorQuote+ anchor={anchor}+ className={styles.cardAnchorCompact}+ orphaned={anchorOrphaned}+ onLocate={() => locateInBody(comment.id)}+ />+ )}+ <Flexbox+ horizontal+ align={compact ? 'flex-start' : 'center'}+ className={cx(styles.header, compact && styles.headerCompact)}+ gap={compact ? 8 : 8}+ ><Avataravatar={comment.author.avatar || authorName}- size={variant === 'reply' ? 28 : 32}+ size={compact ? 28 : variant === 'reply' ? 28 : 32}/>- <Text fontSize={14} weight={600}>- {authorName}- </Text>- {replyToName && (+ {compact ? (+ // Name over time, the way a card in a narrow column reads best.+ <Flexbox gap={2} style={{ minWidth: 0 }}>+ <Flexbox horizontal align={'center'} gap={6} style={{ minWidth: 0 }}>+ <Text ellipsis fontSize={13} weight={600}>+ {authorName}+ </Text>+ {replyToName && (+ <>+ <ChevronRight aria-hidden className={styles.replyTargetIcon} size={12} />+ <Text ellipsis fontSize={13} weight={600}>+ {replyToName}+ </Text>+ </>+ )}+ </Flexbox>+ {time && (+ <Text className={styles.meta} fontSize={12} title={timeTitle}>+ {time}+ {edited && !deleted ? ` · ${t('pageEditor.comments.edited')}` : ''}+ {comment.author.status === 'former'+ ? ` · ${t('pageEditor.comments.author.former')}`+ : ''}+ </Text>+ )}+ </Flexbox>+ ) : (+ <Text fontSize={14} weight={600}>+ {authorName}+ </Text>+ )}+ {!compact && replyToName && (<><ChevronRight aria-hidden className={styles.replyTargetIcon} size={14} /><Text fontSize={14} weight={600}>@@ -213,24 +274,24 @@ const CommentCard = memo<CommentCardProps>(</Text></>)}- {comment.author.status === 'former' && (+ {!compact && comment.author.status === 'former' && (<Text className={styles.meta} fontSize={12}>{t('pageEditor.comments.author.former')}</Text>)}- {time && (+ {!compact && time && (<Text className={styles.meta} fontSize={14} title={timeTitle}>{time}</Text>)}- {edited && !deleted && (+ {!compact && edited && !deleted && (<Text className={styles.meta} fontSize={12}>{t('pageEditor.comments.edited')}</Text>)}</Flexbox>- {anchor && (+ {anchor && !compact && (<AnchorQuoteanchor={anchor}className={styles.cardAnchor}@@ -239,7 +300,13 @@ const CommentCard = memo<CommentCardProps>(/>)}- <div className={`${styles.body} ${variant === 'reply' ? styles.replyBody : ''}`}>+ <div+ className={cx(+ styles.body,+ variant === 'reply' && styles.replyBody,+ compact && styles.bodyCompact,+ )}+ >{deleted ? (<Text className={styles.deleted}>{t('pageEditor.comments.deleted')}</Text>) : editing ? (@@ -312,15 +379,23 @@ const CommentCard = memo<CommentCardProps>(/></ChatInput>) : (- <CommentContent content={comment.content} editorData={comment.editorData} />+ <CommentContent+ compact={compact}+ content={comment.content}+ editorData={comment.editorData}+ />)}</div>{!optimistic && !editing && (onReply || comment.canEdit || comment.canDelete) && (<Flexboxhorizontal- className={`${styles.actions} ${variant === 'reply' ? styles.replyCardActions : ''}`}gap={4}+ className={cx(+ styles.actions,+ variant === 'reply' && styles.replyCardActions,+ compact && styles.actionsCompact,+ )}>{onReply && (<ActionIcondiff --git a/src/features/PageEditor/DocumentComments/Composer.tsx b/src/features/PageEditor/DocumentComments/Composer.tsxindex cc79f643e10..24f957ac89b 100644--- a/src/features/PageEditor/DocumentComments/Composer.tsx+++ b/src/features/PageEditor/DocumentComments/Composer.tsx@@ -1,7 +1,7 @@import type { DocumentCommentJson, DocumentCommentSelectionAnchor } from '@lobechat/types';import { ChatInput, ChatInputActionBar, SendButton, useEditor } from '@lobehub/editor/react';import { Flexbox } from '@lobehub/ui';-import { Avatar, toast } from '@lobehub/ui/base-ui';+import { Avatar, Button, toast } from '@lobehub/ui/base-ui';import { nanoid } from 'nanoid';import { memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -19,14 +19,16 @@ import { useLocalStorageState } from '@/hooks/useLocalStorageState';import { usePermission } from '@/hooks/usePermission';import { useUserAvatar } from '@/hooks/useUserAvatar';-import { usePageEditorStore } from '../store';+import { usePageEditorStore, useStoreApi } from '../store';import AnchorQuote from './anchor/AnchorQuote';-import { DOCUMENT_COMMENT_COMPOSER_ID } from './anchor/constants';+import { prefersReducedMotion } from './anchor/commentLocator';+import { useCommentAnchors } from './anchor/context';import DocumentCommentEditor, { type DocumentCommentEditorRef } from './DocumentCommentEditor';import type { DocumentCommentSubmitInput } from './optimistic';import { COMMENT_INPUT_MAX_HEIGHT, styles } from './styles';+import { useGutterComposerFocus } from './useGutterComposerFocus';-interface Draft {+export interface Draft {clientId: string;content: string;editorData: DocumentCommentJson | null;@@ -37,220 +39,775 @@ interface Draft {selectionAnchor?: DocumentCommentSelectionAnchor;}+const getDraftKey = (workspaceId: string | null | undefined, documentId: string, scope: string) =>+ `document-comment-draft:${workspaceId ?? 'personal'}:${documentId}:${scope}`;++/**+ * The gutter composer only mounts once a pending anchor exists in the store,+ * but the store doesn't survive a reload while the draft does — so nothing+ * would ever re-publish it. Read the persisted anchor directly, outside the+ * composer, to break that chicken-and-egg gate.+ */+export const readAnchoredDraftAnchor = (+ workspaceId: string | null | undefined,+ documentId: string,+): DocumentCommentSelectionAnchor | undefined => {+ try {+ const raw = window.localStorage.getItem(getDraftKey(workspaceId, documentId, 'anchored'));+ if (!raw) return undefined;+ return (JSON.parse(raw) as Draft).selectionAnchor;+ } catch {+ return undefined;+ }+};++/**+ * Moves a stranded document-level draft's full contents — not just its+ * anchor — into the gutter's own scope. The anchor alone would leave the+ * gutter's draft empty while the text and attachments stay behind in the+ * now-unanchored document-level box.+ */+export const migrateDraftToAnchoredScope = (+ workspaceId: string | null | undefined,+ documentId: string,+ draft: Draft,+): void => {+ try {+ window.localStorage.setItem(+ getDraftKey(workspaceId, documentId, 'anchored'),+ JSON.stringify(draft),+ );+ } catch {+ // ignore write failures (private mode, quota)+ }+};++const getFailedDraftKeyPrefix = (workspaceId: string | null | undefined, documentId: string) =>+ getDraftKey(workspaceId, documentId, 'anchored-failed:');++/**+ * A failed anchored submission whose shared slot was reclaimed by a newer+ * pick before the request settled: restoring it there would overwrite the+ * newer draft, but discarding it outright loses the reader's typed text and+ * attachments for a network blip that was never their fault. Stash it under+ * its own key, scoped by clientId, instead; `restoreFailedAnchoredDraft`+ * hands it back to the shared slot the next time that slot is free.+ */+export const preserveFailedAnchoredDraft = (+ workspaceId: string | null | undefined,+ documentId: string,+ draft: Draft,+): void => {+ try {+ window.localStorage.setItem(+ `${getFailedDraftKeyPrefix(workspaceId, documentId)}${draft.clientId}`,+ JSON.stringify(draft),+ );+ } catch {+ // ignore write failures (private mode, quota)+ }+};++/**+ * Removes and returns one stashed failed anchored draft of this document+ * (oldest key first, so repeated failures come back in a stable order), or+ * `null` when there is none. A stash without an anchor or without content is+ * nothing the gutter could show and is dropped on the way.+ */+export const takeFailedAnchoredDraft = (+ workspaceId: string | null | undefined,+ documentId: string,+): Draft | null => {+ try {+ const prefix = getFailedDraftKeyPrefix(workspaceId, documentId);+ const keys: string[] = [];+ for (let index = 0; index < window.localStorage.length; index += 1) {+ const key = window.localStorage.key(index);+ if (key?.startsWith(prefix)) keys.push(key);+ }+ for (const key of keys.sort()) {+ const raw = window.localStorage.getItem(key);+ window.localStorage.removeItem(key);+ if (!raw) continue;+ try {+ const draft = JSON.parse(raw) as Draft;+ if (draft.selectionAnchor && (draft.content || draft.editorData)) return draft;+ } catch {+ // a malformed stash is unrecoverable; keep looking+ }+ }+ return null;+ } catch {+ return null;+ }+};++/**+ * Puts a stashed failed anchored draft back into the shared 'anchored' slot+ * once nothing else owns it — the newer draft that displaced it has since+ * been sent or cancelled — and returns it so the caller can republish its+ * anchor, which is what mounts the gutter composer beside the text again+ * with the failed words and attachments in it, ready to retry. Returns+ * `null` when the slot still holds content of its own or there is nothing+ * stashed. An empty-but-present slot record (what `submit` and `cancel`+ * leave behind) does not count as content, as in `readLegacyRootDraft`.+ */+export const restoreFailedAnchoredDraft = (+ workspaceId: string | null | undefined,+ documentId: string,+): Draft | null => {+ try {+ const raw = window.localStorage.getItem(getDraftKey(workspaceId, documentId, 'anchored'));+ if (raw) {+ const current = JSON.parse(raw) as Draft;+ if (current.content || current.editorData || current.selectionAnchor) return null;+ }+ } catch {+ // an unreadable slot is treated as free; the stash is worth more than it+ }+ const failed = takeFailedAnchoredDraft(workspaceId, documentId);+ if (!failed) return null;+ migrateDraftToAnchoredScope(workspaceId, documentId, failed);+ return failed;+};++/**+ * Before gutter and inline shared a scope, inline mode stored every root+ * draft — anchored or not — under 'root'. Returns a legacy draft still+ * sitting there, or `null` when there is nothing to migrate or the new+ * ('anchored') scope already has content of its own to protect. A cancelled+ * or already-submitted anchored draft leaves an empty-but-present record+ * behind (see `submit`'s and `cancel`'s up-front clear), which doesn't count+ * as "content of its own" — otherwise the very first cancel or send in+ * anchored/gutter mode would block this migration forever.+ */+export const readLegacyRootDraft = (+ workspaceId: string | null | undefined,+ documentId: string,+): Draft | null => {+ try {+ const anchoredRaw = window.localStorage.getItem(+ getDraftKey(workspaceId, documentId, 'anchored'),+ );+ if (anchoredRaw) {+ const anchored = JSON.parse(anchoredRaw) as Draft;+ if (anchored.content || anchored.editorData || anchored.selectionAnchor) return null;+ }+ const raw = window.localStorage.getItem(getDraftKey(workspaceId, documentId, 'root'));+ if (!raw) return null;+ const legacy = JSON.parse(raw) as Draft;+ if (!legacy.content && !legacy.editorData && !legacy.selectionAnchor) return null;+ return legacy;+ } catch {+ return null;+ }+};++export const clearLegacyRootDraft = (+ workspaceId: string | null | undefined,+ documentId: string,+): void => {+ try {+ window.localStorage.removeItem(getDraftKey(workspaceId, documentId, 'root'));+ } catch {+ // ignore+ }+};++/**+ * The mirror image of `readLegacyRootDraft`: a plain comment started in+ * `AgentDocumentPage` (no panel, so its composer shares the gutter's+ * 'anchored' scope even though it never adopted a selection there) is+ * invisible once the same document opens in a panel-capable layout, whose+ * document-level composer only ever reads 'root'. Returns that draft, or+ * `null` when there is nothing to adopt or 'root' already has content of+ * its own to protect.+ */+export const readUnanchoredDraftFromAnchoredScope = (+ workspaceId: string | null | undefined,+ documentId: string,+): Draft | null => {+ try {+ const rootRaw = window.localStorage.getItem(getDraftKey(workspaceId, documentId, 'root'));+ if (rootRaw) {+ const root = JSON.parse(rootRaw) as Draft;+ if (root.content || root.editorData) return null;+ }+ const raw = window.localStorage.getItem(getDraftKey(workspaceId, documentId, 'anchored'));+ if (!raw) return null;+ const draft = JSON.parse(raw) as Draft;+ if (draft.selectionAnchor) return null;+ if (!draft.content && !draft.editorData) return null;+ return draft;+ } catch {+ return null;+ }+};++export const clearAnchoredScopeDraft = (+ workspaceId: string | null | undefined,+ documentId: string,+): void => {+ try {+ window.localStorage.removeItem(getDraftKey(workspaceId, documentId, 'anchored'));+ } catch {+ // ignore+ }+};++/**+ * How a root composer relates to the selection being commented on.+ *+ * - `gutter`: the composer beside the text. Exists only while a selection is+ * pending, adopts it, and keeps its own draft.+ * - `inline`: the composer below the body on a pane too narrow for a gutter.+ * Adopts the pending selection and scrolls itself into view for it.+ * - `none`: the document-level composer below the body while a gutter is+ * present. Never adopts a selection — that is the gutter composer's job.+ */+export type ComposerAnchorMode = 'gutter' | 'inline' | 'none';+interface ComposerProps {+ anchorMode?: ComposerAnchorMode;documentId: string;+ /**+ * Whether the gutter composer's card is positioned and visible. The gutter+ * hides a card until it has measured where it goes, and a hidden box cannot+ * take the caret, so the focus for a fresh selection waits on this.+ */+ focusReady?: boolean;+ /** Dismiss a reply box: the draft is dropped and the caller closes it. */+ onCancel?: () => void;onSubmit: (input: DocumentCommentSubmitInput) => Promise<void>;onSuccess?: () => void;parentCommentId?: string;+ /**+ * The bare layout used beside the text: no avatar, no quote row, no+ * emphasis ring, actions underneath. The gutter composer always uses it;+ * a reply box inside a panel card opts in.+ */+ plain?: boolean;}-const Composer = memo<ComposerProps>(({ documentId, onSubmit, onSuccess, parentCommentId }) => {- const { t } = useTranslation('file');- const workspaceId = useActiveWorkspaceId();- const { allowed: canCreate } = usePermission('create_content');- const avatar = useUserAvatar();- const shouldSendOnEnter = useEnterToSend();- const editor = useEditor();- const editorRef = useRef<DocumentCommentEditorRef>(null);- const inputRef = useRef<HTMLDivElement>(null);- const submittingRef = useRef(false);- const [draft, setDraft] = useLocalStorageState<Draft>(- `document-comment-draft:${workspaceId ?? 'personal'}:${documentId}:${parentCommentId ?? 'root'}`,- { clientId: nanoid(), content: '', editorData: null },- );- // Only a root comment can be anchored; a reply shares its thread's anchor.- const isRootComposer = !parentCommentId;- // The store outlives a document switch, so a quote captured in another- // document is not this composer's to adopt.- const pendingAnchor = usePageEditorStore((s) =>- s.pendingCommentAnchor?.documentId === documentId ? s.pendingCommentAnchor.anchor : undefined,- );- const setPendingCommentAnchor = usePageEditorStore((s) => s.setPendingCommentAnchor);- const anchor = isRootComposer ? draft.selectionAnchor : undefined;- const [showTypoBar, setShowTypoBar] = useLocalStorageState(- 'document-comment:show-formatting-toolbar',- false,- );- const [submitting, setSubmitting] = useState(false);-- // Intake: the toolbar drops a freshly captured selection into the store and- // the root composer adopts it as its draft anchor.- useEffect(() => {- if (!isRootComposer || !pendingAnchor) return;- setDraft((current) =>- current.selectionAnchor === pendingAnchor- ? current- : { ...current, selectionAnchor: pendingAnchor },- );- }, [isRootComposer, pendingAnchor, setDraft]);-- // Restore: the draft outlives a reload, the store doesn't, so republish the- // draft's anchor to keep the body highlight in sync with what will be sent.- useEffect(() => {- if (!isRootComposer || !anchor || pendingAnchor) return;- setPendingCommentAnchor({ anchor, documentId });- }, [anchor, documentId, isRootComposer, pendingAnchor, setPendingCommentAnchor]);-- const clearAnchor = useCallback(() => {- setDraft((current) => ({ ...current, selectionAnchor: undefined }));- setPendingCommentAnchor(undefined);- }, [setDraft, setPendingCommentAnchor]);-- const submit = useCallback(async () => {- const editorValue = editorRef.current?.getValue() ?? {- content: draft.content,- editorData: draft.editorData,- };- const content = editorValue.content.trim();- const attachmentState = getEditorAttachmentStateFromJson(editorValue.editorData);- if (- !workspaceId ||- !canCreate ||- attachmentState.hasIncompleteAttachments ||- (!content && !attachmentState.hasCompletedAttachments) ||- submittingRef.current- )- return;-- submittingRef.current = true;- setSubmitting(true);- const submittedDraft = { clientId: draft.clientId, ...editorValue, selectionAnchor: anchor };- setDraft({ clientId: nanoid(), content: '', editorData: null });- setPendingCommentAnchor(undefined);- editorRef.current?.clean();- try {- await onSubmit({- clientId: submittedDraft.clientId,- content,- editorData: editorValue.editorData,- selectionAnchor: anchor,- });- onSuccess?.();- } catch {- setDraft((current) => (current.content ? current : submittedDraft));- editorRef.current?.setValue(editorValue);- editorRef.current?.focus();- toast.error(t('pageEditor.comments.createFailed'));- } finally {- submittingRef.current = false;- setSubmitting(false);- }- }, [- anchor,- canCreate,- draft,+const Composer = memo<ComposerProps>(+ ({+ anchorMode = 'none',+ documentId,+ focusReady = true,+ onCancel,onSubmit,onSuccess,- setDraft,- setPendingCommentAnchor,- t,- workspaceId,- ]);-- const handleAttach = useCallback(- (files: File[]) => {- insertFilesIntoEditor(editor, files);- },- [editor],- );-- if (!workspaceId || !canCreate || (submitting && parentCommentId)) return null;-- const attachmentState = getEditorAttachmentStateFromJson(draft.editorData);-- return (- <Flexbox- horizontal- align={'flex-start'}- gap={12}- id={isRootComposer ? DOCUMENT_COMMENT_COMPOSER_ID : undefined}- >- <Flexbox className={styles.composerAvatar}>- <Avatar avatar={avatar} size={parentCommentId ? 28 : 32} />- </Flexbox>- <ChatInput- className={styles.composer}- flex={1}- maxHeight={COMMENT_INPUT_MAX_HEIGHT}- minHeight={72}- resize={false}- slashMenuRef={inputRef}- footer={- <ChatInputActionBar- style={{ paddingBlock: 4, paddingInline: 8 }}- left={- <AttachmentMenu- disabled={submitting}- formatEnabled={showTypoBar}- onFiles={handleAttach}- onFormatEnabledChange={setShowTypoBar}- onLibraryFiles={(attachments) =>- insertExistingAttachmentsIntoEditor(editor, attachments)- }- />- }- right={- <SendButton- loading={submitting}- shape={'round'}- type={'primary'}- disabled={- attachmentState.hasIncompleteAttachments ||- (!draft.content.trim() && !attachmentState.hasCompletedAttachments)- }- title={- parentCommentId- ? t('pageEditor.comments.replyAction')- : t('pageEditor.comments.publish')- }- onClick={() => void submit()}+ parentCommentId,+ plain = false,+ }) => {+ const { t } = useTranslation('file');+ const workspaceId = useActiveWorkspaceId();+ const { allowed: canCreate } = usePermission('create_content');+ const avatar = useUserAvatar();+ const shouldSendOnEnter = useEnterToSend();+ const editor = useEditor();+ const editorRef = useRef<DocumentCommentEditorRef>(null);+ const inputRef = useRef<HTMLDivElement>(null);+ const rootRef = useRef<HTMLDivElement>(null);+ // Set by the legacy-migration effect below when this mount adopted an+ // unanchored 'root' draft into 'anchored'; `submit` clears the original+ // once that migrated copy is actually sent.+ const migratedUnanchoredLegacyRef = useRef(false);+ // Same idea, the other direction: set when this 'none'-mode mount adopted+ // an unanchored draft that a panel-less page had left under 'anchored'.+ const adoptedUnanchoredFromAnchoredRef = useRef(false);+ const submittingRef = useRef(false);+ // Only a root comment can be anchored; a reply shares its thread's anchor.+ const isRootComposer = !parentCommentId;+ const isGutterComposer = isRootComposer && anchorMode === 'gutter';+ const isPlain = isGutterComposer || plain;+ const adoptsAnchor = isRootComposer && anchorMode !== 'none';+ // An anchor-adopting composer (gutter or inline) and the document-level+ // composer beside it can be open at the same time, so each keeps its own+ // draft; gutter and inline never coexist (inline only exists without a+ // gutter), so they safely share the same scope across that layout switch+ // instead of stranding one side's content when it happens.+ //+ // A reply box is different: an anchored thread with a gutter open renders+ // twice (gutter + flat list, see Thread's `compact` prop, which `plain`+ // mirrors 1:1 for a reply composer), and both copies stay independently+ // interactive. Sharing one draft key would hydrate both with the same+ // `clientId`; submitting either one first would then have the other's+ // later submit reuse that id as an idempotency key and silently return+ // the first reply instead of creating a second one. Key a reply's scope+ // by which copy it is so the two can never collide.+ const draftScope = parentCommentId+ ? `${parentCommentId}${plain ? ':compact' : ''}`+ : adoptsAnchor+ ? 'anchored'+ : 'root';+ const draftKey = getDraftKey(workspaceId, documentId, draftScope);+ const [draft, setDraft] = useLocalStorageState<Draft>(draftKey, {+ clientId: nanoid(),+ content: '',+ editorData: null,+ });+ // The store outlives a document switch, so a quote captured in another+ // document is not this composer's to adopt.+ const pendingAnchor = usePageEditorStore((s) =>+ s.pendingCommentAnchor?.documentId === documentId ? s.pendingCommentAnchor.anchor : undefined,+ );+ const setPendingCommentAnchor = usePageEditorStore((s) => s.setPendingCommentAnchor);+ // Read fresh in the submit failure handler below, never through the+ // reactive selector: that closure is a snapshot from before the await,+ // so it can't see a newer pick that happened while the request was+ // in flight.+ const storeApi = useStoreApi();+ const anchor = adoptsAnchor ? draft.selectionAnchor : undefined;+ const [showTypoBar, setShowTypoBar] = useLocalStorageState(+ 'document-comment:show-formatting-toolbar',+ false,+ );+ const [submitting, setSubmitting] = useState(false);+ // The draft lives in storage as well as in state. Storage is written from+ // inside the state updater, which React only runs when the box renders+ // again — and releasing the selection unmounts the gutter box in the+ // same batch, so a draft dropped that way would come back on the next+ // open. Writes that must outlive the box go to storage directly.+ const persistDraft = useCallback(+ (next: Draft) => {+ try {+ window.localStorage.setItem(draftKey, JSON.stringify(next));+ } catch {+ // ignore write failures (private mode, quota)+ }+ setDraft(next);+ },+ [draftKey, setDraft],+ );++ // Intake: the toolbar drops a freshly captured selection into the store and+ // the anchored composer adopts it as its draft anchor.+ useEffect(() => {+ if (!adoptsAnchor || !pendingAnchor) return;+ setDraft((current) =>+ current.selectionAnchor === pendingAnchor+ ? current+ : { ...current, selectionAnchor: pendingAnchor },+ );+ }, [adoptsAnchor, pendingAnchor, setDraft]);++ // Restore: the draft outlives a reload, the store doesn't, so republish the+ // draft's anchor to keep the body highlight in sync with what will be sent.+ useEffect(() => {+ if (!adoptsAnchor || !anchor || pendingAnchor) return;+ setPendingCommentAnchor({ anchor, documentId });+ }, [adoptsAnchor, anchor, documentId, pendingAnchor, setPendingCommentAnchor]);++ // A document-level composer next to a gutter never sends an anchor. One+ // left in its draft (from a narrower pane, before a gutter existed) is+ // handed to the gutter composer completely — text and attachments+ // included, not just the anchor — since the anchor alone would leave the+ // gutter's draft empty while the words stay behind in this now-unanchored+ // box, publishable as an unrelated document-level comment.+ useEffect(() => {+ if (anchorMode !== 'none' || !isRootComposer || !draft.selectionAnchor) return;+ const anchor = draft.selectionAnchor;+ migrateDraftToAnchoredScope(workspaceId, documentId, draft);+ persistDraft({ clientId: nanoid(), content: '', editorData: null });+ if (!pendingAnchor) setPendingCommentAnchor({ anchor, documentId });+ }, [+ anchorMode,+ documentId,+ draft,+ isRootComposer,+ pendingAnchor,+ persistDraft,+ setPendingCommentAnchor,+ workspaceId,+ ]);++ // The mirror image of the effect above: a plain comment started in+ // AgentDocumentPage (no panel, so its composer shares the gutter's+ // 'anchored' scope even though it never adopted a selection) is+ // invisible once this same document opens in a panel-capable layout,+ // whose own composer only ever reads 'root'. Adopt it on mount, before+ // this composer's own 'root' draft has ever been written.+ useEffect(() => {+ adoptedUnanchoredFromAnchoredRef.current = false;+ if (anchorMode !== 'none' || !isRootComposer) return;+ const orphaned = readUnanchoredDraftFromAnchoredScope(workspaceId, documentId);+ if (!orphaned) return;+ setDraft(orphaned);+ // Leave 'anchored' in place until this adopted copy is actually sent —+ // see `submit` — or narrowing back to a panel-less layout before then+ // would orphan it again.+ adoptedUnanchoredFromAnchoredRef.current = true;+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [anchorMode, isRootComposer, documentId, workspaceId]);++ // A failed gutter submission stashed while a newer draft owned the shared+ // slot (see `submit`'s failure branch) is handed back by the provider in+ // a panel-capable layout, where no composer is mounted while the slot is+ // free. Here the inline box is always mounted and already holds the+ // slot's state, so it adopts the stash itself: the provider writing+ // storage behind its back would be clobbered by this box's next write.+ // Runs before the legacy upgrade below, whose own read then sees the+ // adopted content in 'anchored' and stands down.+ useEffect(() => {+ if (anchorMode !== 'inline' || !isRootComposer) return;+ const failed = restoreFailedAnchoredDraft(workspaceId, documentId);+ if (failed) setDraft(failed);+ // Deliberately excludes `draft` and `setDraft`: this effect is what+ // writes the draft, and depending on it would re-check on every+ // keystroke instead of once per document.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [anchorMode, isRootComposer, documentId, workspaceId]);++ // One-time upgrade: before gutter and inline shared a scope, inline mode+ // stored every root draft — anchored or not — under 'root'. Adopt a+ // legacy draft still sitting there once, on mount, before this+ // composer's own 'anchored'-scope draft has ever been written, so an+ // unfinished plain comment from before the upgrade doesn't just vanish.+ useEffect(() => {+ migratedUnanchoredLegacyRef.current = false;+ if (anchorMode !== 'inline' || !isRootComposer) return;+ const legacy = readLegacyRootDraft(workspaceId, documentId);+ if (!legacy) return;+ setDraft(legacy);+ // An anchored legacy draft belongs exclusively in the new scope now.+ // An unanchored one never adopted an anchor to begin with, so 'none'+ // mode's own composer still needs it until this migrated copy is+ // actually sent — clearing it here, before that, would orphan it if+ // the pane widens back to a gutter layout first. `submit` clears it+ // once the migrated copy it is standing in for has gone out, using+ // this ref (both scopes can only be written from this one composer+ // while it's mounted, since 'none' and 'inline' never coexist).+ if (legacy.selectionAnchor) clearLegacyRootDraft(workspaceId, documentId);+ else migratedUnanchoredLegacyRef.current = true;+ // Deliberately excludes `draft` and `setDraft`: this effect is what+ // writes the draft, and depending on it would re-check on every+ // keystroke instead of once per document.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [anchorMode, isRootComposer, documentId, workspaceId]);++ // The inline composer sits below the body, so a selection made further up+ // has to bring it into view before it can be typed into. The gutter+ // composer needs neither: it mounts level with the selection, and only+ // has to take focus.+ const previousPendingRef = useRef(pendingAnchor);+ useEffect(() => {+ const arrived = pendingAnchor && previousPendingRef.current !== pendingAnchor;+ previousPendingRef.current = pendingAnchor;+ if (!arrived || anchorMode !== 'inline') return;+ // One frame of delay lets the quote row render first, so the scroll+ // lands on the composer's real height.+ const frame = requestAnimationFrame(() => {+ rootRef.current?.scrollIntoView({+ behavior: prefersReducedMotion() ? 'auto' : 'smooth',+ block: 'center',+ });+ // Focus without its own scroll: the editor's focus would otherwise+ // cut the glide short at "caret barely visible".+ rootRef.current+ ?.querySelector<HTMLElement>('[contenteditable="true"]')+ ?.focus({ preventScroll: true });+ });+ return () => cancelAnimationFrame(frame);+ }, [anchorMode, pendingAnchor]);++ // A fresh selection wants the caret in the gutter composer; see the hook+ // for why that is neither a single call nor a plain autoFocus.+ const pickVersion = usePageEditorStore((s) => s.pendingCommentAnchorVersion);+ const gutterPick = isGutterComposer && anchor ? pickVersion || 1 : 0;+ useGutterComposerFocus({ editorRef, pick: gutterPick, ready: focusReady, rootRef });++ const clearAnchor = useCallback(() => {+ setDraft((current) => ({ ...current, selectionAnchor: undefined }));+ setPendingCommentAnchor(undefined);+ }, [setDraft, setPendingCommentAnchor]);++ // Cancelling the gutter composer drops the whole draft, quote and text: it+ // has nowhere to live once the selection it was written against is gone.+ const cancel = useCallback(() => {+ persistDraft({ clientId: nanoid(), content: '', editorData: null });+ if (isGutterComposer) setPendingCommentAnchor(undefined);+ editorRef.current?.clean();+ onCancel?.();+ }, [isGutterComposer, onCancel, persistDraft, setPendingCommentAnchor]);++ // Clicking back into the document while the box beside it is still empty+ // dismisses the box and its highlight, the way Yuque does: the reader has+ // moved on. A box with something typed in it is left alone — a stray+ // click must not throw away a half-written comment.+ const { bodyElement } = useCommentAnchors();+ const draftRef = useRef(draft);+ draftRef.current = draft;+ const cancelRef = useRef(cancel);+ cancelRef.current = cancel;+ useEffect(() => {+ if (!isGutterComposer || !bodyElement) return;+ const handlePointerDown = () => {+ const current = draftRef.current;+ const attachments = getEditorAttachmentStateFromJson(current.editorData);+ if (+ current.content.trim() ||+ attachments.hasCompletedAttachments ||+ attachments.hasIncompleteAttachments+ )+ return;+ cancelRef.current();+ };+ bodyElement.addEventListener('mousedown', handlePointerDown);+ return () => bodyElement.removeEventListener('mousedown', handlePointerDown);+ }, [bodyElement, isGutterComposer]);++ const submit = useCallback(async () => {+ const editorValue = editorRef.current?.getValue() ?? {+ content: draft.content,+ editorData: draft.editorData,+ };+ const content = editorValue.content.trim();+ const attachmentState = getEditorAttachmentStateFromJson(editorValue.editorData);+ if (+ !workspaceId ||+ !canCreate ||+ attachmentState.hasIncompleteAttachments ||+ (!content && !attachmentState.hasCompletedAttachments) ||+ submittingRef.current+ )+ return;++ submittingRef.current = true;+ setSubmitting(true);+ const submittedDraft = { clientId: draft.clientId, ...editorValue, selectionAnchor: anchor };+ // Clear up front so the optimistic card reads as the sent comment. For+ // the gutter composer, releasing the selection unmounts the box, and+ // the optimistic card takes its place beside the text at once; a box+ // still showing the same words with a spinner would read as a+ // duplicate that failed to close. The store's pending anchor is shared+ // by the whole document, so only the composer that captured it — a+ // reply or the unanchored document-level composer never did — may+ // release it; otherwise a reply's or that composer's own submit would+ // strand an unrelated in-progress gutter draft.+ persistDraft({ clientId: nanoid(), content: '', editorData: null });+ if (adoptsAnchor && anchor) setPendingCommentAnchor(undefined);+ editorRef.current?.clean();+ try {+ await onSubmit({+ clientId: submittedDraft.clientId,+ content,+ editorData: editorValue.editorData,+ selectionAnchor: anchor,+ });+ // The migrated legacy copy this submission was standing in for has+ // now gone out; the original 'root' record would otherwise freeze at+ // its pre-migration text and resurface it — already-sent — the next+ // time this document opens in a panel-capable layout.+ if (migratedUnanchoredLegacyRef.current) {+ clearLegacyRootDraft(workspaceId, documentId);+ migratedUnanchoredLegacyRef.current = false;+ }+ // Same idea for the copy adopted from 'anchored': once this submit+ // sends it, the panel-less page's own draft is no longer standing in+ // for an unfinished comment and can be dropped.+ if (adoptedUnanchoredFromAnchoredRef.current) {+ clearAnchoredScopeDraft(workspaceId, documentId);+ adoptedUnanchoredFromAnchoredRef.current = false;+ }+ onSuccess?.();+ } catch {+ // Releasing the anchor unmounted this box, so the reader could have+ // already picked a new selection and started a different draft in+ // the same shared 'anchored' slot while this request was in flight.+ // Restoring into that slot now would overwrite their text or+ // re-point their draft at this failed submission's anchor instead of+ // theirs — only restore when nothing has claimed it since.+ const slotStillEmpty = storeApi.getState().pendingCommentAnchor === undefined;+ if (isGutterComposer && anchor && slotStillEmpty) {+ // The box is gone by now: the draft goes back to storage, where+ // the box reads it when the republished selection mounts it again.+ persistDraft(submittedDraft);+ setPendingCommentAnchor({ anchor, documentId });+ } else if (isGutterComposer && anchor) {+ // Stashed, not dropped: the provider hands it back into the slot+ // once the newer draft that took it has been sent or cancelled.+ preserveFailedAnchoredDraft(workspaceId, documentId, submittedDraft);+ } else {+ setDraft((current) => (current.content ? current : submittedDraft));+ editorRef.current?.setValue(editorValue);+ editorRef.current?.focus();+ }+ toast.error(t('pageEditor.comments.createFailed'));+ } finally {+ submittingRef.current = false;+ setSubmitting(false);+ }+ }, [+ adoptsAnchor,+ anchor,+ canCreate,+ documentId,+ draft,+ isGutterComposer,+ onSubmit,+ onSuccess,+ persistDraft,+ setDraft,+ setPendingCommentAnchor,+ storeApi,+ t,+ workspaceId,+ ]);++ const handleAttach = useCallback(+ (files: File[]) => {+ insertFilesIntoEditor(editor, files);+ },+ [editor],+ );++ if (!workspaceId || !canCreate) return null;+ // A reply box stands in for the reply it is sending: the optimistic card+ // takes its place until the request settles. (The gutter box needs no+ // such rule: releasing its selection on submit unmounts it outright.)+ if (submitting && parentCommentId) return null;+ // The gutter composer exists for its selection; until the draft has+ // adopted it there is nothing to show.+ if (isGutterComposer && !anchor) return null;++ const attachmentState = getEditorAttachmentStateFromJson(draft.editorData);+ const canSend =+ !attachmentState.hasIncompleteAttachments &&+ (Boolean(draft.content.trim()) || attachmentState.hasCompletedAttachments);++ const editorNode = (+ <DocumentCommentEditor+ autoFocus={Boolean(parentCommentId) || isGutterComposer}+ disabled={submitting}+ editor={editor}+ entityId={draft.clientId}+ flush={isPlain}+ getPopupContainer={() => inputRef.current}+ initialContent={draft.content}+ initialEditorData={draft.editorData}+ ref={editorRef}+ placeholder={+ parentCommentId+ ? t('pageEditor.comments.replyPlaceholder')+ : t('pageEditor.comments.placeholder')+ }+ onChange={({ content, editorData }) => {+ setDraft((current) => ({ ...current, content, editorData }));+ }}+ onPressEnter={(event) => {+ if (!shouldSendOnEnter(event)) return;+ void submit();+ return true;+ }}+ />+ );+ const attachmentMenu = (+ <AttachmentMenu+ disabled={submitting}+ formatEnabled={showTypoBar}+ onFiles={handleAttach}+ onFormatEnabledChange={setShowTypoBar}+ onLibraryFiles={(attachments) => insertExistingAttachmentsIntoEditor(editor, attachments)}+ />+ );++ // Beside the text the selection is already visible in the body, so the+ // box is a plain input with its actions underneath — no quote row, no+ // avatar, no emphasis ring.+ if (isPlain) {+ return (+ <Flexbox gap={8} ref={rootRef}>+ <ChatInput+ className={styles.composerPlain}+ header={showTypoBar ? <TypoBar editor={editor} /> : undefined}+ maxHeight={COMMENT_INPUT_MAX_HEIGHT}+ minHeight={56}+ resize={false}+ slashMenuRef={inputRef}+ footer={+ <ChatInputActionBar+ left={attachmentMenu}+ style={{ paddingBlock: 4, paddingInline: 8 }}/>}- />- }- header={- anchor || showTypoBar ? (- <>- {anchor && (- <AnchorQuote- anchor={anchor}- className={styles.composerAnchor}- onDismiss={clearAnchor}+ onBodyClick={() => editor.focus()}+ >+ {editorNode}+ </ChatInput>+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button disabled={submitting} onClick={cancel}>+ {t('pageEditor.comments.cancel')}+ </Button>+ <Button+ disabled={!canSend}+ loading={submitting}+ type={'primary'}+ onClick={() => void submit()}+ >+ {parentCommentId+ ? t('pageEditor.comments.replyAction')+ : t('pageEditor.comments.publish')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+ }++ return (+ <Flexbox horizontal align={'flex-start'} gap={12} ref={rootRef}>+ <Flexbox className={styles.composerAvatar}>+ <Avatar avatar={avatar} size={parentCommentId ? 28 : 32} />+ </Flexbox>+ <ChatInput+ className={styles.composer}+ flex={1}+ maxHeight={COMMENT_INPUT_MAX_HEIGHT}+ minHeight={72}+ resize={false}+ slashMenuRef={inputRef}+ footer={+ <ChatInputActionBar+ left={attachmentMenu}+ style={{ paddingBlock: 4, paddingInline: 8 }}+ right={+ <SendButton+ disabled={!canSend}+ loading={submitting}+ shape={'round'}+ type={'primary'}+ title={+ parentCommentId+ ? t('pageEditor.comments.replyAction')+ : t('pageEditor.comments.publish')+ }+ onClick={() => void submit()}/>- )}- {showTypoBar && <TypoBar editor={editor} />}- </>- ) : undefined- }- onBodyClick={() => editor.focus()}- >- <DocumentCommentEditor- autoFocus={Boolean(parentCommentId)}- disabled={submitting}- editor={editor}- entityId={draft.clientId}- getPopupContainer={() => inputRef.current}- initialContent={draft.content}- initialEditorData={draft.editorData}- ref={editorRef}- placeholder={- parentCommentId- ? t('pageEditor.comments.replyPlaceholder')- : t('pageEditor.comments.placeholder')+ }+ />+ }+ header={+ anchor || showTypoBar ? (+ <>+ {anchor && (+ <AnchorQuote+ anchor={anchor}+ className={styles.composerAnchor}+ onDismiss={clearAnchor}+ />+ )}+ {showTypoBar && <TypoBar editor={editor} />}+ </>+ ) : undefined}- onChange={({ content, editorData }) => {- setDraft((current) => ({ ...current, content, editorData }));- }}- onPressEnter={(event) => {- if (!shouldSendOnEnter(event)) return;- void submit();- return true;- }}- />- </ChatInput>- </Flexbox>- );-});+ onBodyClick={() => editor.focus()}+ >+ {editorNode}+ </ChatInput>+ </Flexbox>+ );+ },+);Composer.displayName = 'DocumentCommentComposer';diff --git a/src/features/PageEditor/DocumentComments/DocumentCommentEditor.tsx b/src/features/PageEditor/DocumentComments/DocumentCommentEditor.tsxindex 95f447eabb8..0df8545c5f7 100644--- a/src/features/PageEditor/DocumentComments/DocumentCommentEditor.tsx+++ b/src/features/PageEditor/DocumentComments/DocumentCommentEditor.tsx@@ -2,6 +2,7 @@ import type { DocumentCommentJson } from '@lobechat/types';import type { IEditor } from '@lobehub/editor';import type { EditorProps } from '@lobehub/editor/react';import { useEditor } from '@lobehub/editor/react';+import { cx } from 'antd-style';import type { Ref } from 'react';import { memo, useCallback, useImperativeHandle } from 'react';@@ -31,6 +32,8 @@ interface DocumentCommentEditorProps {disabled?: boolean;editor?: IEditor;entityId: string;+ /** Drop the editor's extra inline padding so the caret lines up with the action bar's first icon. */+ flush?: boolean;getPopupContainer?: EditorProps['getPopupContainer'];initialContent: string;initialEditorData?: DocumentCommentJson | null;@@ -46,6 +49,7 @@ const DocumentCommentEditor = memo<DocumentCommentEditorProps>(autoFocus,compact = false,disabled,+ flush = false,editor: externalEditor,entityId,getPopupContainer,@@ -87,7 +91,14 @@ const DocumentCommentEditor = memo<DocumentCommentEditorProps>();return (- <div className={`${styles.commentEditor} ${mentionFilledClassName}`} ref={rootRef}>+ <div+ ref={rootRef}+ className={cx(+ styles.commentEditor,+ flush && styles.commentEditorFlush,+ mentionFilledClassName,+ )}+ ><EditorCanvasblockImageCaretGuarddisabled={disabled}diff --git a/src/features/PageEditor/DocumentComments/Gutter/constants.ts b/src/features/PageEditor/DocumentComments/Gutter/constants.tsnew file mode 100644index 00000000000..aa89eb52b4f--- /dev/null+++ b/src/features/PageEditor/DocumentComments/Gutter/constants.ts@@ -0,0 +1,6 @@+/** Inset between the panel edge and a card's left edge. */+export const GUTTER_INSET_START = 12;+/** Inset between a card's right edge and the panel edge. */+export const GUTTER_INSET_END = 12;+/** Vertical breathing room between stacked cards. */+export const GUTTER_CARD_GAP = 8;diff --git a/src/features/PageEditor/DocumentComments/Gutter/index.tsx b/src/features/PageEditor/DocumentComments/Gutter/index.tsxnew file mode 100644index 00000000000..0d08bea3e8f--- /dev/null+++ b/src/features/PageEditor/DocumentComments/Gutter/index.tsx@@ -0,0 +1,263 @@+'use client';++import { Empty, Flexbox } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { cx } from 'antd-style';+import { MessageSquareTextIcon } from 'lucide-react';+import { memo, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import SurfaceSkeleton from '@/components/Skeleton/Surface';+import NavHeader from '@/features/NavHeader';+import RightPanel from '@/features/RightPanel';+import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';+import { usePermission } from '@/hooks/usePermission';++import { usePageAgentPanelControl } from '../../RightPanel/OverrideContext';+import { usePageEditorStore } from '../../store';+import { useCommentAnchors } from '../anchor/context';+import Composer from '../Composer';+import { useDocumentComments } from '../context';+import { styles } from '../styles';+import Thread from '../Thread';+import type { DocumentCommentsState } from '../useDocumentCommentsState';+import { useForwardWheel } from './useForwardWheel';+import { PENDING_CARD_ID, useGutterLayout } from './useGutterLayout';++const PanelBody = memo<{ state: DocumentCommentsState }>(({ state }) => {+ const { t } = useTranslation('file');+ const {+ anchoredError,+ documentId,+ focus,+ gutterThreads,+ handleCreate,+ handlePinnedRootUpdate,+ handleReplyFocusMissing,+ handleUpdate,+ isAnchoredInitialError,+ isAnchoredLoading,+ isAnchoredRetrying,+ paneRef,+ pinnedThreadInGutter,+ refresh,+ refreshPinned,+ reloadAnchored,+ updatePinnedReplyCount,+ updateReplyCount,+ updateSummaryTotal,+ } = state;+ const { selectedRootId, selectRoot } = useCommentAnchors();+ const { allowed: canComment } = usePermission('create_content');+ const hasPending = usePageEditorStore((s) =>+ Boolean(s.pendingCommentAnchor && s.pendingCommentAnchor.documentId === documentId),+ );+ const hostRef = useRef<HTMLDivElement>(null);+ const trackRef = useRef<HTMLDivElement>(null);+ const threads = pinnedThreadInGutter ? [pinnedThreadInGutter, ...gutterThreads] : gutterThreads;+ const ids = threads.map(({ root }) => root.id);+ // The composer is what the reader is working on, so it takes the line; a+ // picked card takes it otherwise.+ const activeId = hasPending ? PENDING_CARD_ID : selectedRootId;+ const { registerCard, scrollBy, tops } = useGutterLayout({+ activeId,+ hasPending,+ ids,+ paneRef,+ trackRef,+ });+ // The panel is not a scroll container; a wheel over it scrolls the document.+ useForwardWheel(hostRef, scrollBy);+ const isEmpty =+ threads.length === 0 && !hasPending && !isAnchoredLoading && !isAnchoredInitialError;++ const renderCard = (id: string, active: boolean, children: React.ReactNode) => {+ const top = tops.get(id);+ return (+ <div+ key={id}+ ref={registerCard(id)}+ style={{ top }}+ className={cx(+ styles.gutterCard,+ top !== undefined && styles.gutterCardPositioned,+ active && styles.gutterCardActive,+ id === PENDING_CARD_ID && styles.gutterCardComposer,+ )}+ onClick={id === PENDING_CARD_ID ? undefined : () => selectRoot(id)}+ >+ {children}+ </div>+ );+ };++ return (+ <div data-document-comment-gutter className={styles.gutter} ref={hostRef}>+ {isAnchoredInitialError ? (+ <AsyncError error={anchoredError} variant={'block'} onRetry={() => void reloadAnchored()} />+ ) : isAnchoredLoading ? (+ <SurfaceSkeleton header={false} variant={'list'} />+ ) : (+ isEmpty && (+ <Flexbox align={'center'} className={styles.gutterEmpty} justify={'center'}>+ <Empty+ icon={MessageSquareTextIcon}+ description={t(+ canComment+ ? 'pageEditor.comments.gutterEmpty'+ : 'pageEditor.comments.gutterEmptyReadOnly',+ )}+ />+ </Flexbox>+ )+ )}+ {anchoredError && !isAnchoredInitialError && (+ <AsyncError+ error={anchoredError}+ retrying={isAnchoredRetrying}+ variant={'inline'}+ onRetry={() => void reloadAnchored()}+ />+ )}+ <div className={styles.gutterTrack} ref={trackRef}>+ {hasPending &&+ renderCard(+ PENDING_CARD_ID,+ true,+ <Composer+ anchorMode={'gutter'}+ documentId={documentId}+ focusReady={tops.has(PENDING_CARD_ID)}+ key={`anchored:${documentId}`}+ onSubmit={handleCreate}+ />,+ )}+ {pinnedThreadInGutter &&+ renderCard(+ pinnedThreadInGutter.root.id,+ selectedRootId === pinnedThreadInGutter.root.id,+ <Thread+ compact+ documentId={documentId}+ focus={focus}+ replyCount={pinnedThreadInGutter.replyCount}+ root={pinnedThreadInGutter.root}+ onFocusMissing={handleReplyFocusMissing}+ onMutated={refreshPinned}+ onReplyCountChange={updatePinnedReplyCount}+ onRootUpdate={handlePinnedRootUpdate}+ onSummaryChange={updateSummaryTotal}+ />,+ )}+ {gutterThreads.map(({ replyCount, root }) =>+ renderCard(+ root.id,+ selectedRootId === root.id,+ <Thread+ compact+ documentId={documentId}+ focus={focus?.rootCommentId === root.id ? focus : undefined}+ replyCount={replyCount}+ root={root}+ onFocusMissing={handleReplyFocusMissing}+ onMutated={refresh}+ onReplyCountChange={updateReplyCount}+ onRootUpdate={handleUpdate}+ onSummaryChange={updateSummaryTotal}+ />,+ ),+ )}+ </div>+ </div>+ );+});++PanelBody.displayName = 'DocumentCommentsPanelBody';++const DEFAULT_PANEL_WIDTH = 320;++const PanelContent = memo(() => {+ const { t } = useTranslation('file');+ const state = useDocumentComments();+ const setCommentsPanelOpen = usePageEditorStore((s) => s.setCommentsPanelOpen);++ return (+ <Flexbox flex={1} height={'100%'} style={{ minHeight: 0 }}>+ <NavHeader+ showTogglePanelButton={false}+ left={+ <Text+ ellipsis={{ tooltipWhenOverflow: true }}+ style={{ fontSize: 13, fontWeight: 500, marginLeft: 8 }}+ type={'secondary'}+ >+ {t('pageEditor.comments.title')}+ {state?.summary.data ? ` · ${state.summary.data.total}` : ''}+ </Text>+ }+ right={+ <ToggleRightPanelButton+ expand+ showActive={false}+ title={t('pageEditor.comments.toggle')}+ onToggle={() => setCommentsPanelOpen(false)}+ />+ }+ />+ {state ? (+ <PanelBody state={state} />+ ) : (+ <Flexbox align={'center'} className={styles.gutterEmpty} justify={'center'}>+ <Empty description={t('pageEditor.comments.gutterEmpty')} icon={MessageSquareTextIcon} />+ </Flexbox>+ )}+ </Flexbox>+ );+});++PanelContent.displayName = 'DocumentCommentsPanelContent';++/**+ * The sidebar for anchored comments: cards sit level with the text they+ * quote and ride along with the document's scroll, in a column of their own+ * so the page keeps its width. It is a panel in its own right, beside the+ * page-agent panel rather than a mode of it, so the copilot and the+ * comments never displace each other.+ */+const DocumentCommentsPanel = memo(() => {+ const [open, setOpen] = usePageEditorStore((s) => [s.commentsPanelOpen, s.setCommentsPanelOpen]);+ const [width, setWidth] = useState<number | string>(DEFAULT_PANEL_WIDTH);+ const { expand: agentOpen, toggle: toggleAgent } = usePageAgentPanelControl();++ // The two sidebars keep their own state but never show side by side: the+ // one that opens folds the other away. Only the transition into "open"+ // acts, so closing either never reopens the other.+ const wasOpenRef = useRef(open);+ const wasAgentOpenRef = useRef(agentOpen);+ useEffect(() => {+ const opened = open && !wasOpenRef.current;+ const agentOpened = agentOpen && !wasAgentOpenRef.current;+ wasOpenRef.current = open;+ wasAgentOpenRef.current = agentOpen;+ if (opened && agentOpen) toggleAgent(false);+ else if (agentOpened && open) setOpen(false);+ }, [agentOpen, open, setOpen, toggleAgent]);++ return (+ <RightPanel+ defaultWidth={width}+ expand={open}+ onExpandChange={setOpen}+ onSizeChange={(size) => {+ if (size?.width) setWidth(size.width);+ }}+ >+ <PanelContent />+ </RightPanel>+ );+});++DocumentCommentsPanel.displayName = 'DocumentCommentsPanel';++export default DocumentCommentsPanel;diff --git a/src/features/PageEditor/DocumentComments/Gutter/layout.test.ts b/src/features/PageEditor/DocumentComments/Gutter/layout.test.tsnew file mode 100644index 00000000000..fabb51409c6--- /dev/null+++ b/src/features/PageEditor/DocumentComments/Gutter/layout.test.ts@@ -0,0 +1,140 @@+import { describe, expect, it } from 'vitest';++import type { GutterLayoutEntry } from './layout';+import { gutterOverhangBottom, gutterOverhangTop, layoutGutterCards } from './layout';++const entry = (id: string, anchorTop: number, height = 100, order = 0): GutterLayoutEntry => ({+ anchorTop,+ height,+ id,+ order,+});++describe('layoutGutterCards', () => {+ it('leaves cards on their own line when they do not collide', () => {+ const tops = layoutGutterCards([entry('a', 0), entry('b', 400)], { gap: 8 });++ expect(tops.get('a')).toBe(0);+ expect(tops.get('b')).toBe(400);+ });++ it('pushes a colliding card below the one above it', () => {+ const tops = layoutGutterCards([entry('a', 0), entry('b', 20), entry('c', 40)], { gap: 8 });++ expect(tops.get('a')).toBe(0);+ expect(tops.get('b')).toBe(108);+ expect(tops.get('c')).toBe(216);+ });++ it('orders by anchor regardless of input order, then by document order', () => {+ const tops = layoutGutterCards(+ [entry('later', 20, 100, 2), entry('same-line', 20, 100, 1), entry('first', 0)],+ { gap: 8 },+ );++ expect(tops.get('first')).toBe(0);+ expect(tops.get('same-line')).toBe(108);+ expect(tops.get('later')).toBe(216);+ });++ it('never places a card above the gutter', () => {+ const tops = layoutGutterCards([entry('a', -30)], { gap: 8 });++ expect(tops.get('a')).toBe(0);+ });++ it('keeps the active card level with its run and moves neighbours away', () => {+ const tops = layoutGutterCards(+ [entry('a', 300), entry('b', 320), entry('c', 340), entry('d', 900)],+ { activeId: 'b', gap: 8 },+ );++ expect(tops.get('b')).toBe(320);+ expect(tops.get('a')).toBe(212);+ expect(tops.get('c')).toBe(428);+ expect(tops.get('d')).toBe(900);+ });++ it('pushes the cards above the active one past the top edge when they do not fit', () => {+ const tops = layoutGutterCards([entry('a', 0), entry('b', 20), entry('c', 40)], {+ activeId: 'c',+ gap: 8,+ });++ expect(tops.get('c')).toBe(40);+ expect(tops.get('b')).toBe(-68);+ expect(tops.get('a')).toBe(-176);+ });++ it('keeps the active card level when the cluster above fits exactly', () => {+ const tops = layoutGutterCards([entry('a', 0), entry('b', 108)], { activeId: 'b', gap: 8 });++ expect(tops.get('a')).toBe(0);+ expect(tops.get('b')).toBe(108);+ });++ it('ignores an active id that is not in the gutter', () => {+ const tops = layoutGutterCards([entry('a', 0), entry('b', 20)], { activeId: 'zzz', gap: 8 });++ expect(tops.get('a')).toBe(0);+ expect(tops.get('b')).toBe(108);+ });+});++describe('gutterOverhangBottom', () => {+ const base = { hostBottom: 600, paneContentHeight: 2000, paneViewportHeight: 600 };++ it('is zero while the stack ends within the document', () => {+ expect(gutterOverhangBottom({ ...base, stackBottom: 1900 })).toBe(0);+ expect(gutterOverhangBottom({ ...base, stackBottom: 2000 })).toBe(0);+ });++ it('measures exactly what the stack overhangs', () => {+ expect(gutterOverhangBottom({ ...base, stackBottom: 2250 })).toBe(250);+ });++ it('accounts for a panel that ends above the pane bottom', () => {+ // The panel's clip box ends 40px above the pane's bottom edge.+ expect(gutterOverhangBottom({ ...base, hostBottom: 560, stackBottom: 2000 })).toBe(40);+ });++ it('covers a document too short to scroll at all', () => {+ expect(+ gutterOverhangBottom({+ hostBottom: 600,+ paneContentHeight: 400,+ paneViewportHeight: 600,+ stackBottom: 900,+ }),+ ).toBe(300);+ });++ it('rounds up so a fractional overhang is fully revealed', () => {+ expect(gutterOverhangBottom({ ...base, stackBottom: 2000.25 })).toBe(1);+ });+});++describe('gutterOverhangTop', () => {+ it('is zero when every card sits inside the clip box', () => {+ const tops = new Map([+ ['a', 13],+ ['b', 200],+ ]);+ expect(gutterOverhangTop({ clipTop: 13, tops })).toBe(0);+ expect(gutterOverhangTop({ clipTop: 13, tops: new Map() })).toBe(0);+ });++ it('measures how far the highest card rises above the clip box', () => {+ const tops = new Map([+ ['a', -176],+ ['b', -68],+ ['c', 40],+ ]);+ expect(gutterOverhangTop({ clipTop: 0, tops })).toBe(176);+ expect(gutterOverhangTop({ clipTop: 13, tops: new Map([['a', 5]]) })).toBe(8);+ });++ it('rounds up so a fractional overhang is fully covered', () => {+ expect(gutterOverhangTop({ clipTop: 0, tops: new Map([['a', -0.25]]) })).toBe(1);+ });+});diff --git a/src/features/PageEditor/DocumentComments/Gutter/layout.ts b/src/features/PageEditor/DocumentComments/Gutter/layout.tsnew file mode 100644index 00000000000..22d2c5e8011--- /dev/null+++ b/src/features/PageEditor/DocumentComments/Gutter/layout.ts@@ -0,0 +1,117 @@+export interface GutterLayoutEntry {+ /** Where the card wants to sit: the top of its anchored run, in gutter coordinates. */+ anchorTop: number;+ height: number;+ id: string;+ /** Tie-breaker for cards anchored on the same line: document order. */+ order: number;+}++export interface GutterLayoutOptions {+ /**+ * The card that must sit exactly level with its run. Neighbours yield to it+ * — above it they move up, below it they move down — instead of it being+ * pushed off its line by whatever happens to sit above.+ */+ activeId?: string | null;+ /** Vertical breathing room between stacked cards. */+ gap: number;+}++const byAnchor = (left: GutterLayoutEntry, right: GutterLayoutEntry) =>+ left.anchorTop - right.anchorTop || left.order - right.order;++/**+ * Stack comment cards down a gutter so none overlap.+ *+ * Every card starts level with its anchored run. Walking down the document,+ * a card that would overlap the one above it is pushed down to clear it, so+ * two comments on adjacent lines read as a stack rather than a pile. The+ * active card is the exception: it stays put and the stack is resolved+ * outwards from it, which is what makes "click a run, its card lines up"+ * hold even in a dense cluster. Cards above the active one are pushed up+ * as far as they need to go — past the top of the document if the cluster+ * is taller than the room above the run. `useGutterLayout` then makes that+ * room by extending the document upwards, so those cards stay reachable.+ */+export const layoutGutterCards = (+ entries: readonly GutterLayoutEntry[],+ { activeId, gap }: GutterLayoutOptions,+): Map<string, number> => {+ const sorted = [...entries].sort(byAnchor);+ const tops = sorted.map(({ anchorTop }) => Math.max(0, anchorTop));++ const stackDown = (from: number) => {+ for (let index = from; index < sorted.length; index++) {+ const previous = index - 1;+ if (previous < 0) continue;+ const floor = tops[previous] + sorted[previous].height + gap;+ if (tops[index] < floor) tops[index] = floor;+ }+ };++ const activeIndex = activeId ? sorted.findIndex(({ id }) => id === activeId) : -1;+ if (activeIndex === -1) {+ stackDown(0);+ } else {+ // Above the active card, each neighbour rises just enough to clear the+ // one below it; its own anchor is an upper bound, never a floor.+ for (let index = activeIndex - 1; index >= 0; index--) {+ const ceiling = tops[index + 1] - gap - sorted[index].height;+ if (tops[index] > ceiling) tops[index] = ceiling;+ }+ stackDown(activeIndex + 1);+ }++ return new Map(sorted.map(({ id }, index) => [id, tops[index]]));+};++/**+ * How far the stack rises above the panel's clip box: cards above an active+ * card are pushed up as far as they must go, past the first line if the+ * cluster is taller than the room above the run. The pane cannot scroll+ * there, so the panel lets the reader pull the stack down by this much once+ * the pane is at its top (see `useGutterLayout`). Zero with no cards.+ */+export const gutterOverhangTop = ({+ clipTop,+ tops,+}: {+ /** Top of the panel's clip box, in the same coordinates as the card tops. */+ clipTop: number;+ tops: ReadonlyMap<string, number>;+}): number => {+ let min = Infinity;+ for (const top of tops.values()) min = Math.min(min, top);+ return min === Infinity ? 0 : Math.max(0, Math.ceil(clipTop - min));+};++export interface GutterOverflowInput {+ /** Bottom edge of the panel's clip box, relative to the pane's viewport top. */+ hostBottom: number;+ /** The pane's scrollable content height. */+ paneContentHeight: number;+ /** The pane's viewport height. */+ paneViewportHeight: number;+ /** Bottom edge of the lowest card, in the pane's content coordinates. */+ stackBottom: number;+}++/**+ * How far the stack hangs below what the pane can scroll to.+ *+ * Cards are stacked down from their runs, so a dense cluster near the end of+ * the document can extend below the last line of text, past the end of the+ * pane's scroll range. The panel lets the reader pull the stack up by this+ * much once the pane is at its end (see `useGutterLayout`).+ */+export const gutterOverhangBottom = ({+ hostBottom,+ paneContentHeight,+ paneViewportHeight,+ stackBottom,+}: GutterOverflowInput): number => {+ const maxScroll = Math.max(0, paneContentHeight - paneViewportHeight);+ const reachable = maxScroll + hostBottom;+ return Math.max(0, Math.ceil(stackBottom - reachable));+};diff --git a/src/features/PageEditor/DocumentComments/Gutter/useForwardWheel.test.ts b/src/features/PageEditor/DocumentComments/Gutter/useForwardWheel.test.tsnew file mode 100644index 00000000000..fd3acdc8817--- /dev/null+++ b/src/features/PageEditor/DocumentComments/Gutter/useForwardWheel.test.ts@@ -0,0 +1,245 @@+import { renderHook } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { useForwardWheel } from './useForwardWheel';++const setup = () => {+ const host = document.createElement('div');+ const pane = document.createElement('div');+ document.body.append(host, pane);+ Object.defineProperty(host, 'clientHeight', { configurable: true, value: 600 });+ pane.scrollTop = 100;+ renderHook(() =>+ useForwardWheel({ current: host }, (delta) => {+ pane.scrollTop += delta;+ }),+ );+ return { host, pane };+};++const wheel = (target: Element, init: WheelEventInit) => {+ const event = new WheelEvent('wheel', { bubbles: true, cancelable: true, ...init });+ // happy-dom's WheelEvent constructor doesn't forward ctrlKey from its init+ // dict (unlike plain MouseEvent), so set it directly when a test needs it.+ if (init.ctrlKey) Object.defineProperty(event, 'ctrlKey', { value: true });+ target.dispatchEvent(event);+ return event;+};++describe('useForwardWheel', () => {+ it('hands the wheel delta to the sink and consumes the event', () => {+ const { host, pane } = setup();++ const event = wheel(host, { deltaY: 40 });++ expect(pane.scrollTop).toBe(140);+ expect(event.defaultPrevented).toBe(true);+ });++ it('scales line-based deltas into pixels', () => {+ const { host, pane } = setup();++ wheel(host, { deltaMode: WheelEvent.DOM_DELTA_LINE, deltaY: 3 });++ expect(pane.scrollTop).toBeGreaterThan(100 + 3);+ });++ it('leaves a scrollable element inside the panel to scroll itself', () => {+ const { host, pane } = setup();+ const inner = document.createElement('div');+ inner.style.overflowY = 'auto';+ Object.defineProperty(inner, 'clientHeight', { configurable: true, value: 100 });+ Object.defineProperty(inner, 'scrollHeight', { configurable: true, value: 500 });+ host.append(inner);++ const event = wheel(inner, { deltaY: 40 });++ expect(pane.scrollTop).toBe(100);+ expect(event.defaultPrevented).toBe(false);+ });++ it('forwards once an inner scroller has reached its end', () => {+ const { host, pane } = setup();+ const inner = document.createElement('div');+ inner.style.overflowY = 'auto';+ Object.defineProperty(inner, 'clientHeight', { configurable: true, value: 100 });+ Object.defineProperty(inner, 'scrollHeight', { configurable: true, value: 500 });+ inner.scrollTop = 400;+ host.append(inner);++ wheel(inner, { deltaY: 40 });++ expect(pane.scrollTop).toBe(140);+ });++ it('ignores purely horizontal gestures', () => {+ const { host, pane } = setup();++ const event = wheel(host, { deltaX: 40, deltaY: 0 });++ expect(pane.scrollTop).toBe(100);+ expect(event.defaultPrevented).toBe(false);+ });++ it('leaves a ctrl-modified wheel (browser zoom / trackpad pinch) to the browser', () => {+ const { host, pane } = setup();++ const event = wheel(host, { ctrlKey: true, deltaY: 40 });++ expect(pane.scrollTop).toBe(100);+ expect(event.defaultPrevented).toBe(false);+ });++ describe('touch', () => {+ const touch = (+ target: Element,+ type: 'touchend' | 'touchmove' | 'touchstart',+ clientY?: number,+ ) => {+ const event = new TouchEvent(type, {+ bubbles: true,+ cancelable: true,+ touches: clientY === undefined ? [] : ([{ clientY }] as unknown as Touch[]),+ });+ target.dispatchEvent(event);+ return event;+ };++ it('scrolls by the distance a one-finger drag crosses', () => {+ const { host, pane } = setup();++ touch(host, 'touchstart', 300);+ const event = touch(host, 'touchmove', 260);++ expect(pane.scrollTop).toBe(140);+ expect(event.defaultPrevented).toBe(true);+ });++ it('tracks a drag across several moves instead of only the first one', () => {+ const { host, pane } = setup();++ touch(host, 'touchstart', 300);+ touch(host, 'touchmove', 260);+ touch(host, 'touchmove', 240);++ expect(pane.scrollTop).toBe(160);+ });++ it('leaves a scrollable element inside the panel to scroll itself', () => {+ const { host, pane } = setup();+ const inner = document.createElement('div');+ inner.style.overflowY = 'auto';+ Object.defineProperty(inner, 'clientHeight', { configurable: true, value: 100 });+ Object.defineProperty(inner, 'scrollHeight', { configurable: true, value: 500 });+ host.append(inner);++ touch(inner, 'touchstart', 300);+ const event = touch(inner, 'touchmove', 260);++ expect(pane.scrollTop).toBe(100);+ expect(event.defaultPrevented).toBe(false);+ });++ it('starts a fresh drag after the finger lifts', () => {+ const { host, pane } = setup();++ touch(host, 'touchstart', 300);+ touch(host, 'touchend');+ touch(host, 'touchmove', 260);++ expect(pane.scrollTop).toBe(100);+ });+ });++ describe('keyboard', () => {+ const key = (target: Element, init: KeyboardEventInit) => {+ const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init });+ target.dispatchEvent(event);+ return event;+ };++ it('pages the document down on PageDown', () => {+ const { host, pane } = setup();++ const event = key(host, { key: 'PageDown' });++ expect(pane.scrollTop).toBe(700);+ expect(event.defaultPrevented).toBe(true);+ });++ it('pages the document up on PageUp', () => {+ const { host, pane } = setup();++ key(host, { key: 'PageUp' });++ expect(pane.scrollTop).toBe(-500);+ });++ it('pages down on Space and up on Shift+Space', () => {+ const { host, pane } = setup();++ key(host, { key: ' ' });+ expect(pane.scrollTop).toBe(700);++ key(host, { key: ' ', shiftKey: true });+ expect(pane.scrollTop).toBe(100);+ });++ it('leaves Space to a focused button instead of paging the document', () => {+ const { host, pane } = setup();+ const button = document.createElement('button');+ host.append(button);++ const event = key(button, { key: ' ' });++ expect(pane.scrollTop).toBe(100);+ expect(event.defaultPrevented).toBe(false);+ });++ it('still pages the document on PageDown/PageUp from a focused button or link', () => {+ const { host, pane } = setup();+ const button = document.createElement('button');+ const link = document.createElement('a');+ host.append(button, link);++ const down = key(button, { key: 'PageDown' });+ expect(pane.scrollTop).toBe(700);+ expect(down.defaultPrevented).toBe(true);++ const up = key(link, { key: 'PageUp' });+ expect(pane.scrollTop).toBe(100);+ expect(up.defaultPrevented).toBe(true);+ });++ it('leaves PageDown to a focused text field, where it moves the caret', () => {+ const { host, pane } = setup();+ const textarea = document.createElement('textarea');+ host.append(textarea);++ const event = key(textarea, { key: 'PageDown' });++ expect(pane.scrollTop).toBe(100);+ expect(event.defaultPrevented).toBe(false);+ });++ it('leaves Space to a focused text field instead of paging the document', () => {+ const { host, pane } = setup();+ const input = document.createElement('input');+ host.append(input);++ const event = key(input, { key: ' ' });++ expect(pane.scrollTop).toBe(100);+ expect(event.defaultPrevented).toBe(false);+ });++ it('ignores unrelated keys', () => {+ const { host, pane } = setup();++ const event = key(host, { key: 'ArrowDown' });++ expect(pane.scrollTop).toBe(100);+ expect(event.defaultPrevented).toBe(false);+ });+ });+});diff --git a/src/features/PageEditor/DocumentComments/Gutter/useForwardWheel.ts b/src/features/PageEditor/DocumentComments/Gutter/useForwardWheel.tsnew file mode 100644index 00000000000..1948e534808--- /dev/null+++ b/src/features/PageEditor/DocumentComments/Gutter/useForwardWheel.ts@@ -0,0 +1,142 @@+'use client';++import type { RefObject } from 'react';+import { useEffect } from 'react';++/** Pixels per line for `DOM_DELTA_LINE` wheels (Firefox with a mouse wheel). */+const LINE_HEIGHT = 16;++const deltaToPixels = (event: WheelEvent, host: HTMLElement) => {+ switch (event.deltaMode) {+ case WheelEvent.DOM_DELTA_LINE: {+ return event.deltaY * LINE_HEIGHT;+ }+ case WheelEvent.DOM_DELTA_PAGE: {+ return event.deltaY * host.clientHeight;+ }+ default: {+ return event.deltaY;+ }+ }+};++/** Whether an element between the event target and the host can still scroll in this direction. */+const innerScrollerTakesIt = (target: EventTarget | null, host: HTMLElement, deltaY: number) => {+ let node = target instanceof Element ? target : null;+ while (node && node !== host) {+ const { overflowY } = getComputedStyle(node);+ const scrolls = overflowY === 'auto' || overflowY === 'scroll';+ if (scrolls && node.scrollHeight > node.clientHeight) {+ const atEnd =+ deltaY > 0+ ? node.scrollTop + node.clientHeight >= node.scrollHeight - 1+ : node.scrollTop <= 0;+ if (!atEnd) return true;+ }+ node = node.parentElement;+ }+ return false;+};++const EDITABLE_TAGS = new Set(['INPUT', 'SELECT', 'TEXTAREA']);+const CONTROL_TAGS = new Set(['A', 'BUTTON']);++/**+ * Whether the focused target owns this key itself, so paging the document+ * instead would take it away from the control the reader is actually using.+ * Ownership is per key: a field or editable region owns everything typed+ * into it, including PageUp/PageDown, which move its own caret. A button or+ * link owns Space (its activation) and nothing else — PageUp/PageDown on a+ * focused card action have no meaning to the control and cannot page the+ * sibling document pane by default, so they are still forwarded.+ */+export const isKeyOwnedByTarget = (+ key: string,+ target: EventTarget | null,+ host: HTMLElement,+): boolean => {+ let node = target instanceof HTMLElement ? target : null;+ while (node && node !== host) {+ if (node.isContentEditable || EDITABLE_TAGS.has(node.tagName)) return true;+ if (key === ' ' && (CONTROL_TAGS.has(node.tagName) || node.hasAttribute('role'))) return true;+ node = node.parentElement;+ }+ return false;+};++/**+ * The comments panel is not a scroll container — its cards ride along with+ * the document (see `useGutterLayout`). A wheel, touch drag, or PageDown/+ * Space over the panel would therefore do nothing, which reads as a stuck+ * column; hand the gesture's distance to `scrollBy` instead, which scrolls+ * the document and, past its ends, the panel's own overhang.+ *+ * Bound natively rather than through React so the events can be cancelled:+ * React registers wheel and touch listeners as passive.+ */+export const useForwardWheel = (+ hostRef: RefObject<HTMLElement | null>,+ scrollBy: (deltaPixels: number) => void,+) => {+ useEffect(() => {+ const host = hostRef.current;+ if (!host) return;++ const handleWheel = (event: WheelEvent) => {+ // Ctrl+wheel is the browser's zoom gesture (and how a trackpad pinch is+ // reported); hijacking it into a document scroll would block zooming+ // whenever the pointer happens to be over the panel.+ if (event.deltaY === 0 || event.defaultPrevented || event.ctrlKey) return;+ if (innerScrollerTakesIt(event.target, host, event.deltaY)) return;+ event.preventDefault();+ scrollBy(deltaToPixels(event, host));+ };++ // A one-finger drag is the touch equivalent of a wheel: the delta is the+ // distance the finger crossed since the last move, in the direction+ // content should follow it (finger moves up, content scrolls down).+ let touchY: number | undefined;+ const handleTouchStart = (event: TouchEvent) => {+ touchY = event.touches.length === 1 ? event.touches[0].clientY : undefined;+ };+ const handleTouchMove = (event: TouchEvent) => {+ if (touchY === undefined || event.touches.length !== 1) return;+ const y = event.touches[0].clientY;+ const delta = touchY - y;+ touchY = y;+ if (delta === 0 || innerScrollerTakesIt(event.target, host, delta)) return;+ event.preventDefault();+ scrollBy(delta);+ };+ const handleTouchEnd = () => {+ touchY = undefined;+ };++ // Space and PageUp/PageDown are how a reader without a pointer pages a+ // scroll region once focus lands inside it; skip a key the target already+ // owns itself (a button's Space activation, anything typed into a field).+ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.defaultPrevented || isKeyOwnedByTarget(event.key, event.target, host)) return;+ let direction: -1 | 1 | undefined;+ if (event.key === 'PageDown') direction = 1;+ else if (event.key === 'PageUp') direction = -1;+ else if (event.key === ' ') direction = event.shiftKey ? -1 : 1;+ if (!direction) return;+ event.preventDefault();+ scrollBy(direction * host.clientHeight);+ };++ host.addEventListener('wheel', handleWheel, { passive: false });+ host.addEventListener('touchstart', handleTouchStart, { passive: true });+ host.addEventListener('touchmove', handleTouchMove, { passive: false });+ host.addEventListener('touchend', handleTouchEnd, { passive: true });+ host.addEventListener('keydown', handleKeyDown);+ return () => {+ host.removeEventListener('wheel', handleWheel);+ host.removeEventListener('touchstart', handleTouchStart);+ host.removeEventListener('touchmove', handleTouchMove);+ host.removeEventListener('touchend', handleTouchEnd);+ host.removeEventListener('keydown', handleKeyDown);+ };+ }, [hostRef, scrollBy]);+};diff --git a/src/features/PageEditor/DocumentComments/Gutter/useGutterLayout.test.ts b/src/features/PageEditor/DocumentComments/Gutter/useGutterLayout.test.tsnew file mode 100644index 00000000000..93aeeefa0c1--- /dev/null+++ b/src/features/PageEditor/DocumentComments/Gutter/useGutterLayout.test.ts@@ -0,0 +1,177 @@+import { act, renderHook } from '@testing-library/react';+import type { ReactNode } from 'react';+import { createElement } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { DocumentCommentAnchorsProvider } from '../anchor/context';+import type { DocumentCommentAnchorsValue } from '../anchor/useDocumentCommentAnchors';+import { PENDING_CARD_ID, useGutterLayout } from './useGutterLayout';++/** Frames are held until `flush`, the way a background tab never gets one. */+const fakeFrames = () => {+ const queue = new Map<number, FrameRequestCallback>();+ let next = 1;+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ const id = next++;+ queue.set(id, callback);+ return id;+ });+ vi.stubGlobal('cancelAnimationFrame', (id: number) => queue.delete(id));+ return {+ flush: () => {+ const pending = [...queue.values()];+ queue.clear();+ for (const callback of pending) callback(performance.now());+ },+ get size() {+ return queue.size;+ },+ };+};++const rangeAt = (top: number) =>+ ({+ getBoundingClientRect: () => ({ top }) as DOMRect,+ getClientRects: () => [] as unknown as DOMRectList,+ }) as unknown as Range;++const anchors = (+ overrides: Partial<DocumentCommentAnchorsValue> = {},+): DocumentCommentAnchorsValue => ({+ activeRootId: null,+ bodyElement: null,+ getAnchorMatch: () => null,+ getAnchorRange: () => rangeAt(120),+ getPendingAnchorMatch: () => null,+ getPendingAnchorRange: () => null,+ locateInBody: () => {},+ orphanedRootIds: new Set(),+ pickTick: 0,+ resolvedAt: 1,+ selectedRootId: null,+ selectRoot: () => {},+ setHoveredRootId: () => {},+ ...overrides,+});++describe('useGutterLayout', () => {+ beforeEach(() => {+ vi.stubGlobal('ResizeObserver', undefined);+ });+ afterEach(() => vi.unstubAllGlobals());++ it('still measures after the anchors change while a frame is held back', () => {+ const frames = fakeFrames();+ const pane = document.createElement('div');+ pane.getBoundingClientRect = () => ({ top: 0 }) as DOMRect;+ const track = document.createElement('div');+ const host = document.createElement('div');+ host.append(track);+ document.body.append(pane, host);+ const card = document.createElement('div');+ Object.defineProperty(card, 'offsetHeight', { value: 100 });++ let value = anchors();+ const { rerender, result } = renderHook(+ () =>+ useGutterLayout({+ activeId: null,+ hasPending: false,+ ids: ['a'],+ paneRef: { current: pane },+ trackRef: { current: track },+ }),+ {+ wrapper: ({ children }: { children: ReactNode }) =>+ createElement(DocumentCommentAnchorsProvider, { children, value }),+ },+ );+ act(() => result.current.registerCard('a')(card));+ expect(frames.size).toBeGreaterThan(0);++ // The frame never fires (hidden tab); meanwhile the anchors are re-resolved+ // with fresh callbacks, which rebuilds the scheduler.+ value = anchors();+ rerender();+ act(() => frames.flush());++ expect(result.current.tops.get('a')).toBe(120);+ });++ it('docks an orphaned pending draft at the pane top instead of leaving it unmeasured', () => {+ const frames = fakeFrames();+ const pane = document.createElement('div');+ pane.getBoundingClientRect = () => ({ top: 0 }) as DOMRect;+ Object.defineProperty(pane, 'scrollTop', { value: 40 });+ const track = document.createElement('div');+ const host = document.createElement('div');+ host.append(track);+ document.body.append(pane, host);+ const card = document.createElement('div');+ Object.defineProperty(card, 'offsetHeight', { value: 80 });++ // The draft's quote no longer resolves — e.g. the text was edited away.+ const value = anchors({ getPendingAnchorRange: () => null });+ const { result } = renderHook(+ () =>+ useGutterLayout({+ activeId: null,+ hasPending: true,+ ids: [],+ paneRef: { current: pane },+ trackRef: { current: track },+ }),+ {+ wrapper: ({ children }: { children: ReactNode }) =>+ createElement(DocumentCommentAnchorsProvider, { children, value }),+ },+ );+ act(() => result.current.registerCard(PENDING_CARD_ID)(card));+ act(() => frames.flush());++ expect(result.current.tops.get(PENDING_CARD_ID)).toBe(40);+ });++ it('keeps an earlier-in-text comment above a pending draft anchored later on the same line', () => {+ // Both runs sit on the same line (same measured top), so only the text+ // order — not vertical position — can tell them apart.+ const frames = fakeFrames();+ const pane = document.createElement('div');+ pane.getBoundingClientRect = () => ({ top: 0 }) as DOMRect;+ const track = document.createElement('div');+ const host = document.createElement('div');+ host.append(track);+ document.body.append(pane, host);+ const existingCard = document.createElement('div');+ Object.defineProperty(existingCard, 'offsetHeight', { value: 50 });+ const pendingCard = document.createElement('div');+ Object.defineProperty(pendingCard, 'offsetHeight', { value: 50 });++ const value = anchors({+ getAnchorMatch: () => ({ end: 9, start: 5 }),+ getAnchorRange: () => rangeAt(100),+ getPendingAnchorMatch: () => ({ end: 25, start: 20 }),+ getPendingAnchorRange: () => rangeAt(100),+ });+ const { result } = renderHook(+ () =>+ useGutterLayout({+ activeId: null,+ hasPending: true,+ ids: ['a'],+ paneRef: { current: pane },+ trackRef: { current: track },+ }),+ {+ wrapper: ({ children }: { children: ReactNode }) =>+ createElement(DocumentCommentAnchorsProvider, { children, value }),+ },+ );+ act(() => result.current.registerCard('a')(existingCard));+ act(() => result.current.registerCard(PENDING_CARD_ID)(pendingCard));+ act(() => frames.flush());++ expect(result.current.tops.get('a')).toBe(100);+ expect(result.current.tops.get(PENDING_CARD_ID)).toBe(158);+ });+});diff --git a/src/features/PageEditor/DocumentComments/Gutter/useGutterLayout.ts b/src/features/PageEditor/DocumentComments/Gutter/useGutterLayout.tsnew file mode 100644index 00000000000..ae811aa65c4--- /dev/null+++ b/src/features/PageEditor/DocumentComments/Gutter/useGutterLayout.ts@@ -0,0 +1,375 @@+'use client';++import type { RefObject } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';++import { useSingleton } from '@/hooks/useSingleton';++import { useCommentAnchors } from '../anchor/context';+import { GUTTER_CARD_GAP } from './constants';+import type { GutterLayoutEntry } from './layout';+import { gutterOverhangBottom, gutterOverhangTop, layoutGutterCards } from './layout';++/** Card id of the composer for the selection being commented on. */+export const PENDING_CARD_ID = 'pending';++/**+ * Marks the column the body sits in (title, meta bar, body). Its box is+ * watched alongside the body's: the title wrapping onto a second line moves+ * every run down without changing the body's own size.+ */+export const GUTTER_COLUMN_ATTRIBUTE = 'data-document-comment-column';++/**+ * The column animates its width when the pane is resized (see+ * `WideScreenContainer`), so the measurement taken on the resize event itself+ * sees the text mid-reflow. One more pass after the animation settles.+ */+const RESIZE_SETTLE_DELAY = 400;++const EMPTY_TOPS: ReadonlyMap<string, number> = new Map();++const sameTops = (left: ReadonlyMap<string, number>, right: ReadonlyMap<string, number>) => {+ if (left.size !== right.size) return false;+ for (const [id, top] of left) {+ if (right.get(id) !== top) return false;+ }+ return true;+};++/** The top of a run's first line, not of its bounding box — a run that wraps starts on its first line. */+const rangeTop = (range: Range) => {+ const rects = range.getClientRects();+ return (rects.length > 0 ? rects[0] : range.getBoundingClientRect()).top;+};++interface GutterLayoutParams {+ /** The card kept level with its run; see `layoutGutterCards`. */+ activeId: string | null;+ /** Whether the composer card for the pending selection is mounted. */+ hasPending: boolean;+ /** Root ids of the threads mounted in the panel, in any order. */+ ids: readonly string[];+ /** The body's scroll container; card positions are expressed in its content coordinates. */+ paneRef: RefObject<HTMLElement | null>;+ /** The element the cards are absolutely positioned in; it is translated to follow the pane's scroll. */+ trackRef: RefObject<HTMLElement | null>;+}++/**+ * Measure where every card's run sits and stack the cards to match.+ *+ * Positions are document coordinates — a run's viewport top plus the pane's+ * scroll offset — so they hold while the pane scrolls. The track holding the+ * cards is translated to mirror that scroll on every frame it changes, which+ * is a style write, never a re-measure. Only things that move text — an+ * edit, a reflow, a resize — or change a card's height trigger a re-measure.+ */+export const useGutterLayout = ({+ activeId,+ hasPending,+ ids,+ paneRef,+ trackRef,+}: GutterLayoutParams) => {+ const {+ bodyElement,+ getAnchorMatch,+ getAnchorRange,+ getPendingAnchorMatch,+ getPendingAnchorRange,+ resolvedAt,+ } = useCommentAnchors();+ const [tops, setTops] = useState<ReadonlyMap<string, number>>(EMPTY_TOPS);+ const topsRef = useRef(tops);+ const elements = useSingleton(() => new Map<string, HTMLElement>());+ const observerRef = useRef<ResizeObserver | null>(null);+ const frameRef = useRef<number | undefined>(undefined);+ const scrollFrameRef = useRef<number | undefined>(undefined);+ /**+ * How far the stack hangs past each end of the pane's scroll range, in+ * pixels: cards above an active card near the first line are pushed up+ * past it, and a dense cluster near the last line stacks down past it.+ */+ const overhangRef = useRef({ bottom: 0, top: 0 });+ /**+ * The panel's own scroll past the pane's ends. The pane cannot scroll to+ * where the overhang sits and the document must not grow to make room, so+ * once the pane is at an end a wheel over the panel moves the track alone:+ * positive pulls the stack down to reveal cards above the first line,+ * negative pulls it up to reveal cards below the last.+ */+ const overscrollRef = useRef(0);+ const idsRef = useRef(ids);+ idsRef.current = ids;+ const hasPendingRef = useRef(hasPending);+ hasPendingRef.current = hasPending;+ const activeIdRef = useRef(activeId);+ activeIdRef.current = activeId;++ /**+ * The overscroll a scroll position can use: the overhang at that end less+ * the distance the pane still has to reach it. As the reader scrolls the+ * document away from the end, the pull eases off and the cards settle back+ * beside their runs.+ */+ const clampOverscroll = useCallback((pane: HTMLElement, value: number) => {+ const { bottom, top } = overhangRef.current;+ const maxScroll = Math.max(0, pane.scrollHeight - pane.clientHeight);+ const upper = Math.max(0, top - pane.scrollTop);+ const lower = -Math.max(0, bottom - (maxScroll - pane.scrollTop));+ return Math.min(upper, Math.max(lower, value));+ }, []);++ // The track's parent clips it, so the translate is relative to that parent:+ // where the pane's content top sits in the panel's own coordinate space,+ // plus whatever the reader has pulled the stack past the pane's end.+ const syncTrack = useCallback(() => {+ scrollFrameRef.current = undefined;+ const pane = paneRef.current;+ const track = trackRef.current;+ const host = track?.parentElement;+ if (!pane || !track || !host) return;+ overscrollRef.current = clampOverscroll(pane, overscrollRef.current);+ const offset =+ pane.getBoundingClientRect().top -+ host.getBoundingClientRect().top -+ pane.scrollTop ++ overscrollRef.current;+ track.style.transform = `translateY(${Math.round(offset)}px)`;+ }, [clampOverscroll, paneRef, trackRef]);++ /**+ * Scroll the document by a wheel over the panel. The pane takes the+ * distance while it can; what it cannot take at either end goes into the+ * panel's own overscroll, up to the overhang there. Any overscroll in the+ * opposite direction is unwound first, so the stack always returns to its+ * runs before the document moves.+ */+ const scrollBy = useCallback(+ (delta: number) => {+ const pane = paneRef.current;+ if (!pane || delta === 0) return;+ const maxScroll = Math.max(0, pane.scrollHeight - pane.clientHeight);+ let over = clampOverscroll(pane, overscrollRef.current);+ let remaining = delta;+ if (remaining > 0) {+ if (over > 0) {+ const unwind = Math.min(over, remaining);+ over -= unwind;+ remaining -= unwind;+ }+ if (remaining > 0) {+ const room = Math.max(0, maxScroll - pane.scrollTop);+ const take = Math.min(room, remaining);+ if (take > 0) pane.scrollTop += take;+ remaining -= take;+ }+ if (remaining > 0) over = clampOverscroll(pane, over - remaining);+ } else {+ let upward = -remaining;+ if (over < 0) {+ const unwind = Math.min(-over, upward);+ over += unwind;+ upward -= unwind;+ }+ if (upward > 0) {+ const take = Math.min(pane.scrollTop, upward);+ if (take > 0) pane.scrollTop -= take;+ upward -= take;+ }+ if (upward > 0) over = clampOverscroll(pane, over + upward);+ }+ overscrollRef.current = over;+ syncTrack();+ },+ [clampOverscroll, paneRef, syncTrack],+ );++ const scheduleSync = useCallback(() => {+ if (scrollFrameRef.current !== undefined || typeof window === 'undefined') return;+ scrollFrameRef.current = window.requestAnimationFrame(syncTrack);+ }, [syncTrack]);++ const measure = useCallback(() => {+ frameRef.current = undefined;+ const pane = paneRef.current;+ if (!pane) return;+ const host = trackRef.current?.parentElement;++ const layout = () => {+ const paneTop = pane.getBoundingClientRect().top;+ const contentTop = paneTop - pane.scrollTop;+ const entries: GutterLayoutEntry[] = [];++ const push = (id: string, range: Range | null, order: number) => {+ const element = elements.get(id);+ if (!range || !element) return;+ entries.push({+ anchorTop: rangeTop(range) - contentTop,+ height: element.offsetHeight,+ id,+ order,+ });+ };++ for (const id of idsRef.current) {+ push(id, getAnchorRange(id), getAnchorMatch(id)?.start ?? 0);+ }+ if (hasPendingRef.current) {+ const pendingRange = getPendingAnchorRange();+ if (pendingRange) {+ // A hardcoded 0 here would sort the pending card before every real+ // comment whose run starts later on the same line, regardless of+ // where its own run actually sits in the text.+ push(PENDING_CARD_ID, pendingRange, getPendingAnchorMatch()?.start ?? 0);+ } else {+ // An orphaned draft (its quote no longer resolves — edited or+ // removed, e.g. by a collaborator) has no run to sit beside; dock it+ // at the pane's current top instead of leaving it unmeasured and+ // permanently `visibility: hidden`, with no way to read or act on it.+ const element = elements.get(PENDING_CARD_ID);+ if (element) {+ entries.push({+ anchorTop: pane.scrollTop,+ height: element.offsetHeight,+ id: PENDING_CARD_ID,+ order: 0,+ });+ }+ }+ }++ const tops = layoutGutterCards(entries, {+ activeId: activeIdRef.current,+ gap: GUTTER_CARD_GAP,+ });+ // The clip box may start below the pane's top (the panel has its own+ // header), so a card at the pane's very top would be partly covered.+ const clipTop = host ? host.getBoundingClientRect().top - paneTop : 0;+ let stackBottom = 0;+ for (const { height, id } of entries) {+ stackBottom = Math.max(stackBottom, (tops.get(id) ?? 0) + height);+ }+ return { clipTop, stackBottom, tops };+ };++ const result = layout();+ overhangRef.current = {+ bottom: host+ ? gutterOverhangBottom({+ hostBottom: host.getBoundingClientRect().bottom - pane.getBoundingClientRect().top,+ paneContentHeight: pane.scrollHeight,+ paneViewportHeight: pane.clientHeight,+ stackBottom: result.stackBottom,+ })+ : 0,+ top: gutterOverhangTop({ clipTop: result.clipTop, tops: result.tops }),+ };+ syncTrack();+ if (sameTops(topsRef.current, result.tops)) return;+ topsRef.current = result.tops;+ setTops(result.tops);+ }, [+ elements,+ getAnchorMatch,+ getAnchorRange,+ getPendingAnchorMatch,+ getPendingAnchorRange,+ paneRef,+ syncTrack,+ trackRef,+ ]);++ const schedule = useCallback(() => {+ if (frameRef.current !== undefined || typeof window === 'undefined') return;+ frameRef.current = window.requestAnimationFrame(measure);+ }, [measure]);++ // A card's height is part of the stack, so every card is watched for size+ // changes (replies loading, an edit box opening, an image finishing).+ const registerCard = useCallback(+ (id: string) => (element: HTMLElement | null) => {+ const previous = elements.get(id);+ if (previous === element) return;+ if (previous) observerRef.current?.unobserve(previous);+ if (element) {+ elements.set(id, element);+ if (!observerRef.current && typeof ResizeObserver !== 'undefined') {+ observerRef.current = new ResizeObserver(schedule);+ }+ observerRef.current?.observe(element);+ } else {+ elements.delete(id);+ }+ schedule();+ },+ [elements, schedule],+ );++ const idsSignature = ids.join(' ');+ useEffect(() => {+ schedule();+ }, [activeId, hasPending, idsSignature, resolvedAt, schedule]);++ // Text reflows without its content changing — an image finishes loading,+ // the pane is resized, a font swaps in — so the body's box is watched, and+ // the column around it for anything above the body that changes height.+ useEffect(() => {+ if (!bodyElement || typeof ResizeObserver === 'undefined') return;+ const observer = new ResizeObserver(schedule);+ observer.observe(bodyElement);+ const column = bodyElement.closest(`[${GUTTER_COLUMN_ATTRIBUTE}]`);+ if (column) observer.observe(column);+ return () => observer.disconnect();+ }, [bodyElement, schedule]);++ // Scrolling only moves the track. The panel itself can move or resize (it+ // is draggable), which its own ResizeObserver covers.+ useEffect(() => {+ const pane = paneRef.current;+ const host = trackRef.current?.parentElement;+ if (!pane) return;+ pane.addEventListener('scroll', scheduleSync, { passive: true });+ const observer =+ host && typeof ResizeObserver !== 'undefined' ? new ResizeObserver(schedule) : null;+ if (host) observer?.observe(host);+ scheduleSync();+ return () => {+ pane.removeEventListener('scroll', scheduleSync);+ observer?.disconnect();+ };+ }, [paneRef, schedule, scheduleSync, trackRef]);++ useEffect(() => {+ let settle: ReturnType<typeof setTimeout> | undefined;+ const handleResize = () => {+ schedule();+ if (settle !== undefined) clearTimeout(settle);+ settle = setTimeout(schedule, RESIZE_SETTLE_DELAY);+ };+ window.addEventListener('resize', handleResize);+ return () => {+ window.removeEventListener('resize', handleResize);+ if (settle !== undefined) clearTimeout(settle);+ // A frame that is still pending here (the tab was in the background,+ // so no frame was ever painted) is cancelled together with the+ // scheduler that requested it. The slot has to be released too: the+ // next scheduler only requests a frame when none is pending, and a+ // cancelled id left behind would read as one — no card would ever be+ // measured again.+ if (frameRef.current !== undefined) {+ window.cancelAnimationFrame(frameRef.current);+ frameRef.current = undefined;+ }+ if (scrollFrameRef.current !== undefined) {+ window.cancelAnimationFrame(scrollFrameRef.current);+ scrollFrameRef.current = undefined;+ }+ observerRef.current?.disconnect();+ observerRef.current = null;+ };+ }, [schedule]);++ return useMemo(() => ({ registerCard, scrollBy, tops }), [registerCard, scrollBy, tops]);+};diff --git a/src/features/PageEditor/DocumentComments/Thread.tsx b/src/features/PageEditor/DocumentComments/Thread.tsxindex 6fcfbc883b7..d5cbbe4f091 100644--- a/src/features/PageEditor/DocumentComments/Thread.tsx+++ b/src/features/PageEditor/DocumentComments/Thread.tsx@@ -1,11 +1,11 @@import type { DocumentCommentItem, DocumentCommentThread } from '@lobechat/types';import { Center, Flexbox } from '@lobehub/ui';-import { Button } from '@lobehub/ui/base-ui';+import { Button, Skeleton } from '@lobehub/ui/base-ui';+import { cx } from 'antd-style';import { Fragment, memo, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';-import SurfaceSkeleton from '@/components/Skeleton/Surface';import { documentCommentService } from '@/services/documentComment';import CommentCard from './CommentCard';@@ -31,6 +31,8 @@ import type {} from './useDocumentCommentDeepLink';interface ThreadProps extends DocumentCommentThread {+ /** Narrow-column layout for a thread in the gutter. */+ compact?: boolean;documentId: string;/** Deep-link target inside this thread; forces replies to load and highlights the card. */focus?: DocumentCommentFocus;@@ -42,8 +44,33 @@ interface ThreadProps extends DocumentCommentThread {onSummaryChange: (delta: number) => void | Promise<unknown>;}+/** At most this many placeholder rows while a thread's replies load. */+const REPLY_SKELETON_MAX = 3;++/**+ * Placeholder rows shaped like the replies they stand in for — one per+ * expected reply, capped — rather than a generic five-card list that towers+ * over a thread with a single answer.+ */+const ReplySkeleton = memo<{ compact: boolean; count: number }>(({ compact, count }) => (+ <Flexbox gap={compact ? 12 : 16} paddingBlock={compact ? 4 : 8}>+ {Array.from({ length: Math.min(Math.max(count, 1), REPLY_SKELETON_MAX) }).map((_, index) => (+ <Flexbox gap={8} key={index}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Skeleton height={28} radius={14} width={28} />+ <Skeleton height={14} width={96 + (index % 2) * 24} />+ </Flexbox>+ <Skeleton height={14} width={`${48 + (index % 3) * 14}%`} />+ </Flexbox>+ ))}+ </Flexbox>+));++ReplySkeleton.displayName = 'DocumentCommentReplySkeleton';+const Thread = memo<ThreadProps>(({+ compact = false,documentId,focus,onFocusMissing,@@ -58,10 +85,17 @@ const Thread = memo<ThreadProps>(const [replyTargetId, setReplyTargetId] = useState<string | null>(null);const { containerRef, shouldLoad } = useAutoLoadReplies(replyCount > 0);const focusedReplyId = focus && focus.commentId !== root.id ? focus.commentId : undefined;- const replies = useDocumentCommentReplies(- root.id,- shouldLoad || Boolean(replyTargetId) || Boolean(focusedReplyId),- );+ // Once the replies have been asked for they stay subscribed. Closing the+ // reply box after sending would otherwise drop the key for a render or+ // two (until the auto-load observer catches up), which empties the list,+ // discards the optimistic reply on screen, and brings the skeleton back+ // while the server page is refetched.+ const wantsReplies = shouldLoad || Boolean(replyTargetId) || Boolean(focusedReplyId);+ const [repliesLatched, setRepliesLatched] = useState(wantsReplies);+ useEffect(() => {+ if (wantsReplies) setRepliesLatched(true);+ }, [wantsReplies]);+ const replies = useDocumentCommentReplies(root.id, wantsReplies || repliesLatched);const createOptimistic = useOptimisticDocumentComment();const mutateReplies = replies.mutate;const reloadReplies = replies.reload;@@ -232,9 +266,11 @@ const Thread = memo<ThreadProps>(<Fragment key={reply.id}><CommentCardcomment={reply}+ compact={compact}focusScroll={focus?.scroll}focusToken={focusedReplyId === reply.id ? focus?.token : undefined}replying={replyTargetId === reply.id}+ threadAuthor={root.author}variant={'reply'}onMutated={refreshThread}onReply={() => toggleReplyTarget(reply.id)}@@ -245,6 +281,8 @@ const Thread = memo<ThreadProps>(documentId={documentId}key={`reply:${reply.id}`}parentCommentId={reply.id}+ plain={compact}+ onCancel={() => setReplyTargetId(null)}onSubmit={handleReplySubmit}onSuccess={() => setReplyTargetId(null)}/>@@ -253,9 +291,10 @@ const Thread = memo<ThreadProps>();return (- <Flexbox className={styles.thread} ref={containerRef}>+ <Flexbox className={cx(styles.thread, compact && styles.threadCompact)} ref={containerRef}><CommentCardcomment={root}+ compact={compact}focusScroll={focus?.scroll}focusToken={focus && focus.commentId === root.id ? focus.token : undefined}replying={replyTargetId === root.id}@@ -265,19 +304,21 @@ const Thread = memo<ThreadProps>(/>{(replyCount > 0 || replyTargetId || focusedReplyId) && (- <Flexbox className={styles.replyList}>+ <Flexbox className={cx(styles.replyList, compact && styles.replyListCompact)}>{replyTargetId === root.id && (<ComposerdocumentId={documentId}key={`reply:${root.id}`}parentCommentId={root.id}+ plain={compact}+ onCancel={() => setReplyTargetId(null)}onSubmit={handleReplySubmit}onSuccess={() => setReplyTargetId(null)}/>)}{pinnedReply && renderReply(pinnedReply)}{replies.isLoadingInitial && replyCount > 0 ? (- <SurfaceSkeleton header={false} variant={'list'} />+ <ReplySkeleton compact={compact} count={replyCount} />) : replies.isInitialError ? (<AsyncErrorerror={replies.error}diff --git a/src/features/PageEditor/DocumentComments/anchor/commentLocator.test.ts b/src/features/PageEditor/DocumentComments/anchor/commentLocator.test.tsnew file mode 100644index 00000000000..5a27d397330--- /dev/null+++ b/src/features/PageEditor/DocumentComments/anchor/commentLocator.test.ts@@ -0,0 +1,86 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { focusCommentCard } from './commentLocator';++const mountCard = (id: string, options: { inGutter?: boolean } = {}) => {+ const host = options.inGutter+ ? (() => {+ const gutter = document.createElement('div');+ gutter.setAttribute('data-document-comment-gutter', '');+ document.body.append(gutter);+ return gutter;+ })()+ : document.body;+ const card = document.createElement('div');+ card.setAttribute('data-document-comment-id', id);+ card.scrollIntoView = vi.fn();+ host.append(card);+ return card;+};++describe('focusCommentCard', () => {+ afterEach(() => {+ document.body.innerHTML = '';+ });++ it('returns false when the card is not mounted (unloaded page)', () => {+ expect(focusCommentCard('missing')).toBe(false);+ });++ it('does not scroll a gutter card when the caller opts out of scrolling — the panel already shows it', () => {+ const card = mountCard('a', { inGutter: true });++ focusCommentCard('a', { scroll: false });++ expect(card.scrollIntoView).not.toHaveBeenCalled();+ });++ it('scrolls a flat-list card into view even when the caller asked to skip scrolling, since without a gutter it can be off-screen', () => {+ const card = mountCard('a', { inGutter: false });++ const result = focusCommentCard('a', { scroll: false });++ expect(result).toBe(true);+ expect(card.scrollIntoView).toHaveBeenCalled();+ });++ it('still flashes a flat-list card, unlike a gutter one', () => {+ const gutterCard = mountCard('gutter-card', { inGutter: true });+ const flatCard = mountCard('flat-card', { inGutter: false });++ focusCommentCard('gutter-card', { scroll: false });+ focusCommentCard('flat-card', { scroll: false });++ expect(gutterCard.className).toBe('');+ expect(flatCard.className).not.toBe('');+ });++ it('prefers the gutter copy when the same thread renders in both the flat list and the gutter', () => {+ // The flat list is the document's complete record and always includes+ // anchored threads too, so an open gutter renders the same thread twice —+ // the list copy first in DOM order.+ const flatCopy = mountCard('a', { inGutter: false });+ const gutterCopy = mountCard('a', { inGutter: true });++ const result = focusCommentCard('a', { scroll: false });++ expect(result).toBe(true);+ // Must not throw the viewport down to the flat-list copy when the+ // gutter's own copy is already visible beside the clicked run.+ expect(flatCopy.scrollIntoView).not.toHaveBeenCalled();+ expect(gutterCopy.scrollIntoView).not.toHaveBeenCalled();+ expect(flatCopy.className).toBe('');+ });++ it('does not scroll away when a gutter exists but has not mounted its card yet (a closed panel about to open)', () => {+ // Only the flat-list copy exists at this instant — the gutter is mounting+ // in the same tick as a separate effect that opens the panel, so the DOM+ // alone can't yet say a gutter is coming.+ const flatCopy = mountCard('a', { inGutter: false });++ const result = focusCommentCard('a', { hasGutter: true, scroll: false });++ expect(result).toBe(true);+ expect(flatCopy.scrollIntoView).not.toHaveBeenCalled();+ });+});diff --git a/src/features/PageEditor/DocumentComments/anchor/commentLocator.ts b/src/features/PageEditor/DocumentComments/anchor/commentLocator.tsindex eb116140192..8d381dc4256 100644--- a/src/features/PageEditor/DocumentComments/anchor/commentLocator.ts+++ b/src/features/PageEditor/DocumentComments/anchor/commentLocator.ts@@ -12,16 +12,42 @@ const scrollBehavior = (): ScrollBehavior => (prefersReducedMotion() ? 'auto' :* Flash a comment card, the same landing treatment a notification deep link* gets (see `CommentCard`'s `focusToken` effect).*- * `scroll` is opt-in because the two callers want different things: a deep- * link has to bring the card into view, while a click in the body must not- * move the reader's viewport at all.+ * `scroll: false` requests skipping the scroll a deep link otherwise gets,+ * for a click in the body whose card sits (or is about to sit, once a closed+ * panel opens) in a gutter beside the run — but it's only honoured there; a+ * card with no gutter to sit in can be anywhere on the page, so it is always+ * scrolled into view or the click would land on nothing visible.+ *+ * `hasGutter` is the caller's own answer to "will this land in a gutter",+ * for when the DOM can't say yet: opening a closed panel is a separate,+ * slightly later effect, so at click time the gutter copy of the card may+ * not be mounted and the query would otherwise fall through to the flat+ * list's copy — inferring "no gutter" from that would scroll away right as+ * the panel is about to open beside the very text that was clicked.*/-export const focusCommentCard = (commentId: string, { scroll = true } = {}): boolean => {+export const focusCommentCard = (+ commentId: string,+ { hasGutter, scroll = true }: { hasGutter?: boolean; scroll?: boolean } = {},+): boolean => {if (typeof document === 'undefined') return false;- const card = document.querySelector<HTMLElement>(`[data-document-comment-id="${commentId}"]`);+ const selector = `[data-document-comment-id="${commentId}"]`;+ // An anchored thread with a gutter open renders in both the gutter and the+ // flat list below the document (the list is the complete record). Prefer+ // the gutter's copy — the one a body click is actually about — and only+ // fall back to the list's when there is no gutter copy to prefer.+ const card =+ document.querySelector<HTMLElement>(`[data-document-comment-gutter] ${selector}`) ??+ document.querySelector<HTMLElement>(selector);if (!card) return false;- if (scroll) card.scrollIntoView({ behavior: scrollBehavior(), block: 'center' });+ // A card in the panel is already pulled level with its run — a click there+ // must not move the viewport at all. Without a panel (e.g. AgentDocumentPage's+ // rightPanel={false}) the same click's card lives in the flat list below the+ // document, anywhere on the page; `scroll: false` only opts out of the+ // panel's redundant motion, never out of bringing an off-screen card into view.+ const inGutter = hasGutter ?? Boolean(card.closest('[data-document-comment-gutter]'));+ if (scroll || !inGutter) card.scrollIntoView({ behavior: scrollBehavior(), block: 'center' });+ if (inGutter) return true;card.classList.add(styles.highlighted);setTimeout(() => card.classList.remove(styles.highlighted), LOCATE_FLASH_DURATION);return true;diff --git a/src/features/PageEditor/DocumentComments/anchor/constants.ts b/src/features/PageEditor/DocumentComments/anchor/constants.tsdeleted file mode 100644index 9b860db5d4c..00000000000--- a/src/features/PageEditor/DocumentComments/anchor/constants.ts+++ /dev/null@@ -1,6 +0,0 @@-/**- * DOM id of the root comment composer. The selection toolbar lives in the body- * and the composer lives in the list below it — two sibling subtrees with no- * shared ref — so the jump between them goes through the document.- */-export const DOCUMENT_COMMENT_COMPOSER_ID = 'document-comment-composer';diff --git a/src/features/PageEditor/DocumentComments/anchor/context.tsx b/src/features/PageEditor/DocumentComments/anchor/context.tsxindex 8a425162ccb..807200aba71 100644--- a/src/features/PageEditor/DocumentComments/anchor/context.tsx+++ b/src/features/PageEditor/DocumentComments/anchor/context.tsx@@ -5,6 +5,7 @@ import { createContext, type ReactNode, use } from 'react';import type { DocumentCommentAnchorsValue } from './useDocumentCommentAnchors';const noop = () => {};+const nullValue = () => null;/*** Keeps cards that render outside the list — the pinned deep-link thread@@ -12,17 +13,26 @@ const noop = () => {};*/const FALLBACK: DocumentCommentAnchorsValue = {activeRootId: null,+ bodyElement: null,+ getAnchorMatch: nullValue,+ getAnchorRange: nullValue,+ getPendingAnchorMatch: nullValue,+ getPendingAnchorRange: nullValue,locateInBody: noop,orphanedRootIds: new Set(),+ pickTick: 0,+ resolvedAt: 0,+ selectedRootId: null,+ selectRoot: noop,setHoveredRootId: noop,};const DocumentCommentAnchorsContext = createContext<DocumentCommentAnchorsValue>(FALLBACK);/**- * Anchors are resolved once for the whole list — one DOM walk, one repaint —- * and read by every card, so the resolution lives in context rather than being- * recomputed per card.+ * Anchors are resolved once for the whole document — one DOM walk, one+ * repaint — and read by every card and by the gutter, so the resolution lives+ * in context rather than being recomputed per card.*/export const DocumentCommentAnchorsProvider = ({children,diff --git a/src/features/PageEditor/DocumentComments/anchor/textAnchor.ts b/src/features/PageEditor/DocumentComments/anchor/textAnchor.tsindex 5baadafa614..cf3aa186845 100644--- a/src/features/PageEditor/DocumentComments/anchor/textAnchor.ts+++ b/src/features/PageEditor/DocumentComments/anchor/textAnchor.ts@@ -352,21 +352,18 @@ export const locateAnchor = (};/**- * Read the reader's current selection as an anchor.+ * Read a DOM range inside the body as an anchor.** Whitespace at either edge is dropped before the quote is taken so a sloppy* double-click ("word ") doesn't bake a trailing space into the text every- * future re-location has to reproduce. Returns `null` for a collapsed- * selection, one outside the body, or one that is whitespace only.+ * future re-location has to reproduce. Returns `null` for a range outside the+ * body or one that is whitespace only.*/-export const captureSelectionAnchor = (+export const captureRangeAnchor = (root: HTMLElement | null | undefined,+ range: Range | null | undefined,): DocumentCommentSelectionAnchor | null => {- if (!root) return null;- const selection = root.ownerDocument.defaultView?.getSelection();- if (!selection || selection.isCollapsed || selection.rangeCount === 0) return null;-- const range = selection.getRangeAt(0);+ if (!root || !range) return null;if (!root.contains(range.commonAncestorContainer)) return null;const flat = flattenEditorText(root);@@ -407,6 +404,16 @@ export const captureSelectionAnchor = (};};+/** Read the reader's current selection as an anchor; `null` when it is collapsed. */+export const captureSelectionAnchor = (+ root: HTMLElement | null | undefined,+): DocumentCommentSelectionAnchor | null => {+ if (!root) return null;+ const selection = root.ownerDocument.defaultView?.getSelection();+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) return null;+ return captureRangeAnchor(root, selection.getRangeAt(0));+};+/** Which flattened-text offset sits under a viewport point, or `null` when it is outside the body. */export const offsetFromClientPoint = (root: HTMLElement,diff --git a/src/features/PageEditor/DocumentComments/anchor/useDocumentCommentAnchors.test.ts b/src/features/PageEditor/DocumentComments/anchor/useDocumentCommentAnchors.test.tsnew file mode 100644index 00000000000..55fadf038a4--- /dev/null+++ b/src/features/PageEditor/DocumentComments/anchor/useDocumentCommentAnchors.test.ts@@ -0,0 +1,44 @@+import type { DocumentCommentAnchorItem } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { buildAnchorSignature } from './useDocumentCommentAnchors';++const anchor = (id: string, start: number, quote: string): DocumentCommentAnchorItem => ({+ id,+ selectionAnchor: { end: start + quote.length, quote, start },+});++describe('buildAnchorSignature', () => {+ it('produces the same signature for the same anchor set', () => {+ const anchors = [anchor('a', 0, 'hello'), anchor('b', 10, 'world')];++ expect(buildAnchorSignature(anchors)).toBe(buildAnchorSignature(anchors));+ });++ it('does not collide when concatenating id + start + quote would be ambiguous', () => {+ // "abc" + "1" + "22xyz" and "abc1" + "22" + "xyz" both concatenate to+ // "abc122xyz" with no delimiter — a real bug in an earlier version of+ // this function that made two different anchor sets look identical.+ const setX = [anchor('abc', 1, '22xyz')];+ const setY = [anchor('abc1', 22, 'xyz')];++ expect(buildAnchorSignature(setX)).not.toBe(buildAnchorSignature(setY));+ });++ it('does not collide across entries when a quote contains the join character', () => {+ // A quote containing a space (or any other single plain-character+ // delimiter) must not let two entries look like one merged entry.+ const merged = [anchor('a', 0, 'x y')];+ const split = [anchor('a', 0, 'x'), anchor('y', 0, '')];++ expect(buildAnchorSignature(merged)).not.toBe(buildAnchorSignature(split));+ });++ it('changes when any field of any entry changes', () => {+ const base = buildAnchorSignature([anchor('a', 0, 'hello')]);++ expect(buildAnchorSignature([anchor('a', 1, 'hello')])).not.toBe(base);+ expect(buildAnchorSignature([anchor('a', 0, 'hellp')])).not.toBe(base);+ expect(buildAnchorSignature([anchor('b', 0, 'hello')])).not.toBe(base);+ });+});diff --git a/src/features/PageEditor/DocumentComments/anchor/useDocumentCommentAnchors.ts b/src/features/PageEditor/DocumentComments/anchor/useDocumentCommentAnchors.tsindex 04d5240222f..9c7afdace12 100644--- a/src/features/PageEditor/DocumentComments/anchor/useDocumentCommentAnchors.ts+++ b/src/features/PageEditor/DocumentComments/anchor/useDocumentCommentAnchors.ts@@ -100,6 +100,17 @@ const useEditorBody = (editor?: IEditor) => {const sameRootIds = (left: ReadonlySet<string>, right: ReadonlySet<string>) =>left.size === right.size && [...left].every((id) => right.has(id));+/**+ * A stable string for "did the anchor set actually change" `useMemo`/effect+ * deps. A hand-joined string (even with a delimiter) risks two different+ * anchor sets colliding into the same string, since a quote is arbitrary+ * user content; JSON.stringify's array structure and escaping rule that out.+ */+export const buildAnchorSignature = (anchors: readonly DocumentCommentAnchorItem[]): string =>+ JSON.stringify(+ anchors.map(({ id, selectionAnchor }) => [id, selectionAnchor.start, selectionAnchor.quote]),+ );+export interface DocumentCommentAnchorsValue {/*** The thread whose run is emphasised in the body right now. A hover wins@@ -107,15 +118,43 @@ export interface DocumentCommentAnchorsValue {* emphasised, so arriving at a quote does not immediately lose it again.*/activeRootId: string | null;+ /** The rendered body, for surfaces that position themselves against it. */+ bodyElement: HTMLElement | null;+ /** Where a thread's quote sits in the flattened body text; `null` when orphaned. */+ getAnchorMatch: (rootCommentId: string) => AnchorMatch | null;+ /** A live DOM range over a thread's quote; `null` when orphaned or not yet resolved. */+ getAnchorRange: (rootCommentId: string) => Range | null;+ /** Where the selection being composed sits in the flattened body text; `null` when unresolved. */+ getPendingAnchorMatch: () => AnchorMatch | null;+ /** A live DOM range over the selection being composed, if any. */+ getPendingAnchorRange: () => Range | null;/** Scroll the body to a thread's anchor and select it. No-op for an orphaned anchor. */locateInBody: (rootCommentId: string) => void;/** Threads whose quoted run no longer exists in the body. */orphanedRootIds: ReadonlySet<string>;+ /** Ticks on every body-click pick, even a repeat pick of the same thread. */+ pickTick: number;+ /**+ * Ticks every time anchors are re-resolved against the body. Anything that+ * measured a range (card positions) is stale once this changes.+ */+ resolvedAt: number;+ /** The thread the reader last deliberately picked, from either side. */+ selectedRootId: string | null;+ /** Pick a thread (or clear the pick with `null`). */+ selectRoot: (rootCommentId: string | null) => void;/** Transient emphasis while the pointer is over a card. */setHoveredRootId: Dispatch<SetStateAction<string | null>>;}export interface DocumentCommentAnchorsOptions {+ /**+ * Whether a gutter exists for this document (it may currently be closed —+ * a click still opens it). A run picked in the body must not scroll the+ * body when it does: at click time the gutter's own card may not be+ * mounted yet, so the DOM alone can't say whether one is coming.+ */+ hasGutter?: boolean;/*** A run was picked in the body but its card is not mounted — the thread is* on a page the list has not loaded yet. The caller brings it into view@@ -139,7 +178,7 @@ export interface DocumentCommentAnchorsOptions {*/export const useDocumentCommentAnchors = (anchors: readonly DocumentCommentAnchorItem[],- { onPickUnloaded }: DocumentCommentAnchorsOptions = {},+ { hasGutter, onPickUnloaded }: DocumentCommentAnchorsOptions = {},): DocumentCommentAnchorsValue => {const editor = usePageEditorStore((s) => s.editor);// A quote captured before a document switch belongs to the previous body;@@ -153,12 +192,17 @@ export const useDocumentCommentAnchors = (const [hoveredRootId, setHoveredRootId] = useState<string | null>(null);const [selectedRootId, setSelectedRootId] = useState<string | null>(null);+ // `selectedRootId` alone can't signal a repeated pick of the same run: React+ // bails out of the state update, so a listener keyed on it never re-fires.+ // This ticks on every body-click pick regardless of whether the id changed.+ const [pickTick, setPickTick] = useState(0);const activeRootId = hoveredRootId ?? selectedRootId;const [orphanedRootIds, setOrphanedRootIds] = useState<ReadonlySet<string>>(() => new Set());const [resolvedAt, setResolvedAt] = useState(0);const flatRef = useRef<FlattenedText>(EMPTY_FLATTENED_TEXT);const matchesRef = useRef<ReadonlyMap<string, AnchorMatch>>(EMPTY_MATCHES);+ const pendingMatchRef = useRef<AnchorMatch | null>(null);// See `resolveAnchors`: results are reused while the body text is unchanged,// so a formatting-only update never re-scans for orphaned quotes.const resolveCacheRef = useRef<AnchorResolveCache>(EMPTY_ANCHOR_RESOLVE_CACHE);@@ -169,17 +213,10 @@ export const useDocumentCommentAnchors = (anchorsRef.current = anchors;const onPickUnloadedRef = useRef(onPickUnloaded);onPickUnloadedRef.current = onPickUnloaded;+ const hasGutterRef = useRef(hasGutter);+ hasGutterRef.current = hasGutter;- const anchorSignature = useMemo(- () =>- anchors- .map(- ({ id, selectionAnchor }) =>- `${id}\u0001${selectionAnchor.start}\u0001${selectionAnchor.quote}`,- )- .join('\u0000'),- [anchors],- );+ const anchorSignature = useMemo(() => buildAnchorSignature(anchors), [anchors]);const hasPendingAnchor = Boolean(pendingAnchor);useEffect(() => {@@ -197,17 +234,37 @@ export const useDocumentCommentAnchors = (setResolvedAt((current) => current + 1);}, [anchorSignature, element, hasPendingAnchor, revision]);+ // The pending selection is re-located on the same schedule as the stored+ // anchors, so the composer beside it and its highlight never disagree.useEffect(() => {+ pendingMatchRef.current = pendingAnchor ? locateAnchor(flatRef.current, pendingAnchor) : null;paintCommentHighlights({activeRootId,flat: flatRef.current,matches: matchesRef.current,- pending: pendingAnchor ? locateAnchor(flatRef.current, pendingAnchor) : null,+ pending: pendingMatchRef.current,});}, [activeRootId, pendingAnchor, resolvedAt]);useEffect(() => () => clearCommentHighlights(), []);+ const getAnchorMatch = useCallback(+ (rootCommentId: string) => matchesRef.current.get(rootCommentId) ?? null,+ [],+ );++ const getAnchorRange = useCallback((rootCommentId: string) => {+ const match = matchesRef.current.get(rootCommentId);+ return match ? buildAnchorRange(flatRef.current, match) : null;+ }, []);++ const getPendingAnchorRange = useCallback(() => {+ const match = pendingMatchRef.current;+ return match ? buildAnchorRange(flatRef.current, match) : null;+ }, []);++ const getPendingAnchorMatch = useCallback(() => pendingMatchRef.current, []);+const locateInBody = useCallback((rootCommentId: string) => {const match = matchesRef.current.get(rootCommentId);if (!match) return;@@ -218,17 +275,16 @@ export const useDocumentCommentAnchors = (// until another thread is picked or the reader clicks elsewhere in the// body. A timed flash would drop it seconds after they arrive.setSelectedRootId(rootCommentId);+ // Ticks even on a repeat of the same id, for the same reason as the body+ // click below: a re-pick of an already-selected thread must still reopen+ // a panel the reader closed in between.+ setPickTick((tick) => tick + 1);}, []);- // Clicking a run selects its thread. Selecting moves nothing, so unlike the- // old jump-to-the-comment behaviour it can't interrupt someone mid-edit and- // needs no "is the reader typing?" guard — that guard was what made a second- // click inside the body do nothing at all once the editor held focus.- //- // It deliberately does NOT scroll to the card: the comment list lives below- // the body, so scrolling would throw the reader to the bottom of the page- // just for pointing at a sentence. LOBE-14151 (cards beside the text) turns- // this into focusing the card in place.+ // Clicking a run selects its thread. Its card sits beside the text, so the+ // pick is answered in place — the card is emphasised and, in the gutter,+ // pulled level with the run — and the viewport never moves. That is also why+ // no "is the reader typing?" guard is needed: selecting interrupts nothing.useEffect(() => {if (!element) return;@@ -253,10 +309,12 @@ export const useDocumentCommentAnchors = (}setSelectedRootId(hitId);if (!hitId) return;+ setPickTick((tick) => tick + 1);// The card may sit on a thread page the list has not loaded yet — the// highlight exists because anchors are fetched for the whole document.- if (!focusCommentCard(hitId, { scroll: false })) onPickUnloadedRef.current?.(hitId);+ if (!focusCommentCard(hitId, { hasGutter: hasGutterRef.current, scroll: false }))+ onPickUnloadedRef.current?.(hitId);};element.addEventListener('click', handleClick);@@ -264,7 +322,33 @@ export const useDocumentCommentAnchors = (}, [element]);return useMemo(- () => ({ activeRootId, locateInBody, orphanedRootIds, setHoveredRootId }),- [activeRootId, locateInBody, orphanedRootIds],+ () => ({+ activeRootId,+ bodyElement: element,+ getAnchorMatch,+ getAnchorRange,+ getPendingAnchorMatch,+ getPendingAnchorRange,+ locateInBody,+ orphanedRootIds,+ pickTick,+ resolvedAt,+ selectedRootId,+ selectRoot: setSelectedRootId,+ setHoveredRootId,+ }),+ [+ activeRootId,+ element,+ getAnchorMatch,+ getAnchorRange,+ getPendingAnchorMatch,+ getPendingAnchorRange,+ locateInBody,+ orphanedRootIds,+ pickTick,+ resolvedAt,+ selectedRootId,+ ],);};diff --git a/src/features/PageEditor/DocumentComments/context.tsx b/src/features/PageEditor/DocumentComments/context.tsxnew file mode 100644index 00000000000..e06e98ca721--- /dev/null+++ b/src/features/PageEditor/DocumentComments/context.tsx@@ -0,0 +1,126 @@+'use client';++import { createContext, type ReactNode, type RefObject, use, useEffect } from 'react';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { usePermission } from '@/hooks/usePermission';++import { usePageEditorStore } from '../store';+import { DocumentCommentAnchorsProvider } from './anchor/context';+import DocumentCommentHighlightStyle from './anchor/HighlightStyle';+import { readAnchoredDraftAnchor, restoreFailedAnchoredDraft } from './Composer';+import type { DocumentCommentsState } from './useDocumentCommentsState';+import { useDocumentCommentsState } from './useDocumentCommentsState';++const DocumentCommentsContext = createContext<DocumentCommentsState | null>(null);++interface DocumentCommentsProviderProps {+ children: ReactNode;+ documentId: string;+ /**+ * Whether the editor renders its own right panel. Without one there is no+ * comments panel, and anchored threads list below the body instead.+ */+ panelAvailable: boolean;+ /** The body's scroll container; the panel's cards follow its scroll. */+ paneRef: RefObject<HTMLElement | null>;+}++const DocumentCommentsStateProvider = ({+ children,+ documentId,+ paneRef,+ panelAvailable,+}: DocumentCommentsProviderProps) => {+ const workspaceId = useActiveWorkspaceId();+ const { allowed: canCreate } = usePermission('create_content');+ const commentsPanelOpen = usePageEditorStore((s) => s.commentsPanelOpen);+ const setCommentsPanelOpen = usePageEditorStore((s) => s.setCommentsPanelOpen);+ const gutterEnabled = panelAvailable && commentsPanelOpen;+ const state = useDocumentCommentsState({ documentId, gutterEnabled, paneRef, panelAvailable });++ // The gutter composer only mounts once a pending anchor exists in the+ // store, but the store doesn't survive a reload while the draft (in+ // localStorage) does. Republish it here, in a provider that is always+ // mounted for the document, so a reload mid-draft doesn't strand it.+ // Gated on the current permission: `Composer` renders nothing without it,+ // so restoring the anchor for a since-revoked member would only leave a+ // permanently empty, undismissable pending card — the draft stays in+ // storage, recoverable once the permission comes back.+ //+ // The same moment — the shared slot being free — is when a failed gutter+ // submission stashed while a newer draft owned that slot gets handed back+ // (see `Composer`'s `preserveFailedAnchoredDraft`): re-checked whenever+ // the slot frees, i.e. after the newer draft is sent or cancelled, not+ // only on mount. Only in a panel-capable layout, where no composer is+ // mounted while the slot is free; the inline box below the body adopts+ // the stash itself, since it already holds the slot's state.+ const hasPendingForDocument = usePageEditorStore(+ (s) => s.pendingCommentAnchor?.documentId === documentId,+ );+ const setPendingCommentAnchor = usePageEditorStore((s) => s.setPendingCommentAnchor);+ useEffect(() => {+ if (!canCreate || hasPendingForDocument) return;+ const anchor =+ readAnchoredDraftAnchor(workspaceId, documentId) ??+ (panelAvailable+ ? restoreFailedAnchoredDraft(workspaceId, documentId)?.selectionAnchor+ : undefined);+ if (anchor) setPendingCommentAnchor({ anchor, documentId });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [documentId, canCreate, hasPendingForDocument, panelAvailable]);++ // A selection being commented on, or a run picked in the body, is answered+ // in the comments panel: open it on demand. Keyed on tick counters, not the+ // picked value itself — both the store and `selectedRootId` compare by+ // content, so a repeated pick of the same run would otherwise look like no+ // change — so picking again after the panel was closed opens it again,+ // while closing it is never undone by the pick that opened it.+ const pickVersion = usePageEditorStore((s) =>+ s.pendingCommentAnchor?.documentId === documentId ? s.pendingCommentAnchorVersion : 0,+ );+ const { pickTick, selectedRootId } = state.anchors;+ useEffect(() => {+ if (!panelAvailable || !(pickVersion || pickTick || selectedRootId)) return;+ setCommentsPanelOpen(true);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [pickVersion, pickTick, selectedRootId]);++ return (+ <DocumentCommentsContext value={state}>+ <DocumentCommentAnchorsProvider value={state.anchors}>+ <DocumentCommentHighlightStyle />+ {children}+ </DocumentCommentAnchorsProvider>+ </DocumentCommentsContext>+ );+};++/**+ * Hosts the comment state once for the whole editor so the panel beside the+ * text, the header toggle and the list below the body read the same caches.+ * Renders the children untouched when comments are unavailable (no+ * workspace, no document).+ */+export const DocumentCommentsProvider = ({+ children,+ documentId,+ paneRef,+ panelAvailable,+}: Omit<DocumentCommentsProviderProps, 'documentId'> & { documentId?: string }) => {+ const workspaceId = useActiveWorkspaceId();+ if (!workspaceId || !documentId) return children;+ return (+ <DocumentCommentsStateProvider+ documentId={documentId}+ key={documentId}+ paneRef={paneRef}+ panelAvailable={panelAvailable}+ >+ {children}+ </DocumentCommentsStateProvider>+ );+};++/** `null` outside a provider, i.e. where comments are unavailable. */+export const useDocumentComments = () => use(DocumentCommentsContext);diff --git a/src/features/PageEditor/DocumentComments/hooks.test.ts b/src/features/PageEditor/DocumentComments/hooks.test.tsnew file mode 100644index 00000000000..7c4730f338a--- /dev/null+++ b/src/features/PageEditor/DocumentComments/hooks.test.ts@@ -0,0 +1,68 @@+import type { DocumentCommentThreadPage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { ANCHORED_EAGER_PAGE_LIMIT, nextEagerPageCount, partitionThreadPage } from './hooks';++const thread = (id: string, anchored: boolean) =>+ ({+ replyCount: 0,+ root: {+ id,+ selectionAnchor: anchored ? { end: 5, quote: 'hello', start: 0 } : null,+ },+ }) as unknown as DocumentCommentThreadPage['items'][number];++const mixedPage: DocumentCommentThreadPage = {+ items: [thread('a', true), thread('b', false), thread('c', true)],+ nextCursor: 'next',+};++describe('nextEagerPageCount', () => {+ it('requests one more page while under the budget', () => {+ expect(nextEagerPageCount(1, ANCHORED_EAGER_PAGE_LIMIT)).toBe(2);+ expect(nextEagerPageCount(ANCHORED_EAGER_PAGE_LIMIT - 1, ANCHORED_EAGER_PAGE_LIMIT)).toBe(+ ANCHORED_EAGER_PAGE_LIMIT,+ );+ });++ it('stops at the budget instead of draining every page', () => {+ expect(nextEagerPageCount(ANCHORED_EAGER_PAGE_LIMIT, ANCHORED_EAGER_PAGE_LIMIT)).toBe(+ ANCHORED_EAGER_PAGE_LIMIT,+ );+ expect(nextEagerPageCount(ANCHORED_EAGER_PAGE_LIMIT + 3, ANCHORED_EAGER_PAGE_LIMIT)).toBe(+ ANCHORED_EAGER_PAGE_LIMIT + 3,+ );+ });++ it('never fetches ahead with a zero budget (the panel is closed or it is the document list)', () => {+ expect(nextEagerPageCount(1, 0)).toBe(1);+ });+});++describe('partitionThreadPage', () => {+ it('keeps only anchored roots for the anchored scope when the server returned a mixed page', () => {+ const page = partitionThreadPage(mixedPage, 'anchored');++ expect(page.items.map(({ root }) => root.id)).toEqual(['a', 'c']);+ expect(page.nextCursor).toBe('next');+ });++ it('keeps only document-level roots for the document scope', () => {+ expect(partitionThreadPage(mixedPage, 'document').items.map(({ root }) => root.id)).toEqual([+ 'b',+ ]);+ });++ it('returns the page untouched for the all scope', () => {+ expect(partitionThreadPage(mixedPage, 'all')).toBe(mixedPage);+ });++ it('returns the same page object when the server already honoured the scope', () => {+ const anchoredOnly: DocumentCommentThreadPage = {+ items: [thread('a', true)],+ nextCursor: null,+ };++ expect(partitionThreadPage(anchoredOnly, 'anchored')).toBe(anchoredOnly);+ });+});diff --git a/src/features/PageEditor/DocumentComments/hooks.ts b/src/features/PageEditor/DocumentComments/hooks.tsindex c3fd4c5b08d..73218ca1a49 100644--- a/src/features/PageEditor/DocumentComments/hooks.ts+++ b/src/features/PageEditor/DocumentComments/hooks.ts@@ -7,7 +7,7 @@ import type {DocumentCommentSummary,DocumentCommentThreadPage,} from '@lobechat/types';-import { useCallback } from 'react';+import { useCallback, useEffect } from 'react';import useSWRInfinite from 'swr/infinite';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';@@ -25,13 +25,43 @@ import {} from './optimistic';const PAGE_SIZE = 20;+/**+ * The gutter needs every anchored thread mounted at once (each card sits at+ * its own height), so its pages are fetched at the router's cap and drained+ * in the background rather than behind a "load more" button.+ */+const ANCHORED_PAGE_SIZE = 50;++export type DocumentCommentThreadScope = 'all' | 'anchored' | 'document';++/**+ * Keeps a page to its scope's own subset even when the backend ignored the+ * `anchored` parameter — a production server predating it strips the unknown+ * key and answers both scopes with the same mixed pages (the documented debug+ * proxy runs the latest SPA against exactly that). Without this, the two+ * caches overlap and the list below the body renders every such thread+ * twice. The cursor still walks the server's own order, so paging stays+ * consistent; a page may just carry fewer items than asked for.+ */+export const partitionThreadPage = (+ page: DocumentCommentThreadPage,+ scope: DocumentCommentThreadScope,+): DocumentCommentThreadPage => {+ if (scope === 'all') return page;+ const wantsAnchored = scope === 'anchored';+ const items = page.items.filter(({ root }) => Boolean(root.selectionAnchor) === wantsAnchored);+ return items.length === page.items.length ? page : { ...page, items };+};-const fetchThreads = ([, , documentId, cursor]: readonly string[]) =>- documentCommentService.listThreads({+const fetchThreads = async ([, , documentId, cursor, scope]: readonly string[]) => {+ const page = await documentCommentService.listThreads({+ anchored: scope === 'all' ? undefined : scope === 'anchored',cursor: cursor || undefined,documentId,- limit: PAGE_SIZE,+ limit: scope === 'anchored' ? ANCHORED_PAGE_SIZE : PAGE_SIZE,});+ return partitionThreadPage(page, scope as DocumentCommentThreadScope);+};const fetchReplies = ([, , rootCommentId, cursor]: readonly string[]) =>documentCommentService.listReplies({@@ -142,7 +172,32 @@ export const useDocumentCommentAnchorList = (documentId?: string | null) => {);};-export const useDocumentCommentThreads = (documentId?: string | null) => {+/**+ * How many pages of anchored threads the gutter fetches ahead of demand while+ * it is open, so the cards beside the text are there for the runs a reader+ * is most likely looking at. Anything past it stays paginated: a highlight+ * whose thread is not loaded is still painted (from the anchor list) and+ * fetches its own thread on pick, and the list below the body pages the rest.+ */+export const ANCHORED_EAGER_PAGE_LIMIT = 4;++/** The page count to request next while draining ahead of demand, capped at `limit`. */+export const nextEagerPageCount = (current: number, limit: number) =>+ current < limit ? current + 1 : current;++export const useDocumentCommentThreads = (+ documentId?: string | null,+ scope: DocumentCommentThreadScope = 'all',+ {+ eagerPageLimit = 0,+ }: {+ /**+ * Pages to fetch ahead of demand, one after another, without the reader+ * asking; `0` (the default) leaves paging entirely to `loadMore`.+ */+ eagerPageLimit?: number;+ } = {},+) => {const workspaceId = useActiveWorkspaceId();const getKey = useCallback((_index: number, previous: DocumentCommentThreadPage | null) => {@@ -151,25 +206,38 @@ export const useDocumentCommentThreads = (documentId?: string | null) => {workspaceId,documentId,previous?.nextCursor ?? undefined,+ scope,);},- [documentId, workspaceId],+ [documentId, scope, workspaceId],);const response = useSWRInfinite<DocumentCommentThreadPage>(getKey, fetchThreads, {revalidateFirstPage: false,});+ const pagination = getPaginationState(+ response.data,+ response.error,+ response.isLoading,+ response.isValidating,+ response.size,+ );+ const { setSize, size } = response;+ const { hasMore, isLoadingMore } = pagination;++ // Fetch ahead of demand up to the caller's budget: for the gutter, a card+ // it has not loaded is a highlight with nothing beside it. The budget keeps+ // a document with hundreds of anchored roots from mounting every one of+ // them (twice — gutter and list) before the reader has looked at any.+ useEffect(() => {+ if (!hasMore || isLoadingMore || size >= eagerPageLimit) return;+ void setSize((current) => nextEagerPageCount(current, eagerPageLimit));+ }, [eagerPageLimit, hasMore, isLoadingMore, setSize, size]);return {...response,- ...getPaginationState(- response.data,- response.error,- response.isLoading,- response.isValidating,- response.size,- ),+ ...pagination,items: flattenDocumentCommentThreads(response.data),- loadMore: () => response.setSize((current) => current + 1),+ loadMore: () => setSize((current) => current + 1),reload: () => response.mutate(),};};diff --git a/src/features/PageEditor/DocumentComments/index.test.ts b/src/features/PageEditor/DocumentComments/index.test.tsnew file mode 100644index 00000000000..57eda2238a3--- /dev/null+++ b/src/features/PageEditor/DocumentComments/index.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';++import { listThreadOwnsFocusMiss, resolveListThreadFocus } from './index';+import type { DocumentCommentFocus } from './useDocumentCommentDeepLink';++const focus: DocumentCommentFocus = {+ commentId: 'root-1',+ rootCommentId: 'root-1',+ scroll: true,+ token: 1,+};++describe('resolveListThreadFocus', () => {+ it('returns undefined for a root the focus does not target', () => {+ expect(resolveListThreadFocus(focus, new Set(), 'root-2')).toBeUndefined();+ });++ it('returns undefined when there is no focus at all', () => {+ expect(resolveListThreadFocus(undefined, new Set(['root-1']), 'root-1')).toBeUndefined();+ });++ it('passes the focus through unchanged when the gutter has no copy of this thread', () => {+ expect(resolveListThreadFocus(focus, new Set(), 'root-1')).toEqual(focus);+ });++ it('suppresses the scroll when the gutter already shows this thread', () => {+ expect(resolveListThreadFocus(focus, new Set(['root-1']), 'root-1')).toEqual({+ ...focus,+ scroll: false,+ });+ });++ it("leaves an in-body pick's focus (scroll already false) as-is when duplicated in the gutter", () => {+ const pick = { ...focus, scroll: false };++ expect(resolveListThreadFocus(pick, new Set(['root-1']), 'root-1')).toEqual(pick);+ });+});++describe('listThreadOwnsFocusMiss', () => {+ it('lets the flat copy answer for a missing reply when there is no gutter copy', () => {+ expect(listThreadOwnsFocusMiss(new Set(), 'root-1')).toBe(true);+ });++ it('hands that to the gutter copy when it shows the same thread, so it is reported once', () => {+ expect(listThreadOwnsFocusMiss(new Set(['root-1']), 'root-1')).toBe(false);+ });+});diff --git a/src/features/PageEditor/DocumentComments/index.tsx b/src/features/PageEditor/DocumentComments/index.tsxindex 1361cfee90d..f371539d5b3 100644--- a/src/features/PageEditor/DocumentComments/index.tsx+++ b/src/features/PageEditor/DocumentComments/index.tsx@@ -1,387 +1,257 @@'use client';-import type { DocumentCommentAnchorItem } from '@lobechat/types';import { Center, Flexbox } from '@lobehub/ui';-import { Button, Skeleton, Text, toast } from '@lobehub/ui/base-ui';-import { memo, useCallback, useEffect, useMemo } from 'react';+import { Button, Skeleton, Text } from '@lobehub/ui/base-ui';+import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import AsyncError from '@/components/AsyncError';import SurfaceSkeleton from '@/components/Skeleton/Surface';-import { documentCommentService } from '@/services/documentComment';-import { DocumentCommentAnchorsProvider } from './anchor/context';-import DocumentCommentHighlightStyle from './anchor/HighlightStyle';-import { useDocumentCommentAnchors } from './anchor/useDocumentCommentAnchors';import Composer from './Composer';-import {- useDocumentCommentAnchorList,- useDocumentCommentDetail,- useDocumentCommentSummary,- useDocumentCommentThreads,- useOptimisticDocumentComment,-} from './hooks';-import type { DocumentCommentSubmitInput, DocumentCommentUpdateHandler } from './optimistic';-import {- appendOptimisticThread,- removeOptimisticThread,- replaceOptimisticThread,- replaceThreadComment,- updateThreadReplyCount,-} from './optimistic';+import { useDocumentComments } from './context';import { styles } from './styles';import Thread from './Thread';-import {- type DocumentCommentFocusMissReason,- useDocumentCommentDeepLink,-} from './useDocumentCommentDeepLink';+import type { DocumentCommentFocus } from './useDocumentCommentDeepLink';+import type { DocumentCommentsState } from './useDocumentCommentsState';-const DocumentComments = memo<{ documentId: string }>(({ documentId }) => {- const { t } = useTranslation('file');- const workspaceId = useActiveWorkspaceId();- const summary = useDocumentCommentSummary(workspaceId ? documentId : undefined);- const threads = useDocumentCommentThreads(workspaceId ? documentId : undefined);- const anchorList = useDocumentCommentAnchorList(workspaceId ? documentId : undefined);- const createOptimistic = useOptimisticDocumentComment();- const { clearFocus, focus, focusRoot, focusThread } = useDocumentCommentDeepLink(documentId);- const reloadSummary = summary.mutate;- const reloadThreads = threads.reload;- const mutateThreads = threads.mutate;- const mutateAnchors = anchorList.mutate;- const refresh = useCallback(async () => {- await Promise.all([reloadThreads(), reloadSummary(), mutateAnchors()]);- }, [mutateAnchors, reloadSummary, reloadThreads]);- const updateSummaryTotal = useCallback(- (delta: number) =>- reloadSummary(- (current) =>- current ? { ...current, total: Math.max(0, current.total + delta) } : current,- { revalidate: false },- ),- [reloadSummary],- );- const updateReplyCount = useCallback(- (rootCommentId: string, delta: number) =>- mutateThreads((pages) => updateThreadReplyCount(pages, rootCommentId, delta), {- revalidate: false,- }),- [mutateThreads],- );- const handleCreate = useCallback(- async ({ clientId, content, editorData, selectionAnchor }: DocumentCommentSubmitInput) => {- const optimisticComment = createOptimistic({- clientId,- content,- documentId,- editorData,- selectionAnchor,- });- await Promise.all([- mutateThreads((pages) => appendOptimisticThread(pages, optimisticComment), {- revalidate: false,- }),- updateSummaryTotal(1),- ]);+/**+ * An anchored thread mounted in the gutter has two copies on screen at once;+ * only the gutter one sits beside its run, so a deep link scrolls through it+ * alone — the flat copy below the body just highlights, or its own scroll+ * would race the gutter's and could win, throwing the reader past a target+ * that was already in view beside the text.+ */+export const resolveListThreadFocus = (+ focus: DocumentCommentFocus | undefined,+ gutterShownIds: ReadonlySet<string>,+ rootId: string,+): DocumentCommentFocus | undefined => {+ if (focus?.rootCommentId !== rootId) return undefined;+ return gutterShownIds.has(rootId) ? { ...focus, scroll: false } : focus;+};- let created: Awaited<ReturnType<typeof documentCommentService.create>>;- try {- created = await documentCommentService.create({- clientId,- content,- documentId,- editorData,- selectionAnchor,- });- if (!created) throw new Error('Document comment creation returned no result');- } catch (error) {- await Promise.all([- mutateThreads((pages) => removeOptimisticThread(pages, clientId), {- revalidate: false,- }),- updateSummaryTotal(-1),- ]);- throw error;- }-- try {- await mutateThreads((pages) => replaceOptimisticThread(pages, created.comment), {- revalidate: false,- });- } catch (error) {- console.error('Failed to reconcile the created document comment', error);- void reloadThreads();- }- if (created.isDuplicate) void reloadSummary();- // The body paints from the document-wide anchor list, so the new root- // joins it here rather than waiting for the next revalidation.- const createdAnchor = created.comment.selectionAnchor;- if (createdAnchor) {- void mutateAnchors(- (current) =>- current && !current.items.some(({ id }) => id === created.comment.id)- ? {- items: [- ...current.items,- { id: created.comment.id, selectionAnchor: createdAnchor },- ],- }- : current,- { revalidate: false },- );- }- },- [- createOptimistic,- documentId,- mutateAnchors,- mutateThreads,- reloadSummary,- reloadThreads,- updateSummaryTotal,- ],- );- const handleUpdate: DocumentCommentUpdateHandler = useCallback(- async (comment, value) => {- const optimisticComment = { ...comment, ...value, updatedAt: new Date() };- await mutateThreads((pages) => replaceThreadComment(pages, optimisticComment), {- revalidate: false,- });+/**+ * Same split for a deep link whose reply turns out missing or failed: both+ * copies see the focus (the flat one still highlights), but exactly one of+ * them may answer for it — the gutter copy when there is one — or the reader+ * gets the toast twice and the focus token advances twice.+ */+export const listThreadOwnsFocusMiss = (gutterShownIds: ReadonlySet<string>, rootId: string) =>+ !gutterShownIds.has(rootId);- let updated: Awaited<ReturnType<typeof documentCommentService.update>>;- try {- updated = await documentCommentService.update({ ...value, id: comment.id });- if (!updated) throw new Error('Document comment update returned no result');- } catch (error) {- await mutateThreads((pages) => replaceThreadComment(pages, comment), {- revalidate: false,- });- throw error;- }-- try {- await mutateThreads((pages) => replaceThreadComment(pages, updated), {- revalidate: false,- });- } catch (error) {- console.error('Failed to reconcile the updated document comment', error);- void reloadThreads();- }- },- [mutateThreads, reloadThreads],- );- 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 = useMemo(- () =>- focus && !hasFocusedThread && focusedRootData && isFocusedRootUsable- ? { replyCount: focusedRootData.replyCount, root: focusedRootData }- : undefined,- [focus, focusedRootData, hasFocusedThread, isFocusedRootUsable],- );- // Highlights come from the document-wide anchor list so every anchored run- // is discoverable from the body, however far down the list its card sits.- // Loaded pages and the pinned thread are folded in on top: an optimistic- // root has no server row yet, and a pinned root may predate the last fetch.- const anchorItems = useMemo(() => {- const byId = new Map<string, DocumentCommentAnchorItem>();- for (const { id, selectionAnchor } of anchorList.data?.items ?? []) {- byId.set(id, { id, selectionAnchor });- }- const loaded = pinnedThread ? [pinnedThread, ...threads.items] : threads.items;- for (const { root } of loaded) {- if (root.selectionAnchor && !byId.has(root.id)) {- byId.set(root.id, { id: root.id, selectionAnchor: root.selectionAnchor });- }- }- return [...byId.values()];- }, [anchorList.data, pinnedThread, threads.items]);- const anchors = useDocumentCommentAnchors(anchorItems, { onPickUnloaded: focusThread });- 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;+const DocumentCommentList = memo<{ state: DocumentCommentsState }>(({ state }) => {+ const { t } = useTranslation('file');+ const {+ anchoredError,+ documentId,+ documentThreads,+ focus,+ gutterThreads,+ handleCreate,+ handlePinnedRootUpdate,+ handleReplyFocusMissing,+ handleUpdate,+ hasMoreListThreads,+ isAnchoredInitialError,+ isAnchoredLoading,+ isAnchoredRetrying,+ isLoadingMoreListThreads,+ listThreads,+ loadMoreListThreads,+ panelAvailable,+ pinnedThreadInGutter,+ pinnedThreadInList,+ refresh,+ refreshPinned,+ reloadAnchored,+ summary,+ updatePinnedReplyCount,+ updateReplyCount,+ updateSummaryTotal,+ } = state;+ const isLoadingInitial = documentThreads.isLoadingInitial || isAnchoredLoading;+ const isHeaderLoading = isLoadingInitial || (summary.isLoading && !summary.data);+ // The document and anchored queries are independent; one failing or still+ // loading must not hide comments the other already fetched successfully.+ const hasAnyItems = listThreads.length > 0 || Boolean(pinnedThreadInList);+ // An anchored thread also mounted in the gutter has two copies on screen at+ // once; only that copy sits beside its run, so a deep link scrolls through+ // it alone — this one just highlights, or the flat copy's own scroll would+ // race it down to the list below the body.+ const gutterShownIds = useMemo(() => {+ const ids = new Set(gutterThreads.map(({ root }) => root.id));+ if (pinnedThreadInGutter) ids.add(pinnedThreadInGutter.root.id);+ return ids;+ }, [gutterThreads, pinnedThreadInGutter]);return (- <DocumentCommentAnchorsProvider value={anchors}>- <DocumentCommentHighlightStyle />- <Flexbox- data-document-comments- className={styles.section}- gap={24}- onClick={(event) => event.stopPropagation()}- >- <Flexbox horizontal align={'center'} className={styles.header} gap={8}>- {isHeaderLoading ? (- <>- <Skeleton height={28} width={48} />- <Skeleton height={20} width={16} />- </>- ) : (- <>- <Text as={'h2'} fontSize={20} weight={600}>- {t('pageEditor.comments.title')}+ <Flexbox+ data-document-comments+ className={styles.section}+ gap={24}+ onClick={(event) => event.stopPropagation()}+ >+ <Flexbox horizontal align={'center'} className={styles.header} gap={8}>+ {isHeaderLoading ? (+ <>+ <Skeleton height={28} width={48} />+ <Skeleton height={20} width={16} />+ </>+ ) : (+ <>+ <Text as={'h2'} fontSize={20} weight={600}>+ {t('pageEditor.comments.title')}+ </Text>+ {summary.data && (+ <Text className={styles.meta} fontSize={14}>+ {summary.data.total}</Text>- {summary.data && (- <Text className={styles.meta} fontSize={14}>- {summary.data.total}- </Text>- )}- </>- )}- </Flexbox>+ )}+ </>+ )}+ </Flexbox>- {/* The pinned deep-link thread renders on its own, so a pending or failed list+ {/* The pinned deep-link thread renders on its own, so a pending or failed listrequest never hides a target that was already fetched. */}- {threads.isInitialError ||- threads.isLoadingInitial ||- threads.items.length > 0 ||- pinnedThread ? (- <Flexbox className={styles.threadList}>- {pinnedThread && (+ {documentThreads.isInitialError ||+ isAnchoredInitialError ||+ isLoadingInitial ||+ listThreads.length > 0 ||+ pinnedThreadInList ? (+ <Flexbox className={styles.threadList}>+ {pinnedThreadInList && (+ <Thread+ documentId={documentId}+ focus={resolveListThreadFocus(focus, gutterShownIds, pinnedThreadInList.root.id)}+ key={pinnedThreadInList.root.id}+ replyCount={pinnedThreadInList.replyCount}+ root={pinnedThreadInList.root}+ onMutated={refreshPinned}+ onReplyCountChange={updatePinnedReplyCount}+ onRootUpdate={handlePinnedRootUpdate}+ onSummaryChange={updateSummaryTotal}+ onFocusMissing={+ listThreadOwnsFocusMiss(gutterShownIds, pinnedThreadInList.root.id)+ ? handleReplyFocusMissing+ : undefined+ }+ />+ )}+ {hasAnyItems ? (+ listThreads.map(({ replyCount, root }) => (<ThreaddocumentId={documentId}- focus={focus}- key={pinnedThread.root.id}- replyCount={pinnedThread.replyCount}- root={pinnedThread.root}- onFocusMissing={handleReplyFocusMissing}- onMutated={refreshPinned}- onReplyCountChange={updatePinnedReplyCount}- onRootUpdate={handlePinnedRootUpdate}+ focus={resolveListThreadFocus(focus, gutterShownIds, root.id)}+ key={root.id}+ replyCount={replyCount}+ root={root}+ onMutated={refresh}+ onReplyCountChange={updateReplyCount}+ onRootUpdate={handleUpdate}onSummaryChange={updateSummaryTotal}+ onFocusMissing={+ listThreadOwnsFocusMiss(gutterShownIds, root.id)+ ? handleReplyFocusMissing+ : undefined+ }/>- )}- {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}- variant={'inline'}- onRetry={() => void threads.reload()}- />- ) : (- threads.hasMore && (- <Center paddingBlock={12}>- <Button- loading={threads.isLoadingMore}- type={'text'}- onClick={() => void threads.loadMore()}- >- {t('pageEditor.comments.loadMore')}- </Button>- </Center>- )- )}- </Flexbox>- ) : null}+ ))+ ) : documentThreads.isInitialError ? (+ <AsyncError+ error={documentThreads.error}+ variant={'block'}+ onRetry={() => void documentThreads.reload()}+ />+ ) : isAnchoredInitialError ? (+ <AsyncError+ error={anchoredError}+ variant={'block'}+ onRetry={() => void reloadAnchored()}+ />+ ) : (+ isLoadingInitial && <SurfaceSkeleton header={false} variant={'list'} />+ )}+ {/* Shown alongside whichever branch rendered above: a query that+ failed its initial load must not hide comments the other query+ already fetched successfully. */}+ {hasAnyItems && documentThreads.isInitialError && (+ <AsyncError+ error={documentThreads.error}+ variant={'inline'}+ onRetry={() => void documentThreads.reload()}+ />+ )}+ {hasAnyItems && isAnchoredInitialError && (+ <AsyncError+ error={anchoredError}+ retrying={isAnchoredRetrying}+ variant={'inline'}+ onRetry={() => void reloadAnchored()}+ />+ )}+ {documentThreads.error && !documentThreads.isInitialError ? (+ <AsyncError+ error={documentThreads.error}+ retrying={documentThreads.isRetrying}+ variant={'inline'}+ onRetry={() => void documentThreads.reload()}+ />+ ) : (+ hasMoreListThreads && (+ <Center paddingBlock={12}>+ <Button+ loading={isLoadingMoreListThreads}+ type={'text'}+ onClick={() => void loadMoreListThreads()}+ >+ {t('pageEditor.comments.loadMore')}+ </Button>+ </Center>+ )+ )}+ {/* Independent of the document query's own error/load-more slot above:+ an anchored-only failure must not hide document pagination. */}+ {anchoredError && !isAnchoredInitialError && (+ <AsyncError+ error={anchoredError}+ retrying={isAnchoredRetrying}+ variant={'inline'}+ onRetry={() => void reloadAnchored()}+ />+ )}+ </Flexbox>+ ) : null}- {/* While the thread list is still skeleton-loading the composer would+ {/* While the thread list is still skeleton-loading the composer wouldfloat against placeholder content — reveal it with the real list. */}- {!threads.isLoadingInitial && (- <Composer documentId={documentId} key={`root:${documentId}`} onSubmit={handleCreate} />- )}- </Flexbox>- </DocumentCommentAnchorsProvider>+ {!isLoadingInitial && (+ <Composer+ // With a comments panel around, a selection opens the panel and is+ // written there; only an editor without one writes it down here.+ anchorMode={panelAvailable ? 'none' : 'inline'}+ documentId={documentId}+ key={`root:${documentId}`}+ onSubmit={handleCreate}+ />+ )}+ </Flexbox>);});+DocumentCommentList.displayName = 'DocumentCommentList';++/**+ * The comment list below the body: every thread of the document, anchored+ * ones with their quote. Anchored threads with a live run additionally+ * render beside the text in `DocumentCommentsPanel` while it is open.+ */+const DocumentComments = memo(() => {+ const state = useDocumentComments();+ if (!state) return null;+ return <DocumentCommentList state={state} />;+});+DocumentComments.displayName = 'DocumentComments';export default DocumentComments;diff --git a/src/features/PageEditor/DocumentComments/readAnchoredDraftAnchor.test.ts b/src/features/PageEditor/DocumentComments/readAnchoredDraftAnchor.test.tsnew file mode 100644index 00000000000..e30cc0853f6--- /dev/null+++ b/src/features/PageEditor/DocumentComments/readAnchoredDraftAnchor.test.ts@@ -0,0 +1,378 @@+import type { DocumentCommentSelectionAnchor } from '@lobechat/types';+import { beforeEach, describe, expect, it } from 'vitest';++import {+ clearAnchoredScopeDraft,+ clearLegacyRootDraft,+ migrateDraftToAnchoredScope,+ preserveFailedAnchoredDraft,+ readAnchoredDraftAnchor,+ readLegacyRootDraft,+ readUnanchoredDraftFromAnchoredScope,+ restoreFailedAnchoredDraft,+ takeFailedAnchoredDraft,+} from './Composer';++const DOCUMENT_ID = 'doc-1';+const WORKSPACE_ID = 'ws-1';+const KEY = `document-comment-draft:${WORKSPACE_ID}:${DOCUMENT_ID}:anchored`;+const LEGACY_KEY = `document-comment-draft:${WORKSPACE_ID}:${DOCUMENT_ID}:root`;++const anchor: DocumentCommentSelectionAnchor = { end: 12, quote: 'hello world', start: 0 };++beforeEach(() => {+ window.localStorage.clear();+});++describe('readAnchoredDraftAnchor', () => {+ it('returns undefined when no draft was persisted', () => {+ expect(readAnchoredDraftAnchor(WORKSPACE_ID, DOCUMENT_ID)).toBeUndefined();+ });++ it('returns the persisted anchor from the gutter draft', () => {+ window.localStorage.setItem(+ KEY,+ JSON.stringify({+ clientId: 'c1',+ content: 'draft text',+ editorData: null,+ selectionAnchor: anchor,+ }),+ );++ expect(readAnchoredDraftAnchor(WORKSPACE_ID, DOCUMENT_ID)).toEqual(anchor);+ });++ it('returns undefined for a draft with no captured selection', () => {+ window.localStorage.setItem(+ KEY,+ JSON.stringify({ clientId: 'c1', content: 'draft text', editorData: null }),+ );++ expect(readAnchoredDraftAnchor(WORKSPACE_ID, DOCUMENT_ID)).toBeUndefined();+ });++ it('returns undefined for malformed JSON instead of throwing', () => {+ window.localStorage.setItem(KEY, '{not json');++ expect(readAnchoredDraftAnchor(WORKSPACE_ID, DOCUMENT_ID)).toBeUndefined();+ });++ it('falls back to the "personal" scope when there is no workspace', () => {+ window.localStorage.setItem(+ `document-comment-draft:personal:${DOCUMENT_ID}:anchored`,+ JSON.stringify({ clientId: 'c1', content: '', editorData: null, selectionAnchor: anchor }),+ );++ expect(readAnchoredDraftAnchor(undefined, DOCUMENT_ID)).toEqual(anchor);+ });+});++describe('migrateDraftToAnchoredScope', () => {+ it('moves the full draft — content and attachments included, not just the anchor', () => {+ const draft = {+ clientId: 'c1',+ content: 'a comment started before a gutter existed',+ editorData: { root: { children: [] } } as never,+ selectionAnchor: anchor,+ };++ migrateDraftToAnchoredScope(WORKSPACE_ID, DOCUMENT_ID, draft);++ const raw = window.localStorage.getItem(KEY);+ expect(raw && JSON.parse(raw)).toEqual(draft);+ expect(readAnchoredDraftAnchor(WORKSPACE_ID, DOCUMENT_ID)).toEqual(anchor);+ });+});++describe('readLegacyRootDraft', () => {+ const legacyDraft = {+ clientId: 'c1',+ content: 'an unanchored draft from before',+ editorData: null,+ };++ it('returns null when there is no legacy draft', () => {+ expect(readLegacyRootDraft(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ });++ it('returns a legacy plain-comment draft with no anchor', () => {+ window.localStorage.setItem(LEGACY_KEY, JSON.stringify(legacyDraft));++ expect(readLegacyRootDraft(WORKSPACE_ID, DOCUMENT_ID)).toEqual(legacyDraft);+ });++ it('returns null once the new (anchored) scope already has its own draft', () => {+ window.localStorage.setItem(LEGACY_KEY, JSON.stringify(legacyDraft));+ window.localStorage.setItem(+ KEY,+ JSON.stringify({ clientId: 'c2', content: 'a fresh draft', editorData: null }),+ );++ expect(readLegacyRootDraft(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ });++ it('still migrates once the anchored scope holds only an empty (cancelled or sent) draft', () => {+ // `submit` and `cancel` both clear their scope by writing a fresh empty+ // draft, not by removing the key — so the key's mere presence must not+ // be read as "has content of its own to protect".+ window.localStorage.setItem(LEGACY_KEY, JSON.stringify(legacyDraft));+ window.localStorage.setItem(+ KEY,+ JSON.stringify({ clientId: 'c2', content: '', editorData: null }),+ );++ expect(readLegacyRootDraft(WORKSPACE_ID, DOCUMENT_ID)).toEqual(legacyDraft);+ });++ it('returns null for an empty legacy draft (nothing worth migrating)', () => {+ window.localStorage.setItem(+ LEGACY_KEY,+ JSON.stringify({ clientId: 'c1', content: '', editorData: null }),+ );++ expect(readLegacyRootDraft(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ });++ it('does not itself clear the legacy key — callers decide when the migrated copy is safe to drop', () => {+ window.localStorage.setItem(LEGACY_KEY, JSON.stringify(legacyDraft));++ readLegacyRootDraft(WORKSPACE_ID, DOCUMENT_ID);++ expect(window.localStorage.getItem(LEGACY_KEY)).not.toBeNull();+ });+});++describe('clearLegacyRootDraft', () => {+ it('removes the legacy root-scope draft', () => {+ window.localStorage.setItem(LEGACY_KEY, JSON.stringify({ clientId: 'c1' }));++ clearLegacyRootDraft(WORKSPACE_ID, DOCUMENT_ID);++ expect(window.localStorage.getItem(LEGACY_KEY)).toBeNull();+ });+});++describe('readUnanchoredDraftFromAnchoredScope', () => {+ const inlineDraft = {+ clientId: 'c1',+ content: 'a plain comment started in AgentDocumentPage',+ editorData: null,+ };++ it('returns null when there is nothing under the anchored scope', () => {+ expect(readUnanchoredDraftFromAnchoredScope(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ });++ it('adopts an unanchored draft left under the anchored scope', () => {+ window.localStorage.setItem(KEY, JSON.stringify(inlineDraft));++ expect(readUnanchoredDraftFromAnchoredScope(WORKSPACE_ID, DOCUMENT_ID)).toEqual(inlineDraft);+ });++ it('leaves a genuinely anchored draft alone — it belongs to the gutter, not the document-level composer', () => {+ window.localStorage.setItem(KEY, JSON.stringify({ ...inlineDraft, selectionAnchor: anchor }));++ expect(readUnanchoredDraftFromAnchoredScope(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ });++ it("returns null once 'root' already has its own content to protect", () => {+ window.localStorage.setItem(KEY, JSON.stringify(inlineDraft));+ window.localStorage.setItem(+ LEGACY_KEY,+ JSON.stringify({ clientId: 'c2', content: 'a fresh root draft', editorData: null }),+ );++ expect(readUnanchoredDraftFromAnchoredScope(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ });++ it('still adopts once root holds only an empty (cancelled or sent) draft', () => {+ window.localStorage.setItem(KEY, JSON.stringify(inlineDraft));+ window.localStorage.setItem(+ LEGACY_KEY,+ JSON.stringify({ clientId: 'c2', content: '', editorData: null }),+ );++ expect(readUnanchoredDraftFromAnchoredScope(WORKSPACE_ID, DOCUMENT_ID)).toEqual(inlineDraft);+ });++ it('returns null for an empty anchored draft (nothing worth adopting)', () => {+ window.localStorage.setItem(+ KEY,+ JSON.stringify({ clientId: 'c1', content: '', editorData: null }),+ );++ expect(readUnanchoredDraftFromAnchoredScope(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ });++ it('does not itself clear the anchored key — callers decide when the adopted copy is safe to drop', () => {+ window.localStorage.setItem(KEY, JSON.stringify(inlineDraft));++ readUnanchoredDraftFromAnchoredScope(WORKSPACE_ID, DOCUMENT_ID);++ expect(window.localStorage.getItem(KEY)).not.toBeNull();+ });+});++describe('clearAnchoredScopeDraft', () => {+ it('removes the anchored-scope draft', () => {+ window.localStorage.setItem(KEY, JSON.stringify({ clientId: 'c1' }));++ clearAnchoredScopeDraft(WORKSPACE_ID, DOCUMENT_ID);++ expect(window.localStorage.getItem(KEY)).toBeNull();+ });+});++describe('preserveFailedAnchoredDraft', () => {+ it('writes the failed draft under its own key, scoped by clientId', () => {+ const failed = {+ clientId: 'failed-1',+ content: 'a comment the reader typed while offline',+ editorData: null,+ selectionAnchor: anchor,+ };++ preserveFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID, failed);++ const raw = window.localStorage.getItem(+ `document-comment-draft:${WORKSPACE_ID}:${DOCUMENT_ID}:anchored-failed:failed-1`,+ );+ expect(raw && JSON.parse(raw)).toEqual(failed);+ });++ it('does not touch the shared anchored slot a newer draft may already own', () => {+ const newerDraft = { clientId: 'newer', content: 'the new draft', editorData: null };+ window.localStorage.setItem(KEY, JSON.stringify(newerDraft));++ preserveFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID, {+ clientId: 'failed-2',+ content: 'the failed draft',+ editorData: null,+ });++ expect(JSON.parse(window.localStorage.getItem(KEY)!)).toEqual(newerDraft);+ });+});++describe('takeFailedAnchoredDraft', () => {+ const FAILED_PREFIX = `document-comment-draft:${WORKSPACE_ID}:${DOCUMENT_ID}:anchored-failed:`;++ it('returns null when nothing was stashed', () => {+ expect(takeFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ });++ it('removes and returns a stashed draft', () => {+ const failed = {+ clientId: 'f1',+ content: 'typed offline',+ editorData: null,+ selectionAnchor: anchor,+ };+ preserveFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID, failed);++ expect(takeFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)).toEqual(failed);+ expect(window.localStorage.getItem(`${FAILED_PREFIX}f1`)).toBeNull();+ });++ it('returns stashes one at a time, in key order', () => {+ preserveFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID, {+ clientId: 'b',+ content: 'second',+ editorData: null,+ selectionAnchor: anchor,+ });+ preserveFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID, {+ clientId: 'a',+ content: 'first',+ editorData: null,+ selectionAnchor: anchor,+ });++ expect(takeFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)?.content).toBe('first');+ expect(takeFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)?.content).toBe('second');+ expect(takeFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ });++ it('drops a stash the gutter could not show (no anchor, no content, malformed) and keeps looking', () => {+ window.localStorage.setItem(`${FAILED_PREFIX}a`, '{not json');+ window.localStorage.setItem(+ `${FAILED_PREFIX}b`,+ JSON.stringify({ clientId: 'b', content: 'no anchor', editorData: null }),+ );+ window.localStorage.setItem(+ `${FAILED_PREFIX}c`,+ JSON.stringify({ clientId: 'c', content: '', editorData: null, selectionAnchor: anchor }),+ );+ const usable = { clientId: 'd', content: 'usable', editorData: null, selectionAnchor: anchor };+ window.localStorage.setItem(`${FAILED_PREFIX}d`, JSON.stringify(usable));++ expect(takeFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)).toEqual(usable);+ expect(window.localStorage.length).toBe(0);+ });++ it("leaves other documents' stashes alone", () => {+ preserveFailedAnchoredDraft(WORKSPACE_ID, 'doc-2', {+ clientId: 'x',+ content: 'elsewhere',+ editorData: null,+ selectionAnchor: anchor,+ });++ expect(takeFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ expect(window.localStorage.length).toBe(1);+ });+});++describe('restoreFailedAnchoredDraft', () => {+ const failed = {+ clientId: 'f1',+ content: 'typed offline',+ editorData: null,+ selectionAnchor: anchor,+ };++ it('returns null and keeps the stash while the shared slot has content of its own', () => {+ preserveFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID, failed);+ const newer = { clientId: 'n1', content: 'the newer draft', editorData: null };+ window.localStorage.setItem(KEY, JSON.stringify(newer));++ expect(restoreFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ expect(JSON.parse(window.localStorage.getItem(KEY)!)).toEqual(newer);+ expect(takeFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)).toEqual(failed);+ });++ it('keeps the stash while the slot holds an anchor-only draft (a fresh pick not yet typed into)', () => {+ preserveFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID, failed);+ window.localStorage.setItem(+ KEY,+ JSON.stringify({ clientId: 'n1', content: '', editorData: null, selectionAnchor: anchor }),+ );++ expect(restoreFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ });++ it('moves the stash into the slot once it is free and returns it', () => {+ preserveFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID, failed);++ expect(restoreFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)).toEqual(failed);+ expect(JSON.parse(window.localStorage.getItem(KEY)!)).toEqual(failed);+ expect(readAnchoredDraftAnchor(WORKSPACE_ID, DOCUMENT_ID)).toEqual(anchor);+ expect(takeFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ });++ it('treats the empty-but-present record submit and cancel leave behind as a free slot', () => {+ preserveFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID, failed);+ window.localStorage.setItem(+ KEY,+ JSON.stringify({ clientId: 'sent', content: '', editorData: null }),+ );++ expect(restoreFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)).toEqual(failed);+ });++ it('returns null when nothing is stashed, leaving a free slot untouched', () => {+ expect(restoreFailedAnchoredDraft(WORKSPACE_ID, DOCUMENT_ID)).toBeNull();+ expect(window.localStorage.getItem(KEY)).toBeNull();+ });+});diff --git a/src/features/PageEditor/DocumentComments/styles.ts b/src/features/PageEditor/DocumentComments/styles.tsindex 23f6cde723b..4c3526677a8 100644--- a/src/features/PageEditor/DocumentComments/styles.ts+++ b/src/features/PageEditor/DocumentComments/styles.ts@@ -1,5 +1,7 @@import { createStaticStyles, cssVar } from 'antd-style';+import { GUTTER_INSET_END, GUTTER_INSET_START } from './Gutter/constants';+/** Max rendered height of an image inside the comment composer / edit box. */export const COMMENT_EDITOR_IMAGE_MAX_HEIGHT = 400;/** Max rendered height of an image inside a published comment. */@@ -33,6 +35,10 @@ export const styles = createStaticStyles(({ css }) => ({padding-block-start: 8px;color: ${cssVar.colorTextTertiary};`,+ actionsCompact: css`+ margin-inline-start: 0;+ padding-block-start: 4px;+ `,/*** The quoted run a comment is attached to. Shared by the card and the* composer; each host adds its own framing, because what marks the text as@@ -75,11 +81,39 @@ export const styles = createStaticStyles(({ css }) => ({min-width: 0;color: inherit;`,+ /**+ * The margin marker: sits in the body's right margin at the height of the+ * block under the pointer. Hidden until hover, so a reading column stays+ * clean; the gutter beside it is where the marker's comment will land.+ */+ blockMarker: css`+ position: absolute;+ z-index: 1;++ /*+ * A physical transform (translateX) can't flip with direction, so+ * "just past the inline-end edge" is expressed purely with insets+ * instead of inset-inline-end + translateX(100%): pinning the+ * inline-start edge at 100% of the container's width places the box+ * flush against, and extending from, the inline-end edge either way.+ */+ inset-inline-start: 100%;++ padding-inline-start: 4px;++ color: ${cssVar.colorTextTertiary};+ `,body: css`margin-inline-start: 40px;padding-block-start: 8px;line-height: 1.7;`,+ bodyCompact: css`+ margin-inline-start: 0;+ padding-block-start: 6px;+ font-size: 14px;+ line-height: 1.6;+ `,card: css`margin-inline: -12px;padding-block: 20px 12px;@@ -104,6 +138,21 @@ export const styles = createStaticStyles(({ css }) => ({padding-inline-start: 10px;border-inline-start: 2px solid ${cssVar.colorBorder};`,+ /**+ * In the gutter the quote is the card's heading: it names the run the card+ * sits beside, so it goes above the author rather than under it.+ */+ cardAnchorCompact: css`+ margin-block-end: 8px;+ padding-block: 2px;+ padding-inline-start: 8px;+ border-inline-start: 2px solid ${cssVar.colorBorder};+ `,+ /** A card in the gutter: the surface around it is the card, so the card itself is flush. */+ cardCompact: css`+ margin-inline: 0;+ padding: 0;+ `,commentContent: css`/* Published comments render images as left-aligned thumbnails: therenderer inlines the stored (natural) width, which would otherwise span@@ -181,6 +230,13 @@ export const styles = createStaticStyles(({ css }) => ({max-height: ${COMMENT_EDITOR_IMAGE_MAX_HEIGHT}px;}`,+ /**+ * Beside the text the box is narrow and the caret should start where the+ * action bar's first icon starts: ChatInput's own 12px is the whole inset.+ */+ commentEditorFlush: css`+ padding-inline: 0;+ `,composer: css`min-width: 0;transition:@@ -207,6 +263,10 @@ export const styles = createStaticStyles(({ css }) => ({padding-inline: 28px 12px;border-block-end: 1px solid ${cssVar.colorBorderSecondary};`,+ /** The box beside the text: a quiet input, no focus ring — the card around it is the frame. */+ composerPlain: css`+ min-width: 0;+ `,composerAvatar: css`flex: none;align-self: flex-start;@@ -215,6 +275,72 @@ export const styles = createStaticStyles(({ css }) => ({font-style: italic;color: ${cssVar.colorTextTertiary};`,+ /**+ * The comments panel body. It clips a track that mirrors the document's+ * scroll position (see `useGutterLayout`), so cards placed in document+ * coordinates appear beside the text they quote.+ */+ gutter: css`+ position: relative;+ overflow: hidden;+ flex: 1;+ min-height: 0;+ `,+ gutterCard: css`+ cursor: default;++ position: absolute;+ inset-inline: ${GUTTER_INSET_START}px ${GUTTER_INSET_END}px;++ padding-block: 10px;+ padding-inline: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ /* Unmeasured cards wait off-screen at the top rather than flashing at 0. */+ visibility: hidden;+ background: ${cssVar.colorBgElevated};+ `,+ /**+ * The card holding the composer is lifted by a shadow instead of framed:+ * the input draws its own frame, and a border around it would read as a+ * box inside a box. Published cards are framed, not lifted.+ */+ gutterCardComposer: css`+ border-color: transparent;+ box-shadow: ${cssVar.boxShadowSecondary};+ `,+ /**+ * The picked card lifts off the column with the same shadow as the composer+ * card, so the two states the reader is acting on read alike, and wins the+ * stacking order so the lift is not cut by its neighbours.+ */+ gutterCardActive: css`+ z-index: 1;+ box-shadow: ${cssVar.boxShadowSecondary};+ `,+ /** Cards glide to a new stack position and ease into the lift; the first placement is instant. */+ gutterCardPositioned: css`+ visibility: visible;+ transition:+ inset-block-start ${cssVar.motionDurationMid} ${cssVar.motionEaseOut},+ box-shadow ${cssVar.motionDurationMid} ${cssVar.motionEaseOut};++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+ `,+ gutterEmpty: css`+ height: 100%;+ padding: 24px;+ `,+ /** Rides along with the document: translated by the body's scroll offset. */+ gutterTrack: css`+ position: absolute;+ inset-block-start: 0;+ inset-inline: 0;+ height: 0;+ `,editComposer: css`min-width: 0;@@ -226,6 +352,10 @@ export const styles = createStaticStyles(({ css }) => ({header: css`min-height: 32px;`,+ /** A narrow card stacks name over time beside the avatar. */+ headerCompact: css`+ min-height: 28px;+ `,/* Applied briefly when a notification deep link lands on the card. */highlighted: css`background-color: ${cssVar.colorPrimaryBg};@@ -247,6 +377,13 @@ export const styles = createStaticStyles(({ css }) => ({padding-block: 4px;padding-inline-start: 16px;`,+ /** Replies in a panel card list flat under the root, separated by rhythm alone. */+ replyListCompact: css`+ margin-block-start: 4px;+ margin-inline-start: 0;+ padding-inline-start: 0;+ border-inline-start: 0;+ `,replyTargetIcon: css`flex: none;color: ${cssVar.colorTextQuaternary};@@ -270,6 +407,11 @@ export const styles = createStaticStyles(({ css }) => ({border-block-end: 0;}`,+ threadCompact: css`+ gap: 4px;+ padding-block-end: 0;+ border-block-end: 0;+ `,threadList: css`gap: 8px;`,diff --git a/src/features/PageEditor/DocumentComments/useDocumentCommentsState.ts b/src/features/PageEditor/DocumentComments/useDocumentCommentsState.tsnew file mode 100644index 00000000000..9f8321782d5--- /dev/null+++ b/src/features/PageEditor/DocumentComments/useDocumentCommentsState.ts@@ -0,0 +1,400 @@+'use client';++import type {+ DocumentCommentAnchorItem,+ DocumentCommentThread,+ DocumentCommentThreadPage,+} from '@lobechat/types';+import { toast } from '@lobehub/ui/base-ui';+import { type RefObject, useCallback, useEffect, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { documentCommentService } from '@/services/documentComment';++import { useDocumentCommentAnchors } from './anchor/useDocumentCommentAnchors';+import {+ ANCHORED_EAGER_PAGE_LIMIT,+ useDocumentCommentAnchorList,+ useDocumentCommentDetail,+ useDocumentCommentSummary,+ useDocumentCommentThreads,+ useOptimisticDocumentComment,+} from './hooks';+import type { DocumentCommentSubmitInput, DocumentCommentUpdateHandler } from './optimistic';+import {+ appendOptimisticThread,+ removeOptimisticThread,+ replaceOptimisticThread,+ replaceThreadComment,+ updateThreadReplyCount,+} from './optimistic';+import {+ type DocumentCommentFocusMissReason,+ useDocumentCommentDeepLink,+} from './useDocumentCommentDeepLink';++type PageMutator = (+ pages: DocumentCommentThreadPage[] | undefined,+) => DocumentCommentThreadPage[] | undefined;++export interface DocumentCommentsStateOptions {+ documentId: string;+ /**+ * Whether anchored threads render in the comments panel beside the text.+ * While the panel is closed or showing something else, they fall back to+ * the list below the body.+ */+ gutterEnabled: boolean;+ /** Whether a comments panel can exist at all (the editor renders its own right panel). */+ panelAvailable: boolean;+ /** The body's scroll container; the panel's cards follow its scroll. */+ paneRef: RefObject<HTMLElement | null>;+}++/**+ * Everything the two comment surfaces share: the paged thread caches, the+ * optimistic write-through handlers, the deep-link landing and the anchor+ * resolution. Anchored roots and document-level roots are paged separately+ * (see `listThreads`' `anchored` filter) because they render in different+ * places; a write goes to whichever cache the comment belongs in, and a patch+ * that could apply to either is applied to both.+ */+export const useDocumentCommentsState = ({+ documentId,+ gutterEnabled,+ paneRef,+ panelAvailable,+}: DocumentCommentsStateOptions) => {+ const { t } = useTranslation('file');+ const workspaceId = useActiveWorkspaceId();+ const enabledDocumentId = workspaceId ? documentId : undefined;+ const summary = useDocumentCommentSummary(enabledDocumentId);+ // Anchored threads are fetched ahead of demand only while the gutter shows+ // them, and only up to a budget; a closed panel paints its highlights from+ // the anchor list alone and fetches a picked thread on demand.+ const anchoredThreads = useDocumentCommentThreads(enabledDocumentId, 'anchored', {+ eagerPageLimit: gutterEnabled ? ANCHORED_EAGER_PAGE_LIMIT : 0,+ });+ const documentThreads = useDocumentCommentThreads(enabledDocumentId, 'document');+ const anchorList = useDocumentCommentAnchorList(enabledDocumentId);+ const createOptimistic = useOptimisticDocumentComment();+ const { clearFocus, focus, focusRoot, focusThread } = useDocumentCommentDeepLink(documentId);+ const reloadSummary = summary.mutate;+ const reloadAnchored = anchoredThreads.reload;+ const reloadDocument = documentThreads.reload;+ const mutateAnchored = anchoredThreads.mutate;+ const mutateDocument = documentThreads.mutate;+ const mutateAnchors = anchorList.mutate;++ const mutateBoth = useCallback(+ (mutator: PageMutator) =>+ Promise.all([+ mutateAnchored(mutator, { revalidate: false }),+ mutateDocument(mutator, { revalidate: false }),+ ]),+ [mutateAnchored, mutateDocument],+ );+ const reloadThreads = useCallback(+ () => Promise.all([reloadAnchored(), reloadDocument()]),+ [reloadAnchored, reloadDocument],+ );+ const refresh = useCallback(async () => {+ await Promise.all([reloadThreads(), reloadSummary(), mutateAnchors()]);+ }, [mutateAnchors, reloadSummary, reloadThreads]);+ const updateSummaryTotal = useCallback(+ (delta: number) =>+ reloadSummary(+ (current) =>+ current ? { ...current, total: Math.max(0, current.total + delta) } : current,+ { revalidate: false },+ ),+ [reloadSummary],+ );+ const updateReplyCount = useCallback(+ (rootCommentId: string, delta: number) =>+ mutateBoth((pages) => updateThreadReplyCount(pages, rootCommentId, delta)),+ [mutateBoth],+ );+ const handleCreate = useCallback(+ async ({ clientId, content, editorData, selectionAnchor }: DocumentCommentSubmitInput) => {+ // A root lives in exactly one of the two caches, decided by its anchor.+ const mutateOwn = selectionAnchor ? mutateAnchored : mutateDocument;+ const reloadOwn = selectionAnchor ? reloadAnchored : reloadDocument;+ const optimisticComment = createOptimistic({+ clientId,+ content,+ documentId,+ editorData,+ selectionAnchor,+ });+ await Promise.all([+ mutateOwn((pages) => appendOptimisticThread(pages, optimisticComment), {+ revalidate: false,+ }),+ updateSummaryTotal(1),+ ]);++ let created: Awaited<ReturnType<typeof documentCommentService.create>>;+ try {+ created = await documentCommentService.create({+ clientId,+ content,+ documentId,+ editorData,+ selectionAnchor,+ });+ if (!created) throw new Error('Document comment creation returned no result');+ } catch (error) {+ await Promise.all([+ mutateOwn((pages) => removeOptimisticThread(pages, clientId), { revalidate: false }),+ updateSummaryTotal(-1),+ ]);+ throw error;+ }++ try {+ await mutateOwn((pages) => replaceOptimisticThread(pages, created.comment), {+ revalidate: false,+ });+ } catch (error) {+ console.error('Failed to reconcile the created document comment', error);+ void reloadOwn();+ }+ if (created.isDuplicate) void reloadSummary();+ // The body paints from the document-wide anchor list, so the new root+ // joins it here rather than waiting for the next revalidation.+ const createdAnchor = created.comment.selectionAnchor;+ if (createdAnchor) {+ void mutateAnchors(+ (current) =>+ current && !current.items.some(({ id }) => id === created.comment.id)+ ? {+ items: [+ ...current.items,+ { id: created.comment.id, selectionAnchor: createdAnchor },+ ],+ }+ : current,+ { revalidate: false },+ );+ }+ },+ [+ createOptimistic,+ documentId,+ mutateAnchored,+ mutateAnchors,+ mutateDocument,+ reloadAnchored,+ reloadDocument,+ reloadSummary,+ updateSummaryTotal,+ ],+ );+ const handleUpdate: DocumentCommentUpdateHandler = useCallback(+ async (comment, value) => {+ const optimisticComment = { ...comment, ...value, updatedAt: new Date() };+ await mutateBoth((pages) => replaceThreadComment(pages, optimisticComment));++ let updated: Awaited<ReturnType<typeof documentCommentService.update>>;+ try {+ updated = await documentCommentService.update({ ...value, id: comment.id });+ if (!updated) throw new Error('Document comment update returned no result');+ } catch (error) {+ await mutateBoth((pages) => replaceThreadComment(pages, comment));+ throw error;+ }++ try {+ await mutateBoth((pages) => replaceThreadComment(pages, updated));+ } catch (error) {+ console.error('Failed to reconcile the updated document comment', error);+ void reloadThreads();+ }+ },+ [mutateBoth, reloadThreads],+ );++ // 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) &&+ (anchoredThreads.items.some(({ root }) => root.id === focusRootCommentId) ||+ documentThreads.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 = useMemo<DocumentCommentThread | undefined>(+ () =>+ focus && !hasFocusedThread && focusedRootData && isFocusedRootUsable+ ? { replyCount: focusedRootData.replyCount, root: focusedRootData }+ : undefined,+ [focus, focusedRootData, hasFocusedThread, isFocusedRootUsable],+ );+ // Highlights come from the document-wide anchor list so every anchored run+ // is discoverable from the body, however far down the list its card sits.+ // Loaded pages and the pinned thread are folded in on top: an optimistic+ // root has no server row yet, and a pinned root may predate the last fetch.+ const anchorItems = useMemo(() => {+ const byId = new Map<string, DocumentCommentAnchorItem>();+ for (const { id, selectionAnchor } of anchorList.data?.items ?? []) {+ byId.set(id, { id, selectionAnchor });+ }+ const loaded = pinnedThread ? [pinnedThread, ...anchoredThreads.items] : anchoredThreads.items;+ for (const { root } of loaded) {+ if (root.selectionAnchor && !byId.has(root.id)) {+ byId.set(root.id, { id: root.id, selectionAnchor: root.selectionAnchor });+ }+ }+ return [...byId.values()];+ }, [anchorList.data, pinnedThread, anchoredThreads.items]);+ const anchors = useDocumentCommentAnchors(anchorItems, {+ hasGutter: panelAvailable,+ onPickUnloaded: focusThread,+ });+ const { orphanedRootIds } = anchors;++ 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],+ );++ /** A thread belongs in the gutter when it has a run to sit beside. */+ const isGutterThread = useCallback(+ ({ root }: DocumentCommentThread) =>+ gutterEnabled && Boolean(root.selectionAnchor) && !orphanedRootIds.has(root.id),+ [gutterEnabled, orphanedRootIds],+ );+ const gutterThreads = useMemo(+ () => anchoredThreads.items.filter((thread) => isGutterThread(thread)),+ [anchoredThreads.items, isGutterThread],+ );+ // The list below the body is the document's complete record — anchored+ // roots included, each with its quote — while the panel beside the text+ // is the in-context view of the anchored subset. Its header counts every+ // comment, so it lists every comment.+ const listThreads = useMemo(() => {+ if (anchoredThreads.items.length === 0) return documentThreads.items;+ return [...documentThreads.items, ...anchoredThreads.items].sort(+ (left, right) =>+ new Date(left.root.createdAt).getTime() - new Date(right.root.createdAt).getTime(),+ );+ }, [anchoredThreads.items, documentThreads.items]);+ const pinnedInGutter = Boolean(pinnedThread) && isGutterThread(pinnedThread!);+ // The list below the body pages both caches together: anchored roots past+ // the gutter's eager budget (or all of them while the panel is closed)+ // are only reachable through it.+ const hasMoreListThreads = documentThreads.hasMore || anchoredThreads.hasMore;+ const isLoadingMoreListThreads = documentThreads.isLoadingMore || anchoredThreads.isLoadingMore;+ const loadMoreAnchored = anchoredThreads.loadMore;+ const loadMoreDocument = documentThreads.loadMore;+ const loadMoreListThreads = useCallback(+ () =>+ Promise.all([+ documentThreads.hasMore ? loadMoreDocument() : undefined,+ anchoredThreads.hasMore ? loadMoreAnchored() : undefined,+ ]),+ [anchoredThreads.hasMore, documentThreads.hasMore, loadMoreAnchored, loadMoreDocument],+ );++ return {+ anchoredError: anchoredThreads.error,+ anchors,+ documentId,+ documentThreads,+ focus,+ gutterEnabled,+ gutterThreads,+ handleCreate,+ handlePinnedRootUpdate,+ handleReplyFocusMissing,+ handleUpdate,+ hasMoreListThreads,+ isAnchoredInitialError: anchoredThreads.isInitialError,+ isAnchoredLoading: anchoredThreads.isLoadingInitial,+ isAnchoredRetrying: anchoredThreads.isRetrying,+ isLoadingMoreListThreads,+ listThreads,+ loadMoreListThreads,+ paneRef,+ panelAvailable,+ pinnedThread,+ pinnedThreadInGutter: pinnedInGutter ? pinnedThread : undefined,+ pinnedThreadInList: pinnedThread,+ refresh,+ refreshPinned,+ reloadAnchored,+ summary,+ updatePinnedReplyCount,+ updateReplyCount,+ updateSummaryTotal,+ workspaceId,+ };+};++export type DocumentCommentsState = ReturnType<typeof useDocumentCommentsState>;diff --git a/src/features/PageEditor/DocumentComments/useGutterComposerFocus.test.ts b/src/features/PageEditor/DocumentComments/useGutterComposerFocus.test.tsnew file mode 100644index 00000000000..657bff7cb46--- /dev/null+++ b/src/features/PageEditor/DocumentComments/useGutterComposerFocus.test.ts@@ -0,0 +1,166 @@+import { renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useGutterComposerFocus } from './useGutterComposerFocus';++/** A caret inside the box, the way a browser places one when a contenteditable takes focus. */+const placeCaret = (input: HTMLElement) => {+ const range = document.createRange();+ range.setStart(input, 0);+ range.collapse(true);+ const selection = document.getSelection();+ selection?.removeAllRanges();+ selection?.addRange(range);+};++const mount = () => {+ const root = document.createElement('div');+ const input = document.createElement('div');+ input.setAttribute('contenteditable', 'true');+ input.tabIndex = 0;+ root.append(input);+ document.body.append(root);+ const nativeFocus = HTMLElement.prototype.focus;+ const focus = vi.spyOn(input, 'focus').mockImplementation(function (this: HTMLElement) {+ nativeFocus.call(this);+ placeCaret(input);+ });+ return { focus, input, root };+};++const caretIn = (root: HTMLElement) =>+ root.contains(document.activeElement) &&+ root.contains(document.getSelection()?.anchorNode ?? null);++describe('useGutterComposerFocus', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => {+ vi.useRealTimers();+ document.getSelection()?.removeAllRanges();+ document.body.innerHTML = '';+ });++ it('does not try to focus a card that is not positioned yet', () => {+ const { focus, root } = mount();+ const editorFocus = vi.fn();++ renderHook(() =>+ useGutterComposerFocus({+ editorRef: { current: { focus: editorFocus } },+ pick: 1,+ ready: false,+ rootRef: { current: root },+ }),+ );+ vi.advanceTimersByTime(2000);++ expect(focus).not.toHaveBeenCalled();+ expect(editorFocus).not.toHaveBeenCalled();+ });++ it('focuses once the card is positioned, however late that is', () => {+ const { focus, root } = mount();+ const editorFocus = vi.fn();++ const { rerender } = renderHook(+ ({ ready }) =>+ useGutterComposerFocus({+ editorRef: { current: { focus: editorFocus } },+ pick: 1,+ ready,+ rootRef: { current: root },+ }),+ { initialProps: { ready: false } },+ );+ vi.advanceTimersByTime(5000);+ rerender({ ready: true });+ vi.advanceTimersByTime(0);++ expect(focus).toHaveBeenCalled();+ expect(editorFocus).toHaveBeenCalled();+ expect(caretIn(root)).toBe(true);+ });++ it('retries until the focus sticks', () => {+ const { focus, input, root } = mount();+ // Something else keeps taking the focus back for a while.+ const stealer = document.createElement('button');+ document.body.append(stealer);+ let steals = 3;+ focus.mockImplementation(() => {+ if (steals-- > 0) {+ stealer.focus();+ } else {+ HTMLElement.prototype.focus.call(input);+ placeCaret(input);+ }+ });++ renderHook(() =>+ useGutterComposerFocus({+ editorRef: { current: null },+ pick: 1,+ ready: true,+ rootRef: { current: root },+ }),+ );+ vi.advanceTimersByTime(500);++ expect(focus).toHaveBeenCalledTimes(4);+ expect(caretIn(root)).toBe(true);+ vi.advanceTimersByTime(1000);+ expect(focus).toHaveBeenCalledTimes(4);+ });++ it('rebuilds the caret when the box is focused but holds no selection', () => {+ const { focus, input, root } = mount();+ // The box already has DOM focus (its editor auto-focused on mount), but+ // the body's blur wiped every DOM range, so there is no caret to type at.+ HTMLElement.prototype.focus.call(input);+ document.getSelection()?.removeAllRanges();+ expect(document.activeElement).toBe(input);+ const editorFocus = vi.fn(() => placeCaret(input));++ renderHook(() =>+ useGutterComposerFocus({+ editorRef: { current: { focus: editorFocus } },+ pick: 1,+ ready: true,+ rootRef: { current: root },+ }),+ );+ vi.advanceTimersByTime(0);++ expect(editorFocus).toHaveBeenCalledTimes(1);+ expect(caretIn(root)).toBe(true);+ // The DOM focus is left alone: re-focusing an active box is a no-op at+ // best and a scroll jump at worst.+ expect(focus).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1000);+ expect(editorFocus).toHaveBeenCalledTimes(1);+ });++ it('brings the caret back for a repeated pick of the same run', () => {+ const { focus, input, root } = mount();++ const { rerender } = renderHook(+ ({ pick }) =>+ useGutterComposerFocus({+ editorRef: { current: null },+ pick,+ ready: true,+ rootRef: { current: root },+ }),+ { initialProps: { pick: 1 } },+ );+ vi.advanceTimersByTime(0);+ expect(focus).toHaveBeenCalledTimes(1);++ input.blur();+ document.getSelection()?.removeAllRanges();+ rerender({ pick: 2 });+ vi.advanceTimersByTime(0);+ expect(focus).toHaveBeenCalledTimes(2);+ expect(caretIn(root)).toBe(true);+ });+});diff --git a/src/features/PageEditor/DocumentComments/useGutterComposerFocus.ts b/src/features/PageEditor/DocumentComments/useGutterComposerFocus.tsnew file mode 100644index 00000000000..75b5030917b--- /dev/null+++ b/src/features/PageEditor/DocumentComments/useGutterComposerFocus.ts@@ -0,0 +1,76 @@+import type { RefObject } from 'react';+import { useEffect } from 'react';++/** How long the right panel takes to slide in; see `panelSlideMotionVariantsLeft`. */+const PANEL_SETTLE_DELAY = 350;+const RETRY_INTERVAL = 50;++interface GutterComposerFocusParams {+ editorRef: RefObject<{ focus: () => void } | null>;+ /**+ * The pick counter, `0` while the composer has nothing to focus for. Keyed+ * on the counter, not on "has an anchor": the store compares selected+ * values by content, so picking the same run again while the box is still+ * open looks like no change — yet that pick wants the caret back just as+ * the first one did.+ */+ pick: number;+ /**+ * Whether the card can take focus at all. The gutter keeps an unmeasured+ * card `visibility: hidden` until its position is known, and a hidden+ * element silently refuses focus, so trying before this is true is wasted.+ */+ ready: boolean;+ rootRef: RefObject<HTMLElement | null>;+}++/**+ * A caret the reader can type at: the box holds the focus *and* the DOM+ * selection sits inside it. Focus alone is not enough — the body editor's+ * blur clears every DOM range, and a focused box with no range shows no+ * caret and swallows keystrokes.+ */+const hasCaret = (root: HTMLElement) => {+ if (!root.contains(document.activeElement)) return false;+ const anchor = document.getSelection()?.anchorNode ?? null;+ return anchor !== null && root.contains(anchor);+};++/**+ * Put the caret in the gutter composer for a fresh selection.+ *+ * The box shows up while several things are still moving: the body editor is+ * being blurred by the toolbar and refocused by the column's click handler,+ * the panel may still be sliding in, and the card only becomes visible once+ * the gutter has measured where it goes. A single focus call lands in the+ * middle of that, so the attempt waits for the card to be positioned and is+ * then retried until a caret is there or the panel has long since settled.+ */+export const useGutterComposerFocus = ({+ editorRef,+ pick,+ ready,+ rootRef,+}: GutterComposerFocusParams) => {+ useEffect(() => {+ if (!pick || !ready) return;+ const started = Date.now();+ let timer: ReturnType<typeof setTimeout> | undefined;+ const attempt = () => {+ const root = rootRef.current;+ if (!root || hasCaret(root)) return;+ // The DOM focus first, so the editor's own focus finds its root+ // active; the editor's focus then rebuilds the selection at the end+ // of its content, which is what actually paints the caret.+ if (!root.contains(document.activeElement)) {+ root.querySelector<HTMLElement>('[contenteditable="true"]')?.focus({ preventScroll: true });+ }+ editorRef.current?.focus();+ if (hasCaret(root)) return;+ if (Date.now() - started < PANEL_SETTLE_DELAY * 2)+ timer = setTimeout(attempt, RETRY_INTERVAL);+ };+ timer = setTimeout(attempt, 0);+ return () => clearTimeout(timer);+ }, [editorRef, pick, ready, rootRef]);+};diff --git a/src/features/PageEditor/EditorCanvas/useAddCommentItem.tsx b/src/features/PageEditor/EditorCanvas/useAddCommentItem.tsxindex c85c3304564..ed6ece6756a 100644--- a/src/features/PageEditor/EditorCanvas/useAddCommentItem.tsx+++ b/src/features/PageEditor/EditorCanvas/useAddCommentItem.tsx@@ -10,8 +10,6 @@ import { MessageSquarePlus } from 'lucide-react';import { useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';-import { prefersReducedMotion } from '@/features/PageEditor/DocumentComments/anchor/commentLocator';-import { DOCUMENT_COMMENT_COMPOSER_ID } from '@/features/PageEditor/DocumentComments/anchor/constants';import { captureSelectionAnchor } from '@/features/PageEditor/DocumentComments/anchor/textAnchor';import { usePermission } from '@/hooks/usePermission';@@ -75,23 +73,12 @@ export const useAddCommentItem = (capturedAnchorRef.current = null;if (!anchor) return;+ // The composer answers the selection itself: beside the run in+ // the gutter, or scrolled into view below the body on a narrow+ // pane (see `Composer`'s anchor modes).setPendingCommentAnchor({ anchor, documentId });editor.dispatchCommand(HIDE_TOOLBAR_COMMAND, undefined);editor.blur();-- // The composer lives below the body, so it has to be brought into- // view before it can be typed into. One frame of delay lets the- // quote row render first, so the scroll lands on its real height.- requestAnimationFrame(() => {- const composer = document.getElementById(DOCUMENT_COMMENT_COMPOSER_ID);- composer?.scrollIntoView({- behavior: prefersReducedMotion() ? 'auto' : 'smooth',- block: 'center',- });- composer- ?.querySelector<HTMLElement>('[contenteditable="true"]')- ?.focus({ preventScroll: true });- });}}onMouseDown={(event) => {event.preventDefault();diff --git a/src/features/PageEditor/Header/index.tsx b/src/features/PageEditor/Header/index.tsxindex 90849c83c93..51e6ed671b2 100644--- a/src/features/PageEditor/Header/index.tsx+++ b/src/features/PageEditor/Header/index.tsx@@ -1,8 +1,9 @@'use client';-import { DropdownMenu } from '@lobehub/ui';+import { DropdownMenu, Flexbox } from '@lobehub/ui';import { ActionIcon, Avatar, Text } from '@lobehub/ui/base-ui';-import { ArrowLeftIcon, MoreHorizontal } from 'lucide-react';+import { createStaticStyles, cssVar } from 'antd-style';+import { ArrowLeftIcon, MessageSquareTextIcon, MoreHorizontal, SparklesIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -13,12 +14,22 @@ import NavHeader from '@/features/NavHeader';import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';import { usePermission } from '@/hooks/usePermission';+import { useDocumentComments } from '../DocumentComments/context';import EditingIndicator from '../EditingIndicator';import { usePageAgentPanelControl } from '../RightPanel/OverrideContext';import { selectors, usePageEditorStore } from '../store';import Breadcrumb from './Breadcrumb';import { useMenu } from './useMenu';+const styles = createStaticStyles(({ css }) => ({+ /** The two sidebars share one segmented switch; the lit segment is the open one. */+ panelSwitch: css`+ padding: 2px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};+ `,+}));+const Header = memo(() => {const { t } = useTranslation('file');const [documentId, emoji, title, parentId, onBack] = usePageEditorStore((s) => [@@ -37,6 +48,13 @@ const Header = memo(() => {// to everyone. Without this guard the button toggles the store, then disappears// via `hideWhenExpanded` while the panel refuses to open — a no-op control.const canExpandRightPanel = hasEditPermission || rightPanelMode === 'history';+ // Comments exist only for workspace documents with a comments panel to show+ // them in; the provider is absent otherwise.+ const comments = useDocumentComments();+ const [isCommentsPanelOpen, setCommentsPanelOpen] = usePageEditorStore((s) => [+ s.commentsPanelOpen,+ s.setCommentsPanelOpen,+ ]);return (<NavHeader@@ -76,13 +94,36 @@ const Header = memo(() => {><ActionIcon icon={MoreHorizontal} size={DESKTOP_HEADER_ICON_SMALL_SIZE} /></DropdownMenu>- {canExpandRightPanel && (- <ToggleRightPanelButton- hideWhenExpanded- expand={showPageAgentPanel}- showActive={false}- onToggle={() => togglePageAgentPanel()}- />+ {(comments?.panelAvailable || canExpandRightPanel) && (+ // The framed segment control only earns its frame with two+ // segments; a lone toggle (a personal page has no comments, a+ // viewer has no copilot) stays a plain icon.+ <Flexbox+ horizontal+ gap={2}+ className={+ comments?.panelAvailable && canExpandRightPanel ? styles.panelSwitch : undefined+ }+ >+ {comments?.panelAvailable && (+ <ActionIcon+ active={isCommentsPanelOpen}+ icon={MessageSquareTextIcon}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ title={t('pageEditor.comments.toggle')}+ onClick={() => setCommentsPanelOpen(!isCommentsPanelOpen)}+ />+ )}+ {canExpandRightPanel && (+ <ToggleRightPanelButton+ showActive+ expand={showPageAgentPanel}+ icon={SparklesIcon}+ title={t('pageEditor.copilot.toggle')}+ onToggle={() => togglePageAgentPanel()}+ />+ )}+ </Flexbox>)}</>}diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsxindex 12f549b59a9..cba4083f350 100644--- a/src/features/PageEditor/PageEditor.tsx+++ b/src/features/PageEditor/PageEditor.tsx@@ -19,6 +19,10 @@ import { usePageStore } from '@/store/page';import { StyleSheet } from '@/utils/styles';import DocumentComments from './DocumentComments';+import BlockCommentMarker from './DocumentComments/BlockCommentMarker';+import { DocumentCommentsProvider } from './DocumentComments/context';+import DocumentCommentsPanel from './DocumentComments/Gutter';+import { GUTTER_COLUMN_ATTRIBUTE } from './DocumentComments/Gutter/useGutterLayout';import DocumentLikes from './DocumentLikes';import EditorCanvas from './EditorCanvas';import Header from './Header';@@ -170,6 +174,7 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {const lastEditorScrollTopRef = useRef(0);const editorPaneRef = useRef<HTMLDivElement>(null);const contentWrapperRef = useRef<HTMLDivElement>(null);+ const editorContentRef = useRef<HTMLDivElement>(null);const isUserInteractingWithEditor = useCallback(() => {if (isPointerInsideEditorPaneRef.current) return true;@@ -307,7 +312,13 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {editor?.focus();}}>- <Flexbox className={overrideStyles.editorContent} flex={1} style={editorContentStyle}>+ <Flexbox+ className={overrideStyles.editorContent}+ flex={1}+ ref={editorContentRef}+ style={editorContentStyle}+ {...{ [GUTTER_COLUMN_ATTRIBUTE]: true }}+ ><TitleSection /><PageMetaBar />{/* Surfaces local heartbeat health (unstable/lost) for the holder.@@ -317,8 +328,9 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {compact status badge lives in the Header (EditingIndicator). */}<LockedAlert /><EditorCanvas askCopilotTarget={askCopilotTarget} />+ <BlockCommentMarker hostRef={editorContentRef} />{documentId && <DocumentLikes documentId={documentId} key={documentId} />}- {documentId && <DocumentComments documentId={documentId} />}+ <DocumentComments /></Flexbox></WideScreenContainer></Flexbox>@@ -326,19 +338,33 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {</Flexbox>);+ // Comment state is hosted above every surface that reads it: the header's+ // toggle, the list below the body and the panel beside it share one set of+ // caches, and the panel's cards follow the body pane's scroll.+ const withComments = (node: ReactNode) => (+ <DocumentCommentsProvider+ documentId={documentId}+ paneRef={contentWrapperRef}+ panelAvailable={showRightPanel}+ >+ {node}+ </DocumentCommentsProvider>+ );+if (fullWidthHeader) {- return (+ return withComments(<Flexbox height={'100%'} style={{ backgroundColor: cssVar.colorBgContainer }} width={'100%'}>{headerSlot}<Flexbox horizontal flex={1} style={{ minHeight: 0 }} width={'100%'}>{editorPane}+ {showRightPanel && <DocumentCommentsPanel />}{showRightPanel && <RightPanel />}</Flexbox>- </Flexbox>+ </Flexbox>,);}- return (+ return withComments(<Flexboxhorizontalheight={'100%'}@@ -346,8 +372,9 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {width={'100%'}>{editorPane}+ {showRightPanel && <DocumentCommentsPanel />}{showRightPanel && <RightPanel />}- </Flexbox>+ </Flexbox>,);});diff --git a/src/features/PageEditor/StoreUpdater.tsx b/src/features/PageEditor/StoreUpdater.tsxindex bdffaff5d9e..d4cc201dee4 100644--- a/src/features/PageEditor/StoreUpdater.tsx+++ b/src/features/PageEditor/StoreUpdater.tsx@@ -47,6 +47,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(const editor = usePageEditorStore((s) => s.editor);const initMeta = usePageEditorStore((s) => s.initMeta);+ const setDocumentId = usePageEditorStore((s) => s.setDocumentId);const pageAgentEditor = editor as unknown as PageAgentEditor | undefined;// Workspace pages are view-first; resolve once here so the lock + gating read// a single source of truth. Private-visibility pages are creator-only —@@ -75,7 +76,12 @@ const StoreUpdater = memo<StoreUpdaterProps>(usePageDraft();// Update store with props- useStoreUpdater('documentId', pageId);+ // `useStoreUpdater` writes the raw field; `documentId` goes through its own+ // action instead, so a panel left open on the previous document doesn't+ // carry over to this one (see setDocumentId).+ useEffect(() => {+ if (typeof pageId !== 'undefined') setDocumentId(pageId);+ }, [pageId, setDocumentId]);useStoreUpdater('isWorkspacePage', isWorkspacePage);useStoreUpdater('isWorkspaceScopedPage', isWorkspaceScopedPage);useStoreUpdater('knowledgeBaseId', knowledgeBaseId);diff --git a/src/features/PageEditor/store/action.test.ts b/src/features/PageEditor/store/action.test.tsindex b8d42f0bf3e..4b841b47771 100644--- a/src/features/PageEditor/store/action.test.ts+++ b/src/features/PageEditor/store/action.test.ts@@ -18,6 +18,37 @@ describe('PageEditorStore - rightPanelMode', () => {});});+describe('PageEditorStore - commentsPanelOpen', () => {+ it('starts closed and toggles on demand', () => {+ const store = createStore();++ expect(store.getState().commentsPanelOpen).toBe(false);+ store.getState().setCommentsPanelOpen(true);+ expect(store.getState().commentsPanelOpen).toBe(true);+ store.getState().setCommentsPanelOpen(false);+ expect(store.getState().commentsPanelOpen).toBe(false);+ });+});++describe('PageEditorStore - setDocumentId', () => {+ it('closes the comments panel when the document actually changes', () => {+ const store = createStore({ commentsPanelOpen: true, documentId: 'docs_1' });++ store.getState().setDocumentId('docs_2');++ expect(store.getState().documentId).toBe('docs_2');+ expect(store.getState().commentsPanelOpen).toBe(false);+ });++ it('leaves the panel alone when the document id is unchanged', () => {+ const store = createStore({ commentsPanelOpen: true, documentId: 'docs_1' });++ store.getState().setDocumentId('docs_1');++ expect(store.getState().commentsPanelOpen).toBe(true);+ });+});+describe('PageEditorStore - metaReadOnly', () => {it('ignores setTitle when meta is read-only (manual UI, AI, or extraction)', () => {const store = createStore({ metaReadOnly: true, title: 'Skill name' });diff --git a/src/features/PageEditor/store/action.ts b/src/features/PageEditor/store/action.tsindex c28c8f7019c..5ad2ec00de2 100644--- a/src/features/PageEditor/store/action.ts+++ b/src/features/PageEditor/store/action.ts@@ -22,6 +22,13 @@ export interface Action {handleTitleSubmit: () => Promise<void>;initMeta: (title?: string, emoji?: string) => void;performMetaSave: () => Promise<void>;+ setCommentsPanelOpen: (open: boolean) => void;+ /**+ * The store outlives a document switch (the resource manager swaps `pageId`+ * on a mounted PageEditor), so a panel left open on the previous document+ * would otherwise show the next one's gutter with nothing selected.+ */+ setDocumentId: (documentId: string | undefined) => void;setEmoji: (emoji: string | undefined) => void;/*** Mirror the lock health from {@link useEditLock} into the store so banners and@@ -190,6 +197,17 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =}},+ setCommentsPanelOpen: (commentsPanelOpen) => {+ if (get().commentsPanelOpen !== commentsPanelOpen) set({ commentsPanelOpen });+ },++ setDocumentId: (documentId) => {+ if (get().documentId === documentId) return;+ // A restored anchored draft or a fresh pick reopens it for the new+ // document; nothing here to show it for should not carry over.+ set({ commentsPanelOpen: false, documentId });+ },+setEmoji: (emoji: string | undefined) => {const { lastSavedEmoji, metaReadOnly, triggerDebouncedMetaSave } = get();@@ -226,7 +244,14 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =},setPendingCommentAnchor: (pendingCommentAnchor) => {- set({ pendingCommentAnchor });+ set((state) => ({+ pendingCommentAnchor,+ // `?? 0` guards a store instance hydrated before this counter existed+ // (a hot reload keeps the old state), which would otherwise tick to NaN.+ pendingCommentAnchorVersion: pendingCommentAnchor+ ? (state.pendingCommentAnchorVersion ?? 0) + 1+ : (state.pendingCommentAnchorVersion ?? 0),+ }));},setRightPanelMode: (rightPanelMode) => {diff --git a/src/features/PageEditor/store/initialState.ts b/src/features/PageEditor/store/initialState.tsindex 0e735c0de37..94349d0824a 100644--- a/src/features/PageEditor/store/initialState.ts+++ b/src/features/PageEditor/store/initialState.ts@@ -35,6 +35,13 @@ export interface PublicState {}export interface State extends PublicState {+ /**+ * Whether the comments panel beside the body is open. It is its own panel,+ * not a mode of the page-agent panel, so opening it never displaces the+ * copilot and vice versa. Not persisted: a fresh document starts closed+ * and a selection opens it on demand.+ */+ commentsPanelOpen: boolean;documentId: string | undefined;editor?: IEditor;/** True until the first lock peek resolves; the editor stays read-only until then. */@@ -80,11 +87,19 @@ export interface State extends PublicState {* composer, or published against it.*/pendingCommentAnchor?: PendingCommentAnchor;+ /**+ * Ticks every time a selection is captured. The store compares selected+ * values by content, so two picks of the same run look identical to a+ * subscriber; this counter is what tells them apart (the composer takes+ * the caret again on every pick).+ */+ pendingCommentAnchorVersion: number;rightPanelMode: RightPanelMode;}export const initialState: State = {autoSave: true,+ commentsPanelOpen: false,documentId: undefined,emoji: undefined,// Start pending (read-only) so the editor never flashes editable before the@@ -100,6 +115,7 @@ export const initialState: State = {lockOwnerId: undefined,metaSaveStatus: 'idle',pendingCommentAnchor: undefined,+ pendingCommentAnchorVersion: 0,rightPanelMode: 'copilot',title: undefined,};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex c30323a20b4..f07f8b206b1 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -211,12 +211,13 @@ export const documentCommentKeys = {]),threads: def('documentComment:threads',- (workspaceId: string | null, documentId: string, cursor?: string) => [- 'documentComment:threads',- workspaceId ?? '',- documentId,- cursor ?? '',- ],+ (+ workspaceId: string | null,+ documentId: string,+ cursor?: string,+ /** `'anchored'` / `'document'` page one subset; `'all'` pages every root. */+ scope: 'all' | 'anchored' | 'document' = 'all',+ ) => ['documentComment:threads', workspaceId ?? '', documentId, cursor ?? '', scope],),};diff --git a/src/services/documentComment.ts b/src/services/documentComment.tsindex 4b70d35e38d..8d71123a328 100644--- a/src/services/documentComment.ts+++ b/src/services/documentComment.ts@@ -15,8 +15,12 @@ class DocumentCommentService {listReplies = (params: { cursor?: string; limit?: number; rootCommentId: string }) =>lambdaClient.documentComment.listReplies.query(params);- listThreads = (params: { cursor?: string; documentId: string; limit?: number }) =>- lambdaClient.documentComment.listThreads.query(params);+ listThreads = (params: {+ anchored?: boolean;+ cursor?: string;+ documentId: string;+ limit?: number;+ }) => lambdaClient.documentComment.listThreads.query(params);summary = (documentId: string) => lambdaClient.documentComment.summary.query({ documentId });