🤯 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: add workspace topic comments (#17537)
AmAzing-3384fe491e00
diff --git a/apps/server/src/routers/lambda/__tests__/integration/topicComment.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/topicComment.integration.test.tsnew file mode 100644index 00000000000..795b34d5e61--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/integration/topicComment.integration.test.ts@@ -0,0 +1,623 @@+// @vitest-environment node+import type { LobeChatDatabase } from '@lobechat/database';+import {+ agents,+ messages,+ topicComments,+ topics,+ workspaceAuditLogs,+ workspaceMembers,+ workspaces,+} from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { and, eq, sql } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { ResourcePermissionModel } from '@/database/models/resourcePermission';++import { topicCommentRouter } from '../../topicComment';+import { cleanupTestUser, createTestUser } from './setup';++let testDB: LobeChatDatabase;+const notifyTopicCommentActivity = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const notifyTopicCommentModeration = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => testDB) }));+vi.mock('@/business/server/topic-comment/notifyActivity', () => ({+ notifyTopicCommentActivity,+}));+vi.mock('@/business/server/topic-comment/notifyModeration', () => ({+ notifyTopicCommentModeration,+}));+// Post-response work is async (recipient re-authorization runs its own+// queries), so tests must drain it before asserting on the delivery slots.+const afterResponseTasks = vi.hoisted(() => [] as Promise<unknown>[]);+vi.mock('@/server/utils/scheduleAfterResponse', () => ({+ after: (work: () => unknown) => void afterResponseTasks.push(Promise.resolve().then(work)),+}));++const flushAfterResponse = async () => {+ while (afterResponseTasks.length > 0) await Promise.all(afterResponseTasks.splice(0));+};++const context = (userId: string, workspaceId?: string) => ({+ jwtPayload: { userId },+ userId,+ workspaceId,+});++describe('topicCommentRouter integration', () => {+ let adminId: string;+ let db: LobeChatDatabase;+ let memberId: string;+ let ownerId: string;+ let topicId: string;+ let viewerId: string;+ let workspaceId: string;++ beforeEach(async () => {+ notifyTopicCommentActivity.mockReset();+ notifyTopicCommentActivity.mockResolvedValue(undefined);+ notifyTopicCommentModeration.mockReset();+ notifyTopicCommentModeration.mockResolvedValue(undefined);+ db = await getTestDB();+ testDB = db;+ [ownerId, adminId, memberId, viewerId] = await Promise.all([+ createTestUser(db),+ createTestUser(db),+ createTestUser(db),+ createTestUser(db),+ ]);+ const [workspace] = await db+ .insert(workspaces)+ .values({ name: 'Comment test', primaryOwnerId: ownerId, slug: `comment-${ownerId}` })+ .returning();+ workspaceId = workspace.id;+ await db.insert(workspaceMembers).values([+ { role: 'owner', userId: ownerId, workspaceId },+ { role: 'admin', userId: adminId, workspaceId },+ { role: 'member', userId: memberId, workspaceId },+ { role: 'viewer', userId: viewerId, workspaceId },+ ]);+ const [topic] = await db+ .insert(topics)+ .values({ title: 'Comments', userId: ownerId, workspaceId })+ .returning();+ topicId = topic.id;+ });++ afterEach(async () => {+ await flushAfterResponse();+ await db.execute(+ sql`ALTER TABLE workspace_audit_logs DROP CONSTRAINT IF EXISTS reject_topic_comment_audit`,+ );+ await db.delete(workspaces).where(eq(workspaces.id, workspaceId));+ await Promise.all([ownerId, adminId, memberId, viewerId].map((id) => cleanupTestUser(db, id)));+ });++ it('enforces member/owner/viewer mutation permissions', async () => {+ const member = topicCommentRouter.createCaller(context(memberId, workspaceId));+ const owner = topicCommentRouter.createCaller(context(ownerId, workspaceId));+ const viewer = topicCommentRouter.createCaller(context(viewerId, workspaceId));+ const created = await member.create({ clientId: 'member-1', content: 'hello', topicId });+ expect(created.comment.author.status).toBe('active');+ expect((await member.update({ content: 'edited', id: created.comment.id })).content).toBe(+ 'edited',+ );+ await expect(+ viewer.create({ clientId: 'viewer-1', content: 'no', topicId }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect((await viewer.get({ id: created.comment.id })).canEdit).toBe(false);+ await expect(viewer.delete({ id: created.comment.id })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect((await owner.delete({ id: created.comment.id })).mode).toBe('moderated');+ });++ it('enforces target access after conversation access changes', async () => {+ const agentId = 'topic-comment-view-only-agent';+ const agentTopicId = 'topic-comment-view-only-topic';+ await db.insert(agents).values({+ id: agentId,+ title: 'View-only Agent',+ userId: adminId,+ visibility: 'public',+ workspaceId,+ });+ await db.insert(topics).values({+ agentId,+ id: agentTopicId,+ title: 'View-only Topic',+ userId: adminId,+ workspaceId,+ });++ const member = topicCommentRouter.createCaller(context(memberId, workspaceId));+ const owner = topicCommentRouter.createCaller(context(ownerId, workspaceId));+ const created = await member.create({+ clientId: 'member-before-view-only',+ content: 'original',+ topicId: agentTopicId,+ });+ await new ResourcePermissionModel(db, workspaceId).setAccessLevel(+ 'agent',+ agentId,+ 'view',+ adminId,+ );++ await expect(member.get({ id: created.comment.id })).resolves.toMatchObject({+ canDelete: false,+ canEdit: false,+ content: 'original',+ });+ await expect(+ member.update({ content: 'denied', id: created.comment.id }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(member.delete({ id: created.comment.id })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ const [stored] = await db+ .select({+ content: topicComments.content,+ deletedAt: topicComments.deletedAt,+ moderatedAt: topicComments.moderatedAt,+ })+ .from(topicComments)+ .where(eq(topicComments.id, created.comment.id));+ expect(stored).toMatchObject({ content: 'original', deletedAt: null, moderatedAt: null });++ await expect(owner.delete({ id: created.comment.id })).resolves.toMatchObject({+ mode: 'moderated',+ });+ await db.update(agents).set({ visibility: 'private' }).where(eq(agents.id, agentId));+ notifyTopicCommentModeration.mockClear();+ await expect(owner.restore({ id: created.comment.id })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ const [stillModerated] = await db+ .select({ moderatedAt: topicComments.moderatedAt })+ .from(topicComments)+ .where(eq(topicComments.id, created.comment.id));+ expect(stillModerated.moderatedAt).not.toBeNull();+ await flushAfterResponse();+ expect(notifyTopicCommentModeration).not.toHaveBeenCalled();+ });++ it('denies private topic and message targets without leaking inaccessible rows', async () => {+ const privateAgentId = 'topic-comment-private-agent';+ const privateTopicId = 'topic-comment-private-topic';+ const privateMessageId = 'topic-comment-private-message';+ await db.insert(agents).values({+ id: privateAgentId,+ title: 'Private Agent',+ userId: memberId,+ visibility: 'private',+ workspaceId,+ });+ await db.insert(topics).values({+ agentId: privateAgentId,+ id: privateTopicId,+ title: 'Private Topic',+ userId: memberId,+ workspaceId,+ });+ await db.insert(messages).values({+ agentId: privateAgentId,+ content: 'private anchor',+ id: privateMessageId,+ role: 'assistant',+ topicId: privateTopicId,+ userId: memberId,+ workspaceId,+ });++ const admin = topicCommentRouter.createCaller(context(adminId, workspaceId));+ const member = topicCommentRouter.createCaller(context(memberId, workspaceId));+ const owner = topicCommentRouter.createCaller(context(ownerId, workspaceId));++ await expect(+ admin.create({ clientId: 'private-topic', content: 'denied', topicId: privateTopicId }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(+ admin.create({+ clientId: 'private-message',+ content: 'denied',+ messageId: privateMessageId,+ topicId,+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(+ admin.create({ clientId: 'missing-topic', content: 'denied', topicId: 'missing-topic' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ await expect(+ admin.create({+ clientId: 'missing-message',+ content: 'denied',+ messageId: 'missing-message',+ topicId,+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ const privateRoot = await member.create({+ clientId: 'private-member',+ content: 'allowed',+ topicId: privateTopicId,+ });+ await member.create({+ clientId: 'private-member-reply',+ content: 'allowed reply',+ parentCommentId: privateRoot.comment.id,+ topicId: privateTopicId,+ });+ await expect(member.get({ id: privateRoot.comment.id })).resolves.toMatchObject({+ topicId: privateTopicId,+ });++ await expect(admin.get({ id: privateRoot.comment.id })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(+ admin.listReplies({ rootCommentId: privateRoot.comment.id }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(admin.listThreads({ topicId: privateTopicId })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(admin.summary({ topicId: privateTopicId })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(owner.delete({ id: privateRoot.comment.id })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ const [storedPrivateRoot] = await db+ .select({ moderatedAt: topicComments.moderatedAt })+ .from(topicComments)+ .where(eq(topicComments.id, privateRoot.comment.id));+ expect(storedPrivateRoot.moderatedAt).toBeNull();+ await flushAfterResponse();+ expect(notifyTopicCommentModeration).not.toHaveBeenCalled();+ });++ it('notifies topic owners, reply authors, and newly mentioned active members once', async () => {+ const member = topicCommentRouter.createCaller(context(memberId, workspaceId));+ const owner = topicCommentRouter.createCaller(context(ownerId, workspaceId));++ const root = await owner.create({ clientId: 'owner-root', content: 'root', topicId });+ await flushAfterResponse();+ expect(notifyTopicCommentActivity).not.toHaveBeenCalled();++ const topLevel = await member.create({+ clientId: 'member-top-level',+ content: 'comment',+ topicId,+ });+ await flushAfterResponse();+ expect(notifyTopicCommentActivity).toHaveBeenLastCalledWith({+ actorUserId: memberId,+ commentId: topLevel.comment.id,+ recipients: [{ kind: 'commented', userId: ownerId }],+ rootCommentId: topLevel.comment.id,+ topicId,+ workspaceId,+ });++ await member.create({ clientId: 'member-top-level', content: 'retry', topicId });+ await flushAfterResponse();+ expect(notifyTopicCommentActivity).toHaveBeenCalledTimes(1);++ const reply = await member.create({+ clientId: 'member-reply',+ content: 'reply with mentions',+ editorData: {+ root: {+ children: [+ { metadata: { id: ownerId, type: 'member' }, type: 'mention' },+ { metadata: { id: adminId, type: 'member' }, type: 'mention' },+ { metadata: { id: memberId, type: 'member' }, type: 'mention' },+ ],+ },+ },+ parentCommentId: root.comment.id,+ topicId,+ });+ await flushAfterResponse();+ expect(notifyTopicCommentActivity).toHaveBeenLastCalledWith({+ actorUserId: memberId,+ commentId: reply.comment.id,+ recipients: [+ { kind: 'mentioned', userId: ownerId },+ { kind: 'mentioned', userId: adminId },+ ],+ rootCommentId: root.comment.id,+ topicId,+ workspaceId,+ });++ notifyTopicCommentActivity.mockClear();+ await member.update({+ editorData: {+ root: {+ children: [{ metadata: { id: viewerId, type: 'member' }, type: 'mention' }],+ },+ },+ id: topLevel.comment.id,+ });+ await flushAfterResponse();+ expect(notifyTopicCommentActivity).toHaveBeenCalledWith({+ actorUserId: memberId,+ commentId: topLevel.comment.id,+ recipients: [{ kind: 'mentioned', userId: viewerId }],+ rootCommentId: topLevel.comment.id,+ topicId,+ workspaceId,+ });++ notifyTopicCommentActivity.mockClear();+ await member.update({+ editorData: {+ root: {+ children: [{ metadata: { id: viewerId, type: 'member' }, type: 'mention' }],+ },+ },+ id: topLevel.comment.id,+ });+ await flushAfterResponse();+ expect(notifyTopicCommentActivity).not.toHaveBeenCalled();+ });++ it('skips activity recipients without current access to the topic', async () => {+ const member = topicCommentRouter.createCaller(context(memberId, workspaceId));+ const owner = topicCommentRouter.createCaller(context(ownerId, workspaceId));+ const privateAgentId = 'topic-comment-notify-private-agent';+ const privateTopicId = 'topic-comment-notify-private-topic';+ await db.insert(agents).values({+ id: privateAgentId,+ title: 'Private Agent',+ userId: memberId,+ visibility: 'private',+ workspaceId,+ });+ await db.insert(topics).values({+ agentId: privateAgentId,+ id: privateTopicId,+ title: 'Private Topic',+ userId: memberId,+ workspaceId,+ });++ await member.create({+ clientId: 'private-mention',+ content: 'mentioning someone who cannot open this conversation',+ editorData: {+ root: { children: [{ metadata: { id: adminId, type: 'member' }, type: 'mention' }] },+ },+ topicId: privateTopicId,+ });++ await flushAfterResponse();+ expect(notifyTopicCommentActivity).not.toHaveBeenCalled();++ const root = await member.create({ clientId: 'former-member-root', content: 'root', topicId });+ await flushAfterResponse();+ notifyTopicCommentActivity.mockClear();++ await db+ .update(workspaceMembers)+ .set({ deletedAt: new Date() })+ .where(+ and(eq(workspaceMembers.workspaceId, workspaceId), eq(workspaceMembers.userId, memberId)),+ );+ await owner.create({+ clientId: 'reply-to-former-member',+ content: 'reply',+ parentCommentId: root.comment.id,+ topicId,+ });++ await flushAfterResponse();+ expect(notifyTopicCommentActivity).not.toHaveBeenCalled();+ });++ it('lets an owner recoverably remove and restore another member comment', async () => {+ const member = topicCommentRouter.createCaller(context(memberId, workspaceId));+ const owner = topicCommentRouter.createCaller(context(ownerId, workspaceId));+ const viewer = topicCommentRouter.createCaller(context(viewerId, workspaceId));+ const created = await member.create({+ clientId: 'member-moderated',+ content: 'retained secret',+ editorData: { root: { version: 1 } },+ topicId,+ });++ const removed = await owner.delete({ id: created.comment.id });++ expect(removed).toMatchObject({+ comment: {+ canRestore: true,+ content: 'retained secret',+ moderatedAt: expect.any(Date),+ moderationIsOwn: false,+ },+ mode: 'moderated',+ });+ expect(removed.comment).not.toHaveProperty('moderatedByUserId');+ await expect(viewer.get({ id: created.comment.id })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(await member.get({ id: created.comment.id })).toMatchObject({+ canRestore: false,+ content: '',+ editorData: null,+ moderationIsOwn: true,+ });+ await expect(member.restore({ id: created.comment.id })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });++ const restored = await owner.restore({ id: created.comment.id });++ expect(restored).toMatchObject({+ canRestore: false,+ content: 'retained secret',+ moderatedAt: null,+ moderationExpiresAt: null,+ });+ await flushAfterResponse();+ expect(notifyTopicCommentModeration).toHaveBeenNthCalledWith(1, {+ authorUserId: memberId,+ commentId: created.comment.id,+ event: 'removed',+ eventId: expect.any(String),+ rootCommentId: created.comment.id,+ topicId,+ workspaceId,+ });+ await flushAfterResponse();+ expect(notifyTopicCommentModeration).toHaveBeenNthCalledWith(2, {+ authorUserId: memberId,+ commentId: created.comment.id,+ event: 'restored',+ eventId: expect.any(String),+ rootCommentId: created.comment.id,+ topicId,+ workspaceId,+ });+ const auditLogs = await db+ .select()+ .from(workspaceAuditLogs)+ .where(eq(workspaceAuditLogs.resourceId, created.comment.id));+ expect(auditLogs).toHaveLength(2);+ expect(auditLogs).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ action: 'resource.deleted', userId: ownerId, workspaceId }),+ expect.objectContaining({+ action: 'resource.restored',+ userId: ownerId,+ workspaceId,+ }),+ ]),+ );+ });++ it('rolls back moderation when the audit write fails', async () => {+ const member = topicCommentRouter.createCaller(context(memberId, workspaceId));+ const owner = topicCommentRouter.createCaller(context(ownerId, workspaceId));+ const created = await member.create({+ clientId: 'member-moderation-audit-failure',+ content: 'must remain visible',+ topicId,+ });+ await db.execute(sql`+ ALTER TABLE workspace_audit_logs+ ADD CONSTRAINT reject_topic_comment_audit+ CHECK (resource_type <> 'topic_comment')+ `);++ await expect(owner.delete({ id: created.comment.id })).rejects.toThrow();++ const [stored] = await db+ .select({ moderatedAt: topicComments.moderatedAt })+ .from(topicComments)+ .where(eq(topicComments.id, created.comment.id));+ expect(stored.moderatedAt).toBeNull();+ await flushAfterResponse();+ expect(notifyTopicCommentModeration).not.toHaveBeenCalled();+ });++ it('rolls back moderation restore when the audit write fails', async () => {+ const member = topicCommentRouter.createCaller(context(memberId, workspaceId));+ const owner = topicCommentRouter.createCaller(context(ownerId, workspaceId));+ const created = await member.create({+ clientId: 'member-restore-audit-failure',+ content: 'must remain moderated',+ topicId,+ });+ const moderatedAt = new Date();+ await db+ .update(topicComments)+ .set({+ moderatedAt,+ moderatedByUserId: ownerId,+ moderationExpiresAt: new Date(moderatedAt.getTime() + 60_000),+ })+ .where(eq(topicComments.id, created.comment.id));+ await db.execute(sql`+ ALTER TABLE workspace_audit_logs+ ADD CONSTRAINT reject_topic_comment_audit+ CHECK (resource_type <> 'topic_comment')+ `);++ await expect(owner.restore({ id: created.comment.id })).rejects.toThrow();++ const [stored] = await db+ .select({ moderatedAt: topicComments.moderatedAt })+ .from(topicComments)+ .where(eq(topicComments.id, created.comment.id));+ expect(stored.moderatedAt).not.toBeNull();+ await flushAfterResponse();+ expect(notifyTopicCommentModeration).not.toHaveBeenCalled();+ });++ it('keeps an owner self-delete irreversible and preserves moderated threads for other viewers', async () => {+ const member = topicCommentRouter.createCaller(context(memberId, workspaceId));+ const owner = topicCommentRouter.createCaller(context(ownerId, workspaceId));+ const viewer = topicCommentRouter.createCaller(context(viewerId, workspaceId));+ const own = await owner.create({ clientId: 'owner-self-delete', content: 'mine', topicId });+ expect(await owner.delete({ id: own.comment.id })).toEqual({ mode: 'hard' });++ const root = await member.create({+ clientId: 'moderated-root',+ content: 'private root body',+ topicId,+ });+ await owner.create({+ clientId: 'active-reply',+ content: 'reply survives',+ parentCommentId: root.comment.id,+ topicId,+ });+ await owner.delete({ id: root.comment.id });++ const threads = await viewer.listThreads({ topicId });+ expect(threads.items).toEqual([+ expect.objectContaining({+ replyCount: 1,+ root: expect.objectContaining({+ content: '',+ editorData: null,+ id: root.comment.id,+ moderationIsOwn: false,+ }),+ }),+ ]);+ expect(threads.items[0].root).not.toHaveProperty('moderatedByUserId');++ const [stored] = await db+ .select()+ .from(topicComments)+ .where(eq(topicComments.id, root.comment.id));+ expect(stored.content).toBe('private root body');+ });++ it('requires workspace and validates comment content', async () => {+ await expect(+ topicCommentRouter.createCaller(context(memberId)).summary({ topicId }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ const member = topicCommentRouter.createCaller(context(memberId, workspaceId));+ await expect(+ member.create({ clientId: 'empty', content: ' ', topicId }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ await expect(+ member.create({ clientId: 'long', content: 'x'.repeat(10_001), topicId }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });++ it('lists root threads newest first across pages', async () => {+ const member = topicCommentRouter.createCaller(context(memberId, workspaceId));+ await member.create({ clientId: 'first', content: 'first', topicId });+ await member.create({ clientId: 'second', content: 'second', topicId });+ const first = await member.listThreads({ limit: 1, topicId });+ expect(first.items[0].root.content).toBe('second');+ const second = await member.listThreads({ cursor: first.nextCursor!, limit: 1, topicId });+ expect(second.items[0].root.content).toBe('first');+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.ts b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.tsindex 1f35eda24cb..7aeb3b61100 100644--- a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.ts+++ b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.ts@@ -13,6 +13,7 @@ import {assertCanUseMessageTargets,assertCanUseSessionTargets,assertCanUseTopicTargets,+ assertCanViewTopicTargets,} from './conversationResourceGuard';import { getWorkspaceAgentParentGroupIds } from './workspaceAgentGuard';@@ -80,6 +81,17 @@ describe('assertCanUseConversationTargets', () => {);});+ it('forwards request-resolved permission grants', async () => {+ await assertCanUseConversationTargets(+ { ...baseCtx(createDb([])), grantedPermissions: ['ai_model:invoke:owner'] },+ [{ agentId: 'agent-1' }],+ );++ expect(assertActionMock).toHaveBeenCalledWith(+ expect.objectContaining({ grantedPermissions: ['ai_model:invoke:owner'] }),+ );+ });+it('checks both the group and agent when both contexts are supplied', async () => {await assertCanUseConversationTargets(baseCtx(createDb([])), [{ agentId: 'supervisor-1', groupId: 'group-1' },@@ -164,7 +176,21 @@ describe('assertCanUseTopicTargets', () => {await assertCanUseTopicTargets(baseCtx(db), ['t-1']);expect(assertActionMock).toHaveBeenCalledWith(- expect.objectContaining({ resourceId: 'group-1', resourceType: 'agentGroup' }),+ expect.objectContaining({+ action: 'use',+ resourceId: 'group-1',+ resourceType: 'agentGroup',+ }),+ );+ });++ it('can require read-only view access to the owning resource', async () => {+ const db = createDb([[{ agentId: 'agent-1', groupId: null }]]);++ await assertCanViewTopicTargets(baseCtx(db), ['t-1']);++ expect(assertActionMock).toHaveBeenCalledWith(+ expect.objectContaining({ action: 'view', resourceId: 'agent-1', resourceType: 'agent' }),);});});diff --git a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.ts b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.tsindex 47bd87b9a6a..efdaaea66aa 100644--- a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.ts+++ b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.ts@@ -11,6 +11,7 @@ import { getWorkspaceAgentParentGroupIds } from './workspaceAgentGuard';interface ConversationGuardCtx {db: LobeChatDatabase;+ grantedPermissions?: readonly string[];userId: string;workspaceId?: string | null;}@@ -26,22 +27,22 @@ export interface CreateMessageTarget extends ConversationTarget {}/**- * Workspace General-access guard for conversation writes.+ * Workspace General-access guard for conversations.** Workspace topics/messages are visible workspace-wide (`buildWorkspaceWhere`- * matches every member's rows), and shared conversations are intentionally- * co-editable by members — but only for members who can at least USE the- * agent/group the conversation belongs to. `view`-level General access means- * read-only: no sends, no message edits/deletes, no topic co-edits.+ * matches every member's rows), so reads still need VIEW access to the owning+ * agent/group. Shared conversation writes require USE access; `view`-level+ * General access remains read-only.** Personal mode (no workspaceId) is a no-op. Targets that don't resolve to a* workspace-shared agent/group of the CURRENT workspace (inbox, legacy rows,* cross-workspace ids) fall through — the models' workspace ownership WHERE* already keeps those writes scoped.*/-export const assertCanUseConversationTargets = async (+const assertCanAccessConversationTargets = async (ctx: ConversationGuardCtx,targets: ConversationTarget[],+ action: 'use' | 'view',): Promise<void> => {const workspaceId = ctx.workspaceId ?? undefined;if (!workspaceId || targets.length === 0) return;@@ -80,8 +81,9 @@ export const assertCanUseConversationTargets = async (if (!meta || meta.workspaceId !== workspaceId) continue;await assertCanPerformResourceAction({- action: 'use',+ action,db: ctx.db,+ grantedPermissions: ctx.grantedPermissions,meta,resourceId,resourceType,@@ -91,6 +93,11 @@ export const assertCanUseConversationTargets = async (}};+export const assertCanUseConversationTargets = async (+ ctx: ConversationGuardCtx,+ targets: ConversationTarget[],+): Promise<void> => assertCanAccessConversationTargets(ctx, targets, 'use');+/*** Resolve message ids to their owning agent/group from the DB rows (client* context is untrusted) and assert `use` access. Rows without a direct@@ -120,13 +127,10 @@ export const assertCanUseMessageTargets = async (}};-/**- * Resolve topic ids to their owning agent/group from the DB rows and assert- * `use` access.- */-export const assertCanUseTopicTargets = async (+const assertCanAccessTopicTargets = async (ctx: ConversationGuardCtx,topicIds: string[],+ action: 'use' | 'view',): Promise<void> => {if (!ctx.workspaceId || topicIds.length === 0) return;@@ -153,9 +157,21 @@ export const assertCanUseTopicTargets = async (.where(inArray(agentsToSessions.sessionId, unresolvedSessionIds)): [];- await assertCanUseConversationTargets(ctx, [...rows, ...sessionTargets]);+ await assertCanAccessConversationTargets(ctx, [...rows, ...sessionTargets], action);};+/** Resolve topic ids to their owning agent/group and assert `use` access. */+export const assertCanUseTopicTargets = async (+ ctx: ConversationGuardCtx,+ topicIds: string[],+): Promise<void> => assertCanAccessTopicTargets(ctx, topicIds, 'use');++/** Resolve topic ids to their owning agent/group and assert `view` access. */+export const assertCanViewTopicTargets = async (+ ctx: ConversationGuardCtx,+ topicIds: string[],+): Promise<void> => assertCanAccessTopicTargets(ctx, topicIds, 'view');+/*** Resolve session ids to their linked agents via `agentsToSessions` and assert* `use` access — for session-scoped bulk writes that never see a topic id.diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.tsindex 69682df5811..dd2e703a4b4 100644--- a/apps/server/src/routers/lambda/agent.ts+++ b/apps/server/src/routers/lambda/agent.ts@@ -14,6 +14,7 @@ import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';import { ResourcePermissionModel } from '@/database/models/resourcePermission';import { SessionModel } from '@/database/models/session';import { TaskModel } from '@/database/models/task';+import { TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS } from '@/database/models/topicComment';import { UserModel } from '@/database/models/user';import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';import { DEFAULT_RESOURCE_ACCESS_LEVELS, RESOURCE_ACCESS_LEVELS_BY_TYPE } from '@/database/schemas';@@ -842,12 +843,28 @@ export const agentRouter = router({});}- const result = await ctx.agentModel.transferAgent(- input.agentId,- input.targetWorkspaceId,- ctx.userId,- input.targetVisibility,- );+ let result;+ try {+ result = await ctx.agentModel.transferAgent(+ input.agentId,+ input.targetWorkspaceId,+ ctx.userId,+ input.targetVisibility,+ { rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx) },+ );+ } catch (error) {+ if (+ error instanceof Error &&+ error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS+ ) {+ throw new TRPCError({+ cause: { data: { code: TransferErrorCode.OwnerOnly } },+ code: 'FORBIDDEN',+ message: "Only workspace owners can transfer an agent carrying others' conversations",+ });+ }+ throw error;+ }if (ctx.workspaceId) {await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(@@ -962,12 +979,28 @@ export const agentRouter = router({});}- const results = await ctx.agentModel.transferAgents(- agentIds,- input.targetWorkspaceId,- ctx.userId,- input.targetVisibility,- );+ let results;+ try {+ results = await ctx.agentModel.transferAgents(+ agentIds,+ input.targetWorkspaceId,+ ctx.userId,+ input.targetVisibility,+ { rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx) },+ );+ } catch (error) {+ if (+ error instanceof Error &&+ error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS+ ) {+ throw new TRPCError({+ cause: { data: { code: TransferErrorCode.OwnerOnly } },+ code: 'FORBIDDEN',+ message: "Only workspace owners can transfer agents carrying others' conversations",+ });+ }+ throw error;+ }if (ctx.workspaceId) {const sourcePermissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);diff --git a/apps/server/src/routers/lambda/agentGroup.ts b/apps/server/src/routers/lambda/agentGroup.tsindex 08296cbeea4..0ab6af37c00 100644--- a/apps/server/src/routers/lambda/agentGroup.ts+++ b/apps/server/src/routers/lambda/agentGroup.ts@@ -7,6 +7,7 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAimport { AgentModel } from '@/database/models/agent';import { ChatGroupModel } from '@/database/models/chatGroup';import { ResourcePermissionModel } from '@/database/models/resourcePermission';+import { TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS } from '@/database/models/topicComment';import { UserModel } from '@/database/models/user';import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSettings';import { AgentGroupRepository } from '@/database/repositories/agentGroup';@@ -684,12 +685,28 @@ export const agentGroupRouter = router({});}- const result = await ctx.agentGroupRepo.transferToWorkspace(- input.groupId,- input.targetWorkspaceId,- ctx.userId,- input.targetVisibility,- );+ let result;+ try {+ result = await ctx.agentGroupRepo.transferToWorkspace(+ input.groupId,+ input.targetWorkspaceId,+ ctx.userId,+ input.targetVisibility,+ { rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx) },+ );+ } catch (error) {+ if (+ error instanceof Error &&+ error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS+ ) {+ throw new TRPCError({+ cause: { data: { code: TransferErrorCode.OwnerOnly } },+ code: 'FORBIDDEN',+ message: "Only workspace owners can transfer a group carrying others' content",+ });+ }+ throw error;+ }if (ctx.workspaceId) {await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex 437b5e4623f..1b04aef27ca 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -77,6 +77,7 @@ import { shareRouter } from './share';import { taskRouter } from './task';import { threadRouter } from './thread';import { topicRouter } from './topic';+import { topicCommentRouter } from './topicComment';import { uploadRouter } from './upload';import { usageRouter } from './usage';import { userRouter } from './user';@@ -150,6 +151,7 @@ export const lambdaRouter = router({share: shareRouter,thread: threadRouter,topic: topicRouter,+ topicComment: topicCommentRouter,upload: uploadRouter,usage: usageRouter,user: userRouter,diff --git a/apps/server/src/routers/lambda/topicComment.ts b/apps/server/src/routers/lambda/topicComment.tsnew file mode 100644index 00000000000..789b35d7c1b--- /dev/null+++ b/apps/server/src/routers/lambda/topicComment.ts@@ -0,0 +1,731 @@+import type { TopicCommentItem as TopicCommentDTO } from '@lobechat/types';+import { pickNonEmptyString, toRecord } from '@lobechat/utils/object';+import { TRPCError } from '@trpc/server';+import { and, eq, inArray, isNull } from 'drizzle-orm';+import { z } from 'zod';++import type { TopicCommentActivityRecipient } from '@/business/server/topic-comment/notifyActivity';+import { notifyTopicCommentActivity } from '@/business/server/topic-comment/notifyActivity';+import { notifyTopicCommentModeration } from '@/business/server/topic-comment/notifyModeration';+import { wsProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { RbacModel } from '@/database/models/rbac';+import {+ TOPIC_COMMENT_MESSAGE_NOT_IN_TOPIC,+ TOPIC_COMMENT_PARENT_NOT_FOUND,+ TOPIC_COMMENT_REPLY_CANNOT_ANCHOR,+ TOPIC_COMMENT_REPLY_DEPTH_EXCEEDED,+ TOPIC_COMMENT_TOPIC_NOT_FOUND,+ TopicCommentModel,+} from '@/database/models/topicComment';+import { WorkspaceAuditLogModel } from '@/database/models/workspaceAuditLog';+import { users, workspaceMembers } from '@/database/schemas';+import type { TopicCommentItem } from '@/database/schemas/topicComment';+import type { Transaction } from '@/database/type';+import { router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { getWorkspaceScopedPermissionMatches } from '@/server/services/workspacePermission';+import { after } from '@/server/utils/scheduleAfterResponse';++import {+ assertCanUseMessageTargets,+ assertCanUseTopicTargets,+ assertCanViewTopicTargets,+} from './_helpers/conversationResourceGuard';++const MAX_EDITOR_DATA_BYTES = 128 * 1024;+const idSchema = z.string().trim().min(1).max(255);+const contentSchema = z.string().trim().min(1).max(10_000);+const editorDataSchema = z+ .json()+ .refine((value) => Buffer.byteLength(JSON.stringify(value), 'utf8') <= MAX_EDITOR_DATA_BYTES, {+ message: 'editorData must not exceed 128 KiB',+ });+const pageSchema = z.object({+ cursor: z.string().min(1).optional(),+ limit: z.number().int().min(1).max(50).optional(),+});++const topicCommentProcedure = wsProcedure.use(serverDatabase).use(async ({ ctx, next }) => {+ // Lazily resolve active membership and RBAC grants once, then reuse the+ // request-local promise for action checks, target guards and enrichment.+ let permissionCodes: Promise<string[]> | undefined;+ const getTopicCommentPermissionCodes = () => {+ permissionCodes ??= Promise.all([+ ctx.serverDB+ .select({ userId: workspaceMembers.userId })+ .from(workspaceMembers)+ .where(+ and(+ eq(workspaceMembers.workspaceId, ctx.workspaceId),+ eq(workspaceMembers.userId, ctx.userId),+ isNull(workspaceMembers.deletedAt),+ ),+ )+ .limit(1),+ new RbacModel(ctx.serverDB, ctx.userId).getUserPermissions({ workspaceId: ctx.workspaceId }),+ ]).then(([membership, codes]) => (membership[0] ? codes : []));+ return permissionCodes;+ };++ return next({+ ctx: {+ getTopicCommentPermissionCodes,+ topicCommentModel: new TopicCommentModel(ctx.serverDB, ctx.userId, ctx.workspaceId),+ },+ });+});++const forbidden = (): never => {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Insufficient topic comment permission' });+};++const assertPermission = async (+ ctx: {+ getTopicCommentPermissionCodes: () => Promise<string[]>;+ serverDB: Parameters<typeof getWorkspaceScopedPermissionMatches>[0]['db'];+ userId: string;+ workspaceId: string;+ },+ action: 'TOPIC_COMMENT_CREATE' | 'TOPIC_COMMENT_READ' | 'TOPIC_COMMENT_UPDATE',+) => {+ const grantedPermissions = await ctx.getTopicCommentPermissionCodes();+ const matches = await getWorkspaceScopedPermissionMatches({+ action,+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ if (!matches.hasAllScope && !matches.hasOwnerScope) forbidden();+ return grantedPermissions;+};++const canUseTopicCommentTargets = async (+ ctx: {+ getTopicCommentPermissionCodes: () => Promise<string[]>;+ serverDB: Parameters<typeof getWorkspaceScopedPermissionMatches>[0]['db'];+ userId: string;+ workspaceId: string;+ },+ topicIds: string[],+) => {+ try {+ await assertCanUseTopicTargets(+ {+ db: ctx.serverDB,+ grantedPermissions: await ctx.getTopicCommentPermissionCodes(),+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ topicIds,+ );+ return true;+ } catch (error) {+ if (error instanceof TRPCError && error.code === 'FORBIDDEN') return false;+ throw error;+ }+};++const toNotFound = (error: unknown): never => {+ if (+ error instanceof Error &&+ [+ TOPIC_COMMENT_MESSAGE_NOT_IN_TOPIC,+ TOPIC_COMMENT_PARENT_NOT_FOUND,+ TOPIC_COMMENT_REPLY_CANNOT_ANCHOR,+ TOPIC_COMMENT_REPLY_DEPTH_EXCEEDED,+ TOPIC_COMMENT_TOPIC_NOT_FOUND,+ ].includes(error.message)+ )+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic comment resource not found' });+ throw error;+};++const enrich = async (+ ctx: {+ getTopicCommentPermissionCodes: () => Promise<string[]>;+ serverDB: Parameters<typeof getWorkspaceScopedPermissionMatches>[0]['db'];+ userId: string;+ workspaceId: string;+ },+ items: TopicCommentItem[],+ permissionOverride?: Awaited<ReturnType<typeof getViewerPermissions>>,+): Promise<TopicCommentDTO[]> => {+ const authorIds = [+ ...new Set(items.flatMap(({ authorUserId }) => (authorUserId ? [authorUserId] : []))),+ ];+ const topicIds = [...new Set(items.map(({ topicId }) => topicId))];+ const [profiles, memberships, permissions, canUseResource] = await Promise.all([+ authorIds.length+ ? ctx.serverDB+ .select({+ avatar: users.avatar,+ fullName: users.fullName,+ id: users.id,+ username: users.username,+ })+ .from(users)+ .where(inArray(users.id, authorIds))+ : [],+ authorIds.length+ ? ctx.serverDB+ .select({ userId: workspaceMembers.userId })+ .from(workspaceMembers)+ .where(+ and(+ eq(workspaceMembers.workspaceId, ctx.workspaceId),+ inArray(workspaceMembers.userId, authorIds),+ isNull(workspaceMembers.deletedAt),+ ),+ )+ : [],+ permissionOverride ?? getViewerPermissions(ctx),+ canUseTopicCommentTargets(ctx, topicIds),+ ]);+ const profileById = new Map(profiles.map((profile) => [profile.id, profile]));+ const activeIds = new Set(memberships.map(({ userId }) => userId));+ const now = Date.now();++ return items.map((item) => {+ const profile = item.authorUserId ? profileById.get(item.authorUserId) : undefined;+ const own = item.authorUserId === ctx.userId;+ const moderated = Boolean(item.moderatedAt);+ const moderationUnexpired =+ moderated &&+ Boolean(item.moderationExpiresAt) &&+ new Date(item.moderationExpiresAt!).getTime() > now;+ const canViewModeratedContent = permissions.restore.hasAllScope && moderationUnexpired;+ // Concrete moderator identity is audit-only and must never cross this DTO boundary.+ const { moderatedByUserId: _moderatedByUserId, ...safeItem } = item;++ return {+ ...safeItem,+ author: profile+ ? { ...profile, status: activeIds.has(profile.id) ? 'active' : 'former' }+ : { avatar: null, fullName: null, id: null, status: 'deactivated', username: null },+ canDelete:+ !item.deletedAt &&+ !moderated &&+ canUseResource &&+ (permissions.delete.hasAllScope || (permissions.delete.hasOwnerScope && own)),+ canEdit:+ !item.deletedAt &&+ !moderated &&+ canUseResource &&+ own &&+ (permissions.update.hasAllScope || permissions.update.hasOwnerScope),+ canRestore:+ moderated && moderationUnexpired && canUseResource && permissions.restore.hasAllScope,+ content: moderated && !canViewModeratedContent ? '' : item.content,+ editorData: moderated && !canViewModeratedContent ? null : item.editorData,+ moderationIsOwn: moderated && own,+ } as TopicCommentDTO;+ });+};++const getViewerPermissions = async (ctx: {+ getTopicCommentPermissionCodes: () => Promise<string[]>;+ serverDB: Parameters<typeof getWorkspaceScopedPermissionMatches>[0]['db'];+ userId: string;+ workspaceId: string;+}) => {+ const grantedPermissions = await ctx.getTopicCommentPermissionCodes();+ const [update, remove, restore] = await Promise.all([+ getWorkspaceScopedPermissionMatches({+ action: 'TOPIC_COMMENT_UPDATE',+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ getWorkspaceScopedPermissionMatches({+ action: 'TOPIC_COMMENT_DELETE',+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ getWorkspaceScopedPermissionMatches({+ action: 'TOPIC_COMMENT_RESTORE',+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ ]);++ return { delete: remove, restore, update };+};++const recordModerationAudit = async (+ ctx: {+ serverDB: Parameters<typeof getWorkspaceScopedPermissionMatches>[0]['db'];+ userId: string;+ workspaceId: string;+ },+ action: 'resource.deleted' | 'resource.restored',+ commentId: string,+ trx?: Transaction,+) =>+ new WorkspaceAuditLogModel(ctx.serverDB).create(+ {+ action,+ metadata: { operation: 'topic_comment_moderation' },+ resourceId: commentId,+ resourceType: 'topic_comment',+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ trx,+ );++const notifyModerationBestEffort = (params: Parameters<typeof notifyTopicCommentModeration>[0]) => {+ after(async () => {+ try {+ await notifyTopicCommentModeration(params);+ } catch (error) {+ console.error('[topic-comment] Failed to send moderation notification', error);+ }+ });+};++interface NotificationCtx {+ serverDB: Parameters<typeof getWorkspaceScopedPermissionMatches>[0]['db'];+ workspaceId: string;+}++const canViewTopic = async (ctx: NotificationCtx, userId: string, topicId: string) => {+ try {+ await assertCanViewTopicTargets({ db: ctx.serverDB, userId, workspaceId: ctx.workspaceId }, [+ topicId,+ ]);+ return true;+ } catch (error) {+ if (error instanceof TRPCError && error.code === 'FORBIDDEN') return false;+ throw error;+ }+};++/**+ * Recipients come from stored rows (topic owner, root author, mention targets),+ * which can outlive access: a cross-workspace transfer keeps comments whose+ * authors never joined the destination workspace, and membership alone says+ * nothing about a private agent's conversation. Re-authorize every recipient+ * against the current topic before any id reaches the delivery slot.+ */+const filterRecipientsByTopicAccess = async (+ ctx: NotificationCtx,+ topicId: string,+ recipients: TopicCommentActivityRecipient[],+): Promise<TopicCommentActivityRecipient[]> => {+ if (recipients.length === 0) return [];++ const activeMemberships = await ctx.serverDB+ .select({ userId: workspaceMembers.userId })+ .from(workspaceMembers)+ .where(+ and(+ eq(workspaceMembers.workspaceId, ctx.workspaceId),+ inArray(+ workspaceMembers.userId,+ recipients.map(({ userId }) => userId),+ ),+ isNull(workspaceMembers.deletedAt),+ ),+ );+ const activeUserIds = new Set(activeMemberships.map(({ userId }) => userId));+ const members = recipients.filter(({ userId }) => activeUserIds.has(userId));+ const canView = await Promise.all(+ members.map(({ userId }) => canViewTopic(ctx, userId, topicId)),+ );++ return members.filter((_, index) => canView[index]);+};++const notifyActivityBestEffort = (+ ctx: NotificationCtx,+ params: Parameters<typeof notifyTopicCommentActivity>[0],+) => {+ after(async () => {+ try {+ const recipients = await filterRecipientsByTopicAccess(+ ctx,+ params.topicId,+ params.recipients,+ );+ if (recipients.length === 0) return;++ await notifyTopicCommentActivity({ ...params, recipients });+ } catch (error) {+ console.error('[topic-comment] Failed to send activity notification', error);+ }+ });+};++const extractMentionedUserIds = (editorData: unknown): string[] => {+ const root = toRecord(editorData)?.root;+ const pending: unknown[] = root === undefined ? [] : [root];+ const userIds = new Set<string>();++ while (pending.length > 0) {+ const node = toRecord(pending.pop());+ if (!node) continue;++ const metadata = toRecord(node.metadata);+ if (node.type === 'mention' && metadata?.type === 'member') {+ const userId = pickNonEmptyString(metadata.id);+ if (userId) userIds.add(userId);+ }++ if (Array.isArray(node.children)) pending.push(...node.children);+ }++ return [...userIds];+};++const validateMentionedUserIds = async (+ ctx: {+ serverDB: Parameters<typeof getWorkspaceScopedPermissionMatches>[0]['db'];+ userId: string;+ workspaceId: string;+ },+ editorData: unknown,+): Promise<string[]> => {+ const candidateIds = extractMentionedUserIds(editorData).filter((id) => id !== ctx.userId);+ if (candidateIds.length === 0) return [];++ const activeMemberships = await ctx.serverDB+ .select({ userId: workspaceMembers.userId })+ .from(workspaceMembers)+ .where(+ and(+ eq(workspaceMembers.workspaceId, ctx.workspaceId),+ inArray(workspaceMembers.userId, candidateIds),+ isNull(workspaceMembers.deletedAt),+ ),+ );+ const activeUserIds = new Set(activeMemberships.map(({ userId }) => userId));+ return candidateIds.filter((id) => activeUserIds.has(id));+};++export const topicCommentRouter = router({+ create: topicCommentProcedure+ .input(+ z.object({+ clientId: idSchema,+ content: contentSchema,+ editorData: editorDataSchema.optional(),+ messageId: idSchema.optional(),+ parentCommentId: idSchema.optional(),+ topicId: idSchema,+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const grantedPermissions = await assertPermission(ctx, 'TOPIC_COMMENT_CREATE');+ try {+ await Promise.all([+ assertCanUseTopicTargets(+ {+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ [input.topicId],+ ),+ assertCanUseMessageTargets(+ {+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ input.messageId ? [input.messageId] : [],+ ),+ ]);+ const mentionedUserIds = await validateMentionedUserIds(ctx, input.editorData);+ const result = await ctx.topicCommentModel.createWithMentions({+ ...input,+ mentionedUserIds,+ });++ if (!result.isDuplicate) {+ const recipientsByUserId = new Map<string, TopicCommentActivityRecipient>();+ const conversationRecipientUserId = input.parentCommentId+ ? result.parentAuthorUserId+ : result.topicOwnerUserId;+ if (conversationRecipientUserId && conversationRecipientUserId !== ctx.userId) {+ recipientsByUserId.set(conversationRecipientUserId, {+ kind: input.parentCommentId ? 'replied' : 'commented',+ userId: conversationRecipientUserId,+ });+ }+ for (const userId of result.addedMentionUserIds) {+ recipientsByUserId.set(userId, { kind: 'mentioned', userId });+ }++ if (recipientsByUserId.size > 0) {+ notifyActivityBestEffort(ctx, {+ actorUserId: ctx.userId,+ commentId: result.comment.id,+ recipients: [...recipientsByUserId.values()],+ rootCommentId: result.comment.parentCommentId ?? result.comment.id,+ topicId: result.comment.topicId,+ workspaceId: ctx.workspaceId,+ });+ }+ }++ const [comment] = await enrich(ctx, [result.comment]);+ return { comment, isDuplicate: result.isDuplicate };+ } catch (error) {+ return toNotFound(error);+ }+ }),+ delete: topicCommentProcedure+ .input(z.object({ id: idSchema }))+ .mutation(async ({ ctx, input }) => {+ const permissions = await getViewerPermissions(ctx);+ const permission = permissions.delete;+ if (!permission.hasAllScope && !permission.hasOwnerScope) forbidden();++ const current = await ctx.topicCommentModel.findById(input.id, {+ includeAllModerated: true,+ });+ if (!current || (!permission.hasAllScope && current.authorUserId !== ctx.userId))+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic comment not found' });+ const grantedPermissions = await ctx.getTopicCommentPermissionCodes();+ await assertCanUseTopicTargets(+ {+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ [current.topicId],+ );++ if (permission.hasAllScope && current.authorUserId !== ctx.userId) {+ const result = await ctx.serverDB.transaction(async (trx) => {+ const result = await ctx.topicCommentModel.moderateRemove(input.id, undefined, trx);+ if (!result)+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic comment not found' });+ await recordModerationAudit(ctx, 'resource.deleted', result.comment.id, trx);+ return result;+ });+ if (result.comment.authorUserId) {+ notifyModerationBestEffort({+ authorUserId: result.comment.authorUserId,+ commentId: result.comment.id,+ event: 'removed',+ eventId: String(result.moderationExpiresAt.getTime()),+ rootCommentId: result.comment.parentCommentId ?? result.comment.id,+ topicId: result.comment.topicId,+ workspaceId: ctx.workspaceId,+ });+ }+ return {+ comment: (await enrich(ctx, [result.comment], permissions))[0],+ mode: 'moderated' as const,+ };+ }++ const mode = await ctx.topicCommentModel.delete(input.id, {+ overrideAuthorScope: false,+ });+ if (!mode) throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic comment not found' });+ return { mode };+ }),+ get: topicCommentProcedure.input(z.object({ id: idSchema })).query(async ({ ctx, input }) => {+ const grantedPermissions = await assertPermission(ctx, 'TOPIC_COMMENT_READ');+ const permissions = await getViewerPermissions(ctx);+ const item = await ctx.topicCommentModel.findById(input.id, {+ includeAllModerated: permissions.restore.hasAllScope,+ });+ if (!item) throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic comment not found' });+ await assertCanViewTopicTargets(+ {+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ [item.topicId],+ );+ return (await enrich(ctx, [item], permissions))[0];+ }),+ listReplies: topicCommentProcedure+ .input(pageSchema.extend({ rootCommentId: idSchema }))+ .query(async ({ ctx, input }) => {+ const grantedPermissions = await assertPermission(ctx, 'TOPIC_COMMENT_READ');+ const permissions = await getViewerPermissions(ctx);+ const root = await ctx.topicCommentModel.findById(input.rootCommentId, {+ includeAllModerated: permissions.restore.hasAllScope,+ });+ if (!root) throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic comment not found' });+ await assertCanViewTopicTargets(+ {+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ [root.topicId],+ );+ const page = await ctx.topicCommentModel.listReplies(input, {+ includeAllModerated: permissions.restore.hasAllScope,+ });+ return { ...page, items: await enrich(ctx, page.items, permissions) };+ }),+ listThreads: topicCommentProcedure+ .input(pageSchema.extend({ messageId: idSchema.optional(), topicId: idSchema }))+ .query(async ({ ctx, input }) => {+ const grantedPermissions = await assertPermission(ctx, 'TOPIC_COMMENT_READ');+ await assertCanViewTopicTargets(+ {+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ [input.topicId],+ );+ const permissions = await getViewerPermissions(ctx);+ const page = await ctx.topicCommentModel.listThreads(input, {+ includeAllModerated: permissions.restore.hasAllScope,+ });+ const roots = await enrich(+ ctx,+ page.items.map(({ root }) => root),+ permissions,+ );+ return {+ ...page,+ items: page.items.map((thread, index) => ({ ...thread, root: roots[index] })),+ };+ }),+ restore: topicCommentProcedure+ .input(z.object({ id: idSchema }))+ .mutation(async ({ ctx, input }) => {+ const permissions = await getViewerPermissions(ctx);+ if (!permissions.restore.hasAllScope) forbidden();++ const current = await ctx.topicCommentModel.findById(input.id, {+ includeAllModerated: true,+ });+ if (!current)+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Recoverable topic comment not found' });+ const grantedPermissions = await ctx.getTopicCommentPermissionCodes();+ await assertCanUseTopicTargets(+ {+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ [current.topicId],+ );+ if (!current.moderatedAt || !current.moderationExpiresAt)+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Recoverable topic comment not found' });+ if (new Date(current.moderationExpiresAt).getTime() <= Date.now())+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Topic comment recovery window has expired',+ });++ const restored = await ctx.serverDB.transaction(async (trx) => {+ const restored = await ctx.topicCommentModel.restoreModerated(input.id, undefined, trx);+ if (!restored)+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'Topic comment recovery state changed',+ });+ await recordModerationAudit(ctx, 'resource.restored', restored.id, trx);+ return restored;+ });+ if (restored.authorUserId) {+ notifyModerationBestEffort({+ authorUserId: restored.authorUserId,+ commentId: restored.id,+ event: 'restored',+ eventId: String(new Date(current.moderationExpiresAt).getTime()),+ rootCommentId: restored.parentCommentId ?? restored.id,+ topicId: restored.topicId,+ workspaceId: ctx.workspaceId,+ });+ }++ return (await enrich(ctx, [restored], permissions))[0];+ }),+ summary: topicCommentProcedure+ .input(z.object({ topicId: idSchema }))+ .query(async ({ ctx, input }) => {+ const grantedPermissions = await assertPermission(ctx, 'TOPIC_COMMENT_READ');+ await assertCanViewTopicTargets(+ {+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ [input.topicId],+ );+ return ctx.topicCommentModel.summary(input.topicId);+ }),+ update: topicCommentProcedure+ .input(+ z+ .object({+ content: contentSchema.optional(),+ editorData: editorDataSchema.optional(),+ id: idSchema,+ })+ .refine(({ content, editorData }) => content !== undefined || editorData !== undefined, {+ message: 'An update field is required',+ }),+ )+ .mutation(async ({ ctx, input: { id, ...input } }) => {+ const permissions = await getViewerPermissions(ctx);+ if (!permissions.update.hasAllScope && !permissions.update.hasOwnerScope) forbidden();+ const current = await ctx.topicCommentModel.findById(id);+ if (+ !current ||+ current.authorUserId !== ctx.userId ||+ current.deletedAt ||+ current.moderatedAt+ )+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic comment not found' });+ const grantedPermissions = await ctx.getTopicCommentPermissionCodes();+ await assertCanUseTopicTargets(+ {+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ [current.topicId],+ );+ const mentionedUserIds =+ input.editorData === undefined+ ? undefined+ : await validateMentionedUserIds(ctx, input.editorData);+ const result = await ctx.topicCommentModel.update(id, input, { mentionedUserIds });+ if (!result) throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic comment not found' });++ if (result.addedMentionUserIds.length > 0) {+ notifyActivityBestEffort(ctx, {+ actorUserId: ctx.userId,+ commentId: result.comment.id,+ recipients: result.addedMentionUserIds.map((userId) => ({+ kind: 'mentioned',+ userId,+ })),+ rootCommentId: result.comment.parentCommentId ?? result.comment.id,+ topicId: result.comment.topicId,+ workspaceId: ctx.workspaceId,+ });+ }++ return (await enrich(ctx, [result.comment], permissions))[0];+ }),+});diff --git a/apps/server/src/services/resourcePermission/index.test.ts b/apps/server/src/services/resourcePermission/index.test.tsindex 97b753139ce..cb4ccdb001f 100644--- a/apps/server/src/services/resourcePermission/index.test.ts+++ b/apps/server/src/services/resourcePermission/index.test.ts@@ -5,6 +5,7 @@ import type { LobeChatDatabase } from '@/database/type';import {getWorkspaceScopedPermissionMatches,isWorkspacePrimaryOwner,+ resolveWorkspaceGrantedPermissions,} from '@/server/services/workspacePermission';import { canPerformResourceAction } from './index';@@ -20,16 +21,19 @@ vi.mock('@/database/models/resourcePermission', () => ({vi.mock('@/server/services/workspacePermission', () => ({getWorkspaceScopedPermissionMatches: vi.fn(),isWorkspacePrimaryOwner: vi.fn(),+ resolveWorkspaceGrantedPermissions: vi.fn(),}));const permissionMatchesMock = vi.mocked(getWorkspaceScopedPermissionMatches);const primaryOwnerMock = vi.mocked(isWorkspacePrimaryOwner);+const resolveGrantsMock = vi.mocked(resolveWorkspaceGrantedPermissions);const db = {} as LobeChatDatabase;const meta = { userId: 'creator', visibility: 'public', workspaceId: 'ws-1' };describe('canPerformResourceAction', () => {beforeEach(() => {vi.clearAllMocks();+ resolveGrantsMock.mockResolvedValue(['ai_model:invoke:all']);});it('lets a Workspace admin bypass view-only Member Permissions', async () => {@@ -154,8 +158,10 @@ describe('canPerformResourceAction', () => {).resolves.toBe(false);});- it('still applies the resource level to an ordinary member', async () => {- permissionMatchesMock.mockResolvedValue({ hasAllScope: false, hasOwnerScope: true });+ it('still applies the resource level when an ordinary member can invoke all agents', async () => {+ permissionMatchesMock+ .mockResolvedValueOnce({ hasAllScope: true, hasOwnerScope: false })+ .mockResolvedValueOnce({ hasAllScope: false, hasOwnerScope: true });effectiveAccessMock.mockResolvedValue('view');await expect(@@ -169,5 +175,32 @@ describe('canPerformResourceAction', () => {workspaceId: 'ws-1',}),).resolves.toBe(false);+ expect(permissionMatchesMock.mock.calls.map(([input]) => input.action)).toEqual([+ 'AI_MODEL_INVOKE',+ 'AGENT_UPDATE',+ ]);+ });++ it('reads the caller grants once even when two actions are matched', async () => {+ permissionMatchesMock+ .mockResolvedValueOnce({ hasAllScope: true, hasOwnerScope: false })+ .mockResolvedValueOnce({ hasAllScope: false, hasOwnerScope: true });+ effectiveAccessMock.mockResolvedValue('view');++ await canPerformResourceAction({+ action: 'use',+ db,+ meta,+ resourceId: 'agent-1',+ resourceType: 'agent',+ userId: 'member',+ workspaceId: 'ws-1',+ });++ expect(resolveGrantsMock).toHaveBeenCalledTimes(1);+ expect(permissionMatchesMock.mock.calls.map(([input]) => input.grantedPermissions)).toEqual([+ ['ai_model:invoke:all'],+ ['ai_model:invoke:all'],+ ]);});});diff --git a/apps/server/src/services/resourcePermission/index.ts b/apps/server/src/services/resourcePermission/index.tsindex 8212395970e..1f8aeb55e39 100644--- a/apps/server/src/services/resourcePermission/index.ts+++ b/apps/server/src/services/resourcePermission/index.ts@@ -9,6 +9,7 @@ import type { LobeChatDatabase } from '@/database/type';import {getWorkspaceScopedPermissionMatches,isWorkspacePrimaryOwner,+ resolveWorkspaceGrantedPermissions,} from '@/server/services/workspacePermission';export interface ResourceMeta {@@ -101,9 +102,9 @@ const getRequiredAccessLevel = (action: ResourceAccessAction): ResourceAccessLev/*** Merge Workspace RBAC (the capability ceiling) with one public resource's- * Workspace access level. The creator and Workspace admins (`:all`) bypass- * Member Permissions for public resources, but never bypass the RBAC ceiling;- * private resources remain creator-only.+ * Workspace access level. The creator and Workspace admins (resource+ * `UPDATE:all`) bypass Member Permissions for public resources, but never+ * bypass the RBAC ceiling; private resources remain creator-only.*/export const canPerformResourceAction = async (params: {action: ResourceAccessAction;@@ -124,10 +125,15 @@ export const canPerformResourceAction = async (params: {if (isPrivate && !isCreator) return false;const rbacAction = getRbacAction(resourceType, action);+ // Resolve the caller's grants once: the resource-admin check below matches a+ // second action, and re-resolving would double the RBAC round trips on the+ // per-target conversation guards.+ const resolvedPermissions =+ grantedPermissions ?? (await resolveWorkspaceGrantedPermissions({ db, userId, workspaceId }));const { hasAllScope, hasOwnerScope } = await getWorkspaceScopedPermissionMatches({action: rbacAction,db,- grantedPermissions,+ grantedPermissions: resolvedPermissions,userId,workspaceId,});@@ -145,10 +151,26 @@ export const canPerformResourceAction = async (params: {if (action === 'manage') return isCreator || (!isPrivate && hasAllScope);if (action === 'delete') return isCreator || (!isPrivate && hasAllScope);- const bypassesMemberAccessLevel = isCreator || (!isPrivate && hasAllScope);- if (bypassesMemberAccessLevel) return true;+ if (isCreator) return true;if (isPrivate) return false;+ // Ordinary members hold `READ:all` and `AI_MODEL_INVOKE:all`; those are the+ // capability ceiling, not an admin grant that may bypass General Access.+ const resourceEditAction = RESOURCE_ACTIONS[resourceType].edit;+ const hasResourceAdminScope =+ rbacAction === resourceEditAction+ ? hasAllScope+ : (+ await getWorkspaceScopedPermissionMatches({+ action: resourceEditAction,+ db,+ grantedPermissions: resolvedPermissions,+ userId,+ workspaceId,+ })+ ).hasAllScope;+ if (hasResourceAdminScope) return true;+const accessLevel = await new ResourcePermissionModel(db, workspaceId).getEffectiveAccessLevel(resourceType,resourceId,diff --git a/apps/server/src/services/workspacePermission/index.ts b/apps/server/src/services/workspacePermission/index.tsindex f36084489e2..7558cf552d6 100644--- a/apps/server/src/services/workspacePermission/index.ts+++ b/apps/server/src/services/workspacePermission/index.ts@@ -45,28 +45,26 @@ export interface WorkspaceScopedPermissionMatches {}/**- * Resolve both resource scopes with one RBAC read. Membership and permission- * lookup are independent, so run them in parallel to keep permission-panel- * mutations to one database-latency wave.+ * Read the caller's effective workspace permission codes once. Membership and+ * permission lookup are independent, so run them in parallel to keep+ * permission-panel mutations to one database-latency wave. A non-member+ * resolves to no codes at all.+ *+ * Callers that match more than one action must resolve here first and pass the+ * result down as `grantedPermissions`, otherwise every extra action costs+ * another RBAC round trip.*/-export const getWorkspaceScopedPermissionMatches = async ({- action,+export const resolveWorkspaceGrantedPermissions = async ({db,- grantedPermissions,requireMembership = true,userId,workspaceId,-}: Omit<WorkspaceScopedPermissionOptions, 'scopes'> & {- grantedPermissions?: readonly string[];-}): Promise<WorkspaceScopedPermissionMatches> => {- if (grantedPermissions) {- const granted = new Set(grantedPermissions);- return {- hasAllScope: getScopePermissions(action, ['ALL']).some((code) => granted.has(code)),- hasOwnerScope: getScopePermissions(action, ['OWNER']).some((code) => granted.has(code)),- };- }-+}: {+ db: LobeChatDatabase;+ requireMembership?: boolean;+ userId: string;+ workspaceId: string;+}): Promise<string[]> => {const membershipPromise = requireMembership? db.select({ userId: workspaceMembers.userId })@@ -85,9 +83,26 @@ export const getWorkspaceScopedPermissionMatches = async ({membershipPromise,new RbacModel(db, userId).getUserPermissions({ workspaceId }),]);- if (!membership[0]) return { hasAllScope: false, hasOwnerScope: false };- const granted = new Set(resolvedPermissions);+ return membership[0] ? resolvedPermissions : [];+};++/** Match one action's `:all` / `:owner` scopes against the caller's grants. */+export const getWorkspaceScopedPermissionMatches = async ({+ action,+ db,+ grantedPermissions,+ requireMembership = true,+ userId,+ workspaceId,+}: Omit<WorkspaceScopedPermissionOptions, 'scopes'> & {+ grantedPermissions?: readonly string[];+}): Promise<WorkspaceScopedPermissionMatches> => {+ const granted = new Set(+ grantedPermissions ??+ (await resolveWorkspaceGrantedPermissions({ db, requireMembership, userId, workspaceId })),+ );+return {hasAllScope: getScopePermissions(action, ['ALL']).some((code) => granted.has(code)),hasOwnerScope: getScopePermissions(action, ['OWNER']).some((code) => granted.has(code)),diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 304a0713620..0812fcde6dc 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1302,6 +1302,44 @@"topic.recent": "Recent Topics","topic.saveCurrentMessages": "Save current conversation as topic","topic.viewAll": "View All Topics",+ "topicComment.anchor": "Original message",+ "topicComment.anchorDeleted": "Original message deleted",+ "topicComment.anchorEmpty": "Empty message",+ "topicComment.author.deactivated": "Deleted user",+ "topicComment.author.former": "Former member",+ "topicComment.cancel": "Cancel",+ "topicComment.commentOnMessage": "Comment on this message",+ "topicComment.createFailed": "Failed to post comment. Your draft is still here.",+ "topicComment.delete": "Delete",+ "topicComment.deleteConfirm.content": "This comment will be removed. Replies will remain if this starts a thread.",+ "topicComment.deleteConfirm.title": "Delete this comment?",+ "topicComment.deleteFailed": "Failed to delete comment",+ "topicComment.deleted": "This comment was deleted.",+ "topicComment.edit": "Edit",+ "topicComment.edited": "edited",+ "topicComment.empty": "No comments yet",+ "topicComment.loadMore": "Load more",+ "topicComment.messageComments": "Message comments",+ "topicComment.messagePlaceholder": "Comment on this message…",+ "topicComment.notFound": "This comment no longer exists",+ "topicComment.openMessageComments": "Open {{count}} message comments",+ "topicComment.placeholder": "Add a comment…",+ "topicComment.removed": "This comment was removed by a Workspace Owner.",+ "topicComment.removedOwn": "Your comment was removed by a Workspace Owner.",+ "topicComment.removedOwnerView": "Removed by a Workspace Owner. This content is visible only to Workspace Owners during the recovery period.",+ "topicComment.repliesTitle": "Replies",+ "topicComment.replies_one": "{{count}} reply",+ "topicComment.replies_other": "{{count}} replies",+ "topicComment.reply": "Reply",+ "topicComment.replyPlaceholder": "Write a reply…",+ "topicComment.restore": "Restore",+ "topicComment.restoreDeadline": "Restorable until {{date}}",+ "topicComment.restoreFailed": "Failed to restore comment",+ "topicComment.save": "Save",+ "topicComment.sending": "Sending…",+ "topicComment.thread": "Comment thread",+ "topicComment.title": "Comments",+ "topicComment.updateFailed": "Failed to update comment","translate.action": "Translate","translate.clear": "Clear Translation","tts.action": "Text-to-Speech",diff --git a/locales/en-US/notification.json b/locales/en-US/notification.jsonindex 40d4017c4c9..8a4f3a275e9 100644--- a/locales/en-US/notification.json+++ b/locales/en-US/notification.json@@ -42,6 +42,16 @@"subscription_payment_failed": "Your subscription renewal payment failed. Please update your payment method to keep your subscription active.","subscription_payment_failed_action": "Update payment method","subscription_payment_failed_title": "Subscription renewal payment failed",+ "topic_comment_activity": "{{actorLabel}} commented on your topic.",+ "topic_comment_activity_mentioned": "{{actorLabel}} mentioned you in a comment.",+ "topic_comment_activity_mentioned_title": "You were mentioned in a comment",+ "topic_comment_activity_replied": "{{actorLabel}} replied to your comment.",+ "topic_comment_activity_replied_title": "New reply to your comment",+ "topic_comment_activity_title": "New topic comment",+ "topic_comment_removed_by_workspace_owner": "Your comment was removed by a Workspace Owner. Open the discussion to view its place in the thread.",+ "topic_comment_removed_by_workspace_owner_title": "Comment removed",+ "topic_comment_restored_by_workspace_owner": "A Workspace Owner restored your comment.",+ "topic_comment_restored_by_workspace_owner_title": "Comment restored","video_generation_completed": "Your video \"{{prompt}}\" is ready.","video_generation_completed_title": "Video generation completed","workspace_member_invited": "{{inviterLabel}} invited you to join workspace \"{{workspaceName}}\" as a {{role}}.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex fc4c14b1ed4..21f5f2c9d5f 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1302,6 +1302,44 @@"topic.recent": "最近话题","topic.saveCurrentMessages": "保存为话题","topic.viewAll": "查看全部主题",+ "topicComment.anchor": "原消息",+ "topicComment.anchorDeleted": "原消息已删除",+ "topicComment.anchorEmpty": "空消息",+ "topicComment.author.deactivated": "已注销用户",+ "topicComment.author.former": "已离开成员",+ "topicComment.cancel": "取消",+ "topicComment.commentOnMessage": "评论这条消息",+ "topicComment.createFailed": "评论发布失败,草稿已保留",+ "topicComment.delete": "删除",+ "topicComment.deleteConfirm.content": "此评论将被删除。如果已有回复,回复内容会继续保留。",+ "topicComment.deleteConfirm.title": "删除这条评论?",+ "topicComment.deleteFailed": "评论删除失败",+ "topicComment.deleted": "此评论已删除",+ "topicComment.edit": "编辑",+ "topicComment.edited": "已编辑",+ "topicComment.empty": "还没有评论",+ "topicComment.loadMore": "加载更多",+ "topicComment.messageComments": "消息评论",+ "topicComment.messagePlaceholder": "评论这条消息…",+ "topicComment.notFound": "此评论已不存在",+ "topicComment.openMessageComments": "打开 {{count}} 条消息评论",+ "topicComment.placeholder": "添加评论…",+ "topicComment.removed": "此评论已被 Workspace Owner 移除。",+ "topicComment.removedOwn": "你的评论已被 Workspace Owner 移除。",+ "topicComment.removedOwnerView": "此评论已被 Workspace Owner 移除。恢复期内,只有 Workspace Owner 可以查看原内容。",+ "topicComment.repliesTitle": "回复",+ "topicComment.replies_one": "{{count}} 条回复",+ "topicComment.replies_other": "{{count}} 条回复",+ "topicComment.reply": "回复",+ "topicComment.replyPlaceholder": "写下回复…",+ "topicComment.restore": "恢复",+ "topicComment.restoreDeadline": "可恢复至 {{date}}",+ "topicComment.restoreFailed": "评论恢复失败",+ "topicComment.save": "保存",+ "topicComment.sending": "发送中…",+ "topicComment.thread": "评论线程",+ "topicComment.title": "评论",+ "topicComment.updateFailed": "评论更新失败","translate.action": "翻译","translate.clear": "删除翻译","tts.action": "语音朗读",diff --git a/locales/zh-CN/notification.json b/locales/zh-CN/notification.jsonindex c49c4fe0dae..aeaf052a04e 100644--- a/locales/zh-CN/notification.json+++ b/locales/zh-CN/notification.json@@ -42,6 +42,16 @@"subscription_payment_failed": "您的订阅续费扣款失败。请更新您的付款方式以保持订阅有效。","subscription_payment_failed_action": "更新付款方式","subscription_payment_failed_title": "订阅续费扣款失败",+ "topic_comment_activity": "{{actorLabel}} 评论了你的话题。",+ "topic_comment_activity_mentioned": "{{actorLabel}} 在评论中提到了你。",+ "topic_comment_activity_mentioned_title": "你在评论中被提及",+ "topic_comment_activity_replied": "{{actorLabel}} 回复了你的评论。",+ "topic_comment_activity_replied_title": "你的评论有新回复",+ "topic_comment_activity_title": "话题有新评论",+ "topic_comment_removed_by_workspace_owner": "你的评论已被 Workspace Owner 移除。打开讨论可查看它在评论串中的位置。",+ "topic_comment_removed_by_workspace_owner_title": "评论已被移除",+ "topic_comment_restored_by_workspace_owner": "Workspace Owner 已恢复你的评论。",+ "topic_comment_restored_by_workspace_owner_title": "评论已恢复","video_generation_completed": "视频「{{prompt}}」已生成。","video_generation_completed_title": "视频生成完成","workspace_member_invited": "{{inviterLabel}} 邀请您以 {{role}} 的身份加入工作区 \"{{workspaceName}}\"。",diff --git a/packages/business-server/src/topic-comment/notifyActivity.ts b/packages/business-server/src/topic-comment/notifyActivity.tsnew file mode 100644index 00000000000..47a775286e0--- /dev/null+++ b/packages/business-server/src/topic-comment/notifyActivity.ts@@ -0,0 +1,20 @@+export type TopicCommentActivityKind = 'commented' | 'mentioned' | 'replied';++export interface TopicCommentActivityRecipient {+ kind: TopicCommentActivityKind;+ userId: string;+}++export interface NotifyTopicCommentActivityParams {+ actorUserId: string;+ commentId: string;+ recipients: TopicCommentActivityRecipient[];+ rootCommentId: string;+ topicId: string;+ workspaceId: string;+}++/** Optional integration hook for delivering comment activity to recipients. */+export async function notifyTopicCommentActivity(+ _params: NotifyTopicCommentActivityParams,+): Promise<void> {}diff --git a/packages/business-server/src/topic-comment/notifyModeration.ts b/packages/business-server/src/topic-comment/notifyModeration.tsnew file mode 100644index 00000000000..d6aafbb1e12--- /dev/null+++ b/packages/business-server/src/topic-comment/notifyModeration.ts@@ -0,0 +1,14 @@+export interface NotifyTopicCommentModerationParams {+ authorUserId: string;+ commentId: string;+ event: 'removed' | 'restored';+ eventId: string;+ rootCommentId: string;+ topicId: string;+ workspaceId: string;+}++/** Optional integration hook for comment moderation activity. */+export async function notifyTopicCommentModeration(+ _params: NotifyTopicCommentModerationParams,+): Promise<void> {}diff --git a/packages/context-engine/src/processors/PlaceholderVariables.ts b/packages/context-engine/src/processors/PlaceholderVariables.tsindex ca3eb28add8..c5480377334 100644--- a/packages/context-engine/src/processors/PlaceholderVariables.ts+++ b/packages/context-engine/src/processors/PlaceholderVariables.ts@@ -1,3 +1,4 @@+import { truncateSurrogateSafe } from '@lobechat/utils';import debug from 'debug';import { BaseProcessor } from '../base/BaseProcessor';@@ -11,6 +12,8 @@ declare module '../types' {const log = debug('context-engine:processor:PlaceholderVariablesProcessor');+const CONTENT_PREVIEW_LENGTH = 200;+/*** Build a short, log-safe preview of a message's content.*@@ -18,16 +21,17 @@ const log = debug('context-engine:processor:PlaceholderVariablesProcessor');* functions / symbols, so naively calling `.slice` on its result crashes —* this is exactly how a tool error result with `content: undefined`* (e.g. budget-exceeded errors) used to take down the whole processor.- * Always coerce to a string before slicing.+ * Always coerce to a string before slicing, and cut surrogate-safely so a+ * mid-emoji slice cannot leave a lone surrogate in the preview.*/-const buildContentPreview = (content: unknown): string => {- if (typeof content === 'string') return content.slice(0, 200);+export const buildContentPreview = (content: unknown): string => {+ if (typeof content === 'string') return truncateSurrogateSafe(content, CONTENT_PREVIEW_LENGTH);try {const serialized = JSON.stringify(content);- return (serialized ?? String(content)).slice(0, 200);+ return truncateSurrogateSafe(serialized ?? String(content), CONTENT_PREVIEW_LENGTH);} catch {- return String(content).slice(0, 200);+ return truncateSurrogateSafe(String(content), CONTENT_PREVIEW_LENGTH);}};diff --git a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.tsindex 555a5469746..75191f66ee3 100644--- a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts+++ b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import {+ buildContentPreview,formatPlaceholderValues,parsePlaceholderVariables,parsePlaceholderVariablesMessages,@@ -17,6 +18,22 @@ describe('PlaceholderVariablesProcessor', () => {nested: () => 'Value with {{date}} inside',};+ describe('buildContentPreview', () => {+ it('does not split an emoji at the string preview boundary', () => {+ const preview = buildContentPreview(`${'a'.repeat(199)}😀tail`);++ expect(preview).toBe('a'.repeat(199));+ expect(preview).not.toMatch(/[\uD800-\uDFFF]/);+ });++ it('does not split an emoji in a serialized content preview', () => {+ const preview = buildContentPreview({ value: `${'a'.repeat(189)}😀tail` });++ expect(preview).toBe(`{"value":"${'a'.repeat(189)}`);+ expect(preview).not.toMatch(/[\uD800-\uDFFF]/);+ });+ });+describe('parsePlaceholderVariables', () => {it('should replace simple placeholder variables', () => {const text = 'Today is {{date}} and the time is {{time}}';diff --git a/packages/database/src/models/__tests__/agentTransfer.test.ts b/packages/database/src/models/__tests__/agentTransfer.test.tsindex 625d26c3f21..d9149b9bf00 100644--- a/packages/database/src/models/__tests__/agentTransfer.test.ts+++ b/packages/database/src/models/__tests__/agentTransfer.test.ts@@ -25,14 +25,22 @@ import {tasks,taskTopics,threads,+ topicCommentMentions,+ topicComments,topics,users,workspaces,} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AgentModel } from '../agent';+import {+ TOPIC_COMMENT_TOPIC_NOT_FOUND,+ TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS,+ TopicCommentModel,+} from '../topicComment';const serverDB: LobeChatDatabase = await getTestDB();+const isServerDB = process.env.TEST_SERVER_DB === '1';const userId = 'transfer-test-user';const targetUserId = 'transfer-test-target-user';@@ -350,6 +358,174 @@ describe('AgentModel.transferAgent', () => {expect(transferredAgent.workspaceId).toBe(wsId1);});+ it('should move topic comments and mentions with the topic between workspaces', async () => {+ const model = new AgentModel(serverDB, userId, wsId1);+ const agent = await model.create({ title: 'Commented Agent' });+ const originalCommentUpdatedAt = new Date('2024-01-02T03:04:05.000Z');++ await serverDB+ .insert(topics)+ .values({ id: 'comment-topic-1', agentId: agent.id, userId, workspaceId: wsId1 });+ await serverDB.insert(topicComments).values({+ authorUserId: userId,+ clientId: 'comment-client-1',+ content: 'team note',+ id: 'tcm-move-1',+ topicId: 'comment-topic-1',+ updatedAt: originalCommentUpdatedAt,+ workspaceId: wsId1,+ });+ await serverDB.insert(topicCommentMentions).values({+ commentId: 'tcm-move-1',+ mentionedUserId: targetUserId,+ workspaceId: wsId1,+ });++ await model.transferAgent(agent.id, wsId2, targetUserId);++ const [comment] = await serverDB+ .select()+ .from(topicComments)+ .where(eq(topicComments.id, 'tcm-move-1'));+ const [mention] = await serverDB+ .select()+ .from(topicCommentMentions)+ .where(eq(topicCommentMentions.commentId, 'tcm-move-1'));+ expect(comment.workspaceId).toBe(wsId2);+ expect(comment.updatedAt).toEqual(originalCommentUpdatedAt);+ expect(mention.workspaceId).toBe(wsId2);+ });++ it('should delete topic comments when transferring to personal scope', async () => {+ const model = new AgentModel(serverDB, userId, wsId1);+ const agent = await model.create({ title: 'Commented Agent 2' });++ await serverDB+ .insert(topics)+ .values({ id: 'comment-topic-2', agentId: agent.id, userId, workspaceId: wsId1 });+ await serverDB.insert(topicComments).values({+ authorUserId: userId,+ clientId: 'comment-client-root',+ content: 'root',+ id: 'tcm-root',+ topicId: 'comment-topic-2',+ workspaceId: wsId1,+ });+ await serverDB.insert(topicComments).values({+ authorUserId: userId,+ clientId: 'comment-client-reply',+ content: 'reply',+ id: 'tcm-reply',+ parentCommentId: 'tcm-root',+ topicId: 'comment-topic-2',+ workspaceId: wsId1,+ });+ await serverDB.insert(topicCommentMentions).values({+ commentId: 'tcm-root',+ mentionedUserId: targetUserId,+ workspaceId: wsId1,+ });++ await model.transferAgent(agent.id, null, userId);++ // Personal topics cannot hold comments (NOT NULL workspaceId) — the whole+ // thread (root + reply) is removed and mention rows cascade with it+ const remaining = await serverDB+ .select()+ .from(topicComments)+ .where(eq(topicComments.topicId, 'comment-topic-2'));+ const mentions = await serverDB+ .select()+ .from(topicCommentMentions)+ .where(eq(topicCommentMentions.commentId, 'tcm-root'));+ expect(remaining).toHaveLength(0);+ expect(mentions).toHaveLength(0);+ });++ it('should flag teammate-authored and orphaned comments as foreign rows', async () => {+ const model = new AgentModel(serverDB, userId, wsId1);+ const agent = await model.create({ title: 'Guarded Agent' });++ await serverDB+ .insert(topics)+ .values({ id: 'guard-topic', agentId: agent.id, userId, workspaceId: wsId1 });++ // Caller's own comment — not foreign+ await serverDB.insert(topicComments).values({+ authorUserId: userId,+ clientId: 'guard-own',+ content: 'my own note',+ id: 'tcm-guard-own',+ topicId: 'guard-topic',+ workspaceId: wsId1,+ });+ expect(await model.transferHasForeignRows(agent.id)).toBe(false);++ // A teammate's comment on the caller's own topic — foreign+ await serverDB.insert(topicComments).values({+ authorUserId: targetUserId,+ clientId: 'guard-teammate',+ content: 'teammate note',+ id: 'tcm-guard-teammate',+ topicId: 'guard-topic',+ workspaceId: wsId1,+ });+ expect(await model.transferHasForeignRows(agent.id)).toBe(true);++ // Orphaned comment (author account deleted ⇒ NULL) — still not the+ // caller's work; ne() alone would silently skip it+ await serverDB.delete(topicComments).where(eq(topicComments.id, 'tcm-guard-teammate'));+ await serverDB.insert(topicComments).values({+ authorUserId: null,+ clientId: 'guard-orphan',+ content: 'orphaned note',+ id: 'tcm-guard-orphan',+ topicId: 'guard-topic',+ workspaceId: wsId1,+ });+ expect(await model.transferHasForeignRows(agent.id)).toBe(true);+ });++ it.skipIf(!isServerDB)(+ 'should serialize comment creation with the authoritative transfer check',+ async () => {+ const trials = 10;++ for (let i = 0; i < trials; i++) {+ const model = new AgentModel(serverDB, userId, wsId1);+ const commenterModel = new TopicCommentModel(serverDB, targetUserId, wsId1);+ const agent = await model.create({ title: `Race Agent ${i}` });+ const topicId = `transfer-comment-race-topic-${i}`;+ await serverDB.insert(topics).values({+ agentId: agent.id,+ id: topicId,+ userId,+ workspaceId: wsId1,+ });++ const outcomes = await Promise.allSettled([+ model.transferAgent(agent.id, wsId2, userId, undefined, {+ rejectForeignTopicCommentAuthors: true,+ }),+ commenterModel.createWithMentions({+ clientId: `transfer-comment-race-${i}`,+ content: 'concurrent teammate comment',+ topicId,+ }),+ ]);++ expect(outcomes.map(({ status }) => status).sort()).toEqual(['fulfilled', 'rejected']);+ const rejection = outcomes.find(+ (outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected',+ );+ expect([+ TOPIC_COMMENT_TOPIC_NOT_FOUND,+ TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS,+ ]).toContain(rejection?.reason.message);+ }+ },+ );+it('should update bot providers', async () => {const model = new AgentModel(serverDB, userId);const agent = await model.create({ title: 'Agent' });@@ -711,6 +887,37 @@ describe('AgentModel.transferAgents (batch)', () => {expect(untouched?.workspaceId).toBeNull();});+ it('should reject the whole batch when a topic has a foreign comment', async () => {+ const model = new AgentModel(serverDB, userId, wsId1);+ const agent1 = await model.create({ title: 'Guarded 1' });+ const agent2 = await model.create({ title: 'Guarded 2' });+ await serverDB.insert(topics).values({+ agentId: agent2.id,+ id: 'batch-guard-topic',+ userId,+ workspaceId: wsId1,+ });+ await serverDB.insert(topicComments).values({+ authorUserId: targetUserId,+ clientId: 'batch-guard-comment',+ content: 'teammate note',+ id: 'tcm-batch-guard',+ topicId: 'batch-guard-topic',+ workspaceId: wsId1,+ });++ await expect(+ model.transferAgents([agent1.id, agent2.id], wsId2, userId, undefined, {+ rejectForeignTopicCommentAuthors: true,+ }),+ ).rejects.toThrow(TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS);++ for (const agentId of [agent1.id, agent2.id]) {+ const untouched = await serverDB.query.agents.findFirst({ where: eq(agents.id, agentId) });+ expect(untouched?.workspaceId).toBe(wsId1);+ }+ });+it('should return empty array for empty input', async () => {const model = new AgentModel(serverDB, userId);await expect(model.transferAgents([], wsId1, userId)).resolves.toEqual([]);diff --git a/packages/database/src/models/__tests__/topicComment.test.ts b/packages/database/src/models/__tests__/topicComment.test.tsnew file mode 100644index 00000000000..2780f4bbc29--- /dev/null+++ b/packages/database/src/models/__tests__/topicComment.test.ts@@ -0,0 +1,1377 @@+// @vitest-environment node+import { eq, inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import {+ messages,+ topicCommentMentions,+ topicComments,+ topics,+ users,+ workspaces,+} from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import {+ purgeExpiredTopicCommentModeration,+ TOPIC_COMMENT_MESSAGE_NOT_IN_TOPIC,+ TOPIC_COMMENT_PARENT_NOT_FOUND,+ TOPIC_COMMENT_REPLY_CANNOT_ANCHOR,+ TOPIC_COMMENT_REPLY_DEPTH_EXCEEDED,+ TOPIC_COMMENT_TOPIC_NOT_FOUND,+ TOPIC_COMMENT_WORKSPACE_REQUIRED,+ TopicCommentModel,+} from '../topicComment';++const serverDB: LobeChatDatabase = await getTestDB();++const authorId = 'tc-author';+const memberId = 'tc-member';+const outsiderId = 'tc-outsider';++const workspaceAId = 'tc-ws-a';+const workspaceBId = 'tc-ws-b';++const workspaceTopicId = 'tc-topic-a';+const secondWorkspaceTopicId = 'tc-topic-idempotency-a2';+const personalTopicId = 'tc-topic-personal';+const otherWorkspaceTopicId = 'tc-topic-b';++const anchoredMessageId = 'tc-msg-anchor';+const otherTopicMessageId = 'tc-msg-other';++const authorModel = new TopicCommentModel(serverDB, authorId, workspaceAId);+const memberModel = new TopicCommentModel(serverDB, memberId, workspaceAId);+const outsiderModel = new TopicCommentModel(serverDB, outsiderId, workspaceBId);+const authorInOtherWorkspaceModel = new TopicCommentModel(serverDB, authorId, workspaceBId);+const personalModel = new TopicCommentModel(serverDB, authorId);++const cleanup = async () => {+ await serverDB.delete(users);+ await serverDB.delete(workspaces);+};++beforeEach(async () => {+ await cleanup();++ await serverDB.insert(users).values([{ id: authorId }, { id: memberId }, { id: outsiderId }]);++ await serverDB.insert(workspaces).values([+ { id: workspaceAId, name: 'Workspace A', primaryOwnerId: authorId, slug: 'tc-ws-a' },+ { id: workspaceBId, name: 'Workspace B', primaryOwnerId: outsiderId, slug: 'tc-ws-b' },+ ]);++ await serverDB.insert(topics).values([+ { id: workspaceTopicId, userId: authorId, workspaceId: workspaceAId },+ { id: secondWorkspaceTopicId, userId: authorId, workspaceId: workspaceAId },+ { id: personalTopicId, userId: authorId, workspaceId: null },+ { id: otherWorkspaceTopicId, userId: outsiderId, workspaceId: workspaceBId },+ ]);++ await serverDB.insert(messages).values([+ {+ content: 'anchor message content '.repeat(20),+ id: anchoredMessageId,+ role: 'assistant',+ topicId: workspaceTopicId,+ userId: authorId,+ workspaceId: workspaceAId,+ },+ {+ content: 'a message in another workspace topic',+ id: otherTopicMessageId,+ role: 'user',+ topicId: otherWorkspaceTopicId,+ userId: outsiderId,+ workspaceId: workspaceBId,+ },+ ]);+});++afterEach(cleanup);++describe('TopicCommentModel', () => {+ describe('createWithMentions', () => {+ it('should create a topic-level comment stamped with the topic workspaceId', async () => {+ const result = await authorModel.createWithMentions({+ clientId: 'client-1',+ content: 'a topic-level comment',+ topicId: workspaceTopicId,+ });++ expect(result.isDuplicate).toBe(false);+ expect(result.addedMentionUserIds).toEqual([]);+ expect(result.topicOwnerUserId).toBe(authorId);+ expect(result.comment).toMatchObject({+ anchorPreview: null,+ authorUserId: authorId,+ content: 'a topic-level comment',+ messageId: null,+ topicId: workspaceTopicId,+ workspaceId: workspaceAId,+ });+ });++ it('should snapshot a truncated anchorPreview for message-anchored comments', async () => {+ const result = await authorModel.createWithMentions({+ clientId: 'client-2',+ content: 'anchored comment',+ messageId: anchoredMessageId,+ topicId: workspaceTopicId,+ });++ expect(result.comment.messageId).toBe(anchoredMessageId);+ expect(result.comment.anchorPreview?.role).toBe('assistant');+ expect(result.comment.anchorPreview?.excerpt).toHaveLength(200);+ expect(result.comment.anchorPreview?.excerpt.startsWith('anchor message content')).toBe(true);+ });++ it('should not split a surrogate pair at the excerpt cut (jsonb rejects lone surrogates)', async () => {+ // 199 ASCII chars put the 200th code unit in the middle of the emoji's+ // surrogate pair — a bare slice(0, 200) would keep a lone high+ // surrogate, and the jsonb INSERT itself would fail in Postgres.+ const emojiMessageId = 'tc-msg-emoji-boundary';+ await serverDB.insert(messages).values({+ content: 'a'.repeat(199) + '😀 and more text',+ id: emojiMessageId,+ role: 'user',+ topicId: workspaceTopicId,+ userId: authorId,+ workspaceId: workspaceAId,+ });++ const result = await authorModel.createWithMentions({+ clientId: 'client-emoji-cut',+ content: 'anchored across an emoji boundary',+ messageId: emojiMessageId,+ topicId: workspaceTopicId,+ });++ expect(result.comment.anchorPreview?.excerpt).toBe('a'.repeat(199));+ });++ it('should create mention rows and dedupe the input list', async () => {+ const result = await authorModel.createWithMentions({+ clientId: 'client-3',+ content: 'mentioning @member',+ mentionedUserIds: [memberId, memberId],+ topicId: workspaceTopicId,+ });++ expect(result.addedMentionUserIds).toEqual([memberId]);++ const mentions = await authorModel.getMentions(result.comment.id);+ expect(mentions).toHaveLength(1);+ expect(mentions[0]).toMatchObject({+ commentId: result.comment.id,+ mentionedUserId: memberId,+ workspaceId: workspaceAId,+ });+ });++ it('should return the existing row on retried create with the same clientId', async () => {+ const first = await authorModel.createWithMentions({+ clientId: 'client-retry',+ content: 'first attempt',+ mentionedUserIds: [memberId],+ topicId: workspaceTopicId,+ });+ const retry = await authorModel.createWithMentions({+ clientId: 'client-retry',+ content: 'retried attempt',+ mentionedUserIds: [memberId],+ topicId: workspaceTopicId,+ });++ expect(retry.isDuplicate).toBe(true);+ expect(retry.comment.id).toBe(first.comment.id);+ expect(retry.comment.content).toBe('first attempt');+ expect(retry.addedMentionUserIds).toEqual([]);+ expect(retry.topicOwnerUserId).toBe(authorId);++ const rows = await serverDB+ .select()+ .from(topicComments)+ .where(eq(topicComments.authorUserId, authorId));+ expect(rows).toHaveLength(1);+ });++ it('should allow the same clientId for different authors', async () => {+ await authorModel.createWithMentions({+ clientId: 'shared-client-id',+ content: 'author comment',+ topicId: workspaceTopicId,+ });+ const other = await memberModel.createWithMentions({+ clientId: 'shared-client-id',+ content: 'member comment',+ topicId: workspaceTopicId,+ });++ expect(other.isDuplicate).toBe(false);+ expect(other.comment.authorUserId).toBe(memberId);+ });++ it('should return parent-not-found when reply creation races with root deletion', async () => {+ const root = await authorModel.createWithMentions({+ clientId: 'reply-delete-race-root',+ content: 'root deleted during reply creation',+ topicId: workspaceTopicId,+ });+ let releaseDelete!: () => void;+ let reportRootLocked!: () => void;+ const deleteReleased = new Promise<void>((resolve) => {+ releaseDelete = resolve;+ });+ const rootLocked = new Promise<void>((resolve) => {+ reportRootLocked = resolve;+ });+ const deleting = serverDB.transaction(async (tx) => {+ await tx+ .select({ id: topicComments.id })+ .from(topicComments)+ .where(eq(topicComments.id, root.comment.id))+ .for('update');+ reportRootLocked();+ await deleteReleased;+ await tx.delete(topicComments).where(eq(topicComments.id, root.comment.id));+ });+ await rootLocked;++ const creatingReply = memberModel.createWithMentions({+ clientId: 'reply-delete-race-reply',+ content: 'reply racing with root deletion',+ parentCommentId: root.comment.id,+ topicId: workspaceTopicId,+ });+ await new Promise<void>((resolve) => setTimeout(resolve, 50));+ releaseDelete();++ const [deleteResult, createResult] = await Promise.allSettled([deleting, creatingReply]);+ expect(deleteResult.status).toBe('fulfilled');+ expect(createResult).toMatchObject({+ reason: expect.objectContaining({ message: TOPIC_COMMENT_PARENT_NOT_FOUND }),+ status: 'rejected',+ });+ });++ it('should allow the same clientId for the same author in different topics', async () => {+ await authorModel.createWithMentions({+ clientId: 'topic-scoped-client-id',+ content: 'first topic comment',+ topicId: workspaceTopicId,+ });+ const other = await authorModel.createWithMentions({+ clientId: 'topic-scoped-client-id',+ content: 'second topic comment',+ topicId: secondWorkspaceTopicId,+ });++ expect(other.isDuplicate).toBe(false);+ expect(other.comment).toMatchObject({+ content: 'second topic comment',+ topicId: secondWorkspaceTopicId,+ workspaceId: workspaceAId,+ });+ });++ it('should allow the same clientId for the same author in different workspaces', async () => {+ await authorModel.createWithMentions({+ clientId: 'workspace-independent-client-id',+ content: 'workspace A comment',+ topicId: workspaceTopicId,+ });+ const other = await authorInOtherWorkspaceModel.createWithMentions({+ clientId: 'workspace-independent-client-id',+ content: 'workspace B comment',+ topicId: otherWorkspaceTopicId,+ });++ expect(other.isDuplicate).toBe(false);+ expect(other.comment).toMatchObject({+ content: 'workspace B comment',+ topicId: otherWorkspaceTopicId,+ workspaceId: workspaceBId,+ });+ });++ it('should reject personal-mode topics', async () => {+ await expect(+ authorModel.createWithMentions({+ clientId: 'client-4',+ content: 'comment on personal topic',+ topicId: personalTopicId,+ }),+ ).rejects.toThrow(TOPIC_COMMENT_TOPIC_NOT_FOUND);+ });++ it('should reject cross-workspace topics with the same error as missing topics', async () => {+ await expect(+ authorModel.createWithMentions({+ clientId: 'client-5',+ content: 'cross workspace',+ topicId: otherWorkspaceTopicId,+ }),+ ).rejects.toThrow(TOPIC_COMMENT_TOPIC_NOT_FOUND);++ await expect(+ authorModel.createWithMentions({+ clientId: 'client-6',+ content: 'missing topic',+ topicId: 'tc-topic-missing',+ }),+ ).rejects.toThrow(TOPIC_COMMENT_TOPIC_NOT_FOUND);+ });++ it('should reject a messageId that belongs to another topic', async () => {+ await expect(+ authorModel.createWithMentions({+ clientId: 'client-7',+ content: 'bad anchor',+ messageId: otherTopicMessageId,+ topicId: workspaceTopicId,+ }),+ ).rejects.toThrow(TOPIC_COMMENT_MESSAGE_NOT_IN_TOPIC);+ });++ it('should reject callers without a workspaceId', async () => {+ await expect(+ personalModel.createWithMentions({+ clientId: 'client-8',+ content: 'no workspace context',+ topicId: workspaceTopicId,+ }),+ ).rejects.toThrow(TOPIC_COMMENT_WORKSPACE_REQUIRED);+ });+ });++ describe('update', () => {+ it('should let the author update content and editorData', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-u1',+ content: 'original',+ topicId: workspaceTopicId,+ });++ const result = await authorModel.update(comment.id, {+ content: 'edited',+ editorData: { root: {} },+ });++ expect(result?.comment).toMatchObject({ content: 'edited', editorData: { root: {} } });+ });++ it('should NOT let another member update the comment', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-u2',+ content: 'original',+ topicId: workspaceTopicId,+ });++ const result = await memberModel.update(comment.id, { content: 'hacked' });++ expect(result).toBeUndefined();+ const [row] = await serverDB+ .select()+ .from(topicComments)+ .where(eq(topicComments.id, comment.id));+ expect(row.content).toBe('original');+ });++ it('should ignore an overrideAuthorScope-like option — edits are author-only by design', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-u3',+ content: 'original',+ topicId: workspaceTopicId,+ });++ // Moderation is delete-only: rewriting someone else's words under their+ // name is impersonation, so update() deliberately has no override path.+ // Smuggle the flag past the type system to prove the runtime ignores it.+ const result = await memberModel.update(comment.id, { content: 'moderated' }, {+ overrideAuthorScope: true,+ } as never);++ expect(result).toBeUndefined();+ const [row] = await serverDB+ .select()+ .from(topicComments)+ .where(eq(topicComments.id, comment.id));+ expect(row.content).toBe('original');+ });++ it('should diff mentions and report only newly added user ids', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-u5',+ content: 'with mentions',+ mentionedUserIds: [memberId],+ topicId: workspaceTopicId,+ });++ const added = await authorModel.update(+ comment.id,+ { content: 'add outsider' },+ { mentionedUserIds: [memberId, outsiderId] },+ );+ expect(added?.addedMentionUserIds).toEqual([outsiderId]);++ const removed = await authorModel.update(+ comment.id,+ { content: 'drop member' },+ { mentionedUserIds: [outsiderId] },+ );+ expect(removed?.addedMentionUserIds).toEqual([]);++ const mentions = await authorModel.getMentions(comment.id);+ expect(mentions.map((m) => m.mentionedUserId)).toEqual([outsiderId]);+ });++ it('should leave mentions untouched when mentionedUserIds is omitted', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-u6',+ content: 'with mentions',+ mentionedUserIds: [memberId],+ topicId: workspaceTopicId,+ });++ await authorModel.update(comment.id, { content: 'edited' });++ const mentions = await authorModel.getMentions(comment.id);+ expect(mentions.map((m) => m.mentionedUserId)).toEqual([memberId]);+ });+ });++ describe('delete', () => {+ it('should let the author delete own comment and cascade mention rows', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-d1',+ content: 'to delete',+ mentionedUserIds: [memberId],+ topicId: workspaceTopicId,+ });++ const deleted = await authorModel.delete(comment.id);++ expect(deleted).toBe('hard');+ const mentionRows = await serverDB+ .select()+ .from(topicCommentMentions)+ .where(eq(topicCommentMentions.commentId, comment.id));+ expect(mentionRows).toHaveLength(0);+ });++ it('should NOT let another member delete the comment without override', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-d2',+ content: 'protected',+ topicId: workspaceTopicId,+ });++ expect(await memberModel.delete(comment.id)).toBe(false);+ expect(await authorModel.findById(comment.id)).toBeDefined();+ });++ it('should let overrideAuthorScope delete others comments', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-d3',+ content: 'moderated away',+ topicId: workspaceTopicId,+ });++ expect(await memberModel.delete(comment.id, { overrideAuthorScope: true })).toBe('hard');+ });++ it('should NOT cross workspaces even with overrideAuthorScope', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-d4',+ content: 'protected',+ topicId: workspaceTopicId,+ });++ expect(await outsiderModel.delete(comment.id, { overrideAuthorScope: true })).toBe(false);+ expect(await authorModel.findById(comment.id)).toBeDefined();+ });+ });++ describe('workspace owner moderation', () => {+ it('should retain content, editorData and mentions during the 30-day recovery window', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-mod-retain',+ content: 'recoverable content',+ editorData: { root: { children: [] } },+ mentionedUserIds: [memberId],+ topicId: workspaceTopicId,+ });+ const now = new Date('2026-07-22T10:00:00Z');++ const result = await memberModel.moderateRemove(comment.id, now);++ expect(result?.comment).toMatchObject({+ content: 'recoverable content',+ editorData: { root: { children: [] } },+ moderatedAt: now,+ moderatedByUserId: memberId,+ });+ expect(result?.moderationExpiresAt).toEqual(new Date('2026-08-21T10:00:00Z'));+ expect(await authorModel.getMentions(comment.id)).toHaveLength(1);+ expect(+ await authorModel.update(comment.id, { content: 'cannot edit while removed' }),+ ).toBeUndefined();+ expect(await authorModel.delete(comment.id)).toBe(false);+ });++ it('should keep author self-deletion on the irreversible path', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-mod-self',+ content: 'self-owned',+ topicId: workspaceTopicId,+ });++ expect(await authorModel.moderateRemove(comment.id)).toBeUndefined();+ expect(await authorModel.delete(comment.id)).toBe('hard');+ expect(await authorModel.findById(comment.id)).toBeUndefined();+ });++ it('should restore retained content without changing its edit timestamp or mentions', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-mod-restore',+ content: 'restore me',+ editorData: { root: { version: 1 } },+ mentionedUserIds: [memberId],+ topicId: workspaceTopicId,+ });+ const removedAt = new Date('2026-07-22T10:00:00Z');+ await memberModel.moderateRemove(comment.id, removedAt);++ const restored = await authorModel.restoreModerated(+ comment.id,+ new Date('2026-08-01T10:00:00Z'),+ );++ expect(restored).toMatchObject({+ content: 'restore me',+ editorData: { root: { version: 1 } },+ moderatedAt: null,+ moderatedByUserId: null,+ moderationExpiresAt: null,+ updatedAt: comment.updatedAt,+ });+ expect(await authorModel.getMentions(comment.id)).toHaveLength(1);+ });++ it('should reject restore once the recovery window expires', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-mod-expired-restore',+ content: 'too late',+ topicId: workspaceTopicId,+ });+ await memberModel.moderateRemove(comment.id, new Date('2026-07-01T00:00:00Z'));++ expect(+ await authorModel.restoreModerated(comment.id, new Date('2026-08-01T00:00:00Z')),+ ).toBeUndefined();+ expect((await authorModel.findById(comment.id))?.content).toBe('too late');+ });++ it('should hide no-reply removals from other members while retaining the author and owner views', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-mod-visibility',+ content: 'private retained body',+ topicId: workspaceTopicId,+ });+ await memberModel.moderateRemove(comment.id);++ expect(await outsiderModel.findById(comment.id)).toBeUndefined();+ expect(await authorModel.findById(comment.id)).toMatchObject({ id: comment.id });+ expect(await memberModel.findById(comment.id, { includeAllModerated: true })).toMatchObject({+ content: 'private retained body',+ });+ });++ it('should keep a moderated root visible to other members while active replies preserve the thread', async () => {+ const root = await authorModel.createWithMentions({+ clientId: 'client-mod-thread-root',+ content: 'removed root',+ topicId: workspaceTopicId,+ });+ await memberModel.createWithMentions({+ clientId: 'client-mod-thread-reply',+ content: 'active reply',+ parentCommentId: root.comment.id,+ topicId: workspaceTopicId,+ });+ await memberModel.moderateRemove(root.comment.id);++ const page = await new TopicCommentModel(serverDB, outsiderId, workspaceAId).listThreads({+ topicId: workspaceTopicId,+ });+ expect(page.items.map(({ root: item }) => item.id)).toContain(root.comment.id);+ expect(page.items.find(({ root: item }) => item.id === root.comment.id)?.replyCount).toBe(1);+ });++ it('should hard-delete expired removals without replies', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-mod-purge-hard',+ content: 'purge me',+ editorData: { root: {} },+ mentionedUserIds: [memberId],+ topicId: workspaceTopicId,+ });+ await memberModel.moderateRemove(comment.id, new Date('2026-06-01T00:00:00Z'));++ const result = await purgeExpiredTopicCommentModeration(serverDB, {+ now: new Date('2026-07-02T00:00:00Z'),+ });++ expect(result).toMatchObject({ hardDeleted: 1, processed: 1, tombstoned: 0 });+ expect(await authorModel.findById(comment.id)).toBeUndefined();+ expect(await authorModel.getMentions(comment.id)).toHaveLength(0);+ });++ it('should be idempotent when an expired-removal purge is retried', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-mod-purge-idempotent',+ content: 'purge once',+ topicId: workspaceTopicId,+ });+ await memberModel.moderateRemove(comment.id, new Date('2026-06-01T00:00:00Z'));+ const now = new Date('2026-07-02T00:00:00Z');++ const first = await purgeExpiredTopicCommentModeration(serverDB, { now });+ const retry = await purgeExpiredTopicCommentModeration(serverDB, { now });++ expect(first).toMatchObject({ hardDeleted: 1, processed: 1, tombstoned: 0 });+ expect(retry).toEqual({+ garbageCollected: 0,+ hardDeleted: 0,+ processed: 0,+ tombstoned: 0,+ });+ });++ it('should sanitize an expired root and preserve its active replies', async () => {+ const root = await authorModel.createWithMentions({+ clientId: 'client-mod-purge-root',+ content: 'sensitive root',+ editorData: { root: { secret: true } },+ mentionedUserIds: [memberId],+ topicId: workspaceTopicId,+ });+ const reply = await memberModel.createWithMentions({+ clientId: 'client-mod-purge-reply',+ content: 'preserved reply',+ parentCommentId: root.comment.id,+ topicId: workspaceTopicId,+ });+ await memberModel.moderateRemove(root.comment.id, new Date('2026-06-01T00:00:00Z'));++ const result = await purgeExpiredTopicCommentModeration(serverDB, {+ now: new Date('2026-07-02T00:00:00Z'),+ });++ expect(result).toMatchObject({ hardDeleted: 0, processed: 1, tombstoned: 1 });+ expect(await authorModel.findById(root.comment.id)).toMatchObject({+ content: '',+ deletedAt: expect.any(Date),+ editorData: null,+ moderatedAt: null,+ moderationExpiresAt: null,+ });+ expect(await authorModel.getMentions(root.comment.id)).toHaveLength(0);+ expect(await authorModel.findById(reply.comment.id)).toMatchObject({+ content: 'preserved reply',+ });+ });+ });++ describe('findById', () => {+ it('should scope reads to the workspace', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-f1',+ content: 'readable',+ topicId: workspaceTopicId,+ });++ expect(await memberModel.findById(comment.id)).toBeDefined();+ expect(await outsiderModel.findById(comment.id)).toBeUndefined();+ });+ });++ describe('listThreads', () => {+ const seedRoots = async () => {+ const a = await authorModel.createWithMentions({+ clientId: 'client-l1',+ content: 'first',+ topicId: workspaceTopicId,+ });+ const b = await authorModel.createWithMentions({+ clientId: 'client-l2',+ content: 'second',+ messageId: anchoredMessageId,+ topicId: workspaceTopicId,+ });+ const c = await authorModel.createWithMentions({+ clientId: 'client-l3',+ content: 'third',+ topicId: workspaceTopicId,+ });++ // Explicit timestamps — never rely on insert order. b and c share createdAt+ // so cursor pagination exercises the id tie-breaker. Keep the IDs fixed and+ // lowercase so JavaScript and PostgreSQL collations agree on their order.+ const base = new Date('2026-01-01T10:00:00Z');+ const later = new Date('2026-01-02T10:00:00Z');+ const aId = 'tcm_list_root_a';+ const bId = 'tcm_list_root_b';+ const cId = 'tcm_list_root_c';+ await serverDB+ .update(topicComments)+ .set({ createdAt: base, id: aId })+ .where(eq(topicComments.id, a.comment.id));+ await serverDB+ .update(topicComments)+ .set({ createdAt: later, id: bId })+ .where(eq(topicComments.id, b.comment.id));+ await serverDB+ .update(topicComments)+ .set({ createdAt: later, id: cId })+ .where(eq(topicComments.id, c.comment.id));++ return {+ a: { ...a.comment, id: aId },+ b: { ...b.comment, id: bId },+ c: { ...c.comment, id: cId },+ expectedOrder: [cId, bId, aId],+ };+ };++ it('should return newest root threads first with batched reply counts only', async () => {+ const { a, expectedOrder } = await seedRoots();+ await Promise.all([+ memberModel.createWithMentions({+ clientId: 'client-l-reply-1',+ content: 'first reply',+ parentCommentId: a.id,+ topicId: workspaceTopicId,+ }),+ authorModel.createWithMentions({+ clientId: 'client-l-reply-2',+ content: 'second reply',+ parentCommentId: a.id,+ topicId: workspaceTopicId,+ }),+ ]);++ const page = await authorModel.listThreads({ topicId: workspaceTopicId });++ expect(page.items.map((thread) => thread.root.id)).toEqual(expectedOrder);+ expect(page.nextCursor).toBeNull();+ const firstThread = page.items.find((thread) => thread.root.id === a.id);+ expect(firstThread?.replyCount).toBe(2);+ expect(firstThread).not.toHaveProperty('replies');+ });++ it('should continue root pagination after the cursor root is hard-deleted', async () => {+ const { a, expectedOrder } = await seedRoots();+ await memberModel.createWithMentions({+ clientId: 'client-l-page-reply',+ content: 'a reply outside the root-page count',+ parentCommentId: a.id,+ topicId: workspaceTopicId,+ });++ const page1 = await authorModel.listThreads({ limit: 2, topicId: workspaceTopicId });+ expect(page1.items.map((thread) => thread.root.id)).toEqual(expectedOrder.slice(0, 2));+ expect(page1.nextCursor).not.toBeNull();++ // Hard deletion is normal. A value cursor must keep its position without+ // re-reading this now-missing row and silently restarting at page one.+ expect(await authorModel.delete(expectedOrder[1])).toBe('hard');++ const page2 = await authorModel.listThreads({+ cursor: page1.nextCursor!,+ limit: 2,+ topicId: workspaceTopicId,+ });+ expect(page2.items.map((thread) => thread.root.id)).toEqual(expectedOrder.slice(2));+ expect(page2.nextCursor).toBeNull();+ });++ it('should return reply counts when filtering roots by messageId', async () => {+ const { b } = await seedRoots();+ await memberModel.createWithMentions({+ clientId: 'client-l-message-reply',+ content: 'message thread reply',+ parentCommentId: b.id,+ topicId: workspaceTopicId,+ });++ const page = await authorModel.listThreads({+ messageId: anchoredMessageId,+ topicId: workspaceTopicId,+ });++ expect(page.items).toHaveLength(1);+ expect(page.items[0].root.id).toBe(b.id);+ expect(page.items[0].replyCount).toBe(1);+ expect(page.items[0]).not.toHaveProperty('replies');+ });++ it('should return nothing for another workspace context', async () => {+ await seedRoots();++ expect(await outsiderModel.listThreads({ topicId: workspaceTopicId })).toEqual({+ items: [],+ nextCursor: null,+ });+ });+ });++ describe('listReplies', () => {+ it('should paginate one thread replies with a composite cursor', async () => {+ const root = await authorModel.createWithMentions({+ clientId: 'client-lr-root',+ content: 'reply-page root',+ topicId: workspaceTopicId,+ });+ const replies = await Promise.all([+ memberModel.createWithMentions({+ clientId: 'client-lr-1',+ content: 'reply one',+ parentCommentId: root.comment.id,+ topicId: workspaceTopicId,+ }),+ authorModel.createWithMentions({+ clientId: 'client-lr-2',+ content: 'reply two',+ parentCommentId: root.comment.id,+ topicId: workspaceTopicId,+ }),+ memberModel.createWithMentions({+ clientId: 'client-lr-3',+ content: 'reply three',+ parentCommentId: root.comment.id,+ topicId: workspaceTopicId,+ }),+ ]);++ const base = new Date('2026-01-01T10:00:00Z');+ const later = new Date('2026-01-02T10:00:00Z');+ await serverDB+ .update(topicComments)+ .set({ createdAt: base })+ .where(eq(topicComments.id, replies[0].comment.id));+ await serverDB+ .update(topicComments)+ .set({ createdAt: later })+ .where(inArray(topicComments.id, [replies[1].comment.id, replies[2].comment.id]));+ const expectedOrder = [+ replies[0].comment.id,+ ...[replies[1].comment.id, replies[2].comment.id].sort(),+ ];++ const page1 = await authorModel.listReplies({ limit: 2, rootCommentId: root.comment.id });+ expect(page1.items.map((reply) => reply.id)).toEqual(expectedOrder.slice(0, 2));+ expect(page1.nextCursor).not.toBeNull();++ await authorModel.delete(expectedOrder[1], { overrideAuthorScope: true });++ const page2 = await authorModel.listReplies({+ cursor: page1.nextCursor!,+ limit: 2,+ rootCommentId: root.comment.id,+ });+ expect(page2.items.map((reply) => reply.id)).toEqual(expectedOrder.slice(2));+ expect(page2.nextCursor).toBeNull();++ expect(await outsiderModel.listReplies({ rootCommentId: root.comment.id })).toEqual({+ items: [],+ nextCursor: null,+ });+ });+ });++ describe('summary', () => {+ it('should count totals and per-message counts separately', async () => {+ await authorModel.createWithMentions({+ clientId: 'client-s1',+ content: 'topic level',+ topicId: workspaceTopicId,+ });+ await authorModel.createWithMentions({+ clientId: 'client-s2',+ content: 'anchored one',+ messageId: anchoredMessageId,+ topicId: workspaceTopicId,+ });+ await memberModel.createWithMentions({+ clientId: 'client-s3',+ content: 'anchored two',+ messageId: anchoredMessageId,+ topicId: workspaceTopicId,+ });++ const summary = await authorModel.summary(workspaceTopicId);++ expect(summary.total).toBe(3);+ expect(summary.countByMessage).toEqual({ [anchoredMessageId]: 2 });+ });+ });++ describe('anchor message deletion', () => {+ it('should keep the comment with anchorPreview after the message is hard-deleted', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-a1',+ content: 'survives anchor deletion',+ messageId: anchoredMessageId,+ topicId: workspaceTopicId,+ });++ await serverDB.delete(messages).where(eq(messages.id, anchoredMessageId));++ const row = await authorModel.findById(comment.id);+ expect(row?.messageId).toBeNull();+ expect(row?.anchorPreview?.excerpt.startsWith('anchor message content')).toBe(true);+ });+ });++ describe('topic deletion', () => {+ it('should cascade comments and mentions when the topic is deleted', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-t1',+ content: 'cascades away',+ mentionedUserIds: [memberId],+ topicId: workspaceTopicId,+ });++ await serverDB.delete(topics).where(eq(topics.id, workspaceTopicId));++ const rows = await serverDB+ .select()+ .from(topicComments)+ .where(eq(topicComments.id, comment.id));+ expect(rows).toHaveLength(0);+ const mentionRows = await serverDB+ .select()+ .from(topicCommentMentions)+ .where(eq(topicCommentMentions.commentId, comment.id));+ expect(mentionRows).toHaveLength(0);+ });+ });++ describe('author account deletion (tombstone)', () => {+ it('should keep the comment with a NULL author when the author account is deleted', async () => {+ // Author must NOT be the topic creator: deleting the creator cascades the+ // topic (topics.userId) and takes every comment with it — the tombstone+ // only protects against the comment *author* leaving.+ const { comment } = await memberModel.createWithMentions({+ clientId: 'client-tomb-1',+ content: 'survives author deletion',+ mentionedUserIds: [authorId],+ topicId: workspaceTopicId,+ });++ await serverDB.delete(users).where(eq(users.id, memberId));++ const row = await authorModel.findById(comment.id);+ expect(row).toBeDefined();+ expect(row?.authorUserId).toBeNull();+ expect(row?.content).toBe('survives author deletion');+ // Mentions *made by* the tombstoned comment stay (target user still exists)+ expect(await authorModel.getMentions(comment.id)).toHaveLength(1);+ });++ it('should cascade mention rows that point at the deleted user', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-tomb-2',+ content: 'mentions the leaver',+ mentionedUserIds: [memberId],+ topicId: workspaceTopicId,+ });++ await serverDB.delete(users).where(eq(users.id, memberId));++ expect(await authorModel.getMentions(comment.id)).toHaveLength(0);+ });++ it('should make orphaned comments deletable only via overrideAuthorScope, never editable', async () => {+ const { comment } = await memberModel.createWithMentions({+ clientId: 'client-tomb-3',+ content: 'orphaned',+ topicId: workspaceTopicId,+ });++ await serverDB.delete(users).where(eq(users.id, memberId));++ // The author-scoped predicate never matches NULL — no caller owns the row+ expect(await authorModel.update(comment.id, { content: 'hijack' })).toBeUndefined();+ expect(await authorModel.delete(comment.id)).toBe(false);++ // Owner-level override still manages it, within the workspace only+ expect(await outsiderModel.delete(comment.id, { overrideAuthorScope: true })).toBe(false);+ expect(await authorModel.delete(comment.id, { overrideAuthorScope: true })).toBe('hard');+ });++ it('should cascade all comments when the topic creator account is deleted', async () => {+ const { comment } = await memberModel.createWithMentions({+ clientId: 'client-tomb-4',+ content: 'dies with the topic',+ topicId: workspaceTopicId,+ });++ await serverDB.delete(users).where(eq(users.id, authorId));++ const rows = await serverDB+ .select()+ .from(topicComments)+ .where(eq(topicComments.id, comment.id));+ expect(rows).toHaveLength(0);+ });+ });++ describe('anchored-requires-preview CHECK', () => {+ it('should reject a message-anchored row inserted without anchorPreview', async () => {+ const values = {+ authorUserId: authorId,+ clientId: 'client-check-1',+ content: 'anchored but no snapshot',+ messageId: anchoredMessageId,+ topicId: workspaceTopicId,+ workspaceId: workspaceAId,+ };++ // Same row minus the snapshot is rejected; with it, it lands — the CHECK+ // is the only differing variable. (Drizzle wraps the constraint name in+ // the error cause, so we can't match on the message text.)+ await expect(serverDB.insert(topicComments).values(values)).rejects.toThrow();+ await expect(+ serverDB+ .insert(topicComments)+ .values({ ...values, anchorPreview: { excerpt: 'snapshot' } }),+ ).resolves.toBeDefined();+ });++ it('should accept the orphaned state (NULL messageId with a preview)', async () => {+ await expect(+ serverDB.insert(topicComments).values({+ anchorPreview: { excerpt: 'left over from a deleted anchor' },+ authorUserId: authorId,+ clientId: 'client-check-2',+ content: 'orphaned is legal',+ messageId: null,+ topicId: workspaceTopicId,+ workspaceId: workspaceAId,+ }),+ ).resolves.toBeDefined();+ });+ });++ describe('threads (replies)', () => {+ const seedThread = async () => {+ const root = await authorModel.createWithMentions({+ clientId: 'client-th-root',+ content: 'thread root',+ messageId: anchoredMessageId,+ topicId: workspaceTopicId,+ });+ const reply = await memberModel.createWithMentions({+ clientId: 'client-th-reply',+ content: 'a reply',+ parentCommentId: root.comment.id,+ topicId: workspaceTopicId,+ });+ return { reply: reply.comment, root: root.comment };+ };++ it('should create a reply without any anchor of its own', async () => {+ const { root, reply } = await seedThread();++ expect(reply.parentCommentId).toBe(root.id);+ expect(reply.messageId).toBeNull();+ expect(reply.anchorPreview).toBeNull();+ });++ it('should reject replying to a reply (single level only)', async () => {+ const { reply } = await seedThread();++ await expect(+ authorModel.createWithMentions({+ clientId: 'client-th-deep',+ content: 'reply to a reply',+ parentCommentId: reply.id,+ topicId: workspaceTopicId,+ }),+ ).rejects.toThrow(TOPIC_COMMENT_REPLY_DEPTH_EXCEEDED);+ });++ it('should reject a reply that tries to anchor to a message', async () => {+ const { root } = await seedThread();++ await expect(+ memberModel.createWithMentions({+ clientId: 'client-th-anchor',+ content: 'anchored reply',+ messageId: anchoredMessageId,+ parentCommentId: root.id,+ topicId: workspaceTopicId,+ }),+ ).rejects.toThrow(TOPIC_COMMENT_REPLY_CANNOT_ANCHOR);+ });++ it('should reject cross-topic and cross-workspace parents with one error', async () => {+ const { root } = await seedThread();++ await serverDB+ .insert(topics)+ .values([{ id: 'tc-topic-a2', userId: authorId, workspaceId: workspaceAId }]);++ // Parent exists but lives in another topic of the same workspace+ await expect(+ authorModel.createWithMentions({+ clientId: 'client-th-cross-topic',+ content: 'cross-topic reply',+ parentCommentId: root.id,+ topicId: 'tc-topic-a2',+ }),+ ).rejects.toThrow(TOPIC_COMMENT_PARENT_NOT_FOUND);++ // Parent in another workspace is indistinguishable from missing+ const foreign = await outsiderModel.createWithMentions({+ clientId: 'client-th-foreign',+ content: 'foreign root',+ topicId: otherWorkspaceTopicId,+ });+ await expect(+ authorModel.createWithMentions({+ clientId: 'client-th-cross-ws',+ content: 'cross-workspace reply',+ parentCommentId: foreign.comment.id,+ topicId: workspaceTopicId,+ }),+ ).rejects.toThrow(TOPIC_COMMENT_PARENT_NOT_FOUND);+ });++ it('should soft-delete a root with live replies and keep the thread anchor', async () => {+ const { root, reply } = await seedThread();+ await authorModel.update(root.id, {}, { mentionedUserIds: [memberId] });++ const mode = await authorModel.delete(root.id);+ expect(mode).toBe('soft');++ const tombstone = await authorModel.findById(root.id);+ // Content retracted, structure and anchor retained+ expect(tombstone?.deletedAt).not.toBeNull();+ expect(tombstone?.content).toBe('');+ expect(tombstone?.editorData).toBeNull();+ expect(tombstone?.messageId).toBe(anchoredMessageId);+ expect(tombstone?.anchorPreview).not.toBeNull();+ // Mentions dropped, replies untouched+ expect(await authorModel.getMentions(root.id)).toHaveLength(0);+ expect(await authorModel.findById(reply.id)).toMatchObject({ content: 'a reply' });+ });++ it('should make tombstones neither editable nor deletable again', async () => {+ const { root } = await seedThread();+ await authorModel.delete(root.id);++ expect(await authorModel.update(root.id, { content: 'necromancy' })).toBeUndefined();+ expect(await authorModel.delete(root.id)).toBe(false);+ expect(await authorModel.delete(root.id, { overrideAuthorScope: true })).toBe(false);+ });++ it('should allow replying to a tombstoned root (thread is still alive)', async () => {+ const { root } = await seedThread();+ await authorModel.delete(root.id);++ const late = await authorModel.createWithMentions({+ clientId: 'client-th-late',+ content: 'late reply',+ parentCommentId: root.id,+ topicId: workspaceTopicId,+ });++ expect(late.comment.parentCommentId).toBe(root.id);+ });++ it('should GC the tombstone when its last live reply is hard-deleted', async () => {+ const { root, reply } = await seedThread();+ const second = await authorModel.createWithMentions({+ clientId: 'client-th-second',+ content: 'second reply',+ parentCommentId: root.id,+ topicId: workspaceTopicId,+ });+ await authorModel.delete(root.id);++ // First reply goes — tombstone stays (one live reply left)+ expect(await memberModel.delete(reply.id)).toBe('hard');+ expect(await authorModel.findById(root.id)).toBeDefined();++ // Last reply goes — tombstone is GC'd in the same transaction+ expect(await authorModel.delete(second.comment.id)).toBe('hard');+ expect(await authorModel.findById(root.id)).toBeUndefined();+ });++ it('should serialize concurrent final-reply deletes before tombstone GC', async () => {+ // PGlite serializes transactions on one connection; TEST_SERVER_DB=1+ // exercises the real race across separate PostgreSQL pool connections.+ const trials = 20;+ const orphanedRootIds: string[] = [];++ for (let i = 0; i < trials; i++) {+ const root = await authorModel.createWithMentions({+ clientId: `client-th-concurrent-replies-root-${i}`,+ content: 'concurrent replies root',+ topicId: workspaceTopicId,+ });+ const [first, second] = await Promise.all([+ memberModel.createWithMentions({+ clientId: `client-th-concurrent-replies-first-${i}`,+ content: 'first concurrent reply',+ parentCommentId: root.comment.id,+ topicId: workspaceTopicId,+ }),+ authorModel.createWithMentions({+ clientId: `client-th-concurrent-replies-second-${i}`,+ content: 'second concurrent reply',+ parentCommentId: root.comment.id,+ topicId: workspaceTopicId,+ }),+ ]);+ expect(await authorModel.delete(root.comment.id)).toBe('soft');++ await Promise.all([+ memberModel.delete(first.comment.id),+ authorModel.delete(second.comment.id),+ ]);++ if (await authorModel.findById(root.comment.id)) {+ orphanedRootIds.push(root.comment.id);+ // Keep later trials independent if this regression reappears.+ await serverDB.delete(topicComments).where(eq(topicComments.id, root.comment.id));+ }+ }++ expect(orphanedRootIds).toEqual([]);+ });++ it('should serialize deleting a root with deleting its last reply', async () => {+ const trials = 20;+ const orphanedRootIds: string[] = [];++ for (let i = 0; i < trials; i++) {+ const root = await authorModel.createWithMentions({+ clientId: `client-th-concurrent-root-${i}`,+ content: 'concurrent root delete',+ topicId: workspaceTopicId,+ });+ const reply = await memberModel.createWithMentions({+ clientId: `client-th-concurrent-root-reply-${i}`,+ content: 'last concurrent reply',+ parentCommentId: root.comment.id,+ topicId: workspaceTopicId,+ });++ await Promise.all([+ authorModel.delete(root.comment.id),+ memberModel.delete(reply.comment.id),+ ]);++ if (await authorModel.findById(root.comment.id)) {+ orphanedRootIds.push(root.comment.id);+ await serverDB.delete(topicComments).where(eq(topicComments.id, root.comment.id));+ }+ }++ expect(orphanedRootIds).toEqual([]);+ });++ it('should hard-delete a root whose replies were all deleted first', async () => {+ const { root, reply } = await seedThread();++ expect(await memberModel.delete(reply.id)).toBe('hard');+ // No live replies left — the root deletes hard, no tombstone+ expect(await authorModel.delete(root.id)).toBe('hard');+ expect(await authorModel.findById(root.id)).toBeUndefined();+ });++ it('should reject raw hard-deleting a parent with replies at the DB layer', async () => {+ const { root } = await seedThread();++ // Self-FK has no delete action: the DB itself is the backstop against+ // destroying a thread by hard-deleting its root outside the model.+ await expect(+ serverDB.delete(topicComments).where(eq(topicComments.id, root.id)),+ ).rejects.toThrow();+ });++ it('should still cascade whole threads when the topic is deleted', async () => {+ const { root, reply } = await seedThread();++ await serverDB.delete(topics).where(eq(topics.id, workspaceTopicId));++ const rows = await serverDB+ .select()+ .from(topicComments)+ .where(inArray(topicComments.id, [root.id, reply.id]));+ expect(rows).toHaveLength(0);+ });++ it('should exclude tombstones from total while keeping live threads in message counts', async () => {+ const { reply, root } = await seedThread();++ const before = await authorModel.summary(workspaceTopicId);+ // Root (anchored) + reply: total counts both, the badge counts the thread+ expect(before.total).toBe(2);+ expect(before.countByMessage).toEqual({ [anchoredMessageId]: 1 });++ await authorModel.delete(root.id);++ const after = await authorModel.summary(workspaceTopicId);+ // The tombstone drops out of total, but keeps the live thread discoverable+ // from its anchored message until the last reply is deleted.+ expect(after.total).toBe(1);+ expect(after.countByMessage).toEqual({ [anchoredMessageId]: 1 });++ await memberModel.delete(reply.id);++ const afterLastReply = await authorModel.summary(workspaceTopicId);+ expect(afterLastReply.total).toBe(0);+ expect(afterLastReply.countByMessage).toEqual({});+ });+ });++ describe('getMentions', () => {+ it('should scope mention reads to the workspace', async () => {+ const { comment } = await authorModel.createWithMentions({+ clientId: 'client-m1',+ content: 'with mention',+ mentionedUserIds: [memberId],+ topicId: workspaceTopicId,+ });++ expect(await authorModel.getMentions(comment.id)).toHaveLength(1);+ expect(await outsiderModel.getMentions(comment.id)).toHaveLength(0);+ });++ it('should reject workspace-less callers for every method', async () => {+ await expect(personalModel.listThreads({ topicId: workspaceTopicId })).rejects.toThrow(+ TOPIC_COMMENT_WORKSPACE_REQUIRED,+ );+ await expect(personalModel.listReplies({ rootCommentId: 'any' })).rejects.toThrow(+ TOPIC_COMMENT_WORKSPACE_REQUIRED,+ );+ await expect(personalModel.summary(workspaceTopicId)).rejects.toThrow(+ TOPIC_COMMENT_WORKSPACE_REQUIRED,+ );+ await expect(personalModel.findById('any')).rejects.toThrow(TOPIC_COMMENT_WORKSPACE_REQUIRED);+ await expect(personalModel.delete('any')).rejects.toThrow(TOPIC_COMMENT_WORKSPACE_REQUIRED);+ await expect(personalModel.update('any', { content: 'x' })).rejects.toThrow(+ TOPIC_COMMENT_WORKSPACE_REQUIRED,+ );+ await expect(personalModel.getMentions('any')).rejects.toThrow(+ TOPIC_COMMENT_WORKSPACE_REQUIRED,+ );+ });+ });+});diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex ac8bb8fbdb1..daffdcbc153 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -8,6 +8,7 @@ import {import { TRPCError } from '@trpc/server';import {and,+ asc,count,desc,eq,@@ -54,6 +55,11 @@ import type { LobeChatDatabase } from '../type';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { normalizeInboxAgentMeta } from '../utils/inboxAgent';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';+import {+ hasForeignTopicComments,+ syncTopicCommentsOnTopicTransfer,+ TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS,+} from './topicComment';/*** Fields the Agent Builder's own row (`slug = BUILTIN_AGENT_SLUGS.agentBuilder`) must never@@ -1394,6 +1400,11 @@ export class AgentModel {.limit(1);if (foreignTopic) return true;+ // Comments move (or die, when the target is personal scope) with their+ // topics — a teammate's comment on the caller's own topic is still their+ // work. NULL authors (deleted accounts) count as foreign too.+ if (await hasForeignTopicComments(this.db, this.userId, topicWhere!)) return true;+const messageWhere =sessionIds.length > 0? or(inArray(messages.sessionId, sessionIds), inArray(messages.agentId, agentIds))@@ -1430,12 +1441,14 @@ export class AgentModel {targetWorkspaceId: string | null,targetUserId: string,targetVisibility?: 'private' | 'public',+ options: { rejectForeignTopicCommentAuthors?: boolean } = {},): Promise<{ agentId: string; slug: string | null }> => {const [result] = await this.transferAgents([agentId],targetWorkspaceId,targetUserId,targetVisibility,+ options,);return result;};@@ -1451,6 +1464,7 @@ export class AgentModel {targetWorkspaceId: string | null,targetUserId: string,targetVisibility?: 'private' | 'public',+ options: { rejectForeignTopicCommentAuthors?: boolean } = {},): Promise<{ agentId: string; slug: string | null }[]> => {if (agentIds.length === 0) return [];@@ -1647,10 +1661,38 @@ export class AgentModel {sessionIds.length > 0? or(inArray(topics.sessionId, sessionIds), inArray(topics.agentId, agentIds)): inArray(topics.agentId, agentIds);++ // Create locks the topic before inserting a comment. Lock every topic in+ // the same order before the authoritative transfer authorization check,+ // so either the create becomes visible here or it observes the moved+ // scope and fails after this transaction commits.await trx+ .select({ id: topics.id })+ .from(topics)+ .where(topicCondition!)+ .orderBy(asc(topics.id))+ .for('update');++ if (+ options.rejectForeignTopicCommentAuthors &&+ (await hasForeignTopicComments(trx, this.userId, topicCondition!))+ ) {+ throw new Error(TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS);+ }+ const movedTopics = await trx.update(topics).set({ ...ownershipUpdate, updatedAt: topics.updatedAt })- .where(topicCondition!);+ .where(topicCondition!)+ .returning({ id: topics.id });++ // 6a. Topic comments denormalize the topic's workspaceId — move them+ // with the topic (or drop them when leaving workspace scope entirely),+ // otherwise workspace-filtered comment reads go stale. See the helper doc.+ await syncTopicCommentsOnTopicTransfer(+ trx,+ movedTopics.map((topic) => topic.id),+ targetWorkspaceId,+ );// 7. Update messages (linked via sessionId or agentId)const messageCondition =diff --git a/packages/database/src/models/topicComment.ts b/packages/database/src/models/topicComment.tsnew file mode 100644index 00000000000..eea373ce8bd--- /dev/null+++ b/packages/database/src/models/topicComment.ts@@ -0,0 +1,1053 @@+import { truncateSurrogateSafe } from '@lobechat/utils';+import type { SQL } from 'drizzle-orm';+import {+ and,+ asc,+ count,+ desc,+ eq,+ exists,+ getTableColumns,+ gt,+ inArray,+ isNotNull,+ isNull,+ lt,+ lte,+ ne,+ notExists,+ or,+ sql,+} from 'drizzle-orm';+import { alias } from 'drizzle-orm/pg-core';++import { messages } from '../schemas/message';+import { topics } from '../schemas/topic';+import type { TopicCommentAnchorPreview, TopicCommentItem } from '../schemas/topicComment';+import { topicCommentMentions, topicComments } from '../schemas/topicComment';+import type { LobeChatDatabase, Transaction } from '../type';++export const TOPIC_COMMENT_WORKSPACE_REQUIRED =+ 'Topic comments are workspace-scoped; a workspaceId is required';+/**+ * Single message for missing / cross-workspace / personal-mode topics so the+ * error reveals nothing about topics outside the caller's workspace.+ */+export const TOPIC_COMMENT_TOPIC_NOT_FOUND = 'Topic not found in current workspace';+export const TOPIC_COMMENT_MESSAGE_NOT_IN_TOPIC = 'Message does not belong to the topic';+/** Single message for missing / cross-topic / cross-workspace parents (no existence leak) */+export const TOPIC_COMMENT_PARENT_NOT_FOUND = 'Parent comment not found in the topic';+export const TOPIC_COMMENT_REPLY_DEPTH_EXCEEDED = 'Replies can only target a top-level comment';+export const TOPIC_COMMENT_REPLY_CANNOT_ANCHOR = 'A reply cannot anchor to a message';+export const TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS =+ 'Topic transfer includes comments authored by another user';+export const TOPIC_COMMENT_NOT_MODERATED = 'Topic comment is not recoverable';+export const TOPIC_COMMENT_MODERATION_EXPIRED = 'Topic comment recovery window has expired';++const TOPIC_COMMENT_MODERATION_RECOVERY_MS = 30 * 24 * 60 * 60 * 1000;+const topicCommentChildren = alias(topicComments, 'topic_comment_children');++/**+ * Anchor excerpts must be cut surrogate-safely: a lone surrogate left by a+ * mid-emoji `slice` would be escaped as an unpaired `\ud8xx` that PostgreSQL's+ * jsonb parser rejects, failing anchored-comment creation outright (see+ * `truncateSurrogateSafe`).+ */+const ANCHOR_PREVIEW_MAX_LENGTH = 200;++/**+ * Deletion-stable keyset cursor over the exact database `(createdAt, id)` key.+ * The timestamp is selected as text so PostgreSQL microseconds survive the+ * round-trip instead of being truncated by JavaScript `Date`.+ */+const topicCommentCursorSelection = {+ ...getTableColumns(topicComments),+ cursorCreatedAt: sql<string>`${topicComments.createdAt}::text`.as('cursor_created_at'),+};++const encodeTopicCommentCursor = (createdAt: string, id: string): string => `${createdAt}|${id}`;++const decodeTopicCommentCursor = (cursor?: string): { createdAt: string; id: string } | null => {+ if (!cursor) return null;++ const separator = cursor.lastIndexOf('|');+ if (separator <= 0) return null;++ const createdAt = cursor.slice(0, separator);+ const id = cursor.slice(separator + 1);+ if (!id || Number.isNaN(Date.parse(createdAt))) return null;++ return { createdAt, id };+};++export interface CreateTopicCommentParams {+ clientId: string;+ content: string;+ editorData?: unknown;+ /** Validated (active-membership) user ids parsed from editorData by the caller */+ mentionedUserIds?: string[];+ messageId?: string;+ /**+ * Thread root to reply to. Single level: the target must itself be+ * top-level, and a reply cannot carry a messageId (the thread's anchor+ * lives on the root). Replying to a tombstoned root is allowed — the+ * thread is still alive by definition (a tombstone implies live replies).+ */+ parentCommentId?: string;+ topicId: string;+}++export interface CreateTopicCommentResult {+ addedMentionUserIds: string[];+ comment: TopicCommentItem;+ /** true when the insert hit the (topicId, authorUserId, clientId) idempotency key and the existing row is returned */+ isDuplicate: boolean;+ /** Author of the root when this is a reply; used for post-commit activity delivery. */+ parentAuthorUserId?: string | null;+ /** User who owns the topic; used for post-commit activity delivery. */+ topicOwnerUserId: string;+}++export interface UpdateTopicCommentParams {+ content?: string;+ editorData?: unknown;+}++export interface UpdateTopicCommentOptions {+ /**+ * Replace the mention set with this list (diff is computed against the+ * mentions table). Omit to leave mentions untouched.+ */+ mentionedUserIds?: string[];+}++export interface DeleteTopicCommentOptions {+ /**+ * Drops the author predicate so workspace owners can moderate others'+ * comments away. Only pass after an explicit owner-level RBAC check+ * (e.g. `topic_comment:delete:all`) — never from plain member requests.+ *+ * Delete-only on purpose: `update` has no override path. Moderation means+ * removing content, never rewriting someone else's words under their name+ * (impersonation risk, and there is no edit history to audit it) — the same+ * boundary Slack/GitHub draw for admins.+ */+ overrideAuthorScope?: boolean;+}++export interface TopicCommentReadOptions {+ /** Owner-only: include recoverable comments authored by any workspace member. */+ includeAllModerated?: boolean;+}++export interface ModerateTopicCommentResult {+ comment: TopicCommentItem;+ moderationExpiresAt: Date;+}++export interface PurgeExpiredTopicCommentModerationResult {+ garbageCollected: number;+ hardDeleted: number;+ processed: number;+ tombstoned: number;+}++export interface UpdateTopicCommentResult {+ /** Newly added mention targets — the only ones the caller should notify */+ addedMentionUserIds: string[];+ comment: TopicCommentItem;+}++export interface ListTopicCommentRepliesParams {+ /** Opaque value cursor over the ascending `(createdAt, id)` reply order */+ cursor?: string;+ limit?: number;+ rootCommentId: string;+}++export interface ListTopicCommentThreadsParams {+ /** Opaque value cursor over the descending `(createdAt, id)` root order */+ cursor?: string;+ limit?: number;+ messageId?: string;+ topicId: string;+}++export interface TopicCommentReplyPage {+ items: TopicCommentItem[];+ nextCursor: string | null;+}++export interface TopicCommentSummary {+ /**+ * Per-message counts. Only anchored roots carry a messageId, so each unit+ * here is a thread — replies never inflate a message badge. An anchored+ * tombstone still counts because it exists only while live replies keep the+ * thread alive.+ */+ countByMessage: Record<string, number>;+ /** Live comments (roots + replies); tombstones are excluded */+ total: number;+}++export interface TopicCommentThread {+ replyCount: number;+ root: TopicCommentItem;+}++export interface TopicCommentThreadPage {+ items: TopicCommentThread[];+ nextCursor: string | null;+}++/**+ * Workspace-scoped topic comments. Every method requires a workspaceId —+ * personal-mode callers (workspaceId undefined) are rejected, and the comment+ * row's workspaceId is always copied from the parent topic inside the create+ * transaction, never from the constructor argument alone (the topic lookup+ * asserts they match).+ *+ * Authorization layering: this model enforces workspace scoping plus+ * author-only mutations as defense in depth. Membership/RBAC checks and the+ * owner override decision live in the router layer. Edits are author-only by+ * design — the owner override exists solely on `delete` (see+ * {@link DeleteTopicCommentOptions}).+ *+ * Tombstoned rows (author account deleted ⇒ `authorUserId` NULL): the+ * author-scoped predicate `eq(authorUserId, userId)` never matches NULL, so+ * orphaned comments can only be deleted via `overrideAuthorScope`, never+ * edited.+ */+export class TopicCommentModel {+ private readonly db: LobeChatDatabase;+ private readonly userId: string;+ private readonly workspaceId?: string | null;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string | null) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ }++ private requireWorkspaceId = (): string => {+ if (!this.workspaceId) throw new Error(TOPIC_COMMENT_WORKSPACE_REQUIRED);+ return this.workspaceId;+ };++ /**+ * Non-owners can read their own recoverable placeholder. Everyone can read+ * a recoverable root while active replies need its thread structure. The+ * body is still redacted at the DTO boundary; this predicate only controls+ * row visibility and pagination.+ */+ private moderatedReadCondition = (options: TopicCommentReadOptions): SQL | undefined => {+ if (options.includeAllModerated) return undefined;++ return or(+ isNull(topicComments.moderatedAt),+ eq(topicComments.authorUserId, this.userId),+ and(+ isNull(topicComments.parentCommentId),+ exists(+ this.db+ .select({ id: topicCommentChildren.id })+ .from(topicCommentChildren)+ .where(+ and(+ eq(topicCommentChildren.parentCommentId, topicComments.id),+ isNull(topicCommentChildren.deletedAt),+ isNull(topicCommentChildren.moderatedAt),+ ),+ ),+ ),+ ),+ );+ };++ async createWithMentions(params: CreateTopicCommentParams): Promise<CreateTopicCommentResult> {+ const workspaceId = this.requireWorkspaceId();++ return this.db.transaction(async (tx) => {+ const [topic] = await tx+ .select({ id: topics.id, userId: topics.userId, workspaceId: topics.workspaceId })+ .from(topics)+ .where(eq(topics.id, params.topicId))+ .limit(1)+ .for('update');++ // Covers missing, cross-workspace and personal-mode (workspaceId NULL) topics+ if (!topic || topic.workspaceId !== workspaceId)+ throw new Error(TOPIC_COMMENT_TOPIC_NOT_FOUND);++ let parentAuthorUserId: string | null | undefined;+ if (params.parentCommentId) {+ if (params.messageId) throw new Error(TOPIC_COMMENT_REPLY_CANNOT_ANCHOR);++ const [parent] = await tx+ .select({+ authorUserId: topicComments.authorUserId,+ id: topicComments.id,+ parentCommentId: topicComments.parentCommentId,+ topicId: topicComments.topicId,+ workspaceId: topicComments.workspaceId,+ })+ .from(topicComments)+ .where(eq(topicComments.id, params.parentCommentId))+ .limit(1)+ .for('key share');++ // One message for missing / cross-topic / cross-workspace parents+ if (!parent || parent.workspaceId !== workspaceId || parent.topicId !== params.topicId)+ throw new Error(TOPIC_COMMENT_PARENT_NOT_FOUND);+ if (parent.parentCommentId) throw new Error(TOPIC_COMMENT_REPLY_DEPTH_EXCEEDED);+ parentAuthorUserId = parent.authorUserId;+ }++ let anchorPreview: TopicCommentAnchorPreview | undefined;+ if (params.messageId) {+ const [message] = await tx+ .select({+ content: messages.content,+ id: messages.id,+ role: messages.role,+ topicId: messages.topicId,+ })+ .from(messages)+ .where(eq(messages.id, params.messageId))+ .limit(1);++ if (!message || message.topicId !== params.topicId)+ throw new Error(TOPIC_COMMENT_MESSAGE_NOT_IN_TOPIC);++ anchorPreview = {+ excerpt: truncateSurrogateSafe(message.content ?? '', ANCHOR_PREVIEW_MAX_LENGTH),+ role: message.role,+ };+ }++ const mentionedUserIds = [...new Set(params.mentionedUserIds ?? [])];++ const [inserted] = await tx+ .insert(topicComments)+ .values({+ anchorPreview,+ authorUserId: this.userId,+ clientId: params.clientId,+ content: params.content,+ editorData: params.editorData,+ messageId: params.messageId ?? null,+ parentCommentId: params.parentCommentId ?? null,+ topicId: params.topicId,+ workspaceId: topic.workspaceId,+ })+ .onConflictDoNothing({+ target: [topicComments.topicId, topicComments.authorUserId, topicComments.clientId],+ })+ .returning();++ if (!inserted) {+ // Retried create: the idempotency key already has a row — return it as-is+ const [existing] = await tx+ .select()+ .from(topicComments)+ .where(+ and(+ eq(topicComments.topicId, params.topicId),+ eq(topicComments.workspaceId, workspaceId),+ eq(topicComments.clientId, params.clientId),+ eq(topicComments.authorUserId, this.userId),+ ),+ )+ .limit(1);++ // Conflict raced with a delete of the original row; let the caller retry+ if (!existing) throw new Error('Failed to create topic comment');++ return {+ addedMentionUserIds: [],+ comment: existing,+ isDuplicate: true,+ parentAuthorUserId,+ topicOwnerUserId: topic.userId,+ };+ }++ if (mentionedUserIds.length > 0) {+ await tx+ .insert(topicCommentMentions)+ .values(+ mentionedUserIds.map((mentionedUserId) => ({+ commentId: inserted.id,+ mentionedUserId,+ workspaceId,+ })),+ )+ .onConflictDoNothing();+ }++ return {+ addedMentionUserIds: mentionedUserIds,+ comment: inserted,+ isDuplicate: false,+ parentAuthorUserId,+ topicOwnerUserId: topic.userId,+ };+ });+ }++ async update(+ id: string,+ params: UpdateTopicCommentParams,+ options: UpdateTopicCommentOptions = {},+ ): Promise<UpdateTopicCommentResult | undefined> {+ const workspaceId = this.requireWorkspaceId();++ return this.db.transaction(async (tx) => {+ const conditions = [+ eq(topicComments.id, id),+ eq(topicComments.workspaceId, workspaceId),+ // Edits are strictly author-scoped — no owner override here on+ // purpose (see DeleteTopicCommentOptions.overrideAuthorScope)+ eq(topicComments.authorUserId, this.userId),+ // Tombstones are dead rows — never editable+ isNull(topicComments.deletedAt),+ // Owner-moderated rows are frozen until restored+ isNull(topicComments.moderatedAt),+ ];++ const [comment] = await tx+ .update(topicComments)+ .set({+ updatedAt: new Date(),+ ...(params.content === undefined ? {} : { content: params.content }),+ ...(params.editorData === undefined ? {} : { editorData: params.editorData }),+ })+ .where(and(...conditions))+ .returning();++ if (!comment) return undefined;++ let addedMentionUserIds: string[] = [];+ if (options.mentionedUserIds) {+ const next = [...new Set(options.mentionedUserIds)];+ const existingRows = await tx+ .select({ mentionedUserId: topicCommentMentions.mentionedUserId })+ .from(topicCommentMentions)+ .where(eq(topicCommentMentions.commentId, id));+ const existing = new Set(existingRows.map((row) => row.mentionedUserId));++ addedMentionUserIds = next.filter((userId) => !existing.has(userId));+ const removed = [...existing].filter((userId) => !next.includes(userId));++ if (addedMentionUserIds.length > 0) {+ await tx+ .insert(topicCommentMentions)+ .values(+ addedMentionUserIds.map((mentionedUserId) => ({+ commentId: id,+ mentionedUserId,+ workspaceId,+ })),+ )+ .onConflictDoNothing();+ }++ if (removed.length > 0) {+ await tx+ .delete(topicCommentMentions)+ .where(+ and(+ eq(topicCommentMentions.commentId, id),+ inArray(topicCommentMentions.mentionedUserId, removed),+ ),+ );+ }+ }++ return { addedMentionUserIds, comment };+ });+ }++ /**+ * Hybrid delete. A comment with live replies is soft-deleted (content and+ * editorData blanked, mentions dropped, `deletedAt` stamped) so the replies+ * — other people's work — survive under a placeholder; the anchor fields+ * stay so the thread keeps its message anchor. A reply-less comment is+ * hard-deleted, and if it was the last live reply of a tombstoned root the+ * tombstone is garbage-collected in the same transaction. Tombstones+ * themselves are not deletable again (only GC removes them).+ *+ * Returns the mode used, or false when the row wasn't found / not owned.+ */+ async delete(+ id: string,+ options: DeleteTopicCommentOptions = {},+ ): Promise<'hard' | 'soft' | false> {+ const workspaceId = this.requireWorkspaceId();++ return this.db.transaction(async (tx) => {+ const conditions = [+ eq(topicComments.id, id),+ eq(topicComments.workspaceId, workspaceId),+ isNull(topicComments.moderatedAt),+ ];+ if (!options.overrideAuthorScope)+ conditions.push(eq(topicComments.authorUserId, this.userId));++ // Discover the thread root first, then serialize every structural delete+ // in the thread on that one row. Locking only the target would still let+ // two sibling replies be deleted concurrently and both observe the other+ // uncommitted reply, leaving an empty tombstone behind.+ const [candidate] = await tx+ .select({ id: topicComments.id, parentCommentId: topicComments.parentCommentId })+ .from(topicComments)+ .where(and(...conditions))+ .limit(1);++ if (!candidate) return false;++ const rootId = candidate.parentCommentId ?? candidate.id;+ const [lockedRoot] = await tx+ .select({ id: topicComments.id })+ .from(topicComments)+ .where(+ and(+ eq(topicComments.id, rootId),+ eq(topicComments.workspaceId, workspaceId),+ isNull(topicComments.parentCommentId),+ ),+ )+ .for('update');++ if (!lockedRoot) return false;++ // The target may have changed while this transaction waited for the root+ // lock, so authorization and deletion state must be checked again.+ const [comment] = await tx+ .select({+ deletedAt: topicComments.deletedAt,+ id: topicComments.id,+ parentCommentId: topicComments.parentCommentId,+ })+ .from(topicComments)+ .where(and(...conditions))+ .limit(1);++ if (!comment || comment.deletedAt) return false;++ const [structuralReplies] = await tx+ .select({ total: count() })+ .from(topicComments)+ .where(eq(topicComments.parentCommentId, id));++ if ((structuralReplies?.total ?? 0) > 0) {+ await tx+ .update(topicComments)+ .set({ content: '', deletedAt: new Date(), editorData: null, updatedAt: new Date() })+ .where(eq(topicComments.id, id));+ // Retracted content must not keep notifying/relating people+ await tx.delete(topicCommentMentions).where(eq(topicCommentMentions.commentId, id));++ return 'soft';+ }++ await tx.delete(topicComments).where(eq(topicComments.id, id));++ // Tombstone GC: a soft-deleted root exists iff it still has live replies+ if (comment.parentCommentId) {+ const [parent] = await tx+ .select({ deletedAt: topicComments.deletedAt, id: topicComments.id })+ .from(topicComments)+ .where(eq(topicComments.id, comment.parentCommentId))+ .limit(1);++ if (parent?.deletedAt) {+ const [siblings] = await tx+ .select({ total: count() })+ .from(topicComments)+ .where(eq(topicComments.parentCommentId, parent.id));++ if ((siblings?.total ?? 0) === 0)+ await tx.delete(topicComments).where(eq(topicComments.id, parent.id));+ }+ }++ return 'hard';+ });+ }++ /**+ * Recoverably remove another user's active comment. Authorization is owner-+ * only at the router; the author inequality remains here as defense in depth+ * so this path can never change self-delete semantics.+ */+ async moderateRemove(+ id: string,+ now = new Date(),+ trx?: Transaction,+ ): Promise<ModerateTopicCommentResult | undefined> {+ const workspaceId = this.requireWorkspaceId();+ const moderationExpiresAt = new Date(now.getTime() + TOPIC_COMMENT_MODERATION_RECOVERY_MS);++ const [comment] = await (trx ?? this.db)+ .update(topicComments)+ .set({+ moderatedAt: now,+ moderatedByUserId: this.userId,+ moderationExpiresAt,+ // Moderation is not an author edit and must not change the displayed edit time.+ updatedAt: sql`${topicComments.updatedAt}`,+ })+ .where(+ and(+ eq(topicComments.id, id),+ eq(topicComments.workspaceId, workspaceId),+ isNull(topicComments.deletedAt),+ isNull(topicComments.moderatedAt),+ or(ne(topicComments.authorUserId, this.userId), isNull(topicComments.authorUserId)),+ ),+ )+ .returning();++ return comment ? { comment, moderationExpiresAt } : undefined;+ }++ /** Owner-only at the router. Restoring does not touch updatedAt or mentions. */+ async restoreModerated(+ id: string,+ now = new Date(),+ trx?: Transaction,+ ): Promise<TopicCommentItem | undefined> {+ const workspaceId = this.requireWorkspaceId();++ const [comment] = await (trx ?? this.db)+ .update(topicComments)+ .set({+ moderatedAt: null,+ moderatedByUserId: null,+ moderationExpiresAt: null,+ // Restoring the retained version is not a content edit.+ updatedAt: sql`${topicComments.updatedAt}`,+ })+ .where(+ and(+ eq(topicComments.id, id),+ eq(topicComments.workspaceId, workspaceId),+ isNotNull(topicComments.moderatedAt),+ gt(topicComments.moderationExpiresAt, now),+ isNull(topicComments.deletedAt),+ ),+ )+ .returning();++ return comment;+ }++ async findById(+ id: string,+ options: TopicCommentReadOptions = {},+ ): Promise<TopicCommentItem | undefined> {+ const workspaceId = this.requireWorkspaceId();+ const moderatedReadCondition = this.moderatedReadCondition(options);++ const [comment] = await this.db+ .select()+ .from(topicComments)+ .where(+ and(+ eq(topicComments.id, id),+ eq(topicComments.workspaceId, workspaceId),+ moderatedReadCondition,+ ),+ )+ .limit(1);++ return comment;+ }++ /**+ * Root-thread page ordered newest-first by `(createdAt, id)`, with live-reply counts loaded+ * in one bounded group-by query. Reply bodies are deliberately omitted and+ * paged only through `listReplies`, so one hot thread cannot make this response+ * grow without bound. Tombstoned roots remain visible while their replies live.+ */+ async listThreads(+ params: ListTopicCommentThreadsParams,+ options: TopicCommentReadOptions = {},+ ): Promise<TopicCommentThreadPage> {+ const workspaceId = this.requireWorkspaceId();+ const { cursor, limit = 20, messageId, topicId } = params;++ const rootConditions = [+ eq(topicComments.topicId, topicId),+ eq(topicComments.workspaceId, workspaceId),+ isNull(topicComments.parentCommentId),+ ];+ const moderatedReadCondition = this.moderatedReadCondition(options);+ if (moderatedReadCondition) rootConditions.push(moderatedReadCondition);+ if (messageId !== undefined) rootConditions.push(eq(topicComments.messageId, messageId));++ const decodedCursor = decodeTopicCommentCursor(cursor);+ if (decodedCursor) {+ const cursorCreatedAt = sql`${decodedCursor.createdAt}::timestamptz`;+ rootConditions.push(+ or(+ lt(topicComments.createdAt, cursorCreatedAt),+ and(eq(topicComments.createdAt, cursorCreatedAt), lt(topicComments.id, decodedCursor.id)),+ )!,+ );+ }++ const rows = await this.db+ .select(topicCommentCursorSelection)+ .from(topicComments)+ .where(and(...rootConditions))+ .orderBy(desc(topicComments.createdAt), desc(topicComments.id))+ .limit(limit + 1);++ const hasMore = rows.length > limit;+ const pageRows = hasMore ? rows.slice(0, limit) : rows;+ const roots = pageRows.map(({ cursorCreatedAt: _cursorCreatedAt, ...root }) => root);+ const rootIds = roots.map((root) => root.id);+ const replyCountRows =+ rootIds.length === 0+ ? []+ : await this.db+ .select({ parentCommentId: topicComments.parentCommentId, total: count() })+ .from(topicComments)+ .where(+ and(+ eq(topicComments.workspaceId, workspaceId),+ inArray(topicComments.parentCommentId, rootIds),+ isNull(topicComments.deletedAt),+ isNull(topicComments.moderatedAt),+ ),+ )+ .groupBy(topicComments.parentCommentId);++ const replyCountByRootId = new Map<string, number>();+ for (const row of replyCountRows) {+ if (row.parentCommentId) replyCountByRootId.set(row.parentCommentId, row.total);+ }++ return {+ items: roots.map((root) => ({ replyCount: replyCountByRootId.get(root.id) ?? 0, root })),+ nextCursor: hasMore+ ? encodeTopicCommentCursor(pageRows.at(-1)!.cursorCreatedAt, pageRows.at(-1)!.id)+ : null,+ };+ }++ /** Independently paginated replies for expanding or incrementally loading one thread. */+ async listReplies(+ params: ListTopicCommentRepliesParams,+ options: TopicCommentReadOptions = {},+ ): Promise<TopicCommentReplyPage> {+ const workspaceId = this.requireWorkspaceId();+ const { cursor, limit = 50, rootCommentId } = params;+ const conditions = [+ eq(topicComments.parentCommentId, rootCommentId),+ eq(topicComments.workspaceId, workspaceId),+ ];+ const moderatedReadCondition = this.moderatedReadCondition(options);+ if (moderatedReadCondition) conditions.push(moderatedReadCondition);++ const decodedCursor = decodeTopicCommentCursor(cursor);+ if (decodedCursor) {+ const cursorCreatedAt = sql`${decodedCursor.createdAt}::timestamptz`;+ conditions.push(+ or(+ gt(topicComments.createdAt, cursorCreatedAt),+ and(eq(topicComments.createdAt, cursorCreatedAt), gt(topicComments.id, decodedCursor.id)),+ )!,+ );+ }++ const rows = await this.db+ .select(topicCommentCursorSelection)+ .from(topicComments)+ .where(and(...conditions))+ .orderBy(asc(topicComments.createdAt), asc(topicComments.id))+ .limit(limit + 1);+ const hasMore = rows.length > limit;+ const pageRows = hasMore ? rows.slice(0, limit) : rows;+ const items = pageRows.map(({ cursorCreatedAt: _cursorCreatedAt, ...item }) => item);++ return {+ items,+ nextCursor: hasMore+ ? encodeTopicCommentCursor(pageRows.at(-1)!.cursorCreatedAt, pageRows.at(-1)!.id)+ : null,+ };+ }++ async summary(topicId: string): Promise<TopicCommentSummary> {+ const workspaceId = this.requireWorkspaceId();+ const scope = and(+ eq(topicComments.topicId, topicId),+ eq(topicComments.workspaceId, workspaceId),+ );++ const [totalRow] = await this.db+ .select({ total: count() })+ .from(topicComments)+ .where(and(scope, isNull(topicComments.deletedAt), isNull(topicComments.moderatedAt)));++ const byMessage = await this.db+ .select({ messageCount: count(), messageId: topicComments.messageId })+ .from(topicComments)+ .where(+ and(+ scope,+ isNotNull(topicComments.messageId),+ or(+ and(isNull(topicComments.deletedAt), isNull(topicComments.moderatedAt)),+ exists(+ this.db+ .select({ id: topicCommentChildren.id })+ .from(topicCommentChildren)+ .where(+ and(+ eq(topicCommentChildren.parentCommentId, topicComments.id),+ isNull(topicCommentChildren.deletedAt),+ isNull(topicCommentChildren.moderatedAt),+ ),+ ),+ ),+ ),+ ),+ )+ .groupBy(topicComments.messageId);++ return {+ countByMessage: Object.fromEntries(+ byMessage.map((row) => [row.messageId as string, row.messageCount]),+ ),+ total: totalRow?.total ?? 0,+ };+ }++ async getMentions(commentId: string) {+ const workspaceId = this.requireWorkspaceId();++ return this.db+ .select()+ .from(topicCommentMentions)+ .where(+ and(+ eq(topicCommentMentions.commentId, commentId),+ eq(topicCommentMentions.workspaceId, workspaceId),+ ),+ )+ .orderBy(asc(topicCommentMentions.createdAt));+ }+}++/**+ * Permanently sanitize expired owner-moderated comments in a bounded batch.+ * Candidate rows are locked so a concurrent restore or reply creation cannot+ * race the destructive transition.+ */+export const purgeExpiredTopicCommentModeration = async (+ db: LobeChatDatabase,+ options: { limit?: number; now?: Date } = {},+): Promise<PurgeExpiredTopicCommentModerationResult> => {+ const { limit = 500, now = new Date() } = options;++ return db.transaction(async (tx) => {+ const candidates = await tx+ .select({+ id: topicComments.id,+ parentCommentId: topicComments.parentCommentId,+ })+ .from(topicComments)+ .where(+ and(+ isNotNull(topicComments.moderatedAt),+ lte(topicComments.moderationExpiresAt, now),+ isNull(topicComments.deletedAt),+ ),+ )+ .orderBy(asc(topicComments.moderationExpiresAt), asc(topicComments.id))+ .limit(limit)+ .for('update');++ if (candidates.length === 0)+ return { garbageCollected: 0, hardDeleted: 0, processed: 0, tombstoned: 0 };++ const candidateIds = candidates.map(({ id }) => id);+ const children = await tx+ .select({ parentCommentId: topicComments.parentCommentId })+ .from(topicComments)+ .where(inArray(topicComments.parentCommentId, candidateIds));+ const idsWithChildren = new Set(+ children.flatMap(({ parentCommentId }) => (parentCommentId ? [parentCommentId] : [])),+ );+ const tombstoneIds = candidateIds.filter((id) => idsWithChildren.has(id));+ const hardDeleteIds = candidateIds.filter((id) => !idsWithChildren.has(id));++ let tombstoned = 0;+ if (tombstoneIds.length > 0) {+ await tx+ .delete(topicCommentMentions)+ .where(inArray(topicCommentMentions.commentId, tombstoneIds));+ const rows = await tx+ .update(topicComments)+ .set({+ content: '',+ deletedAt: now,+ editorData: null,+ moderatedAt: null,+ moderatedByUserId: null,+ moderationExpiresAt: null,+ })+ .where(+ and(+ inArray(topicComments.id, tombstoneIds),+ isNotNull(topicComments.moderatedAt),+ lte(topicComments.moderationExpiresAt, now),+ ),+ )+ .returning({ id: topicComments.id });+ tombstoned = rows.length;+ }++ let hardDeleted = 0;+ if (hardDeleteIds.length > 0) {+ const rows = await tx+ .delete(topicComments)+ .where(+ and(+ inArray(topicComments.id, hardDeleteIds),+ isNotNull(topicComments.moderatedAt),+ lte(topicComments.moderationExpiresAt, now),+ ),+ )+ .returning({ id: topicComments.id });+ hardDeleted = rows.length;+ }++ // If a candidate child was the last row preserving a permanent root+ // tombstone, collect that now-empty root in the same transaction. A root+ // and its expired child can also both appear in this batch.+ const gcCandidateIds = [+ ...new Set([+ ...tombstoneIds,+ ...candidates.flatMap(({ parentCommentId }) => (parentCommentId ? [parentCommentId] : [])),+ ]),+ ];+ const garbageCollectedRows =+ gcCandidateIds.length === 0+ ? []+ : await tx+ .delete(topicComments)+ .where(+ and(+ inArray(topicComments.id, gcCandidateIds),+ isNotNull(topicComments.deletedAt),+ isNull(topicComments.moderatedAt),+ notExists(+ tx+ .select({ id: topicCommentChildren.id })+ .from(topicCommentChildren)+ .where(eq(topicCommentChildren.parentCommentId, topicComments.id)),+ ),+ ),+ )+ .returning({ id: topicComments.id });++ return {+ garbageCollected: garbageCollectedRows.length,+ hardDeleted,+ processed: candidates.length,+ tombstoned,+ };+ });+};++/**+ * Keeps the denormalized comment scope consistent when topics change+ * ownership. `AgentModel.transferAgent` and+ * `AgentGroupRepository.transferToWorkspace` rewrite `topics.workspaceId`+ * (including to NULL for personal scope); without this call the comments keep+ * the source workspaceId — destination-scoped reads lose them, source-scoped+ * reads keep leaking them, and deleting the source workspace cascades rows+ * that no longer belong to it. Must run inside the same transaction that+ * moves the topics.+ *+ * - Cross-workspace move: comments and mention rows follow the topic — they+ * are part of its history, exactly like `messages`. Authors / mentioned+ * users may not be members of the target workspace; that renders the same+ * as any other non-member author (same class as a deactivated account).+ * - Move to personal scope: comments are deleted. Personal topics cannot be+ * commented on by design and `workspaceId` is NOT NULL, so there is no+ * representable state to keep. One DELETE removes roots and replies alike —+ * parent and child rows die in the same statement, so the self-FK+ * (NO ACTION) passes; mention rows go via ON DELETE CASCADE.+ */+export const syncTopicCommentsOnTopicTransfer = async (+ trx: Transaction,+ topicIds: string[],+ targetWorkspaceId: string | null,+): Promise<void> => {+ if (topicIds.length === 0) return;++ if (!targetWorkspaceId) {+ await trx.delete(topicComments).where(inArray(topicComments.topicId, topicIds));+ return;+ }++ await trx+ .update(topicComments)+ // Moving a comment is not an author edit. Explicitly preserve updatedAt to+ // bypass the schema's Drizzle $onUpdate hook.+ .set({ updatedAt: topicComments.updatedAt, workspaceId: targetWorkspaceId })+ .where(inArray(topicComments.topicId, topicIds));++ await trx+ .update(topicCommentMentions)+ .set({ workspaceId: targetWorkspaceId })+ .where(+ inArray(+ topicCommentMentions.commentId,+ trx+ .select({ id: topicComments.id })+ .from(topicComments)+ .where(inArray(topicComments.topicId, topicIds)),+ ),+ );+};++/**+ * Whether any comment on the given topics was authored by someone other than+ * `userId`. Transfer guards (`AgentModel.transferHasForeignRows`,+ * `AgentGroupRepository.transferHasForeignRows`) must include this check:+ * comments move — or die, when the target is personal scope — with their+ * topics (see {@link syncTopicCommentsOnTopicTransfer}), so a non-owner+ * member must not be able to rehome or destroy a teammate's comment just+ * because every other cascaded row happens to be their own.+ *+ * `topicWhere` is a predicate over the joined `topics` table selecting the+ * topics the transfer would move. NULL authors (account deleted) count as+ * foreign: the row is definitionally not the caller's, and SQL `ne()` would+ * silently skip it.+ */+export const hasForeignTopicComments = async (+ db: Pick<LobeChatDatabase, 'select'>,+ userId: string,+ topicWhere: SQL,+): Promise<boolean> => {+ const [foreign] = await db+ .select({ id: topicComments.id })+ .from(topicComments)+ .innerJoin(topics, eq(topicComments.topicId, topics.id))+ .where(+ and(+ topicWhere,+ or(ne(topicComments.authorUserId, userId), isNull(topicComments.authorUserId)),+ ),+ )+ .limit(1);++ return !!foreign;+};diff --git a/packages/database/src/models/workspaceAuditLog.ts b/packages/database/src/models/workspaceAuditLog.tsindex 6ecb8a943df..8518467d88c 100644--- a/packages/database/src/models/workspaceAuditLog.ts+++ b/packages/database/src/models/workspaceAuditLog.ts@@ -1,7 +1,7 @@import { and, desc, eq, gte, ilike, inArray, lt, lte, or } from 'drizzle-orm';import { workspaceAuditLogs } from '../schemas/workspace';-import type { LobeChatDatabase } from '../type';+import type { LobeChatDatabase, Transaction } from '../type';export type WorkspaceAuditAction =| 'workspace.created'@@ -108,8 +108,8 @@ export class WorkspaceAuditLogModel {this.db = db;}- create = async (params: CreateAuditLogParams) => {- const [row] = await this.db+ create = async (params: CreateAuditLogParams, trx?: Transaction) => {+ const [row] = await (trx ?? this.db).insert(workspaceAuditLogs).values({action: params.action,diff --git a/packages/database/src/repositories/agentGroup/index.test.ts b/packages/database/src/repositories/agentGroup/index.test.tsindex 2cbb62192a0..b6f1eeded05 100644--- a/packages/database/src/repositories/agentGroup/index.test.ts+++ b/packages/database/src/repositories/agentGroup/index.test.ts@@ -5,10 +5,16 @@ import { beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';import { ChatGroupModel } from '../../models/chatGroup';+import {+ TOPIC_COMMENT_TOPIC_NOT_FOUND,+ TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS,+ TopicCommentModel,+} from '../../models/topicComment';import { agents } from '../../schemas/agent';import { chatGroups, chatGroupsAgents } from '../../schemas/chatGroup';import { messagePlugins, messages } from '../../schemas/message';import { threads, topics } from '../../schemas/topic';+import { topicCommentMentions, topicComments } from '../../schemas/topicComment';import { users } from '../../schemas/user';import { workspaces } from '../../schemas/workspace';import type { LobeChatDatabase } from '../../type';@@ -20,6 +26,7 @@ const otherUserId = 'other-agent-group-user';let agentGroupRepo: AgentGroupRepository;const serverDB: LobeChatDatabase = await getTestDB();+const isServerDB = process.env.TEST_SERVER_DB === '1';beforeEach(async () => {// Clean up@@ -1552,6 +1559,21 @@ describe('AgentGroupRepository', () => {userId,workspaceId,});+ const originalCommentUpdatedAt = new Date('2024-01-02T03:04:05.000Z');+ await serverDB.insert(topicComments).values({+ authorUserId: userId,+ clientId: 'transfer-comment-client',+ content: 'team note',+ id: 'transfer-comment',+ topicId: 'transfer-topic',+ updatedAt: originalCommentUpdatedAt,+ workspaceId,+ });+ await serverDB.insert(topicCommentMentions).values({+ commentId: 'transfer-comment',+ mentionedUserId: userId,+ workspaceId,+ });const wsRepo = new AgentGroupRepository(serverDB, userId, workspaceId);const result = await wsRepo.transferToWorkspace('transfer-group', targetWorkspaceId, userId);@@ -1585,8 +1607,114 @@ describe('AgentGroupRepository', () => {expect(topic!.workspaceId).toBe(targetWorkspaceId);expect(thread!.workspaceId).toBe(targetWorkspaceId);expect(message!.workspaceId).toBe(targetWorkspaceId);++ // Comments denormalize the topic's workspaceId — they must follow the move+ const [comment] = await serverDB+ .select()+ .from(topicComments)+ .where(eq(topicComments.id, 'transfer-comment'));+ const [mention] = await serverDB+ .select()+ .from(topicCommentMentions)+ .where(eq(topicCommentMentions.commentId, 'transfer-comment'));+ expect(comment.workspaceId).toBe(targetWorkspaceId);+ expect(comment.updatedAt).toEqual(originalCommentUpdatedAt);+ expect(mention.workspaceId).toBe(targetWorkspaceId);+ });++ it('flags teammate-authored comments as foreign transfer rows', async () => {+ await serverDB.insert(chatGroups).values({+ id: 'guard-group',+ title: 'Guard Group',+ userId,+ workspaceId,+ });+ await serverDB.insert(topics).values({+ groupId: 'guard-group',+ id: 'guard-group-topic',+ title: 'Own Topic',+ userId,+ workspaceId,+ });++ const wsRepo = new AgentGroupRepository(serverDB, userId, workspaceId);++ // Caller's own comment — not foreign+ await serverDB.insert(topicComments).values({+ authorUserId: userId,+ clientId: 'guard-group-own',+ content: 'my note',+ id: 'tcm-group-guard-own',+ topicId: 'guard-group-topic',+ workspaceId,+ });+ expect(await wsRepo.transferHasForeignRows('guard-group')).toBe(false);++ // A teammate's comment on the caller's own topic — foreign+ await serverDB.insert(topicComments).values({+ authorUserId: otherUserId,+ clientId: 'guard-group-teammate',+ content: 'teammate note',+ id: 'tcm-group-guard-teammate',+ topicId: 'guard-group-topic',+ workspaceId,+ });+ expect(await wsRepo.transferHasForeignRows('guard-group')).toBe(true);});+ it.skipIf(!isServerDB)(+ 'serializes comment creation with the authoritative group transfer check',+ async () => {+ const targetWorkspaceId = 'agent-group-race-target-ws';+ await serverDB.insert(workspaces).values({+ id: targetWorkspaceId,+ name: 'Race Target Workspace',+ primaryOwnerId: userId,+ slug: targetWorkspaceId,+ });+ const wsRepo = new AgentGroupRepository(serverDB, userId, workspaceId);+ const commenterModel = new TopicCommentModel(serverDB, otherUserId, workspaceId);++ for (let i = 0; i < 10; i++) {+ const groupId = `transfer-group-race-${i}`;+ const topicId = `transfer-group-race-topic-${i}`;+ await serverDB.insert(chatGroups).values({+ id: groupId,+ title: `Race Group ${i}`,+ userId,+ workspaceId,+ });+ await serverDB.insert(topics).values({+ groupId,+ id: topicId,+ title: `Race Topic ${i}`,+ userId,+ workspaceId,+ });++ const outcomes = await Promise.allSettled([+ wsRepo.transferToWorkspace(groupId, targetWorkspaceId, userId, undefined, {+ rejectForeignTopicCommentAuthors: true,+ }),+ commenterModel.createWithMentions({+ clientId: `transfer-group-race-comment-${i}`,+ content: 'concurrent teammate comment',+ topicId,+ }),+ ]);++ expect(outcomes.map(({ status }) => status).sort()).toEqual(['fulfilled', 'rejected']);+ const rejection = outcomes.find(+ (outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected',+ );+ expect([+ TOPIC_COMMENT_TOPIC_NOT_FOUND,+ TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS,+ ]).toContain(rejection?.reason.message);+ }+ },+ );+it('copies a workspace group and all members into the target scope', async () => {const targetWorkspaceId = 'agent-group-copy-target-ws';await serverDB.insert(workspaces).values({diff --git a/packages/database/src/repositories/agentGroup/index.ts b/packages/database/src/repositories/agentGroup/index.tsindex 56c19c9e221..5f63e828a51 100644--- a/packages/database/src/repositories/agentGroup/index.ts+++ b/packages/database/src/repositories/agentGroup/index.ts@@ -1,8 +1,13 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';import type { AgentGroupDetail, AgentGroupMember, AgentPluginEntry } from '@lobechat/types';import { cleanObject } from '@lobechat/utils';-import { and, eq, inArray, ne, not, sql } from 'drizzle-orm';+import { and, asc, eq, inArray, ne, not, sql } from 'drizzle-orm';+import {+ hasForeignTopicComments,+ syncTopicCommentsOnTopicTransfer,+ TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS,+} from '../../models/topicComment';import type {AgentItem,ChatGroupItem,@@ -798,6 +803,12 @@ export class AgentGroupRepository {.limit(1);if (foreignTopic) return true;+ // Comments move (or die, when the target is personal scope) with their+ // topics — a teammate's comment on the caller's own topic is still their+ // work. NULL authors (deleted accounts) count as foreign too.+ if (await hasForeignTopicComments(this.db, this.userId, eq(topics.groupId, groupId)))+ return true;+const [foreignThread] = await this.db.select({ id: threads.id }).from(threads)@@ -818,6 +829,7 @@ export class AgentGroupRepository {targetWorkspaceId: string | null,targetUserId: string,targetVisibility?: 'private' | 'public',+ options: { rejectForeignTopicCommentAuthors?: boolean } = {},): Promise<{ groupId: string } | null> {const sourceGroup = await this.db.query.chatGroups.findFirst({where: and(eq(chatGroups.id, groupId), this.groupOwnership()),@@ -868,25 +880,43 @@ export class AgentGroupRepository {.where(inArray(agents.id, agentIds));}- const groupTopics = await trx+ await trx.select({ id: topics.id }).from(topics)- .where(eq(topics.groupId, groupId));- const groupTopicIds = groupTopics.map((topic) => topic.id);+ .where(eq(topics.groupId, groupId))+ .orderBy(asc(topics.id))+ .for('update');++ if (+ options.rejectForeignTopicCommentAuthors &&+ (await hasForeignTopicComments(trx, this.userId, eq(topics.groupId, groupId)))+ ) {+ throw new Error(TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS);+ }- await trx.update(topics).set(ownershipUpdate).where(eq(topics.groupId, groupId));+ const movedTopics = await trx+ .update(topics)+ .set(ownershipUpdate)+ .where(eq(topics.groupId, groupId))+ .returning({ id: topics.id });+ const movedTopicIds = movedTopics.map((topic) => topic.id);await trx.update(threads).set(ownershipUpdate).where(eq(threads.groupId, groupId));await trx.update(messages).set(ownershipUpdate).where(eq(messages.groupId, groupId));- if (groupTopicIds.length > 0) {+ // Topic comments denormalize the topic's workspaceId — move them with+ // the topic (or drop them when leaving workspace scope entirely),+ // otherwise workspace-filtered comment reads go stale. See the helper doc.+ await syncTopicCommentsOnTopicTransfer(trx, movedTopicIds, targetWorkspaceId);++ if (movedTopicIds.length > 0) {await trx.update(threads).set(ownershipUpdate)- .where(inArray(threads.topicId, groupTopicIds));+ .where(inArray(threads.topicId, movedTopicIds));await trx.update(messages).set(ownershipUpdate)- .where(inArray(messages.topicId, groupTopicIds));+ .where(inArray(messages.topicId, movedTopicIds));}return { groupId };diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 7388252ca68..dac1e799fb1 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1462,6 +1462,46 @@ export default {'topic.recent': 'Recent Topics','topic.saveCurrentMessages': 'Save current conversation as topic','topic.viewAll': 'View All Topics',+ 'topicComment.anchor': 'Original message',+ 'topicComment.anchorDeleted': 'Original message deleted',+ 'topicComment.anchorEmpty': 'Empty message',+ 'topicComment.author.deactivated': 'Deleted user',+ 'topicComment.author.former': 'Former member',+ 'topicComment.cancel': 'Cancel',+ 'topicComment.commentOnMessage': 'Comment on this message',+ 'topicComment.createFailed': 'Failed to post comment. Your draft is still here.',+ 'topicComment.delete': 'Delete',+ 'topicComment.deleteConfirm.content':+ 'This comment will be removed. Replies will remain if this starts a thread.',+ 'topicComment.deleteConfirm.title': 'Delete this comment?',+ 'topicComment.deleteFailed': 'Failed to delete comment',+ 'topicComment.deleted': 'This comment was deleted.',+ 'topicComment.edit': 'Edit',+ 'topicComment.edited': 'edited',+ 'topicComment.empty': 'No comments yet',+ 'topicComment.loadMore': 'Load more',+ 'topicComment.messageComments': 'Message comments',+ 'topicComment.messagePlaceholder': 'Comment on this message…',+ 'topicComment.notFound': 'This comment no longer exists',+ 'topicComment.openMessageComments': 'Open {{count}} message comments',+ 'topicComment.placeholder': 'Add a comment…',+ 'topicComment.repliesTitle': 'Replies',+ 'topicComment.replies_one': '{{count}} reply',+ 'topicComment.replies_other': '{{count}} replies',+ 'topicComment.reply': 'Reply',+ 'topicComment.replyPlaceholder': 'Write a reply…',+ 'topicComment.removed': 'This comment was removed by a Workspace Owner.',+ 'topicComment.removedOwn': 'Your comment was removed by a Workspace Owner.',+ 'topicComment.removedOwnerView':+ 'Removed by a Workspace Owner. This content is visible only to Workspace Owners during the recovery period.',+ 'topicComment.restore': 'Restore',+ 'topicComment.restoreDeadline': 'Restorable until {{date}}',+ 'topicComment.restoreFailed': 'Failed to restore comment',+ 'topicComment.save': 'Save',+ 'topicComment.sending': 'Sending…',+ 'topicComment.thread': 'Comment thread',+ 'topicComment.title': 'Comments',+ 'topicComment.updateFailed': 'Failed to update comment','translate.action': 'Translate','translate.clear': 'Clear Translation','tts.action': 'Text-to-Speech',diff --git a/packages/locales/src/default/notification.ts b/packages/locales/src/default/notification.tsindex a49d8e8a19f..7849ce25dee 100644--- a/packages/locales/src/default/notification.ts+++ b/packages/locales/src/default/notification.ts@@ -50,6 +50,17 @@ export default {'Your subscription renewal payment failed. Please update your payment method to keep your subscription active.','subscription_payment_failed_action': 'Update payment method','subscription_payment_failed_title': 'Subscription renewal payment failed',+ 'topic_comment_activity': '{{actorLabel}} commented on your topic.',+ 'topic_comment_activity_mentioned': '{{actorLabel}} mentioned you in a comment.',+ 'topic_comment_activity_mentioned_title': 'You were mentioned in a comment',+ 'topic_comment_activity_replied': '{{actorLabel}} replied to your comment.',+ 'topic_comment_activity_replied_title': 'New reply to your comment',+ 'topic_comment_activity_title': 'New topic comment',+ 'topic_comment_removed_by_workspace_owner':+ 'Your comment was removed by a Workspace Owner. Open the discussion to view its place in the thread.',+ 'topic_comment_removed_by_workspace_owner_title': 'Comment removed',+ 'topic_comment_restored_by_workspace_owner': 'A Workspace Owner restored your comment.',+ 'topic_comment_restored_by_workspace_owner_title': 'Comment restored','video_generation_completed': 'Your video "{{prompt}}" is ready.','video_generation_completed_title': 'Video generation completed','workspace_member_invited':diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 5c5592d0b33..48879e5ee7e 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -41,6 +41,7 @@ export * from './stepContext';export * from './task';export * from './tool';export * from './topic';+export * from './topicComment';export * from './user';export * from './userMemory';export * from './verify';diff --git a/packages/types/src/topicComment.ts b/packages/types/src/topicComment.tsnew file mode 100644index 00000000000..70106a09921--- /dev/null+++ b/packages/types/src/topicComment.ts@@ -0,0 +1,74 @@+export type TopicCommentAuthorStatus = 'active' | 'deactivated' | 'former';++export type TopicCommentJson =+ boolean | number | string | null | TopicCommentJson[] | { [key: string]: TopicCommentJson };++export interface TopicCommentAnchorPreview {+ excerpt: string;+ role?: string;+}++export interface TopicCommentAuthor {+ avatar: string | null;+ fullName: string | null;+ id: string | null;+ status: TopicCommentAuthorStatus;+ username: string | null;+}++export interface TopicCommentItem {+ anchorPreview: TopicCommentAnchorPreview | null;+ author: TopicCommentAuthor;+ authorUserId: string | null;+ canDelete: boolean;+ canEdit: boolean;+ canRestore: boolean;+ clientId: string;+ content: string;+ createdAt: Date;+ deletedAt: Date | null;+ editorData: TopicCommentJson | null;+ id: string;+ messageId: string | null;+ /** Recoverable Workspace Owner removal; the acting owner's identity is intentionally omitted. */+ moderatedAt: Date | null;+ moderationExpiresAt: Date | null;+ /** True only for the original author viewing their owner-removed placeholder. */+ moderationIsOwn: boolean;+ parentCommentId: string | null;+ topicId: string;+ updatedAt: Date;+ workspaceId: string;+}++export interface TopicCommentThread {+ replyCount: number;+ root: TopicCommentItem;+}+export interface TopicCommentThreadPage {+ items: TopicCommentThread[];+ nextCursor: string | null;+}+export interface TopicCommentReplyPage {+ items: TopicCommentItem[];+ nextCursor: string | null;+}+export interface TopicCommentSummary {+ countByMessage: Record<string, number>;+ total: number;+}++export interface CreateTopicCommentInput {+ clientId: string;+ content: string;+ editorData?: TopicCommentJson;+ messageId?: string;+ parentCommentId?: string;+ topicId: string;+}++export interface UpdateTopicCommentInput {+ content?: string;+ editorData?: TopicCommentJson;+ id: string;+}diff --git a/packages/utils/src/__tests__/truncateSurrogateSafe.test.ts b/packages/utils/src/__tests__/truncateSurrogateSafe.test.tsnew file mode 100644index 00000000000..39b746e67c6--- /dev/null+++ b/packages/utils/src/__tests__/truncateSurrogateSafe.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';++import { truncateSurrogateSafe } from '../truncateSurrogateSafe';++describe('truncateSurrogateSafe', () => {+ it('truncates plain text to maxLength', () => {+ expect(truncateSurrogateSafe('a'.repeat(300), 200)).toBe('a'.repeat(200));+ });++ it('returns short strings unchanged', () => {+ expect(truncateSurrogateSafe('hello 😀', 200)).toBe('hello 😀');+ });++ it('drops the lone high surrogate when the cut splits an emoji', () => {+ const result = truncateSurrogateSafe(`${'a'.repeat(199)}😀tail`, 200);++ expect(result).toBe('a'.repeat(199));+ // no surrogate code unit survives, so a JSON/jsonb write cannot be rejected+ expect(result).not.toMatch(/[\uD800-\uDFFF]/);+ });++ it('keeps a surrogate pair that fits exactly at the boundary', () => {+ // the emoji occupies code units 198–199, so the cut lands after the pair+ expect(truncateSurrogateSafe(`${'a'.repeat(198)}😀tail`, 200)).toBe(`${'a'.repeat(198)}😀`);+ });++ it('trims a pre-existing trailing lone high surrogate on short input', () => {+ expect(truncateSurrogateSafe('abc\uD83D', 200)).toBe('abc');+ });++ it('handles empty strings', () => {+ expect(truncateSurrogateSafe('', 10)).toBe('');+ });+});diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex ae2191dcd06..49715224a77 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -23,6 +23,7 @@ export * from './safeParseJSON';export * from './sanitizeToolCallArguments';export * from './sleep';export * from './timing';+export * from './truncateSurrogateSafe';export * from './uriParser';export * from './url';export * from './uuid';diff --git a/packages/utils/src/truncateSurrogateSafe.ts b/packages/utils/src/truncateSurrogateSafe.tsnew file mode 100644index 00000000000..ebae4a3c587--- /dev/null+++ b/packages/utils/src/truncateSurrogateSafe.ts@@ -0,0 +1,23 @@+/**+ * Truncate a string to at most `maxLength` UTF-16 code units without letting+ * the cut split a surrogate pair.+ *+ * A bare `String#slice` can cut an astral-plane character (e.g. emoji) in+ * half, leaving a lone high surrogate at the end of the result.+ * `JSON.stringify` escapes it as an unpaired `\ud8xx`, which PostgreSQL's+ * jsonb parser rejects — so embedding a naively truncated preview in a jsonb+ * write fails the whole statement. Dropping that final code unit keeps the+ * result valid UTF-16.+ *+ * Scope: this only guards the boundary the cut itself creates (a trailing+ * high surrogate — one that pre-existed at the end of a short input is+ * trimmed the same way). Interior lone surrogates in already-invalid input+ * are `sanitizeUTF8`'s job, not this function's.+ */+export const truncateSurrogateSafe = (content: string, maxLength: number): string => {+ const sliced = content.slice(0, maxLength);+ const lastCode = sliced.charCodeAt(sliced.length - 1);++ // 0xD800–0xDBFF = high surrogate left at the cut, i.e. we split a pair+ return lastCode >= 0xd8_00 && lastCode <= 0xdb_ff ? sliced.slice(0, -1) : sliced;+};diff --git a/src/features/Conversation/ChatItem/ChatItem.tsx b/src/features/Conversation/ChatItem/ChatItem.tsxindex 7ee84061d70..d7d7062a8d1 100644--- a/src/features/Conversation/ChatItem/ChatItem.tsx+++ b/src/features/Conversation/ChatItem/ChatItem.tsx@@ -12,7 +12,7 @@ import ErrorContent from './components/ErrorContent';import MessageContent from './components/MessageContent';import Title from './components/Title';import { styles } from './style';-import { type ChatItemProps } from './type';+import type { ChatItemProps } from './type';const ChatItem = memo<ChatItemProps>(({diff --git a/src/features/Conversation/ChatItem/components/Actions.tsx b/src/features/Conversation/ChatItem/components/Actions.tsxindex 5c37275da45..823b2871fc5 100644--- a/src/features/Conversation/ChatItem/components/Actions.tsx+++ b/src/features/Conversation/ChatItem/components/Actions.tsx@@ -6,7 +6,7 @@ import { builtinAgentSelectors } from '@/store/agent/selectors';import { isDev } from '@/utils/env';import { contextSelectors, useConversationStore } from '../../store';-import { type ChatItemProps } from '../type';+import type { ChatItemProps } from '../type';export interface ActionsProps {actionAddon?: ChatItemProps['actionAddon'];@@ -14,7 +14,7 @@ export interface ActionsProps {placement?: ChatItemProps['placement'];}-const Actions = memo<ActionsProps>(({ placement, actionAddon, actions }) => {+const Actions = memo<ActionsProps>(({ actionAddon, placement, actions }) => {const onboardingAgentId = useAgentStore(builtinAgentSelectors.webOnboardingAgentId);const conversationAgentId = useConversationStore(contextSelectors.agentId);if (!isDev && onboardingAgentId && conversationAgentId === onboardingAgentId) return null;@@ -24,14 +24,18 @@ const Actions = memo<ActionsProps>(({ placement, actionAddon, actions }) => {<Flexboxalign={'center'}direction={'horizontal'}- gap={8}- role="menubar"+ gap={4}style={{alignSelf: isUser ? 'flex-end' : 'flex-start',}}>- {actionAddon}- {actions && <Flexbox role="menubar">{actions}</Flexbox>}+ {!isUser && actionAddon}+ {actions && (+ <Flexbox horizontal align={'center'} role="menubar">+ {actions}+ </Flexbox>+ )}+ {isUser && actionAddon}</Flexbox>);});diff --git a/src/features/Conversation/ChatItem/style.ts b/src/features/Conversation/ChatItem/style.tsindex 2dd8f864542..19e18e1f8ab 100644--- a/src/features/Conversation/ChatItem/style.ts+++ b/src/features/Conversation/ChatItem/style.ts@@ -1,11 +1,26 @@-import { createStaticStyles } from 'antd-style';+import { createStaticStyles, keyframes } from 'antd-style';export const styles = createStaticStyles(({ css, cssVar }) => {+ const locateHighlight = keyframes`+ 0%, 100% {+ background: transparent;+ }++ 15%, 55% {+ background: ${cssVar.colorPrimaryBg};+ }+ `;+return {container: css`position: relative;max-width: 100%;+ &[data-message-locate-highlight] {+ border-radius: ${cssVar.borderRadiusLG};+ animation: ${locateHighlight} 1400ms ${cssVar.motionEaseOut};+ }+time,div[role='menubar'] {pointer-events: none;@@ -36,6 +51,13 @@ export const styles = createStaticStyles(({ css, cssVar }) => {opacity: 1;}}++ @media (prefers-reduced-motion: reduce) {+ &[data-message-locate-highlight] {+ background: ${cssVar.colorPrimaryBg};+ animation: none;+ }+ }`,loading: css`position: absolute;diff --git a/src/features/Conversation/ChatItem/type.ts b/src/features/Conversation/ChatItem/type.tsindex 40f1892bf69..20fa25e1f51 100644--- a/src/features/Conversation/ChatItem/type.ts+++ b/src/features/Conversation/ChatItem/type.ts@@ -1,6 +1,6 @@-import { type AlertProps, type AvatarProps, type DivProps, type FlexboxProps } from '@lobehub/ui';-import { type EditableMessageProps, type MetaData } from '@lobehub/ui/chat';-import { type ReactNode } from 'react';+import type { AlertProps, AvatarProps, DivProps, FlexboxProps } from '@lobehub/ui';+import type { EditableMessageProps, MetaData } from '@lobehub/ui/chat';+import type { ReactNode } from 'react';export interface ChatItemProps extends Omit<FlexboxProps, 'children' | 'onChange'> {aboveMessage?: ReactNode;diff --git a/src/features/Conversation/Messages/Assistant/Actions/index.tsx b/src/features/Conversation/Messages/Assistant/Actions/index.tsxindex 4d80d7aaf0b..07eb80dcbfb 100644--- a/src/features/Conversation/Messages/Assistant/Actions/index.tsx+++ b/src/features/Conversation/Messages/Assistant/Actions/index.tsx@@ -15,6 +15,7 @@ const DEFAULT_BAR: MessageActionSlot[] = ['edit', 'copy'];const DEFAULT_MENU: MessageActionSlot[] = ['edit','copy',+ 'comments','branching','collapse','divider',@@ -29,7 +30,7 @@ const DEFAULT_MENU: MessageActionSlot[] = ['del',];const ERROR_BAR: MessageActionSlot[] = ['regenerate', 'del'];-const ERROR_MENU: MessageActionSlot[] = ['edit', 'copy', 'divider', 'del'];+const ERROR_MENU: MessageActionSlot[] = ['edit', 'copy', 'comments', 'divider', 'del'];interface AssistantActionsBarProps {actionsConfig?: MessageActionsConfig;diff --git a/src/features/Conversation/Messages/Assistant/index.tsx b/src/features/Conversation/Messages/Assistant/index.tsxindex 51ddc3d0e54..92c764eb636 100644--- a/src/features/Conversation/Messages/Assistant/index.tsx+++ b/src/features/Conversation/Messages/Assistant/index.tsx@@ -8,6 +8,8 @@ import { memo, useCallback, useMemo } from 'react';import { MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES } from '@/const/messageActionPortal';import { ChatItem } from '@/features/Conversation/ChatItem';+import { useMessageCommentCount } from '@/features/TopicComment/hooks';+import MessageCommentBadge from '@/features/TopicComment/MessageCommentBadge';import { useUserStore } from '@/store/user';import { userGeneralSettingsSelectors, userProfileSelectors } from '@/store/user/selectors';@@ -105,6 +107,7 @@ const AssistantMessage = memo<AssistantMessageProps>(const setMessageItemActionTypeContext = useSetMessageItemActionTypeContext();const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);+ const { count: commentCount, topicId: commentTopicId } = useMessageCommentCount(id);const onMouseEnter: MouseEventHandler<HTMLDivElement> = useCallback((e) => {@@ -138,12 +141,19 @@ const AssistantMessage = memo<AssistantMessageProps>(placement={'left'}time={createdAt}actionAddon={- reactions.length > 0 ? (- <ReactionDisplay- isActive={isReactionActive}- reactions={reactions}- onReactionClick={handleReactionClick}- />+ reactions.length > 0 || (commentCount > 0 && commentTopicId) ? (+ <>+ {reactions.length > 0 && (+ <ReactionDisplay+ isActive={isReactionActive}+ reactions={reactions}+ onReactionClick={handleReactionClick}+ />+ )}+ {commentCount > 0 && commentTopicId && (+ <MessageCommentBadge count={commentCount} messageId={id} topicId={commentTopicId} />+ )}+ </>) : undefined}actions={diff --git a/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsxindex 9f18ab535be..455dae9e731 100644--- a/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx@@ -15,6 +15,7 @@ const DEFAULT_BAR: MessageActionSlot[] = ['edit', 'copy'];const DEFAULT_MENU: MessageActionSlot[] = ['edit','copy',+ 'comments','branching','collapse','divider',@@ -31,7 +32,7 @@ const IN_PROGRESS_BAR: MessageActionSlot[] = ['del'];// shared and multi-selected/forwarded as one aggregated assistant reply. The// forward serializer keeps child text while excluding child tool payloads.const NO_TEXT_BLOCK_BAR: MessageActionSlot[] = ['delAndRegenerate'];-const NO_TEXT_BLOCK_MENU: MessageActionSlot[] = ['share', 'select', 'divider', 'del'];+const NO_TEXT_BLOCK_MENU: MessageActionSlot[] = ['comments', 'share', 'select', 'divider', 'del'];interface GroupActionsProps {actionsConfig?: MessageActionsConfig;diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsxindex 5f0edaa5aa2..3424f8068c1 100644--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx@@ -10,6 +10,8 @@ import { useTranslation } from 'react-i18next';import { MESSAGE_ACTION_BAR_PORTAL_ATTRIBUTES } from '@/const/messageActionPortal';import AgentGroupAvatar from '@/features/AgentGroupAvatar';import { ChatItem } from '@/features/Conversation/ChatItem';+import { useMessageCommentCount } from '@/features/TopicComment/hooks';+import MessageCommentBadge from '@/features/TopicComment/MessageCommentBadge';import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';import dynamic from '@/libs/next/dynamic';import { useAgentStore } from '@/store/agent';@@ -111,6 +113,7 @@ const GroupMessage = memo<GroupMessageProps>(isEqual,);const { t } = useTranslation('chat');+ const { count: commentCount, topicId: commentTopicId } = useMessageCommentCount(id);// Collect fileList from all children blocksconst aggregatedFileList = useMemo(() => {@@ -224,12 +227,19 @@ const GroupMessage = memo<GroupMessageProps>(time={createdAt}titleAddon={isSupervisor ? <Tag>{t('supervisor.label')}</Tag> : undefined}actionAddon={- reactions.length > 0 ? (- <ReactionDisplay- isActive={isReactionActive}- reactions={reactions}- onReactionClick={handleReactionClick}- />+ reactions.length > 0 || (commentCount > 0 && commentTopicId) ? (+ <>+ {reactions.length > 0 && (+ <ReactionDisplay+ isActive={isReactionActive}+ reactions={reactions}+ onReactionClick={handleReactionClick}+ />+ )}+ {commentCount > 0 && commentTopicId && (+ <MessageCommentBadge count={commentCount} messageId={id} topicId={commentTopicId} />+ )}+ </>) : undefined}actions={diff --git a/src/features/Conversation/Messages/Task/Actions/index.tsx b/src/features/Conversation/Messages/Task/Actions/index.tsxindex fd386429f3b..6b8e65546d0 100644--- a/src/features/Conversation/Messages/Task/Actions/index.tsx+++ b/src/features/Conversation/Messages/Task/Actions/index.tsx@@ -14,6 +14,7 @@ const DEFAULT_BAR: MessageActionSlot[] = ['edit', 'copy'];const DEFAULT_MENU: MessageActionSlot[] = ['edit','copy',+ 'comments','collapse','divider','share',@@ -22,7 +23,7 @@ const DEFAULT_MENU: MessageActionSlot[] = ['del',];const ERROR_BAR: MessageActionSlot[] = ['regenerate', 'del'];-const ERROR_MENU: MessageActionSlot[] = ['edit', 'copy', 'divider', 'del'];+const ERROR_MENU: MessageActionSlot[] = ['edit', 'copy', 'comments', 'divider', 'del'];interface AssistantActionsBarProps {actionsConfig?: MessageActionsConfig;diff --git a/src/features/Conversation/Messages/Task/index.tsx b/src/features/Conversation/Messages/Task/index.tsxindex ab8bfc06979..b99de4b902f 100644--- a/src/features/Conversation/Messages/Task/index.tsx+++ b/src/features/Conversation/Messages/Task/index.tsx@@ -8,6 +8,8 @@ import { useTranslation } from 'react-i18next';import { ChatItem } from '@/features/Conversation/ChatItem';import TaskAvatar from '@/features/Conversation/Messages/Tasks/shared/TaskAvatar';+import { useMessageCommentCount } from '@/features/TopicComment/hooks';+import MessageCommentBadge from '@/features/TopicComment/MessageCommentBadge';import { useOpenChatSettings } from '@/hooks/useInterceptingRoutes';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';@@ -28,7 +30,7 @@ interface TaskMessageProps {isLatestItem?: boolean;}-const TaskMessage = memo<TaskMessageProps>(({ id, index, disableEditing }) => {+const TaskMessage = memo<TaskMessageProps>(({ id, disableEditing }) => {const { t } = useTranslation('chat');// Get message and actionsConfig from ConversationStore@@ -58,12 +60,13 @@ const TaskMessage = memo<TaskMessageProps>(({ id, index, disableEditing }) => {} else {openChatSettings();}- }, [isInbox]);+ }, [isInbox, openChatSettings, toggleSystemRole]);const onDoubleClick = useDoubleClickEdit({ disableEditing, error, id, role });// Use taskTitle from metadata if available, otherwise fall back to avatar titleconst title = metadata?.taskTitle || avatar?.title;+ const { count: commentCount, topicId: commentTopicId } = useMessageCommentCount(id);return (<ChatItem@@ -80,6 +83,11 @@ const TaskMessage = memo<TaskMessageProps>(({ id, index, disableEditing }) => {placement={'left'}time={createdAt}titleAddon={<Tag>{t('task.subtask')}</Tag>}+ actionAddon={+ commentCount > 0 && commentTopicId ? (+ <MessageCommentBadge count={commentCount} messageId={id} topicId={commentTopicId} />+ ) : undefined+ }error={errorContent && error && (message === LOADING_FLAT || !message) ? errorContent : undefined}diff --git a/src/features/Conversation/Messages/User/Actions/index.tsx b/src/features/Conversation/Messages/User/Actions/index.tsxindex 5b8fa86278e..a1664008650 100644--- a/src/features/Conversation/Messages/User/Actions/index.tsx+++ b/src/features/Conversation/Messages/User/Actions/index.tsx@@ -18,6 +18,7 @@ const DEFAULT_BAR: MessageActionSlot[] = ['regenerate', 'edit', 'copy'];const DEFAULT_MENU: MessageActionSlot[] = ['edit','copy',+ 'comments','branching','divider','tts',diff --git a/src/features/Conversation/Messages/User/index.tsx b/src/features/Conversation/Messages/User/index.tsxindex 8bf90b98e1a..30b0e0b5ca5 100644--- a/src/features/Conversation/Messages/User/index.tsx+++ b/src/features/Conversation/Messages/User/index.tsx@@ -6,6 +6,8 @@ import { useTranslation } from 'react-i18next';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { ChatItem } from '@/features/Conversation/ChatItem';+import { useMessageCommentCount } from '@/features/TopicComment/hooks';+import MessageCommentBadge from '@/features/TopicComment/MessageCommentBadge';import { useUserAvatar } from '@/hooks/useUserAvatar';import { useSessionStore } from '@/store/session';import { sessionSelectors } from '@/store/session/selectors';@@ -37,6 +39,7 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {const selfAvatar = useUserAvatar();const selfTitle = useUserStore(userProfileSelectors.displayUserName);const activeWorkspaceId = useActiveWorkspaceId();+ const { count: commentCount, topicId: commentTopicId } = useMessageCommentCount(id);// In workspaces every user bubble shows its sender avatar so ownership is// visible even during single-user testing; personal mode keeps the legacy@@ -99,6 +102,11 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {showTitle={showSender}time={createdAt}titleAddon={dmIndicator}+ actionAddon={+ commentCount > 0 && commentTopicId ? (+ <MessageCommentBadge count={commentCount} messageId={id} topicId={commentTopicId} />+ ) : undefined+ }onDoubleClick={onDoubleClick}onMouseEnter={onMouseEnter}>diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/comments.test.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/comments.test.tsnew file mode 100644index 00000000000..43f04857033--- /dev/null+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/comments.test.ts@@ -0,0 +1,84 @@+/**+ * @vitest-environment happy-dom+ */+import type { UIChatMessage } from '@lobechat/types';+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { commentsAction } from './comments';++const mocks = vi.hoisted(() => ({+ commentCount: 0,+ openTopicComments: vi.fn(),+ topicId: 'topic-1' as string | null,+ workspaceId: 'workspace-1' as string | null,+}));++vi.mock('@/features/TopicComment/hooks', () => ({+ useMessageCommentCount: () => ({+ count: mocks.commentCount,+ topicId: mocks.workspaceId ? mocks.topicId : null,+ }),+}));++vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>+ selector({ activeTopicId: mocks.topicId, openTopicComments: mocks.openTopicComments }),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++const build = () =>+ renderHook(() =>+ commentsAction.useBuild({+ data: { content: 'Hello', role: 'assistant' } as UIChatMessage,+ id: 'message-1',+ role: 'assistant',+ }),+ ).result.current;++describe('commentsAction', () => {+ beforeEach(() => {+ mocks.commentCount = 0;+ mocks.openTopicComments.mockReset();+ mocks.topicId = 'topic-1';+ mocks.workspaceId = 'workspace-1';+ });++ it('opens the message-filtered comments portal', () => {+ const action = build();++ act(() => action?.handleClick?.());++ expect(mocks.openTopicComments).toHaveBeenCalledWith('topic-1', 'message-1');+ });++ it('is absent when the message already has comments', () => {+ mocks.commentCount = 1;++ expect(build()).toBeNull();+ });++ it('is absent outside a saved workspace topic', () => {+ mocks.workspaceId = null;+ expect(build()).toBeNull();++ mocks.workspaceId = 'workspace-1';+ mocks.topicId = null;+ expect(build()).toBeNull();+ });++ it.each(['tasks', 'groupTasks'])('is absent for virtual %s aggregate messages', (role) => {+ const action = renderHook(() =>+ commentsAction.useBuild({+ data: { content: '', role } as UIChatMessage,+ id: `${role}-virtual-id`,+ role: 'assistant',+ }),+ ).result.current;++ expect(action).toBeNull();+ });+});diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/comments.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/comments.tsnew file mode 100644index 00000000000..7ceb2d280a3--- /dev/null+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/comments.ts@@ -0,0 +1,31 @@+import { MessageCircle } from 'lucide-react';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useMessageCommentCount } from '@/features/TopicComment/hooks';+import { useChatStore } from '@/store/chat';++import { defineAction } from '../defineAction';++export const commentsAction = defineAction({+ key: 'comments',+ useBuild: (ctx) => {+ const { t } = useTranslation('chat');+ const { count, topicId } = useMessageCommentCount(ctx.id);+ const openTopicComments = useChatStore((s) => s.openTopicComments);+ const hasPersistedMessageId = ctx.data.role !== 'tasks' && ctx.data.role !== 'groupTasks';++ return useMemo(+ () =>+ hasPersistedMessageId && count === 0 && topicId+ ? {+ handleClick: () => openTopicComments(topicId, ctx.id),+ icon: MessageCircle,+ key: 'comments',+ label: t('topicComment.commentOnMessage'),+ }+ : null,+ [count, ctx.id, hasPersistedMessageId, openTopicComments, t, topicId],+ );+ },+});diff --git a/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx b/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsxindex a945f526876..08aa4bf01d7 100644--- a/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx+++ b/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx@@ -10,6 +10,9 @@ import { MessageActionBar } from './index';const permissionMock = vi.hoisted(() => ({canEdit: true,}));+const actionMocks = vi.hoisted(() => ({+ commentsAvailable: true,+}));vi.mock('@lobehub/ui', () => ({ActionIconGroup: ({@@ -42,6 +45,12 @@ vi.mock('@/hooks/usePermission', () => ({vi.mock('./useBuildActions', () => ({useBuildActions: () => ({+ comments: actionMocks.commentsAvailable+ ? {+ key: 'comments',+ label: 'Comments',+ }+ : null,copy: { key: 'copy', label: 'Copy' },del: { key: 'del', label: 'Delete' },edit: { key: 'edit', label: 'Edit' },@@ -72,7 +81,8 @@ describe('MessageActionBar', () => {expect(actionGroup).toHaveStyle({ background: 'transparent', borderRadius: '0' });});- it('limits workspace viewers to copy only', () => {+ it('keeps read-only comments available to workspace viewers', () => {+ actionMocks.commentsAvailable = true;permissionMock.canEdit = false;render(@@ -87,6 +97,48 @@ describe('MessageActionBar', () => {/>,);+ const group = screen.getByTestId('action-group');+ expect(group).toHaveAttribute('data-items', 'copy,comments');+ expect(group).toHaveAttribute('data-menu', '');+ });++ it('promotes the zero-comment entry from the menu to the action bar', () => {+ actionMocks.commentsAvailable = true;+ permissionMock.canEdit = true;++ render(+ <MessageActionBar+ bar={['copy']}+ menu={['comments']}+ ctx={{+ data: { content: 'hello', role: 'assistant' } as UIChatMessage,+ id: 'message-1',+ role: 'assistant',+ }}+ />,+ );++ const group = screen.getByTestId('action-group');+ expect(group).toHaveAttribute('data-items', 'copy,comments');+ expect(group).toHaveAttribute('data-menu', '');+ });++ it('keeps the direct action absent when the message already has comments', () => {+ actionMocks.commentsAvailable = false;+ permissionMock.canEdit = true;++ render(+ <MessageActionBar+ bar={['copy']}+ menu={['comments']}+ ctx={{+ data: { content: 'hello', role: 'assistant' } as UIChatMessage,+ id: 'message-1',+ role: 'assistant',+ }}+ />,+ );+const group = screen.getByTestId('action-group');expect(group).toHaveAttribute('data-items', 'copy');expect(group).toHaveAttribute('data-menu', '');diff --git a/src/features/Conversation/Messages/components/MessageActionBar/index.tsx b/src/features/Conversation/Messages/components/MessageActionBar/index.tsxindex 1b95833e83a..29b54fe99d1 100644--- a/src/features/Conversation/Messages/components/MessageActionBar/index.tsx+++ b/src/features/Conversation/Messages/components/MessageActionBar/index.tsx@@ -10,7 +10,7 @@ import { DIVIDER_KEY, type MessageActionContext, type MessageActionSlot } from 'import { useBuildActions } from './useBuildActions';const DIVIDER: MessageActionItemOrDivider = { type: 'divider' };-const VIEWER_BAR: MessageActionSlot[] = ['copy'];+const VIEWER_BAR: MessageActionSlot[] = ['copy', 'comments'];const stripHandleClick = (item: MessageActionItemOrDivider): ActionIconGroupItemType => {if ('type' in item && item.type === 'divider') return item as unknown as ActionIconGroupItemType;@@ -84,11 +84,22 @@ export const MessageActionBar = memo<MessageActionBarProps>(({ ctx, bar, leadingconst effectiveBar = canEdit ? bar : VIEWER_BAR;const effectiveMenu = canEdit ? menu : undefined;-- const barItems = useMemo(() => resolveSlots(effectiveBar, built), [effectiveBar, built]);+ const [barSlots, menuSlots] = useMemo(() => {+ const shouldPromoteComments =+ Boolean(built.comments) &&+ !effectiveBar.includes('comments') &&+ Boolean(effectiveMenu?.includes('comments'));++ return [+ shouldPromoteComments ? [...effectiveBar, 'comments'] : effectiveBar,+ shouldPromoteComments ? effectiveMenu?.filter((slot) => slot !== 'comments') : effectiveMenu,+ ];+ }, [built.comments, effectiveBar, effectiveMenu]);++ const barItems = useMemo(() => resolveSlots(barSlots, built), [barSlots, built]);const menuItems = useMemo(- () => (effectiveMenu ? resolveSlots(effectiveMenu, built) : undefined),- [effectiveMenu, built],+ () => (menuSlots ? resolveSlots(menuSlots, built) : undefined),+ [menuSlots, built],);const items = useMemo(diff --git a/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts b/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.tsindex 8b397532eed..95f75d33b86 100644--- a/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts+++ b/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts@@ -2,6 +2,7 @@ import { useConversationResourceAccess } from '../../../hooks/useConversationResimport { type MessageActionItem } from '../../../types';import { branchingAction } from './actions/branching';import { collapseAction } from './actions/collapse';+import { commentsAction } from './actions/comments';import { continueGenerationAction } from './actions/continueGeneration';import { copyAction } from './actions/copy';import { delAction } from './actions/del';@@ -35,6 +36,7 @@ export const useBuildActions = (const actions: Record<string, MessageActionItem | null> = {branching: branchingAction.useBuild(ctx),collapse: collapseAction.useBuild(ctx),+ comments: commentsAction.useBuild(ctx),continueGeneration: continueGenerationAction.useBuild(ctx),copy: copyAction.useBuild(ctx),del: delAction.useBuild(ctx),diff --git a/src/features/Portal/Mobile.tsx b/src/features/Portal/Mobile.tsxindex d4e8af89069..2fb54cbee19 100644--- a/src/features/Portal/Mobile.tsx+++ b/src/features/Portal/Mobile.tsx@@ -15,6 +15,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({container: css`background: linear-gradient(${cssVar.colorBgElevated}, ${cssVar.colorBgContainer}) !important;`,+ modal: css`+ & > div {+ height: 95dvh;+ max-height: 95dvh;+ }+ `,}));const MobilePortal = () => {@@ -41,7 +47,7 @@ const MobilePortal = () => {<ImperativeModalallowFullscreendestroyOnHidden- className={cx(isPortalThread && styles.container)}+ className={cx(styles.modal, isPortalThread && styles.container)}footer={null}height={'95%'}open={showMobilePortal}diff --git a/src/features/Portal/TopicComments/AnchorPreview.tsx b/src/features/Portal/TopicComments/AnchorPreview.tsxnew file mode 100644index 00000000000..6716c2d1373--- /dev/null+++ b/src/features/Portal/TopicComments/AnchorPreview.tsx@@ -0,0 +1,70 @@+import type { TopicCommentItem } from '@lobechat/types';+import { Flexbox, Icon, Text } from '@lobehub/ui';+import { MessageSquareText } from 'lucide-react';+import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';+import { displayMessageSelectors } from '@/store/chat/selectors';++import {+ highlightMessageWhenScrollSettles,+ resolveTopicCommentMessageLocation,+} from './messageLocator';+import { styles } from './styles';++const AnchorPreview = memo<{ comment: TopicCommentItem }>(({ comment }) => {+ const { t } = useTranslation('chat');+ const [messageIndex, messageElementId, scrollToIndex] = useChatStore((s) => {+ if (!s.activeAgentId || s.activeTopicId !== comment.topicId)+ return [-1, undefined, s.mainConversationScrollToIndex] as const;++ const location = resolveTopicCommentMessageLocation(+ displayMessageSelectors.mainDisplayChats(s),+ comment.messageId,+ );++ return [location?.index ?? -1, location?.elementId, s.mainConversationScrollToIndex] as const;+ });+ const hasMessage = messageIndex >= 0;++ const locateMessage = useCallback(() => {+ if (!messageElementId || !hasMessage || !scrollToIndex) return;+ requestAnimationFrame(() => {+ scrollToIndex(messageIndex, { align: 'center', smooth: true });+ highlightMessageWhenScrollSettles(messageElementId);+ });+ }, [hasMessage, messageElementId, messageIndex, scrollToIndex]);++ if (!comment.anchorPreview) return null;++ return (+ <Flexbox+ aria-disabled={hasMessage ? undefined : true}+ className={styles.anchor}+ gap={4}+ role={hasMessage ? 'button' : undefined}+ tabIndex={hasMessage ? 0 : undefined}+ onClick={locateMessage}+ onKeyDown={(event) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ locateMessage();+ }}+ >+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon icon={MessageSquareText} size={14} />+ <Text fontSize={12} weight={500}>+ {hasMessage ? t('topicComment.anchor') : t('topicComment.anchorDeleted')}+ </Text>+ </Flexbox>+ <Text ellipsis={{ rows: 2 }} fontSize={12} type={'secondary'}>+ {comment.anchorPreview.excerpt || t('topicComment.anchorEmpty')}+ </Text>+ </Flexbox>+ );+});++AnchorPreview.displayName = 'TopicCommentAnchorPreview';++export default AnchorPreview;diff --git a/src/features/Portal/TopicComments/Body.tsx b/src/features/Portal/TopicComments/Body.tsxnew file mode 100644index 00000000000..80de0b41923--- /dev/null+++ b/src/features/Portal/TopicComments/Body.tsx@@ -0,0 +1,91 @@+import { Center, Empty, Flexbox } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { MessageCircle } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import Loading from '@/components/Loading/BrandTextLoading';+import { useTopicCommentThreads } from '@/features/TopicComment/hooks';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';++import CommentCard from './CommentCard';+import Composer from './Composer';+import { styles } from './styles';++const Body = memo(() => {+ const { t } = useTranslation('chat');+ const view = useChatStore(chatPortalSelectors.topicCommentsView);+ const openThread = useChatStore((s) => s.openTopicCommentThread);+ const {+ error,+ hasMore,+ isInitialError,+ isLoadingInitial,+ isLoadingMore,+ isRetrying,+ items,+ loadMore,+ pendingCommentIds,+ reload,+ } = useTopicCommentThreads(view?.topicId, view?.messageId);++ if (!view) return null;+ if (isInitialError) {+ return (+ <Flexbox className={styles.body}>+ <AsyncError error={error} variant={'page'} onRetry={() => void reload()} />+ </Flexbox>+ );+ }++ return (+ <Flexbox className={styles.body}>+ <Flexbox className={styles.list}>+ {isLoadingInitial ? (+ <Loading debugId="TopicCommentsPortal" />+ ) : items.length === 0 ? (+ <Center className={styles.empty}>+ <Empty description={t('topicComment.empty')} icon={MessageCircle} />+ </Center>+ ) : (+ items.map(({ replyCount, root }) => {+ const pending = pendingCommentIds.has(root.id);+ return (+ <CommentCard+ comment={root}+ key={root.id}+ pending={pending}+ replyCount={replyCount}+ onMutated={() => void reload()}+ onOpenThread={+ pending ? undefined : () => openThread(view.topicId, root.id, root, replyCount)+ }+ />+ );+ })+ )}+ {error ? (+ <AsyncError+ error={error}+ retrying={isRetrying}+ variant={'inline'}+ onRetry={() => void reload()}+ />+ ) : (+ hasMore && (+ <Center paddingBlock={12}>+ <Button loading={isLoadingMore} type={'text'} onClick={() => void loadMore()}>+ {t('topicComment.loadMore')}+ </Button>+ </Center>+ )+ )}+ </Flexbox>+ <Composer messageId={view.messageId} topicId={view.topicId} onCreated={() => void reload()} />+ </Flexbox>+ );+});++export default Body;diff --git a/src/features/Portal/TopicComments/CommentCard.tsx b/src/features/Portal/TopicComments/CommentCard.tsxnew file mode 100644index 00000000000..d22e20257b3--- /dev/null+++ b/src/features/Portal/TopicComments/CommentCard.tsx@@ -0,0 +1,269 @@+import type { TopicCommentItem } from '@lobechat/types';+import { ActionIcon, Avatar, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';+import type { DropdownItem } from '@lobehub/ui/base-ui';+import { Button, confirmModal, DropdownMenu } from '@lobehub/ui/base-ui';+import { App } from 'antd';+import { MessageCircle, MoreHorizontal, Pencil, Trash } from 'lucide-react';+import { memo, useCallback, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import RichTextMessage from '@/features/Conversation/Messages/User/components/RichTextMessage';+import { useTopicCommentMutations } from '@/features/TopicComment/hooks';+import { useActivityTime } from '@/hooks/useActivityTime';++import AnchorPreview from './AnchorPreview';+import { createTopicCommentUpdateInput, hasTopicCommentEditorData } from './commentContent';+import { styles } from './styles';+import TopicCommentEditor, {+ type TopicCommentEditorRef,+ type TopicCommentEditorValue,+} from './TopicCommentEditor';++interface CommentCardProps {+ comment: TopicCommentItem;+ onDeleted?: (mode: 'hard' | 'moderated' | 'soft') => void;+ onMutated?: () => void;+ onOpenThread?: () => void;+ pending?: boolean;+ replyCount?: number;+ replyStyle?: boolean;+ rootReplyCount?: number;+}++const CommentContent = memo<Pick<TopicCommentItem, 'content' | 'editorData'>>(+ ({ content, editorData }) => {+ return hasTopicCommentEditorData(editorData) ? (+ <RichTextMessage editorState={editorData} />+ ) : (+ <Markdown fontSize={14} variant={'chat'}>+ {content}+ </Markdown>+ );+ },+);++CommentContent.displayName = 'TopicCommentContent';++const CommentCard = memo<CommentCardProps>(+ ({+ comment,+ onDeleted,+ onMutated,+ onOpenThread,+ pending,+ replyCount,+ replyStyle,+ rootReplyCount,+ }) => {+ const { t } = useTranslation('chat');+ const { message } = App.useApp();+ const { text: time, title: timeTitle } = useActivityTime(comment.createdAt);+ const { mutatingIds, remove, restore, update } = useTopicCommentMutations();+ const [editing, setEditing] = useState(false);+ const [nextContent, setNextContent] = useState(comment.content);+ const [nextEditorData, setNextEditorData] = useState(comment.editorData);+ const editorRef = useRef<TopicCommentEditorRef>(null);+ const mutating = mutatingIds.has(comment.id);+ const deleted = Boolean(comment.deletedAt);+ const moderated = Boolean(comment.moderatedAt);+ const authorName =+ comment.author.fullName || comment.author.username || t('topicComment.author.deactivated');+ const edited = new Date(comment.updatedAt).getTime() > new Date(comment.createdAt).getTime();++ const handleUpdate = useCallback(async () => {+ const editorValue: TopicCommentEditorValue = editorRef.current?.getValue() ?? {+ content: nextContent,+ editorData: nextEditorData ?? null,+ };+ const input = createTopicCommentUpdateInput(comment.id, editorValue);+ if (!input.content || mutating) return;+ setNextContent(editorValue.content);+ setNextEditorData(editorValue.editorData);+ try {+ setEditing(false);+ await update(input, comment);+ onMutated?.();+ } catch {+ setEditing(true);+ message.error(t('topicComment.updateFailed'));+ }+ }, [comment, message, mutating, nextContent, nextEditorData, onMutated, t, update]);++ const handleDelete = useCallback(() => {+ confirmModal({+ content: t('topicComment.deleteConfirm.content'),+ okButtonProps: { danger: true },+ okText: t('topicComment.delete'),+ onOk: () => {+ void remove(comment, replyCount ? 'soft' : 'hard', { rootReplyCount })+ .then((result) => {+ onDeleted?.(result.mode);+ onMutated?.();+ })+ .catch(() => {+ message.error(t('topicComment.deleteFailed'));+ });+ },+ title: t('topicComment.deleteConfirm.title'),+ });+ }, [comment, message, onDeleted, onMutated, remove, replyCount, rootReplyCount, t]);++ const handleRestore = useCallback(async () => {+ try {+ await restore(comment, { rootReplyCount: replyCount });+ onMutated?.();+ } catch {+ message.error(t('topicComment.restoreFailed'));+ }+ }, [comment, message, onMutated, replyCount, restore, t]);++ const menuItems = useMemo<DropdownItem[]>(() => {+ const items: DropdownItem[] = [];+ if (comment.canEdit) {+ items.push({+ icon: <Icon icon={Pencil} />,+ key: 'edit',+ label: t('topicComment.edit'),+ onClick: () => {+ setNextContent(comment.content);+ setNextEditorData(comment.editorData);+ setEditing(true);+ },+ });+ }+ if (comment.canDelete) {+ items.push({+ danger: true,+ icon: <Icon icon={Trash} />,+ key: 'delete',+ label: t('topicComment.delete'),+ onClick: handleDelete,+ });+ }+ return items;+ }, [comment.canDelete, comment.canEdit, comment.content, comment.editorData, handleDelete, t]);++ return (+ <Flexbox+ className={`${styles.card} ${replyStyle ? styles.reply : ''}`}+ data-topic-comment-id={comment.id}+ gap={8}+ >+ <Flexbox horizontal align={'center'} gap={8}>+ <Avatar avatar={comment.author.avatar || authorName} size={24} />+ <Text fontSize={13} weight={500}>+ {authorName}+ </Text>+ {comment.author.status === 'former' && (+ <Text fontSize={12} type={'secondary'}>+ {t('topicComment.author.former')}+ </Text>+ )}+ {pending ? (+ <Text fontSize={12} type={'secondary'}>+ {t('topicComment.sending')}+ </Text>+ ) : (+ time && (+ <Text fontSize={12} title={timeTitle} type={'secondary'}>+ {time}+ </Text>+ )+ )}+ {edited && !deleted && (+ <Text className={styles.edited} fontSize={12}>+ {t('topicComment.edited')}+ </Text>+ )}+ </Flexbox>++ <AnchorPreview comment={comment} />++ {deleted ? (+ <Text className={styles.deleted}>{t('topicComment.deleted')}</Text>+ ) : moderated ? (+ <Flexbox gap={8}>+ <Text className={styles.deleted}>+ {comment.moderationIsOwn+ ? t('topicComment.removedOwn')+ : comment.canRestore+ ? t('topicComment.removedOwnerView')+ : t('topicComment.removed')}+ </Text>+ {comment.canRestore && comment.content && (+ <div className={styles.moderatedContent}>+ <CommentContent content={comment.content} editorData={comment.editorData} />+ </div>+ )}+ {comment.canRestore && comment.moderationExpiresAt && (+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Text fontSize={12} type={'secondary'}>+ {t('topicComment.restoreDeadline', {+ date: new Date(comment.moderationExpiresAt).toLocaleString(),+ })}+ </Text>+ <Button loading={mutating} size={'small'} onClick={handleRestore}>+ {t('topicComment.restore')}+ </Button>+ </Flexbox>+ )}+ </Flexbox>+ ) : editing ? (+ <Flexbox gap={8}>+ <div className={styles.editEditor}>+ <TopicCommentEditor+ autoFocus+ disabled={mutating}+ initialContent={nextContent}+ initialEditorData={nextEditorData}+ placeholder={t('topicComment.placeholder')}+ ref={editorRef}+ onChange={({ content, editorData }) => {+ setNextContent(content);+ setNextEditorData(editorData);+ }}+ />+ </div>+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button disabled={mutating} size={'small'} onClick={() => setEditing(false)}>+ {t('topicComment.cancel')}+ </Button>+ <Button loading={mutating} size={'small'} type={'primary'} onClick={handleUpdate}>+ {t('topicComment.save')}+ </Button>+ </Flexbox>+ </Flexbox>+ ) : (+ <CommentContent content={comment.content} editorData={comment.editorData} />+ )}++ {onOpenThread && (+ <Flexbox horizontal justify={'flex-end'}>+ <Button+ icon={<Icon icon={MessageCircle} />}+ size={'small'}+ type={'text'}+ onClick={onOpenThread}+ >+ {replyCount+ ? t('topicComment.replies', { count: replyCount })+ : t('topicComment.reply')}+ </Button>+ </Flexbox>+ )}++ {!editing && menuItems.length > 0 && (+ <div className={`${styles.cardActions} topic-comment-actions`}>+ <DropdownMenu items={menuItems}>+ <ActionIcon icon={MoreHorizontal} loading={mutating} size={'small'} />+ </DropdownMenu>+ </div>+ )}+ </Flexbox>+ );+ },+);++CommentCard.displayName = 'TopicCommentCard';++export default CommentCard;diff --git a/src/features/Portal/TopicComments/Composer.tsx b/src/features/Portal/TopicComments/Composer.tsxnew file mode 100644index 00000000000..1e2ed45cbba--- /dev/null+++ b/src/features/Portal/TopicComments/Composer.tsx@@ -0,0 +1,117 @@+import { ChatInput, ChatInputActionBar, SendButton } from '@lobehub/editor/react';+import { Flexbox } from '@lobehub/ui';+import { App } from 'antd';+import { memo, useCallback, useRef } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useConversationResourceAccess } from '@/features/Conversation/hooks/useConversationResourceAccess';+import { useTopicCommentMutations } from '@/features/TopicComment/hooks';+import { useEnterToSend } from '@/hooks/useEnterToSend';+import {+ createTopicCommentDraftKey,+ topicCommentSelectors,+ useTopicCommentStore,+} from '@/store/topicComment';++import { styles } from './styles';+import TopicCommentEditor, { type TopicCommentEditorRef } from './TopicCommentEditor';+import { useComposerSubmit } from './useComposerSubmit';++interface ComposerProps {+ messageId?: string;+ onCreated?: () => void;+ parentCommentId?: string;+ rootReplyCount?: number;+ topicId: string;+}++const Composer = memo<ComposerProps>(+ ({ messageId, onCreated, parentCommentId, rootReplyCount, topicId }) => {+ const { t } = useTranslation('chat');+ const { message } = App.useApp();+ const workspaceId = useActiveWorkspaceId();+ const { canUseResource } = useConversationResourceAccess();+ const key = workspaceId+ ? createTopicCommentDraftKey({ messageId, parentCommentId, topicId, workspaceId })+ : '';+ const draft = useTopicCommentStore(topicCommentSelectors.draft(key));+ const [setDraft, setDraftContent, clearDraft] = useTopicCommentStore((s) => [+ s.setDraft,+ s.setDraftContent,+ s.clearDraft,+ ]);+ const { create, creating } = useTopicCommentMutations();+ const shouldSendOnEnter = useEnterToSend();+ const editorRef = useRef<TopicCommentEditorRef>(null);+ const content = draft?.content ?? '';+ const onError = useCallback(() => {+ message.error(t('topicComment.createFailed'));+ }, [message, t]);+ const { onPressEnter, submit, submitting } = useComposerSubmit({+ clearDraft,+ content,+ create,+ creating,+ draft,+ editorRef,+ key,+ messageId,+ onCreated,+ onError,+ parentCommentId,+ rootReplyCount,+ setDraft,+ shouldSendOnEnter,+ topicId,+ });++ if (!workspaceId || !canUseResource) return null;++ return (+ <Flexbox className={styles.composer}>+ <ChatInput+ resize={false}+ styles={{ body: { padding: 8 } }}+ footer={+ <ChatInputActionBar+ justify={'flex-end'}+ right={+ <SendButton+ disabled={creating || submitting || !content.trim()}+ loading={creating || submitting}+ shape={'round'}+ title={t('input.send')}+ type={'text'}+ onClick={submit}+ />+ }+ />+ }+ >+ <TopicCommentEditor+ disabled={creating || submitting}+ initialContent={content}+ initialEditorData={draft?.editorData}+ ref={editorRef}+ placeholder={+ parentCommentId+ ? t('topicComment.replyPlaceholder')+ : messageId+ ? t('topicComment.messagePlaceholder')+ : t('topicComment.placeholder')+ }+ onPressEnter={onPressEnter}+ onChange={({ content: nextContent, editorData }) =>+ setDraftContent(key, nextContent, editorData)+ }+ />+ </ChatInput>+ </Flexbox>+ );+ },+);++Composer.displayName = 'TopicCommentComposer';++export default Composer;diff --git a/src/features/Portal/TopicComments/Sidebar.tsx b/src/features/Portal/TopicComments/Sidebar.tsxnew file mode 100644index 00000000000..8faea683ddc--- /dev/null+++ b/src/features/Portal/TopicComments/Sidebar.tsx@@ -0,0 +1,65 @@+import { ActionIcon, Flexbox, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ArrowLeft } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';+import { PortalViewType } from '@/store/chat/slices/portal/initialState';++import Body from './Body';+import ThreadBody from './ThreadBody';++const styles = createStaticStyles(({ css }) => ({+ container: css`+ overflow: hidden;+ flex: 1;+ min-height: 0;+ `,+ subheader: css`+ flex-shrink: 0;+ height: 40px;+ padding-inline: 8px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+}));++const TopicCommentsSidebar = memo(() => {+ const { t } = useTranslation('chat');+ const view = useChatStore(chatPortalSelectors.currentView);+ const [goBack, openTopicComments] = useChatStore((s) => [s.goBack, s.openTopicComments]);++ if (view?.type === PortalViewType.TopicComments && !view.messageId) {+ return <Body />;+ }++ if (+ view?.type !== PortalViewType.TopicComments &&+ view?.type !== PortalViewType.TopicCommentThread+ )+ return null;++ const isThread = view.type === PortalViewType.TopicCommentThread;++ return (+ <Flexbox className={styles.container}>+ <Flexbox horizontal align={'center'} className={styles.subheader} gap={4}>+ <ActionIcon+ icon={ArrowLeft}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ onClick={isThread ? goBack : () => openTopicComments(view.topicId)}+ />+ <Text fontSize={13} weight={500}>+ {t(isThread ? 'topicComment.thread' : 'topicComment.messageComments')}+ </Text>+ </Flexbox>+ {isThread ? <ThreadBody /> : <Body />}+ </Flexbox>+ );+});++TopicCommentsSidebar.displayName = 'TopicCommentsSidebar';++export default TopicCommentsSidebar;diff --git a/src/features/Portal/TopicComments/ThreadBody.tsx b/src/features/Portal/TopicComments/ThreadBody.tsxnew file mode 100644index 00000000000..a790f39b780--- /dev/null+++ b/src/features/Portal/TopicComments/ThreadBody.tsx@@ -0,0 +1,144 @@+import { Center, Empty, Flexbox, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { MessageCircle } from 'lucide-react';+import { memo, useEffect, useMemo, useRef } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import Loading from '@/components/Loading/BrandTextLoading';+import {+ useTopicCommentDetail,+ useTopicCommentReplies,+ useTopicCommentReplyCount,+} from '@/features/TopicComment/hooks';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';++import CommentCard from './CommentCard';+import Composer from './Composer';+import { styles } from './styles';+import { resolveTopicCommentThreadState } from './threadState';++const ThreadBody = memo(() => {+ const { t } = useTranslation('chat');+ const view = useChatStore(chatPortalSelectors.topicCommentThreadView);+ const popPortalView = useChatStore((s) => s.popPortalView);+ const root = useTopicCommentDetail(view?.rootCommentId, view?.initialRoot);+ const focusedReply = useTopicCommentDetail(+ view?.focusCommentId && view.focusCommentId !== view.rootCommentId+ ? view.focusCommentId+ : undefined,+ );+ const replies = useTopicCommentReplies(view?.rootCommentId, view?.initialReplyCount);+ const replyCount = useTopicCommentReplyCount(+ view?.rootCommentId,+ view?.initialReplyCount ?? replies.items.length,+ );+ const listRef = useRef<HTMLDivElement>(null);+ const visibleReplies = useMemo(() => {+ const focused = focusedReply.data;+ if (+ !focused ||+ focused.parentCommentId !== view?.rootCommentId ||+ replies.items.some(({ id }) => id === focused.id)+ )+ return replies.items;++ return [focused, ...replies.items];+ }, [focusedReply.data, replies.items, view?.rootCommentId]);++ useEffect(() => {+ if (!view?.focusCommentId) return;+ const target = Array.from(+ listRef.current?.querySelectorAll<HTMLElement>('[data-topic-comment-id]') ?? [],+ ).find((element) => element.dataset.topicCommentId === view.focusCommentId);+ if (!target) return;++ requestAnimationFrame(() => target.scrollIntoView({ behavior: 'smooth', block: 'center' }));+ }, [focusedReply.data, replies.items, root.data, view?.focusCommentId]);++ if (!view) return null;+ const state = resolveTopicCommentThreadState({+ error: root.error,+ hasData: Boolean(root.data),+ isDeleting: root.isDeleting,+ isLoading: root.isLoading,+ });+ if (state === 'hidden') return null;+ if (state === 'notFound') {+ return (+ <Center className={styles.empty}>+ <Empty description={t('topicComment.notFound')} icon={MessageCircle} />+ </Center>+ );+ }+ if (state === 'error') {+ return (+ <Flexbox className={styles.body}>+ <AsyncError error={root.error} variant={'page'} onRetry={() => void root.mutate()} />+ </Flexbox>+ );+ }+ if (state === 'loading') {+ return <Loading debugId="TopicCommentThreadPortal" />;+ }+ if (!root.data) return null;++ return (+ <Flexbox className={styles.body}>+ <Flexbox className={styles.list} ref={listRef}>+ <CommentCard+ comment={root.data}+ replyCount={replyCount}+ onDeleted={(mode) => {+ if (mode === 'hard') popPortalView();+ }}+ onMutated={() => {+ void root.mutate();+ }}+ />+ <Text fontSize={12} style={{ marginTop: 16 }} type={'secondary'} weight={500}>+ {t('topicComment.repliesTitle')}+ </Text>+ {visibleReplies.map((reply) => (+ <CommentCard+ replyStyle+ comment={reply}+ key={reply.id}+ pending={replies.pendingCommentIds.has(reply.id)}+ rootReplyCount={replyCount}+ onMutated={() => void replies.reload()}+ />+ ))}+ {replies.error ? (+ <AsyncError+ error={replies.error}+ retrying={replies.isRetrying}+ variant={'inline'}+ onRetry={() => void replies.reload()}+ />+ ) : (+ replies.hasMore && (+ <Center paddingBlock={12}>+ <Button+ loading={replies.isLoadingMore}+ type={'text'}+ onClick={() => void replies.loadMore()}+ >+ {t('topicComment.loadMore')}+ </Button>+ </Center>+ )+ )}+ </Flexbox>+ <Composer+ parentCommentId={root.data.id}+ rootReplyCount={replyCount}+ topicId={view.topicId}+ onCreated={() => void replies.reload()}+ />+ </Flexbox>+ );+});++export default ThreadBody;diff --git a/src/features/Portal/TopicComments/Title.tsx b/src/features/Portal/TopicComments/Title.tsxnew file mode 100644index 00000000000..25d5d9ee4c7--- /dev/null+++ b/src/features/Portal/TopicComments/Title.tsx@@ -0,0 +1,26 @@+import { Flexbox, Icon, Text } from '@lobehub/ui';+import { MessageCircle } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';++export const TopicCommentsTitle = memo(() => {+ const { t } = useTranslation('chat');+ const view = useChatStore(chatPortalSelectors.topicCommentsView);++ return (+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon icon={MessageCircle} size={18} />+ <Text weight={500}>+ {view?.messageId ? t('topicComment.messageComments') : t('topicComment.title')}+ </Text>+ </Flexbox>+ );+});++export const TopicCommentThreadTitle = memo(() => {+ const { t } = useTranslation('chat');+ return <Text weight={500}>{t('topicComment.thread')}</Text>;+});diff --git a/src/features/Portal/TopicComments/TopicCommentEditor.tsx b/src/features/Portal/TopicComments/TopicCommentEditor.tsxnew file mode 100644index 00000000000..3900638112c--- /dev/null+++ b/src/features/Portal/TopicComments/TopicCommentEditor.tsx@@ -0,0 +1,121 @@+import type { TopicCommentJson } from '@lobechat/types';+import type { IEditor, ISlashMenuOption } from '@lobehub/editor';+import { INSERT_MENTION_COMMAND } from '@lobehub/editor';+import { Editor, useEditor } from '@lobehub/editor/react';+import { Avatar } from '@lobehub/ui';+import type { Ref } from 'react';+import { memo, useCallback, useImperativeHandle, useMemo } from 'react';++import { useWorkspaceMembers } from '@/business/client/hooks/useWorkspaceMembers';++import {+ createTopicCommentMentionItems,+ createTopicCommentMentionPayload,+ type MentionableWorkspaceMember,+ readTopicCommentEditorValue,+ resolveTopicCommentEditorContent,+ type TopicCommentEditorValue,+ writeTopicCommentMentionMarkdown,+} from './editorUtils';++export type { TopicCommentEditorValue } from './editorUtils';++export interface TopicCommentEditorRef {+ clean: () => void;+ focus: () => void;+ getValue: () => TopicCommentEditorValue;+ setValue: (value: TopicCommentEditorValue) => void;+}++interface TopicCommentEditorProps {+ autoFocus?: boolean;+ disabled?: boolean;+ initialContent: string;+ initialEditorData?: TopicCommentJson | null;+ onChange?: (value: TopicCommentEditorValue) => void;+ onPressEnter?: (event: KeyboardEvent) => boolean | void;+ placeholder: string;+}++const TopicCommentEditor = memo(+ ({+ ref,+ autoFocus,+ disabled,+ initialContent,+ initialEditorData,+ onChange,+ onPressEnter,+ placeholder,+ }: TopicCommentEditorProps & { ref?: Ref<TopicCommentEditorRef> }) => {+ const editor = useEditor();+ const workspaceMembers = useWorkspaceMembers() as MentionableWorkspaceMember[];++ const mentionItems = useMemo<ISlashMenuOption[]>(+ () =>+ createTopicCommentMentionItems(workspaceMembers).map(({ avatar, ...item }) => ({+ ...item,+ icon: <Avatar avatar={avatar} size={24} />,+ })),+ [workspaceMembers],+ );++ const handleMentionSelect = useCallback((currentEditor: IEditor, option: ISlashMenuOption) => {+ currentEditor.dispatchCommand(+ INSERT_MENTION_COMMAND,+ createTopicCommentMentionPayload(option),+ );+ }, []);++ const setValue = useCallback(+ (value: TopicCommentEditorValue) => {+ if (value.editorData) editor.setDocument('json', value.editorData);+ else editor.setDocument('markdown', value.content);+ },+ [editor],+ );++ useImperativeHandle(+ ref,+ () => ({+ clean: () => editor.cleanDocument(),+ focus: () => editor.focus(),+ getValue: () => readTopicCommentEditorValue(editor),+ setValue,+ }),+ [editor, setValue],+ );++ const { content, type } = resolveTopicCommentEditorContent(initialContent, initialEditorData);++ return (+ <Editor+ pasteAsPlainText+ autoFocus={autoFocus}+ content={content}+ debounceWait={0}+ editable={!disabled}+ editor={editor}+ enablePasteMarkdown={false}+ markdownOption={false}+ placeholder={placeholder}+ style={{ maxHeight: 184, minHeight: 44, overflowY: 'auto', padding: 0 }}+ type={type}+ variant={'chat'}+ mentionOption={{+ fuseOptions: { keys: ['label', 'metadata.description'], threshold: 0.35 },+ items: mentionItems,+ markdownWriter: writeTopicCommentMentionMarkdown,+ maxLength: 50,+ onSelect: handleMentionSelect,+ }}+ onPressEnter={({ event }) => onPressEnter?.(event)}+ onTextChange={(currentEditor) => onChange?.(readTopicCommentEditorValue(currentEditor))}+ />+ );+ },+);++TopicCommentEditor.displayName = 'TopicCommentEditor';++export default TopicCommentEditor;diff --git a/src/features/Portal/TopicComments/commentContent.test.ts b/src/features/Portal/TopicComments/commentContent.test.tsnew file mode 100644index 00000000000..e143ef0bea9--- /dev/null+++ b/src/features/Portal/TopicComments/commentContent.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';++import { createTopicCommentUpdateInput, hasTopicCommentEditorData } from './commentContent';++describe('hasTopicCommentEditorData', () => {+ it('recognizes persisted rich-text editor data', () => {+ expect(hasTopicCommentEditorData({ root: { children: [] } })).toBe(true);+ expect(hasTopicCommentEditorData({})).toBe(false);+ expect(hasTopicCommentEditorData(null)).toBe(false);+ expect(hasTopicCommentEditorData([])).toBe(false);+ });+});++describe('createTopicCommentUpdateInput', () => {+ it('preserves member mention data and trims the submitted markdown', () => {+ const editorData = {+ root: {+ children: [+ {+ label: 'Member',+ metadata: { id: 'member-1', type: 'member' },+ type: 'mention',+ },+ ],+ },+ };++ expect(+ createTopicCommentUpdateInput('comment-1', {+ content: ' Hello <mention name="Member" id="member-1" /> ',+ editorData,+ }),+ ).toEqual({+ content: 'Hello <mention name="Member" id="member-1" />',+ editorData,+ id: 'comment-1',+ });+ });+});diff --git a/src/features/Portal/TopicComments/commentContent.ts b/src/features/Portal/TopicComments/commentContent.tsnew file mode 100644index 00000000000..cd7acbcde63--- /dev/null+++ b/src/features/Portal/TopicComments/commentContent.ts@@ -0,0 +1,18 @@+import type { TopicCommentJson, UpdateTopicCommentInput } from '@lobechat/types';++export const hasTopicCommentEditorData = (editorData: TopicCommentJson | null) =>+ Boolean(+ editorData &&+ typeof editorData === 'object' &&+ !Array.isArray(editorData) &&+ Object.keys(editorData).length > 0,+ );++export const createTopicCommentUpdateInput = (+ id: string,+ value: { content: string; editorData: TopicCommentJson },+): UpdateTopicCommentInput => ({+ content: value.content.trim(),+ editorData: value.editorData,+ id,+});diff --git a/src/features/Portal/TopicComments/editorUtils.test.ts b/src/features/Portal/TopicComments/editorUtils.test.tsnew file mode 100644index 00000000000..7d734ec5968--- /dev/null+++ b/src/features/Portal/TopicComments/editorUtils.test.ts@@ -0,0 +1,88 @@+import type { IEditor } from '@lobehub/editor';+import { describe, expect, it, vi } from 'vitest';++import {+ createTopicCommentMentionItems,+ createTopicCommentMentionPayload,+ readTopicCommentEditorValue,+ resolveTopicCommentEditorContent,+ writeTopicCommentMentionMarkdown,+} from './editorUtils';++describe('topic comment editor utilities', () => {+ it('builds deduplicated mention options from active workspace members', () => {+ const items = createTopicCommentMentionItems([+ {+ user: {+ avatar: 'avatar.png',+ email: '[email protected]',+ fullName: 'Alice',+ username: 'alice',+ },+ userId: 'user-alice',+ },+ {+ user: { avatar: null, email: '[email protected]', fullName: null, username: 'bob' },+ userId: 'user-bob',+ },+ { userId: 'user-alice' },+ ]);++ expect(items).toHaveLength(2);+ expect(items[0]).toEqual({+ avatar: 'avatar.png',+ key: 'member-user-alice',+ label: 'Alice',+ metadata: {+ description: '[email protected]',+ id: 'user-alice',+ timestamp: 0,+ type: 'member',+ },+ });+ });++ it('serializes mention options with the shared editor format', () => {+ const option = {+ key: 'member-user-alice',+ label: 'Alice',+ metadata: { id: 'user-alice', type: 'member' },+ };++ expect(createTopicCommentMentionPayload(option)).toEqual({+ label: 'Alice',+ metadata: option.metadata,+ });+ expect(writeTopicCommentMentionMarkdown(option)).toBe(+ '<mention name="Alice" id="user-alice" />',+ );+ });++ it('reads markdown and JSON from the editor for create and edit flows', () => {+ const editorData = { root: { children: [] } };+ const editor = {+ getDocument: vi.fn((type: 'json' | 'markdown') =>+ type === 'json' ? editorData : 'Draft comment',+ ),+ } as unknown as IEditor;++ expect(readTopicCommentEditorValue(editor)).toEqual({+ content: 'Draft comment',+ editorData,+ });+ });++ it('selects the correct editor data source for empty, markdown, and rich-text content', () => {+ const editorData = { root: { children: [] } };++ expect(resolveTopicCommentEditorContent('', null)).toEqual({ content: '', type: 'text' });+ expect(resolveTopicCommentEditorContent('Draft', null)).toEqual({+ content: 'Draft',+ type: 'markdown',+ });+ expect(resolveTopicCommentEditorContent('ignored', editorData)).toEqual({+ content: editorData,+ type: 'json',+ });+ });+});diff --git a/src/features/Portal/TopicComments/editorUtils.ts b/src/features/Portal/TopicComments/editorUtils.tsnew file mode 100644index 00000000000..510f37f2b8e--- /dev/null+++ b/src/features/Portal/TopicComments/editorUtils.ts@@ -0,0 +1,71 @@+import type { TopicCommentJson } from '@lobechat/types';+import type { IEditor, ISlashMenuOption } from '@lobehub/editor';++export interface MentionableWorkspaceMember {+ user?: {+ avatar?: string | null;+ email?: string | null;+ fullName?: string | null;+ username?: string | null;+ } | null;+ userId: string;+}++export interface TopicCommentEditorValue {+ content: string;+ editorData: TopicCommentJson;+}++export const createTopicCommentMentionItems = (members: MentionableWorkspaceMember[]) => {+ const seen = new Set<string>();++ return members.flatMap((member) => {+ if (!member.userId || seen.has(member.userId)) return [];+ seen.add(member.userId);++ const profile = member.user;+ const label = profile?.fullName || profile?.username || profile?.email || member.userId;+ const description = profile?.email && profile.email !== label ? profile.email : undefined;++ return [+ {+ avatar: profile?.avatar || label,+ key: `member-${member.userId}`,+ label,+ metadata: {+ description,+ id: member.userId,+ timestamp: 0,+ type: 'member',+ },+ },+ ];+ });+};++export const writeTopicCommentMentionMarkdown = (mention: {+ label?: string;+ metadata?: Record<string, unknown>;+}) => `<mention name="${mention.label ?? ''}" id="${String(mention.metadata?.id ?? '')}" />`;++export const createTopicCommentMentionPayload = (option: ISlashMenuOption) => ({+ label: String(option.label),+ metadata: option.metadata,+});++export const readTopicCommentEditorValue = (editor: IEditor): TopicCommentEditorValue => ({+ content: String(editor.getDocument('markdown') ?? ''),+ editorData: (editor.getDocument('json') ?? null) as unknown as TopicCommentJson,+});++export const resolveTopicCommentEditorContent = (+ initialContent: string,+ initialEditorData?: TopicCommentJson | null,+) => ({+ content: initialEditorData ?? initialContent,+ type: initialEditorData+ ? ('json' as const)+ : initialContent+ ? ('markdown' as const)+ : ('text' as const),+});diff --git a/src/features/Portal/TopicComments/index.ts b/src/features/Portal/TopicComments/index.tsnew file mode 100644index 00000000000..45c67337b7e--- /dev/null+++ b/src/features/Portal/TopicComments/index.ts@@ -0,0 +1,14 @@+import type { PortalImpl } from '../type';+import Body from './Body';+import ThreadBody from './ThreadBody';+import { TopicCommentsTitle, TopicCommentThreadTitle } from './Title';++export const TopicComments: PortalImpl = {+ Body,+ Title: TopicCommentsTitle,+};++export const TopicCommentThread: PortalImpl = {+ Body: ThreadBody,+ Title: TopicCommentThreadTitle,+};diff --git a/src/features/Portal/TopicComments/messageLocator.test.ts b/src/features/Portal/TopicComments/messageLocator.test.tsnew file mode 100644index 00000000000..74ce8591f3a--- /dev/null+++ b/src/features/Portal/TopicComments/messageLocator.test.ts@@ -0,0 +1,112 @@+/**+ * @vitest-environment happy-dom+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ highlightMessageWhenScrollSettles,+ resolveTopicCommentMessageLocation,+} from './messageLocator';++describe('resolveTopicCommentMessageLocation', () => {+ it('locates a main-conversation message at its rendered index', () => {+ expect(+ resolveTopicCommentMessageLocation([{ id: 'message-1' }, { id: 'message-2' }], 'message-2'),+ ).toEqual({ elementId: 'message-2', index: 1 });+ });++ it('locates a message rendered in the active thread', () => {+ expect(+ resolveTopicCommentMessageLocation(+ [{ id: 'message-1' }, { id: 'thread-message', threadId: 'thread-1' }],+ 'thread-message',+ ),+ ).toEqual({ elementId: 'thread-message', index: 1 });+ });++ it('locates a persisted task inside its virtual aggregate row', () => {+ expect(+ resolveTopicCommentMessageLocation(+ [{ id: 'virtual-tasks', tasks: [{ id: 'message-2' }] }],+ 'message-2',+ ),+ ).toEqual({ elementId: 'virtual-tasks', index: 0 });+ });+});++describe('highlightMessageWhenScrollSettles', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ afterEach(() => {+ document.body.replaceChildren();+ vi.unstubAllGlobals();+ });++ it('starts highlighting only after the target message stops moving', () => {+ const frames: FrameRequestCallback[] = [];+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ frames.push(callback);+ return frames.length;+ });+ const runNextFrame = (timestamp: number) => {+ const frame = frames.shift();+ expect(frame).toBeDefined();+ frame!(timestamp);+ };+ const target = document.createElement('div');+ target.setAttribute('data-message-id', 'message-2');+ let targetTop = 300;+ vi.spyOn(target, 'getBoundingClientRect').mockImplementation(+ () => new DOMRect(0, targetTop, 100, 40),+ );+ document.body.appendChild(target);++ highlightMessageWhenScrollSettles('message-2');+ runNextFrame(0);+ expect(target).not.toHaveAttribute('data-message-locate-highlight');++ for (const [timestamp, top] of [+ [16, 300],+ [32, 240],+ [48, 180],+ [64, 120],+ ] as const) {+ targetTop = top;+ runNextFrame(timestamp);+ expect(target).not.toHaveAttribute('data-message-locate-highlight');+ }++ for (let timestamp = 80; timestamp <= 224; timestamp += 16) {+ runNextFrame(timestamp);+ expect(target).not.toHaveAttribute('data-message-locate-highlight');+ }++ runNextFrame(240);+ expect(target).toHaveAttribute('data-message-locate-highlight');+ });++ it('does not highlight when the target never stops moving', () => {+ const frames: FrameRequestCallback[] = [];+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ frames.push(callback);+ return frames.length;+ });+ const target = document.createElement('div');+ target.setAttribute('data-message-id', 'message-2');+ let targetTop = 300;+ vi.spyOn(target, 'getBoundingClientRect').mockImplementation(+ () => new DOMRect(0, targetTop--, 100, 40),+ );+ document.body.appendChild(target);++ highlightMessageWhenScrollSettles('message-2');+ for (let frame = 0; frame < 260 && frames.length > 0; frame += 1) {+ frames.shift()!(frame * 16);+ }++ expect(frames).toHaveLength(0);+ expect(target).not.toHaveAttribute('data-message-locate-highlight');+ });+});diff --git a/src/features/Portal/TopicComments/messageLocator.ts b/src/features/Portal/TopicComments/messageLocator.tsnew file mode 100644index 00000000000..9ce07e6b136--- /dev/null+++ b/src/features/Portal/TopicComments/messageLocator.ts@@ -0,0 +1,82 @@+interface LocatableMessage {+ id: string;+ tasks?: Array<{ id: string }>;+ threadId?: string | null;+}++const MESSAGE_HIGHLIGHT_ATTRIBUTE = 'data-message-locate-highlight';+const MESSAGE_HIGHLIGHT_DURATION_MS = 1400;+const MESSAGE_HIGHLIGHT_MAX_FRAMES = 240;+const MESSAGE_HIGHLIGHT_POSITION_EPSILON = 0.5;+const MESSAGE_HIGHLIGHT_SETTLE_MS = 150;+let messageHighlightSequence = 0;++export const resolveTopicCommentMessageLocation = (+ messages: LocatableMessage[],+ messageId: string | null,+) => {+ if (!messageId) return;++ const index = messages.findIndex(+ ({ id, tasks }) => id === messageId || tasks?.some((task) => task.id === messageId),+ );++ if (index < 0) return;+ return { elementId: messages[index].id, index };+};++export const highlightMessageWhenScrollSettles = (messageId: string) => {+ const sequence = ++messageHighlightSequence;+ let remainingFrames = MESSAGE_HIGHLIGHT_MAX_FRAMES;+ let lastMessageElement: HTMLElement | undefined;+ let lastTop: number | undefined;+ let stableSince: number | undefined;++ document+ .querySelectorAll<HTMLElement>(`[${MESSAGE_HIGHLIGHT_ATTRIBUTE}]`)+ .forEach((element) => element.removeAttribute(MESSAGE_HIGHLIGHT_ATTRIBUTE));++ const waitForScrollEnd = (timestamp: number) => {+ if (sequence !== messageHighlightSequence) return;++ const messageElement = Array.from(+ document.querySelectorAll<HTMLElement>('[data-message-id]'),+ ).find((element) => element.dataset.messageId === messageId);++ if (!messageElement) {+ if (remainingFrames-- > 0) requestAnimationFrame(waitForScrollEnd);+ return;+ }++ const top = messageElement.getBoundingClientRect().top;+ if (messageElement !== lastMessageElement || lastTop === undefined) {+ lastMessageElement = messageElement;+ stableSince = undefined;+ } else if (Math.abs(top - lastTop) <= MESSAGE_HIGHLIGHT_POSITION_EPSILON) {+ stableSince ??= timestamp;+ } else {+ stableSince = undefined;+ }+ lastTop = top;++ const hasSettled =+ stableSince !== undefined && timestamp - stableSince >= MESSAGE_HIGHLIGHT_SETTLE_MS;+ if (!hasSettled) {+ if (remainingFrames-- > 0) requestAnimationFrame(waitForScrollEnd);+ return;+ }++ const sequenceValue = String(sequence);+ messageElement.removeAttribute(MESSAGE_HIGHLIGHT_ATTRIBUTE);+ void messageElement.offsetWidth;+ messageElement.setAttribute(MESSAGE_HIGHLIGHT_ATTRIBUTE, sequenceValue);++ window.setTimeout(() => {+ if (messageElement.getAttribute(MESSAGE_HIGHLIGHT_ATTRIBUTE) === sequenceValue) {+ messageElement.removeAttribute(MESSAGE_HIGHLIGHT_ATTRIBUTE);+ }+ }, MESSAGE_HIGHLIGHT_DURATION_MS);+ };++ requestAnimationFrame(waitForScrollEnd);+};diff --git a/src/features/Portal/TopicComments/styles.ts b/src/features/Portal/TopicComments/styles.tsnew file mode 100644index 00000000000..81952da1662--- /dev/null+++ b/src/features/Portal/TopicComments/styles.ts@@ -0,0 +1,101 @@+import { createStaticStyles, cssVar } from 'antd-style';++export const styles = createStaticStyles(({ css }) => ({+ anchor: css`+ cursor: pointer;++ padding-block: 8px;+ padding-inline: 10px;+ border-inline-start: 2px solid ${cssVar.colorBorder};+ border-radius: 0 ${cssVar.borderRadius} ${cssVar.borderRadius} 0;++ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillQuaternary};++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillTertiary};+ }++ &[aria-disabled='true'] {+ cursor: default;++ &:hover {+ color: ${cssVar.colorTextSecondary};+ background: ${cssVar.colorFillQuaternary};+ }+ }+ `,+ body: css`+ overflow: hidden;+ flex: 1;+ min-height: 0;+ `,+ card: css`+ position: relative;+ padding-block: 14px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ &:hover .topic-comment-actions {+ opacity: 1;+ }+ `,+ cardActions: css`+ position: absolute;+ inset-block-start: 8px;+ inset-inline-end: 0;++ opacity: 1;++ transition: opacity ${cssVar.motionDurationFast};++ @media (hover: hover) {+ opacity: 0;+ }+ `,+ composer: css`+ flex-shrink: 0;+ margin-block: 12px 16px;+ margin-inline: 16px;+ `,+ deleted: css`+ font-style: italic;+ color: ${cssVar.colorTextTertiary};+ `,+ editEditor: css`+ padding-block: 8px;+ padding-inline: 10px;+ border: 1px solid ${cssVar.colorBorder};+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorBgContainer};++ &:focus-within {+ border-color: ${cssVar.colorPrimary};+ }+ `,+ edited: css`+ color: ${cssVar.colorTextTertiary};+ `,+ empty: css`+ flex: 1;+ min-height: 240px;+ `,+ list: css`+ overflow-y: auto;+ overscroll-behavior: contain;+ flex: 1;++ min-height: 0;+ padding-inline: 16px;+ `,+ moderatedContent: css`+ opacity: 0.62;+ `,+ reply: css`+ margin-inline-start: 20px;+ padding-inline-start: 12px;+ border-inline-start: 1px solid ${cssVar.colorBorderSecondary};+ `,+}));diff --git a/src/features/Portal/TopicComments/threadState.test.ts b/src/features/Portal/TopicComments/threadState.test.tsnew file mode 100644index 00000000000..4e2234b8370--- /dev/null+++ b/src/features/Portal/TopicComments/threadState.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { resolveTopicCommentThreadState } from './threadState';++describe('resolveTopicCommentThreadState', () => {+ it('treats a garbage-collected thread root as not found', () => {+ expect(+ resolveTopicCommentThreadState({+ error: { data: { code: 'NOT_FOUND' } },+ hasData: false,+ isDeleting: false,+ isLoading: false,+ }),+ ).toBe('notFound');+ });++ it('keeps a snapshotted root ready while it revalidates in the background', () => {+ expect(+ resolveTopicCommentThreadState({+ hasData: true,+ isDeleting: false,+ isLoading: true,+ }),+ ).toBe('ready');+ });++ it.each([+ [{ error: new Error('network'), hasData: false, isDeleting: false, isLoading: false }, 'error'],+ [{ hasData: false, isDeleting: false, isLoading: true }, 'loading'],+ [{ hasData: false, isDeleting: true, isLoading: false }, 'hidden'],+ [{ hasData: false, isDeleting: false, isLoading: false }, 'notFound'],+ ] as const)('resolves %o to %s', (input, expected) => {+ expect(resolveTopicCommentThreadState(input)).toBe(expected);+ });+});diff --git a/src/features/Portal/TopicComments/threadState.ts b/src/features/Portal/TopicComments/threadState.tsnew file mode 100644index 00000000000..5816e226e92--- /dev/null+++ b/src/features/Portal/TopicComments/threadState.ts@@ -0,0 +1,21 @@+import { isTrpcErrorCode } from '@/utils/trpcError';++export type TopicCommentThreadState = 'error' | 'hidden' | 'loading' | 'notFound' | 'ready';++export const resolveTopicCommentThreadState = ({+ error,+ hasData,+ isDeleting,+ isLoading,+}: {+ error?: unknown;+ hasData: boolean;+ isDeleting: boolean;+ isLoading: boolean;+}): TopicCommentThreadState => {+ if (isDeleting && !hasData) return 'hidden';+ if (isTrpcErrorCode(error, 'NOT_FOUND')) return 'notFound';+ if (error && !hasData) return 'error';+ if (isLoading && !hasData) return 'loading';+ return hasData ? 'ready' : 'notFound';+};diff --git a/src/features/Portal/TopicComments/useComposerSubmit.test.ts b/src/features/Portal/TopicComments/useComposerSubmit.test.tsnew file mode 100644index 00000000000..f1b5c8c4334--- /dev/null+++ b/src/features/Portal/TopicComments/useComposerSubmit.test.ts@@ -0,0 +1,178 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook, waitFor } from '@testing-library/react';+import type { RefObject } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { TopicCommentEditorRef } from './TopicCommentEditor';+import { useComposerSubmit } from './useComposerSubmit';++const mocks = vi.hoisted(() => ({+ clean: vi.fn(),+ clearDraft: vi.fn(),+ create: vi.fn(),+ focus: vi.fn(),+ getValue: vi.fn(),+ onCreated: vi.fn(),+ onError: vi.fn(),+ setDraft: vi.fn(),+ setValue: vi.fn(),+ shouldSendOnEnter: vi.fn(),+}));++const editorRef = {+ current: {+ clean: mocks.clean,+ focus: mocks.focus,+ getValue: mocks.getValue,+ setValue: mocks.setValue,+ },+} as RefObject<TopicCommentEditorRef>;++const renderSubmitHook = () =>+ renderHook(() =>+ useComposerSubmit({+ clearDraft: mocks.clearDraft,+ content: 'New topic comment',+ create: mocks.create,+ creating: false,+ draft: { clientId: 'client-1', content: 'New topic comment' },+ editorRef,+ key: 'draft-key',+ onCreated: mocks.onCreated,+ onError: mocks.onError,+ setDraft: mocks.setDraft,+ shouldSendOnEnter: mocks.shouldSendOnEnter,+ topicId: 'topic-1',+ }),+ );++describe('useComposerSubmit', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.create.mockResolvedValue({ comment: { id: 'comment-1' }, isDuplicate: false });+ mocks.getValue.mockReturnValue({+ content: 'New topic comment',+ editorData: { root: { children: [] } },+ });+ mocks.shouldSendOnEnter.mockReturnValue(true);+ });++ it('clears the submitted draft immediately and reports success after create resolves', async () => {+ let resolveCreate: (() => void) | undefined;+ mocks.create.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveCreate = () => resolve({ comment: { id: 'comment-1' }, isDuplicate: false });+ }),+ );+ const { result } = renderSubmitHook();+ let submission: Promise<void>;++ act(() => {+ submission = result.current.submit();+ });++ expect(mocks.clearDraft).toHaveBeenCalledWith('draft-key', 'client-1');+ expect(mocks.clean).toHaveBeenCalledOnce();+ expect(result.current.submitting).toBe(true);+ expect(mocks.onCreated).not.toHaveBeenCalled();++ await act(async () => {+ resolveCreate?.();+ await submission!;+ });++ expect(result.current.submitting).toBe(false);+ expect(mocks.onCreated).toHaveBeenCalledOnce();+ });++ it('restores the submitted draft and editor when create fails', async () => {+ mocks.create.mockRejectedValueOnce(new Error('network failed'));+ const { result } = renderSubmitHook();++ await act(async () => {+ await result.current.submit();+ });++ const expectedValue = {+ content: 'New topic comment',+ editorData: { root: { children: [] } },+ };+ expect(mocks.setDraft).toHaveBeenLastCalledWith('draft-key', {+ clientId: 'client-1',+ ...expectedValue,+ });+ expect(mocks.setValue).toHaveBeenCalledWith(expectedValue);+ expect(mocks.focus).toHaveBeenCalledOnce();+ expect(mocks.onError).toHaveBeenCalledOnce();+ });++ it('submits member mention editor data with the comment markdown', async () => {+ const editorData = {+ root: {+ children: [+ {+ label: 'Workspace Member',+ metadata: { id: 'member-1', type: 'member' },+ type: 'mention',+ },+ ],+ },+ };+ mocks.getValue.mockReturnValueOnce({+ content: 'Hello <mention name="Workspace Member" id="member-1" />',+ editorData,+ });+ const { result } = renderSubmitHook();++ await act(async () => {+ await result.current.submit();+ });++ expect(mocks.create).toHaveBeenCalledWith(+ {+ clientId: 'client-1',+ content: 'Hello <mention name="Workspace Member" id="member-1" />',+ editorData,+ messageId: undefined,+ parentCommentId: undefined,+ topicId: 'topic-1',+ },+ { rootReplyCount: undefined },+ );+ });++ it('ignores a second submit before the creating state rerenders', async () => {+ let resolveCreate: (() => void) | undefined;+ mocks.create.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveCreate = () => resolve({ comment: { id: 'comment-1' }, isDuplicate: false });+ }),+ );+ const { result } = renderSubmitHook();++ act(() => {+ void result.current.submit();+ void result.current.submit();+ });++ expect(mocks.create).toHaveBeenCalledOnce();+ await act(async () => resolveCreate?.());+ });++ it('uses the shared enter-to-send preference', async () => {+ const { result } = renderSubmitHook();+ const event = new KeyboardEvent('keydown', { key: 'Enter' });++ mocks.shouldSendOnEnter.mockReturnValueOnce(false);+ expect(result.current.onPressEnter(event)).toBeUndefined();+ expect(mocks.create).not.toHaveBeenCalled();++ expect(result.current.onPressEnter(event)).toBe(true);+ await waitFor(() => expect(mocks.create).toHaveBeenCalledOnce());+ expect(mocks.shouldSendOnEnter).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/features/Portal/TopicComments/useComposerSubmit.ts b/src/features/Portal/TopicComments/useComposerSubmit.tsnew file mode 100644index 00000000000..0d51d34bda7--- /dev/null+++ b/src/features/Portal/TopicComments/useComposerSubmit.ts@@ -0,0 +1,116 @@+import type { CreateTopicCommentInput } from '@lobechat/types';+import { nanoid } from 'nanoid';+import type { RefObject } from 'react';+import { useCallback, useRef, useState } from 'react';++import type { TopicCommentDraft } from '@/store/topicComment/initialState';++import type { TopicCommentEditorRef } from './TopicCommentEditor';++interface UseComposerSubmitOptions {+ clearDraft: (key: string, expectedClientId?: string) => void;+ content: string;+ create: (+ input: CreateTopicCommentInput,+ options: { rootReplyCount?: number },+ ) => Promise<unknown>;+ creating: boolean;+ draft?: TopicCommentDraft;+ editorRef: RefObject<TopicCommentEditorRef | null>;+ key: string;+ messageId?: string;+ onCreated?: () => void;+ onError: () => void;+ parentCommentId?: string;+ rootReplyCount?: number;+ setDraft: (key: string, draft: TopicCommentDraft) => void;+ shouldSendOnEnter: (event: KeyboardEvent) => boolean;+ topicId: string;+}++export const useComposerSubmit = ({+ clearDraft,+ content,+ create,+ creating,+ draft,+ editorRef,+ key,+ messageId,+ onCreated,+ onError,+ parentCommentId,+ rootReplyCount,+ setDraft,+ shouldSendOnEnter,+ topicId,+}: UseComposerSubmitOptions) => {+ const submittingRef = useRef(false);+ const [submitting, setSubmitting] = useState(false);++ const submit = useCallback(async () => {+ const editorValue = editorRef.current?.getValue() ?? {+ content,+ editorData: draft?.editorData ?? null,+ };+ const value = editorValue.content.trim();+ if (!key || !value || creating || submittingRef.current) return;++ submittingRef.current = true;+ setSubmitting(true);+ const clientId = draft?.clientId ?? nanoid();+ const submittedDraft = { clientId, ...editorValue };+ setDraft(key, submittedDraft);+ clearDraft(key, clientId);+ editorRef.current?.clean();+ try {+ await create(+ {+ clientId,+ content: value,+ editorData: editorValue.editorData,+ messageId,+ parentCommentId,+ topicId,+ },+ { rootReplyCount },+ );+ onCreated?.();+ } catch {+ setDraft(key, submittedDraft);+ editorRef.current?.setValue(editorValue);+ editorRef.current?.focus();+ onError();+ } finally {+ submittingRef.current = false;+ setSubmitting(false);+ }+ }, [+ clearDraft,+ content,+ create,+ creating,+ draft?.clientId,+ draft?.editorData,+ editorRef,+ key,+ messageId,+ onCreated,+ onError,+ parentCommentId,+ rootReplyCount,+ setDraft,+ topicId,+ ]);++ const onPressEnter = useCallback(+ (event: KeyboardEvent) => {+ if (!shouldSendOnEnter(event)) return;+ void submit();+ return true;+ },+ [shouldSendOnEnter, submit],+ );++ return { onPressEnter, submit, submitting };+};diff --git a/src/features/Portal/router.tsx b/src/features/Portal/router.tsxindex d4c3257fdfb..7b50276595e 100644--- a/src/features/Portal/router.tsx+++ b/src/features/Portal/router.tsx@@ -21,6 +21,7 @@ import { Notebook } from './Notebook';import { Plugins } from './Plugins';import { TaskDetail } from './TaskDetail';import { Thread } from './Thread';+import { TopicComments, TopicCommentThread } from './TopicComments';import { type PortalImpl } from './type';import { VerifyReport } from './VerifyReport';import { VerifyResult } from './VerifyResult';@@ -43,6 +44,8 @@ const VIEW_COMPONENTS: Record<PortalViewType, PortalImpl> = {[PortalViewType.ToolUI]: Plugins,[PortalViewType.TaskDetail]: TaskDetail,[PortalViewType.Thread]: Thread,+ [PortalViewType.TopicCommentThread]: TopicCommentThread,+ [PortalViewType.TopicComments]: TopicComments,[PortalViewType.GroupThread]: GroupThread,[PortalViewType.VerifyResult]: VerifyResult,[PortalViewType.VerifyReport]: VerifyReport,diff --git a/src/features/TopicComment/MessageCommentBadge.tsx b/src/features/TopicComment/MessageCommentBadge.tsxnew file mode 100644index 00000000000..4ddea47c194--- /dev/null+++ b/src/features/TopicComment/MessageCommentBadge.tsx@@ -0,0 +1,65 @@+import { Flexbox } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { MessageCircle } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';++const styles = createStaticStyles(({ css, cssVar }) => ({+ button: css`+ && {+ gap: 4px;+ padding-inline: 6px;+ border-radius: ${cssVar.borderRadiusXS};+ color: ${cssVar.colorTextTertiary};+ }++ &&:hover {+ color: ${cssVar.colorTextSecondary};+ background: ${cssVar.colorFillTertiary};+ }++ &&:active {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillTertiary};+ }+ `,+ container: css`+ border-radius: ${cssVar.borderRadius};+ background: ${cssVar.colorFillTertiary};+ `,+}));++interface MessageCommentBadgeProps {+ count: number;+ messageId: string;+ topicId: string;+}++const MessageCommentBadge = memo<MessageCommentBadgeProps>(({ count, messageId, topicId }) => {+ const { t } = useTranslation('chat');+ const openTopicComments = useChatStore((s) => s.openTopicComments);+ const label = t('topicComment.openMessageComments', { count });++ return (+ <Flexbox horizontal align={'center'} className={styles.container} flex={'none'} padding={2}>+ <Button+ aria-label={label}+ className={styles.button}+ icon={MessageCircle}+ size={'small'}+ title={label}+ type={'text'}+ onClick={() => openTopicComments(topicId, messageId)}+ >+ {count > 99 ? '99+' : count}+ </Button>+ </Flexbox>+ );+});++MessageCommentBadge.displayName = 'MessageCommentBadge';++export default MessageCommentBadge;diff --git a/src/features/TopicComment/TopicCommentButton.tsx b/src/features/TopicComment/TopicCommentButton.tsxnew file mode 100644index 00000000000..29340cfe70c--- /dev/null+++ b/src/features/TopicComment/TopicCommentButton.tsx@@ -0,0 +1,38 @@+import { ActionIcon } from '@lobehub/ui';+import { Badge } from 'antd';+import { MessageCircle } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { DESKTOP_HEADER_ICON_SMALL_SIZE, MOBILE_HEADER_ICON_SIZE } from '@/const/layoutTokens';+import { useChatStore } from '@/store/chat';++import { usePrefetchTopicCommentsOnTopicLoad, useTopicCommentSummary } from './hooks';++const TopicCommentButton = memo<{ mobile?: boolean }>(({ mobile }) => {+ const { t } = useTranslation('chat');+ const workspaceId = useActiveWorkspaceId();+ const topicId = useChatStore((s) => s.activeTopicId);+ const openTopicComments = useChatStore((s) => s.openTopicComments);+ const { data } = useTopicCommentSummary(workspaceId ? topicId : undefined);+ usePrefetchTopicCommentsOnTopicLoad(workspaceId ? topicId : undefined);++ if (!workspaceId || !topicId) return null;++ return (+ <Badge count={data?.total} offset={[-3, 3]} overflowCount={99} size={'small'}>+ <ActionIcon+ icon={MessageCircle}+ size={mobile ? MOBILE_HEADER_ICON_SIZE : DESKTOP_HEADER_ICON_SMALL_SIZE}+ title={t('topicComment.title')}+ tooltipProps={{ placement: 'bottom' }}+ onClick={() => openTopicComments(topicId)}+ />+ </Badge>+ );+});++TopicCommentButton.displayName = 'TopicCommentButton';++export default TopicCommentButton;diff --git a/src/features/TopicComment/hooks.test.ts b/src/features/TopicComment/hooks.test.tsnew file mode 100644index 00000000000..2ae1bc75420--- /dev/null+++ b/src/features/TopicComment/hooks.test.ts@@ -0,0 +1,1427 @@+/**+ * @vitest-environment happy-dom+ */+import type { TopicCommentItem } from '@lobechat/types';+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useTopicCommentStore } from '@/store/topicComment';++import {+ useMessageCommentCount,+ usePrefetchTopicCommentsOnTopicLoad,+ useTopicCommentDetail,+ useTopicCommentMutations,+ useTopicCommentReplies,+ useTopicCommentSummary,+ useTopicCommentThreads,+} from './hooks';++const mocks = vi.hoisted(() => ({+ cacheGet: vi.fn(),+ create: vi.fn(),+ infiniteResponse: {} as Record<string, unknown>,+ listReplies: vi.fn(),+ listThreads: vi.fn(),+ mutate: vi.fn(),+ remove: vi.fn(),+ restore: vi.fn(),+ scopedMutate: vi.fn(),+ topicId: 'topic-1' as string | null,+ update: vi.fn(),+ user: {+ avatar: 'https://example.com/avatar.png',+ fullName: 'Current User',+ id: 'user-1',+ username: 'current-user',+ },+ useClientDataSWR: vi.fn(),+ useSWRInfinite: vi.fn(),+ workspaceId: 'workspace-1' as string | null,+}));++vi.mock('@/libs/swr', () => ({+ mutate: mocks.mutate,+ useClientDataSWR: mocks.useClientDataSWR,+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => mocks.workspaceId,+}));++vi.mock('@/store/user', () => ({+ useUserStore: (selector: (state: Record<string, unknown>) => unknown) =>+ selector({ user: mocks.user }),+}));++vi.mock('@/store/user/slices/auth/selectors', () => ({+ userProfileSelectors: { userProfile: (state: { user: unknown }) => state.user },+}));++vi.mock('swr', () => ({+ unstable_serialize: (key: unknown) => JSON.stringify(key),+ useSWRConfig: () => ({+ cache: { get: mocks.cacheGet },+ mutate: mocks.scopedMutate,+ }),+}));++vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>+ selector({ activeTopicId: mocks.topicId }),+}));++vi.mock('swr/infinite', () => ({+ default: (...args: unknown[]) => {+ mocks.useSWRInfinite(...args);+ return mocks.infiniteResponse;+ },+}));++vi.mock('@/services/topicComment', () => ({+ topicCommentService: {+ create: mocks.create,+ delete: mocks.remove,+ listReplies: mocks.listReplies,+ listThreads: mocks.listThreads,+ restore: mocks.restore,+ update: mocks.update,+ },+}));++const createComment = (overrides: Partial<TopicCommentItem> = {}): TopicCommentItem => ({+ anchorPreview: null,+ author: {+ avatar: null,+ fullName: 'Current User',+ id: 'user-1',+ status: 'active',+ username: 'current-user',+ },+ authorUserId: 'user-1',+ canDelete: true,+ canEdit: true,+ canRestore: false,+ clientId: 'client-1',+ content: 'Original comment',+ createdAt: new Date('2026-07-20T00:00:00.000Z'),+ deletedAt: null,+ editorData: null,+ id: 'comment-1',+ messageId: null,+ moderatedAt: null,+ moderationExpiresAt: null,+ moderationIsOwn: false,+ parentCommentId: null,+ topicId: 'topic-1',+ updatedAt: new Date('2026-07-20T00:00:00.000Z'),+ workspaceId: 'workspace-1',+ ...overrides,+});++describe('useTopicCommentMutations', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useTopicCommentStore.getState().reset();+ mocks.infiniteResponse = {+ data: undefined,+ error: undefined,+ isLoading: true,+ isValidating: true,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ mocks.cacheGet.mockReturnValue(undefined);+ mocks.mutate.mockResolvedValue(undefined);+ mocks.scopedMutate.mockResolvedValue(undefined);+ mocks.topicId = 'topic-1';+ mocks.useClientDataSWR.mockReturnValue({ data: undefined });+ mocks.workspaceId = 'workspace-1';+ });++ it('returns a successful create even when background cache refresh fails', async () => {+ const response = { comment: { id: 'comment-1' }, isDuplicate: false };+ mocks.create.mockResolvedValue(response);+ mocks.mutate.mockRejectedValue(new Error('refresh failed'));+ const { result } = renderHook(() => useTopicCommentMutations());++ await act(async () => {+ await expect(+ result.current.create({+ clientId: 'client-1',+ content: 'Hello',+ topicId: 'topic-1',+ }),+ ).resolves.toBe(response);+ });++ expect(mocks.create).toHaveBeenCalledWith({+ clientId: 'client-1',+ content: 'Hello',+ topicId: 'topic-1',+ });+ expect(result.current.creating).toBe(false);+ });++ it('keeps mutation failures observable to preserve the draft for retry', async () => {+ mocks.create.mockRejectedValue(new Error('network failed'));+ const { result } = renderHook(() => useTopicCommentMutations());++ await act(async () => {+ await expect(+ result.current.create({+ clientId: 'client-1',+ content: 'Hello',+ topicId: 'topic-1',+ }),+ ).rejects.toThrow('network failed');+ });++ expect(mocks.mutate).not.toHaveBeenCalled();+ expect(result.current.creating).toBe(false);+ });++ it('shows a topic comment immediately and reconciles it without waiting for refresh', async () => {+ let resolveCreate: ((value: unknown) => void) | undefined;+ let resolveRefresh: (() => void) | undefined;+ mocks.create.mockReturnValue(+ new Promise((resolve) => {+ resolveCreate = resolve;+ }),+ );+ mocks.mutate.mockImplementation((key) =>+ typeof key === 'function'+ ? new Promise<void>((resolve) => {+ resolveRefresh = resolve;+ })+ : Promise.resolve(undefined),+ );+ mocks.infiniteResponse = {+ data: [{ items: [], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.create({+ clientId: 'client-1',+ content: 'Optimistic comment',+ topicId: 'topic-1',+ });+ });++ await waitFor(() =>+ expect(threads.result.current.items[0]?.root).toMatchObject({+ clientId: 'client-1',+ content: 'Optimistic comment',+ }),+ );+ expect(threads.result.current.pendingCommentIds.has('optimistic-topic-comment-client-1')).toBe(+ true,+ );++ await act(async () => {+ resolveCreate?.({+ comment: {+ ...threads.result.current.items[0].root,+ canDelete: true,+ canEdit: true,+ id: 'comment-1',+ },+ isDuplicate: false,+ });+ await request;+ });++ expect(threads.result.current.items[0].root.id).toBe('comment-1');+ expect(threads.result.current.pendingCommentIds.has('comment-1')).toBe(false);+ expect(mutations.result.current.creating).toBe(false);++ await act(async () => resolveRefresh?.());+ expect(threads.result.current.items[0].root.id).toBe('comment-1');++ const reconciledRoot = threads.result.current.items[0].root;+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 0, root: reconciledRoot }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ threads.rerender();++ await waitFor(() =>+ expect(Object.keys(useTopicCommentStore.getState().optimisticComments)).toHaveLength(0),+ );+ expect(threads.result.current.items).toHaveLength(1);+ expect(threads.result.current.items[0].root.id).toBe('comment-1');+ });++ it('rolls back an optimistic topic comment when creation fails', async () => {+ let rejectCreate: ((reason: unknown) => void) | undefined;+ mocks.create.mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectCreate = reject;+ }),+ );+ mocks.infiniteResponse = {+ data: [{ items: [], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.create({+ clientId: 'client-1',+ content: 'Optimistic comment',+ topicId: 'topic-1',+ });+ });++ await waitFor(() => expect(threads.result.current.items).toHaveLength(1));+ await act(async () => {+ rejectCreate?.(new Error('network failed'));+ await expect(request).rejects.toThrow('network failed');+ });++ expect(threads.result.current.items).toEqual([]);+ });++ it('optimistically updates and rolls back the topic summary count', async () => {+ let rejectCreate: ((reason: unknown) => void) | undefined;+ mocks.create.mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectCreate = reject;+ }),+ );+ mocks.useClientDataSWR.mockReturnValue({+ data: { countByMessage: {}, total: 4 },+ });+ const mutations = renderHook(() => useTopicCommentMutations());+ const summary = renderHook(() => useTopicCommentSummary('topic-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.create({+ clientId: 'client-1',+ content: 'Optimistic comment',+ topicId: 'topic-1',+ });+ });++ await waitFor(() => expect(summary.result.current.data?.total).toBe(5));++ await act(async () => {+ rejectCreate?.(new Error('network failed'));+ await expect(request).rejects.toThrow('network failed');+ });+ expect(summary.result.current.data?.total).toBe(4);+ });++ it('does not double-count an idempotent retry after the server confirms it', async () => {+ let resolveCreate: ((value: unknown) => void) | undefined;+ mocks.create.mockReturnValue(+ new Promise((resolve) => {+ resolveCreate = resolve;+ }),+ );+ mocks.useClientDataSWR.mockReturnValue({+ data: { countByMessage: {}, total: 4 },+ });+ mocks.infiniteResponse = {+ data: [{ items: [], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const summary = renderHook(() => useTopicCommentSummary('topic-1'));+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.create({+ clientId: 'client-1',+ content: 'Retried comment',+ topicId: 'topic-1',+ });+ });++ await waitFor(() => expect(summary.result.current.data?.total).toBe(5));+ await act(async () => {+ resolveCreate?.({+ comment: {+ ...threads.result.current.items[0].root,+ id: 'comment-1',+ },+ isDuplicate: true,+ });+ await request;+ });++ expect(summary.result.current.data?.total).toBe(4);+ expect(threads.result.current.pendingCommentIds.has('comment-1')).toBe(false);+ expect(+ mocks.mutate.mock.calls.some(([key]) =>+ Array.isArray(key) ? key[0] === 'topicComment:summary' : false,+ ),+ ).toBe(true);+ });++ it('shows a message comment in both its message scope and the topic-wide scope', async () => {+ let rejectCreate: ((reason: unknown) => void) | undefined;+ mocks.create.mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectCreate = reject;+ }),+ );+ mocks.infiniteResponse = {+ data: [{ items: [], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const topicThreads = renderHook(() => useTopicCommentThreads('topic-1'));+ const messageThreads = renderHook(() => useTopicCommentThreads('topic-1', 'message-1'));+ const otherMessageThreads = renderHook(() => useTopicCommentThreads('topic-1', 'message-2'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.create({+ clientId: 'client-1',+ content: 'Message comment',+ messageId: 'message-1',+ topicId: 'topic-1',+ });+ });++ await waitFor(() => expect(topicThreads.result.current.items).toHaveLength(1));+ expect(messageThreads.result.current.items).toHaveLength(1);+ expect(otherMessageThreads.result.current.items).toEqual([]);++ await act(async () => {+ rejectCreate?.(new Error('network failed'));+ await expect(request).rejects.toThrow('network failed');+ });+ });++ it('keeps an optimistic reply out of root threads', async () => {+ let rejectCreate: ((reason: unknown) => void) | undefined;+ mocks.create.mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectCreate = reject;+ }),+ );+ mocks.infiniteResponse = {+ data: [{ items: [], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));+ const replies = renderHook(() => useTopicCommentReplies('root-comment-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.create({+ clientId: 'client-1',+ content: 'Reply',+ parentCommentId: 'root-comment-1',+ topicId: 'topic-1',+ });+ });++ await waitFor(() => expect(replies.result.current.items).toHaveLength(1));+ expect(threads.result.current.items).toEqual([]);++ await act(async () => {+ rejectCreate?.(new Error('network failed'));+ await expect(request).rejects.toThrow('network failed');+ });+ });++ it('optimistically increments a root reply count and keeps it until the list reconciles', async () => {+ const root = createComment({ id: 'root-comment-1' });+ let resolveCreate: ((value: unknown) => void) | undefined;+ mocks.create.mockReturnValue(+ new Promise((resolve) => {+ resolveCreate = resolve;+ }),+ );+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 2, root }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.create(+ {+ clientId: 'reply-client-1',+ content: 'Reply',+ parentCommentId: root.id,+ topicId: 'topic-1',+ },+ { rootReplyCount: 2 },+ );+ });++ await waitFor(() => expect(threads.result.current.items[0].replyCount).toBe(3));++ const reply = createComment({+ clientId: 'reply-client-1',+ id: 'reply-1',+ parentCommentId: root.id,+ });+ await act(async () => {+ resolveCreate?.({ comment: reply, isDuplicate: false });+ await request;+ });++ expect(threads.result.current.items[0].replyCount).toBe(3);+ expect(+ useTopicCommentStore.getState().optimisticReplyCountMutations['reply-client-1']?.pending,+ ).toBe(false);++ mocks.infiniteResponse = {+ ...mocks.infiniteResponse,+ data: [{ items: [{ replyCount: 3, root }], nextCursor: null }],+ };+ threads.rerender();++ await waitFor(() =>+ expect(+ useTopicCommentStore.getState().optimisticReplyCountMutations['reply-client-1'],+ ).toBeUndefined(),+ );+ expect(threads.result.current.items[0].replyCount).toBe(3);+ });++ it('clears the optimistic reply count delta when a retried create is duplicate', async () => {+ const root = createComment({ id: 'root-comment-1' });+ const reply = createComment({+ clientId: 'reply-client-1',+ id: 'reply-1',+ parentCommentId: root.id,+ });+ mocks.create.mockResolvedValue({ comment: reply, isDuplicate: true });+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 3, root }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));++ await act(async () => {+ await mutations.result.current.create(+ {+ clientId: 'reply-client-1',+ content: 'Retried reply',+ parentCommentId: root.id,+ topicId: 'topic-1',+ },+ { rootReplyCount: 3 },+ );+ });++ expect(useTopicCommentStore.getState().optimisticReplyCountMutations).toEqual({});+ expect(threads.result.current.items[0].replyCount).toBe(3);+ });++ it('optimistically decrements a root reply count and rolls it back when delete fails', async () => {+ const root = createComment({ id: 'root-comment-1' });+ const reply = createComment({ id: 'reply-1', parentCommentId: root.id });+ let rejectDelete: ((reason: unknown) => void) | undefined;+ mocks.remove.mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectDelete = reject;+ }),+ );+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 2, root }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.remove(reply, 'hard', { rootReplyCount: 2 });+ });++ await waitFor(() => expect(threads.result.current.items[0].replyCount).toBe(1));++ await act(async () => {+ rejectDelete?.(new Error('network failed'));+ await expect(request).rejects.toThrow('network failed');+ });++ expect(threads.result.current.items[0].replyCount).toBe(2);+ expect(useTopicCommentStore.getState().optimisticReplyCountMutations).toEqual({});+ });++ it('does not leave a stale count after settled reply operations cancel each other out', async () => {+ const root = createComment({ id: 'root-comment-1' });+ useTopicCommentStore.getState().upsertOptimisticReplyCountMutation({+ baselineCount: 2,+ delta: 1,+ id: 'create:reply-1',+ pending: false,+ rootCommentId: root.id,+ topicId: root.topicId,+ workspaceId: root.workspaceId,+ });+ useTopicCommentStore.getState().upsertOptimisticReplyCountMutation({+ baselineCount: 3,+ delta: -1,+ id: 'delete:reply-1',+ pending: false,+ rootCommentId: root.id,+ topicId: root.topicId,+ workspaceId: root.workspaceId,+ });+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 2, root }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };++ const threads = renderHook(() => useTopicCommentThreads('topic-1'));++ expect(threads.result.current.items[0].replyCount).toBe(2);+ await waitFor(() =>+ expect(useTopicCommentStore.getState().optimisticReplyCountMutations).toEqual({}),+ );+ });++ it('shows an edit immediately, keeps it over stale data, and reconciles the server result', async () => {+ const comment = createComment();+ let resolveUpdate: ((value: TopicCommentItem) => void) | undefined;+ mocks.mutate.mockReturnValue(new Promise(() => undefined));+ mocks.update.mockReturnValue(+ new Promise((resolve) => {+ resolveUpdate = resolve;+ }),+ );+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.update(+ { content: 'Edited comment', id: comment.id },+ comment,+ );+ });++ await waitFor(() =>+ expect(threads.result.current.items[0].root.content).toBe('Edited comment'),+ );++ const confirmed = createComment({+ content: 'Edited comment',+ updatedAt: new Date('2026-07-21T00:00:00.000Z'),+ });+ await act(async () => {+ resolveUpdate?.(confirmed);+ await request;+ });++ expect(threads.result.current.items[0].root).toEqual(confirmed);+ expect(mocks.mutate).toHaveBeenCalledWith(['topicComment:detail', comment.id], confirmed, {+ revalidate: false,+ });+ expect(mocks.mutate.mock.calls.some(([key]) => typeof key === 'function')).toBe(false);++ mocks.infiniteResponse = {+ ...mocks.infiniteResponse,+ data: [{ items: [{ replyCount: 0, root: confirmed }], nextCursor: null }],+ };+ threads.rerender();+ await waitFor(() =>+ expect(useTopicCommentStore.getState().optimisticMutations[comment.id]).toBeUndefined(),+ );+ expect(threads.result.current.items[0].root).toEqual(confirmed);+ });++ it('rolls back an optimistic edit when the request fails', async () => {+ const comment = createComment();+ let rejectUpdate: ((reason: unknown) => void) | undefined;+ mocks.update.mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectUpdate = reject;+ }),+ );+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.update(+ { content: 'Edited comment', id: comment.id },+ comment,+ );+ });+ await waitFor(() =>+ expect(threads.result.current.items[0].root.content).toBe('Edited comment'),+ );++ await act(async () => {+ rejectUpdate?.(new Error('network failed'));+ await expect(request).rejects.toThrow('network failed');+ });++ expect(threads.result.current.items[0].root).toEqual(comment);+ expect(useTopicCommentStore.getState().optimisticMutations).toEqual({});+ });++ it('applies an optimistic edit to the standalone thread detail', async () => {+ const comment = createComment();+ let rejectUpdate: ((reason: unknown) => void) | undefined;+ mocks.update.mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectUpdate = reject;+ }),+ );+ mocks.useClientDataSWR.mockReturnValue({ data: comment });+ const mutations = renderHook(() => useTopicCommentMutations());+ const detail = renderHook(() => useTopicCommentDetail(comment.id));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.update(+ { content: 'Edited detail', id: comment.id },+ comment,+ );+ });++ await waitFor(() => expect(detail.result.current.data?.content).toBe('Edited detail'));+ await act(async () => {+ rejectUpdate?.(new Error('network failed'));+ await expect(request).rejects.toThrow('network failed');+ });+ expect(detail.result.current.data).toEqual(comment);+ });++ it('keeps a root visible during a pending hard delete and hides it after confirmation', () => {+ const comment = createComment();+ mocks.useClientDataSWR.mockReturnValue({ data: comment });+ useTopicCommentStore.getState().upsertOptimisticMutation({+ comment,+ deleteMode: 'hard',+ kind: 'delete',+ pending: true,+ });+ const detail = renderHook(() => useTopicCommentDetail(comment.id));++ expect(detail.result.current.data).toEqual(comment);+ expect(detail.result.current.isDeleting).toBe(true);++ act(() => {+ useTopicCommentStore.getState().upsertOptimisticMutation({+ comment,+ deleteMode: 'hard',+ kind: 'delete',+ pending: false,+ });+ });++ expect(detail.result.current.data).toBeUndefined();+ expect(detail.result.current.isDeleting).toBe(true);+ });++ it('rolls a failed second edit back to the last confirmed optimistic value', async () => {+ const staleComment = createComment();+ const confirmedComment = createComment({+ content: 'First confirmed edit',+ updatedAt: new Date('2026-07-21T00:00:00.000Z'),+ });+ useTopicCommentStore.getState().upsertOptimisticMutation({+ comment: confirmedComment,+ kind: 'update',+ pending: false,+ });+ mocks.update.mockRejectedValue(new Error('network failed'));+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 0, root: staleComment }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));++ await act(async () => {+ await expect(+ mutations.result.current.update(+ { content: 'Second failed edit', id: staleComment.id },+ confirmedComment,+ ),+ ).rejects.toThrow('network failed');+ });++ expect(threads.result.current.items[0].root).toEqual(confirmedComment);+ expect(useTopicCommentStore.getState().optimisticMutations[staleComment.id]?.comment).toEqual(+ confirmedComment,+ );+ });++ it('hides a hard delete and decrements counts immediately, then rolls back on failure', async () => {+ const comment = createComment({ messageId: 'message-1' });+ let rejectDelete: ((reason: unknown) => void) | undefined;+ mocks.remove.mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectDelete = reject;+ }),+ );+ mocks.useClientDataSWR.mockReturnValue({+ data: { countByMessage: { 'message-1': 1 }, total: 1 },+ });+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));+ const summary = renderHook(() => useTopicCommentSummary('topic-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.remove(comment);+ });++ await waitFor(() => expect(threads.result.current.items).toEqual([]));+ expect(summary.result.current.data).toEqual({ countByMessage: {}, total: 0 });++ await act(async () => {+ rejectDelete?.(new Error('network failed'));+ await expect(request).rejects.toThrow('network failed');+ });++ expect(threads.result.current.items[0].root).toEqual(comment);+ expect(summary.result.current.data).toEqual({ countByMessage: { 'message-1': 1 }, total: 1 });+ });++ it('keeps a confirmed hard delete hidden until refreshed data no longer contains it', async () => {+ const comment = createComment();+ mocks.remove.mockResolvedValue({ mode: 'hard' });+ mocks.mutate.mockReturnValue(new Promise(() => undefined));+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));++ await act(async () => {+ await mutations.result.current.remove(comment);+ });++ expect(threads.result.current.items).toEqual([]);+ expect(useTopicCommentStore.getState().optimisticMutations[comment.id]?.pending).toBe(false);+ expect(+ mocks.mutate.mock.calls.filter(+ ([key]) => Array.isArray(key) && key[0] === 'topicComment:summary',+ ),+ ).toHaveLength(1);+ expect(mocks.mutate).toHaveBeenCalledWith(['topicComment:detail', comment.id], undefined, {+ revalidate: false,+ });+ expect(mocks.mutate.mock.calls.some(([key]) => typeof key === 'function')).toBe(false);++ mocks.infiniteResponse = {+ ...mocks.infiniteResponse,+ data: [{ items: [], nextCursor: null }],+ };+ threads.rerender();+ await waitFor(() =>+ expect(useTopicCommentStore.getState().optimisticMutations[comment.id]).toBeUndefined(),+ );+ expect(threads.result.current.items).toEqual([]);+ });++ it('shows an owner-moderated placeholder immediately and reconciles the server result', async () => {+ const comment = createComment({+ authorUserId: 'other-user',+ canEdit: false,+ messageId: 'message-1',+ });+ let resolveDelete:+ ((value: { comment: TopicCommentItem; mode: 'moderated' }) => void) | undefined;+ mocks.remove.mockReturnValue(+ new Promise((resolve) => {+ resolveDelete = resolve;+ }),+ );+ mocks.useClientDataSWR.mockReturnValue({+ data: { countByMessage: { 'message-1': 1 }, total: 1 },+ });+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));+ const summary = renderHook(() => useTopicCommentSummary('topic-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.remove(comment);+ });++ await waitFor(() => expect(threads.result.current.items[0].root.canRestore).toBe(true));+ expect(threads.result.current.items[0].root.content).toBe('Original comment');+ expect(summary.result.current.data).toEqual({ countByMessage: {}, total: 0 });++ const moderated = createComment({+ ...comment,+ canDelete: false,+ canEdit: false,+ canRestore: true,+ moderatedAt: new Date('2026-07-22T00:00:00.000Z'),+ moderationExpiresAt: new Date('2026-08-21T00:00:00.000Z'),+ });+ await act(async () => {+ resolveDelete?.({ comment: moderated, mode: 'moderated' });+ await request;+ });++ expect(threads.result.current.items[0].root).toEqual(moderated);+ expect(mocks.mutate).toHaveBeenCalledWith(['topicComment:detail', comment.id], moderated, {+ revalidate: false,+ });+ });++ it('restores a moderated comment immediately and rolls back when restore fails', async () => {+ const comment = createComment({+ authorUserId: 'other-user',+ canDelete: false,+ canEdit: false,+ canRestore: true,+ messageId: 'message-1',+ moderatedAt: new Date('2026-07-22T00:00:00.000Z'),+ moderationExpiresAt: new Date('2026-08-21T00:00:00.000Z'),+ });+ let rejectRestore: ((reason: unknown) => void) | undefined;+ mocks.restore.mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectRestore = reject;+ }),+ );+ mocks.useClientDataSWR.mockReturnValue({ data: { countByMessage: {}, total: 0 } });+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));+ const summary = renderHook(() => useTopicCommentSummary('topic-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.restore(comment, { rootReplyCount: 0 });+ });++ await waitFor(() => expect(threads.result.current.items[0].root.moderatedAt).toBeNull());+ expect(summary.result.current.data).toEqual({+ countByMessage: { 'message-1': 1 },+ total: 1,+ });++ await act(async () => {+ rejectRestore?.(new Error('network failed'));+ await expect(request).rejects.toThrow('network failed');+ });++ expect(threads.result.current.items[0].root).toEqual(comment);+ expect(summary.result.current.data).toEqual({ countByMessage: {}, total: 0 });+ });++ it('does not reconcile a confirmed hard delete against a list that has not loaded', async () => {+ const comment = createComment();+ useTopicCommentStore.getState().upsertOptimisticMutation({+ comment,+ deleteMode: 'hard',+ kind: 'delete',+ pending: false,+ });+ mocks.infiniteResponse = {+ data: undefined,+ error: undefined,+ isLoading: true,+ isValidating: true,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));++ expect(useTopicCommentStore.getState().optimisticMutations[comment.id]).toBeDefined();++ mocks.infiniteResponse = {+ ...mocks.infiniteResponse,+ data: [{ items: [], nextCursor: null }],+ isLoading: false,+ isValidating: false,+ };+ threads.rerender();+ await waitFor(() =>+ expect(useTopicCommentStore.getState().optimisticMutations[comment.id]).toBeUndefined(),+ );+ });++ it('optimistically hides and rolls back a deleted reply', async () => {+ const reply = createComment({ id: 'reply-1', parentCommentId: 'comment-1' });+ let rejectDelete: ((reason: unknown) => void) | undefined;+ mocks.remove.mockReturnValue(+ new Promise((_resolve, reject) => {+ rejectDelete = reject;+ }),+ );+ mocks.infiniteResponse = {+ data: [{ items: [reply], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ const mutations = renderHook(() => useTopicCommentMutations());+ const replies = renderHook(() => useTopicCommentReplies('comment-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.remove(reply);+ });++ await waitFor(() => expect(replies.result.current.items).toEqual([]));+ await act(async () => {+ rejectDelete?.(new Error('network failed'));+ await expect(request).rejects.toThrow('network failed');+ });+ expect(replies.result.current.items).toEqual([reply]);+ });++ it('shows a tombstone immediately for a root with replies and reconciles a soft delete', async () => {+ const comment = createComment({ messageId: 'message-1' });+ let resolveDelete: ((value: { mode: 'soft' }) => void) | undefined;+ mocks.remove.mockReturnValue(+ new Promise((resolve) => {+ resolveDelete = resolve;+ }),+ );+ mocks.infiniteResponse = {+ data: [{ items: [{ replyCount: 2, root: comment }], nextCursor: null }],+ error: undefined,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };+ mocks.useClientDataSWR.mockReturnValue({+ data: { countByMessage: { 'message-1': 1 }, total: 2 },+ });+ const mutations = renderHook(() => useTopicCommentMutations());+ const threads = renderHook(() => useTopicCommentThreads('topic-1'));+ const summary = renderHook(() => useTopicCommentSummary('topic-1'));++ let request: Promise<unknown>;+ act(() => {+ request = mutations.result.current.remove(comment, 'soft');+ });++ await waitFor(() => expect(threads.result.current.items[0].root.deletedAt).not.toBeNull());+ expect(threads.result.current.items[0].root.content).toBe('');+ expect(summary.result.current.data).toEqual({+ countByMessage: { 'message-1': 1 },+ total: 1,+ });++ await act(async () => {+ resolveDelete?.({ mode: 'soft' });+ await request;+ });+ expect(threads.result.current.items[0].root.deletedAt).not.toBeNull();++ const tombstone = createComment({+ canDelete: false,+ canEdit: false,+ content: '',+ deletedAt: new Date('2026-07-21T00:00:00.000Z'),+ updatedAt: new Date('2026-07-21T00:00:00.000Z'),+ });+ mocks.infiniteResponse = {+ ...mocks.infiniteResponse,+ data: [{ items: [{ replyCount: 2, root: tombstone }], nextCursor: null }],+ };+ threads.rerender();++ await waitFor(() =>+ expect(useTopicCommentStore.getState().optimisticMutations[comment.id]).toBeUndefined(),+ );+ expect(threads.result.current.items[0].root).toEqual(tombstone);+ });+});++describe('topic comment read hooks', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useTopicCommentStore.getState().reset();+ mocks.cacheGet.mockReturnValue(undefined);+ mocks.scopedMutate.mockResolvedValue(undefined);+ mocks.topicId = 'topic-1';+ mocks.workspaceId = 'workspace-1';+ mocks.useClientDataSWR.mockReturnValue({ data: undefined });+ });++ it('reads a message badge from the root-thread summary', () => {+ mocks.useClientDataSWR.mockReturnValue({+ data: { countByMessage: { 'message-1': 3 }, total: 8 },+ });++ const { result } = renderHook(() => useMessageCommentCount('message-1'));++ expect(result.current).toEqual({ count: 3, topicId: 'topic-1' });+ });++ it('warms and caches the topic first page before the summary loads', async () => {+ const page = { items: [{ replyCount: 0, root: { id: 'comment-1' } }], nextCursor: null };+ mocks.listThreads.mockResolvedValue(page);+ mocks.useClientDataSWR.mockImplementation((key, fetcher) => {+ if (Array.isArray(key) && key[0] === 'topicComment:warmup') void fetcher();+ return { data: undefined };+ });++ renderHook(() => usePrefetchTopicCommentsOnTopicLoad('topic-1'));++ await waitFor(() =>+ expect(mocks.scopedMutate).toHaveBeenCalledWith(+ ['topicComment:threads', 'workspace-1', 'topic-1', '', ''],+ page,+ { revalidate: false },+ ),+ );+ });++ it('warms and caches first-page replies for roots that have replies', async () => {+ const threadPage = {+ items: [+ { replyCount: 2, root: { id: 'comment-1' } },+ { replyCount: 0, root: { id: 'comment-2' } },+ ],+ nextCursor: null,+ };+ const replyPage = { items: [{ id: 'reply-1' }], nextCursor: null };+ mocks.listThreads.mockResolvedValue(threadPage);+ mocks.listReplies.mockResolvedValue(replyPage);+ mocks.useClientDataSWR.mockImplementation((key, fetcher) => {+ if (Array.isArray(key) && key[0] === 'topicComment:warmup') void fetcher();+ return { data: undefined };+ });++ renderHook(() => usePrefetchTopicCommentsOnTopicLoad('topic-1'));++ await waitFor(() =>+ expect(mocks.scopedMutate).toHaveBeenCalledWith(+ ['topicComment:replies', 'workspace-1', 'comment-1', ''],+ replyPage,+ { revalidate: false },+ ),+ );+ expect(mocks.listReplies).toHaveBeenCalledOnce();+ expect(mocks.listReplies).toHaveBeenCalledWith({+ cursor: undefined,+ limit: 30,+ rootCommentId: 'comment-1',+ });+ });++ it('keeps a failed topic warmup retryable and caches a later successful retry', async () => {+ const error = new Error('prefetch failed');+ const page = { items: [{ replyCount: 0, root: { id: 'comment-1' } }], nextCursor: null };+ let warmupFetcher: (() => Promise<boolean>) | undefined;+ mocks.listThreads.mockRejectedValueOnce(error).mockResolvedValueOnce(page);+ mocks.useClientDataSWR.mockImplementation((key, fetcher) => {+ if (Array.isArray(key) && key[0] === 'topicComment:warmup') warmupFetcher = fetcher;+ return { data: undefined };+ });++ renderHook(() => usePrefetchTopicCommentsOnTopicLoad('topic-1'));++ await expect(warmupFetcher?.()).rejects.toBe(error);+ await expect(warmupFetcher?.()).resolves.toBe(true);+ expect(mocks.scopedMutate).toHaveBeenCalledWith(+ ['topicComment:threads', 'workspace-1', 'topic-1', '', ''],+ page,+ { revalidate: false },+ );+ });++ it('registers only the bounded topic-level warmup', () => {+ renderHook(() => usePrefetchTopicCommentsOnTopicLoad('topic-1'));++ expect(mocks.useClientDataSWR).toHaveBeenCalledOnce();+ expect(mocks.useClientDataSWR).toHaveBeenCalledWith(+ ['topicComment:warmup', 'workspace-1', 'topic-1'],+ expect.any(Function),+ { revalidateOnFocus: false },+ );+ });++ it('refreshes only the affected summary after a comment write', async () => {+ const response = { comment: { id: 'comment-1' }, isDuplicate: false };+ mocks.create.mockResolvedValue(response);+ const { result } = renderHook(() => useTopicCommentMutations());++ await act(async () => {+ await result.current.create({+ clientId: 'client-1',+ content: 'Hello',+ topicId: 'topic-1',+ });+ });++ expect(mocks.mutate.mock.calls.some(([key]) => typeof key === 'function')).toBe(false);+ expect(+ mocks.mutate.mock.calls.filter(+ ([key]) => Array.isArray(key) && key[0] === 'topicComment:summary',+ ),+ ).toHaveLength(1);+ expect(+ mocks.mutate.mock.calls.some(+ ([key]) => Array.isArray(key) && key[0] === 'topicComment:warmup',+ ),+ ).toBe(false);+ });++ it('uses the summary as an immediate empty fallback while revalidating in the background', () => {+ mocks.useClientDataSWR.mockReturnValue({+ data: { countByMessage: {}, total: 0 },+ });++ renderHook(() => useTopicCommentThreads('topic-1', 'message-without-comments'));++ expect(mocks.useSWRInfinite).toHaveBeenCalledWith(+ expect.any(Function),+ expect.any(Function),+ expect.objectContaining({+ fallbackData: [{ items: [], nextCursor: null }],+ revalidateOnMount: true,+ }),+ );+ });++ it('uses a zero reply snapshot as an immediate empty fallback while revalidating', () => {+ renderHook(() => useTopicCommentReplies('root-comment-1', 0));++ expect(mocks.useSWRInfinite).toHaveBeenCalledWith(+ expect.any(Function),+ expect.any(Function),+ expect.objectContaining({+ fallbackData: [{ items: [], nextCursor: null }],+ revalidateOnMount: true,+ }),+ );+ });++ it('uses prefetched first-page replies as an immediate fallback while revalidating', () => {+ const page = { items: [{ id: 'reply-1' }], nextCursor: null };+ mocks.cacheGet.mockImplementation((key) =>+ key === JSON.stringify(['topicComment:replies', 'workspace-1', 'root-comment-1', ''])+ ? { data: page }+ : undefined,+ );++ renderHook(() => useTopicCommentReplies('root-comment-1', 1));++ expect(mocks.useSWRInfinite).toHaveBeenCalledWith(+ expect.any(Function),+ expect.any(Function),+ expect.objectContaining({+ fallbackData: [page],+ revalidateOnMount: true,+ }),+ );+ });++ it('uses a prefetched first page as an immediate fallback while revalidating', () => {+ const page = { items: [{ replyCount: 0, root: { id: 'comment-1' } }], nextCursor: null };+ mocks.cacheGet.mockReturnValue({ data: page });++ renderHook(() => useTopicCommentThreads('topic-1', 'message-1'));++ expect(mocks.useSWRInfinite).toHaveBeenCalledWith(+ expect.any(Function),+ expect.any(Function),+ expect.objectContaining({+ fallbackData: [page],+ revalidateOnMount: true,+ }),+ );+ });++ it('revalidates the first page when returning from a comment thread', () => {+ renderHook(() => useTopicCommentThreads('topic-1'));++ expect(mocks.useSWRInfinite).toHaveBeenCalledWith(+ expect.any(Function),+ expect.any(Function),+ expect.objectContaining({ revalidateOnMount: true }),+ );+ });++ it('keeps loaded threads visible while the next page is loading', () => {+ const thread = {+ replyCount: 2,+ root: { id: 'comment-1' },+ };+ mocks.infiniteResponse = {+ data: [{ items: [thread], nextCursor: 'next' }, undefined],+ error: undefined,+ isLoading: false,+ isValidating: true,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 2,+ };++ const { result } = renderHook(() => useTopicCommentThreads('topic-1'));++ expect(result.current.items).toEqual([thread]);+ expect(result.current.hasMore).toBe(true);+ expect(result.current.isLoadingMore).toBe(true);+ });++ it('exposes a tail error without turning it into an initial failure', () => {+ const error = new Error('next page failed');+ const thread = {+ replyCount: 0,+ root: { id: 'comment-1' },+ };+ mocks.infiniteResponse = {+ data: [{ items: [thread], nextCursor: 'next' }, undefined],+ error,+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 2,+ };++ const { result } = renderHook(() => useTopicCommentThreads('topic-1'));++ expect(result.current.items).toEqual([thread]);+ expect(result.current.isInitialError).toBe(false);+ expect(result.current.isLoadingMore).toBe(false);+ expect(result.current.hasMore).toBe(false);+ });++ it('marks a first-page failure as an initial error', () => {+ mocks.infiniteResponse = {+ data: undefined,+ error: new Error('first page failed'),+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ setSize: vi.fn(),+ size: 1,+ };++ const { result } = renderHook(() => useTopicCommentThreads('topic-1'));++ expect(result.current.items).toEqual([]);+ expect(result.current.isInitialError).toBe(true);+ });+});diff --git a/src/features/TopicComment/hooks.ts b/src/features/TopicComment/hooks.tsnew file mode 100644index 00000000000..9762da892a3--- /dev/null+++ b/src/features/TopicComment/hooks.ts@@ -0,0 +1,877 @@+import type {+ CreateTopicCommentInput,+ TopicCommentItem,+ TopicCommentReplyPage,+ TopicCommentSummary,+ TopicCommentThreadPage,+ UpdateTopicCommentInput,+} from '@lobechat/types';+import { useCallback, useEffect, useMemo, useState } from 'react';+import { unstable_serialize, useSWRConfig } from 'swr';+import type { ScopedMutator } from 'swr/_internal';+import useSWRInfinite from 'swr/infinite';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { mutate, useClientDataSWR } from '@/libs/swr';+import { topicCommentKeys } from '@/libs/swr/keys';+import { topicCommentService } from '@/services/topicComment';+import { useChatStore } from '@/store/chat';+import {+ createTopicCommentDraftKey,+ topicCommentSelectors,+ useTopicCommentStore,+} from '@/store/topicComment';+import type {+ OptimisticTopicCommentMutation,+ OptimisticTopicCommentReplyCountMutation,+} from '@/store/topicComment/initialState';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/slices/auth/selectors';++const PAGE_SIZE = 30;+const PREFETCH_CONCURRENCY = 4;+const EMPTY_TOPIC_COMMENT_THREAD_PAGES: TopicCommentThreadPage[] = [+ { items: [], nextCursor: null },+];+const topicCommentClientKey = ({+ authorUserId,+ clientId,+}: Pick<TopicCommentItem, 'authorUserId' | 'clientId'>) => `${authorUserId ?? ''}:${clientId}`;+const isOptimisticMutationReconciled = (+ mutation: OptimisticTopicCommentMutation,+ remoteComment: TopicCommentItem | undefined,+) => {+ if (mutation.pending) return false;+ if (mutation.kind === 'delete' && mutation.deleteMode === 'hard') return !remoteComment;+ if (!remoteComment) return false;+ if (mutation.kind === 'restore') return !remoteComment.moderatedAt;+ if (mutation.kind === 'delete')+ return mutation.deleteMode === 'soft'+ ? Boolean(remoteComment.deletedAt)+ : Boolean(remoteComment.moderatedAt);++ return (+ new Date(remoteComment.updatedAt).getTime() >= new Date(mutation.comment.updatedAt).getTime()+ );+};++const areReplyCountMutationsReconciled = (+ mutations: OptimisticTopicCommentReplyCountMutation[],+ remoteCount: number,+) => {+ if (mutations.length === 0 || mutations.some(({ pending }) => pending)) return false;+ const baselineCount = mutations[0].baselineCount;+ const lastMutation = mutations.at(-1)!;+ const targetCount = Math.max(0, lastMutation.baselineCount + lastMutation.delta);+ if (targetCount === baselineCount) return true;+ return targetCount > baselineCount ? remoteCount >= targetCount : remoteCount <= targetCount;+};++const resolveReplyCount = (+ remoteCount: number,+ mutations: OptimisticTopicCommentReplyCountMutation[],+) => {+ if (mutations.length === 0) return remoteCount;+ if (areReplyCountMutationsReconciled(mutations, remoteCount)) return remoteCount;+ const lastMutation = mutations.at(-1)!;+ return Math.max(0, lastMutation.baselineCount + lastMutation.delta);+};++const fetchTopicCommentThreads = ([+ ,+ ,+ currentTopicId,+ currentMessageId,+ cursor,+]: readonly string[]) =>+ topicCommentService.listThreads({+ cursor: cursor || undefined,+ limit: PAGE_SIZE,+ messageId: currentMessageId || undefined,+ topicId: currentTopicId,+ });++const fetchTopicCommentReplies = ([, , currentRootCommentId, cursor]: readonly string[]) =>+ topicCommentService.listReplies({+ cursor: cursor || undefined,+ limit: PAGE_SIZE,+ rootCommentId: currentRootCommentId,+ });++const preloadTopicCommentThreads = (+ populateCache: ScopedMutator,+ workspaceId: string,+ topicId: string,+ messageId?: string,+) => {+ const key = topicCommentKeys.threads(workspaceId, topicId, messageId);+ return fetchTopicCommentThreads(key as readonly string[]).then(async (page) => {+ await populateCache(key, page, { revalidate: false });+ return page;+ });+};++const preloadTopicCommentReplies = (+ populateCache: ScopedMutator,+ workspaceId: string,+ rootCommentId: string,+) => {+ const key = topicCommentKeys.replies(workspaceId, rootCommentId);+ return fetchTopicCommentReplies(key as readonly string[]).then(async (page) => {+ await populateCache(key, page, { revalidate: false });+ return page;+ });+};++export const useTopicCommentSummary = (topicId?: string | null) => {+ const workspaceId = useActiveWorkspaceId();+ const pendingComments = useTopicCommentStore(+ topicCommentSelectors.summaryPendingComments(workspaceId, topicId),+ );+ const pendingDeletes = useTopicCommentStore(+ topicCommentSelectors.summaryPendingDeletes(workspaceId, topicId),+ );+ const pendingRestores = useTopicCommentStore(+ topicCommentSelectors.summaryPendingRestores(workspaceId, topicId),+ );+ const response = useClientDataSWR<TopicCommentSummary>(+ topicId ? topicCommentKeys.summary(topicId) : null,+ () => topicCommentService.summary(topicId!),+ { dedupingInterval: 30_000 },+ );+ const data = useMemo(() => {+ if (+ !response.data ||+ (pendingComments.length === 0 && pendingDeletes.length === 0 && pendingRestores.length === 0)+ )+ return response.data;++ const countByMessage = { ...response.data.countByMessage };+ for (const { comment } of pendingComments) {+ if (comment.messageId)+ countByMessage[comment.messageId] = (countByMessage[comment.messageId] ?? 0) + 1;+ }+ for (const { affectsMessageCount, comment } of pendingDeletes) {+ if (affectsMessageCount && comment.messageId) {+ const nextCount = Math.max(0, (countByMessage[comment.messageId] ?? 0) - 1);+ if (nextCount === 0) delete countByMessage[comment.messageId];+ else countByMessage[comment.messageId] = nextCount;+ }+ }+ for (const { affectsMessageCount, comment } of pendingRestores) {+ if (affectsMessageCount && comment.messageId)+ countByMessage[comment.messageId] = (countByMessage[comment.messageId] ?? 0) + 1;+ }++ return {+ countByMessage,+ total: Math.max(+ 0,+ response.data.total ++ pendingComments.length -+ pendingDeletes.length ++ pendingRestores.length,+ ),+ };+ }, [pendingComments, pendingDeletes, pendingRestores, response.data]);++ return { ...response, data };+};++export const useMessageCommentCount = (messageId: string) => {+ const workspaceId = useActiveWorkspaceId();+ const topicId = useChatStore((s) => s.activeTopicId);+ const { data } = useTopicCommentSummary(workspaceId ? topicId : undefined);++ return {+ count: data?.countByMessage[messageId] ?? 0,+ topicId: workspaceId ? topicId : null,+ };+};++export const useTopicCommentDetail = (+ commentId?: string | null,+ fallbackData?: TopicCommentItem,+) => {+ const optimisticMutation = useTopicCommentStore(+ topicCommentSelectors.optimisticMutation(commentId),+ );+ const response = useClientDataSWR(+ commentId ? topicCommentKeys.detail(commentId) : null,+ () => topicCommentService.get(commentId!),+ { fallbackData },+ );+ const isDeleting =+ optimisticMutation?.kind === 'delete' && optimisticMutation.deleteMode === 'hard';++ return {+ ...response,+ data:+ isDeleting && !optimisticMutation?.pending+ ? undefined+ : (optimisticMutation?.comment ?? response.data),+ isDeleting,+ };+};++export const usePrefetchTopicCommentsOnTopicLoad = (topicId: string | null | undefined) => {+ const workspaceId = useActiveWorkspaceId();+ const { mutate: populateCache } = useSWRConfig();+ const topicParams = topicId && workspaceId ? { topicId, workspaceId } : undefined;++ useClientDataSWR(+ topicParams ? topicCommentKeys.warmup(topicParams.workspaceId, topicParams.topicId) : null,+ topicParams+ ? async () => {+ // Let the initial topic/message queries flush their tRPC batch first so this+ // background warmup starts immediately without delaying the primary payload.+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ const page = await preloadTopicCommentThreads(+ populateCache,+ topicParams.workspaceId,+ topicParams.topicId,+ );+ const rootCommentIds = page.items.flatMap(({ replyCount, root }) =>+ replyCount > 0 ? [root.id] : [],+ );+ for (let index = 0; index < rootCommentIds.length; index += PREFETCH_CONCURRENCY) {+ await Promise.all(+ rootCommentIds+ .slice(index, index + PREFETCH_CONCURRENCY)+ .map((rootCommentId) =>+ preloadTopicCommentReplies(populateCache, topicParams.workspaceId, rootCommentId),+ ),+ );+ }+ return true;+ }+ : null,+ {+ revalidateOnFocus: false,+ },+ );+};++export const useTopicCommentReplyCount = (+ rootCommentId: string | null | undefined,+ remoteCount: number,+) => {+ const mutations = useTopicCommentStore(+ topicCommentSelectors.optimisticReplyCountMutations(rootCommentId),+ );+ const removeOptimisticReplyCountMutation = useTopicCommentStore(+ (s) => s.removeOptimisticReplyCountMutation,+ );+ useEffect(() => {+ if (!areReplyCountMutationsReconciled(mutations, remoteCount)) return;+ for (const mutation of mutations) {+ removeOptimisticReplyCountMutation(mutation.id);+ }+ }, [mutations, remoteCount, removeOptimisticReplyCountMutation]);++ return useMemo(() => resolveReplyCount(remoteCount, mutations), [mutations, remoteCount]);+};++export const useTopicCommentThreads = (topicId?: string | null, messageId?: string) => {+ const workspaceId = useActiveWorkspaceId();+ const { cache } = useSWRConfig();+ const { data: summary } = useTopicCommentSummary(workspaceId ? topicId : undefined);+ const optimisticComments = useTopicCommentStore(+ topicCommentSelectors.optimisticThreads(workspaceId, topicId, messageId),+ );+ const optimisticMutations = useTopicCommentStore(+ topicCommentSelectors.optimisticThreadMutations(workspaceId, topicId, messageId),+ );+ const optimisticReplyCountMutations = useTopicCommentStore(+ topicCommentSelectors.optimisticReplyCountMutationsByTopic(workspaceId, topicId),+ );+ const removeOptimisticComment = useTopicCommentStore((s) => s.removeOptimisticComment);+ const removeOptimisticMutation = useTopicCommentStore((s) => s.removeOptimisticMutation);+ const removeOptimisticReplyCountMutation = useTopicCommentStore(+ (s) => s.removeOptimisticReplyCountMutation,+ );+ const isKnownEmpty = Boolean(+ summary && (messageId ? (summary.countByMessage[messageId] ?? 0) === 0 : summary.total === 0),+ );+ const firstPageKey =+ topicId && workspaceId+ ? unstable_serialize(topicCommentKeys.threads(workspaceId, topicId, messageId))+ : undefined;+ const cachedFirstPage = firstPageKey+ ? (cache.get(firstPageKey)?.data as TopicCommentThreadPage | undefined)+ : undefined;+ const getKey = useCallback(+ (_index: number, previous: TopicCommentThreadPage | null) => {+ if (!topicId || !workspaceId || previous?.nextCursor === null) return null;+ return topicCommentKeys.threads(+ workspaceId,+ topicId,+ messageId,+ previous?.nextCursor ?? undefined,+ );+ },+ [messageId, topicId, workspaceId],+ );+ const response = useSWRInfinite<TopicCommentThreadPage>(getKey, fetchTopicCommentThreads, {+ fallbackData: isKnownEmpty+ ? EMPTY_TOPIC_COMMENT_THREAD_PAGES+ : cachedFirstPage+ ? [cachedFirstPage]+ : undefined,+ revalidateFirstPage: false,+ revalidateOnMount: true,+ });+ const data = response.data;+ useEffect(() => {+ if (!data || optimisticComments.length === 0) return;+ const remoteClientKeys = new Set(+ data.flatMap((page) => page?.items.map(({ root }) => topicCommentClientKey(root)) ?? []),+ );+ for (const { comment, targetKey } of optimisticComments) {+ if (remoteClientKeys.has(topicCommentClientKey(comment))) {+ removeOptimisticComment(targetKey, comment.clientId);+ }+ }+ }, [data, optimisticComments, removeOptimisticComment]);+ const remoteItems = data?.flatMap((page) => page?.items ?? []) ?? [];+ useEffect(() => {+ if (!data || optimisticMutations.length === 0) return;+ const remoteById = new Map(remoteItems.map(({ root }) => [root.id, root]));+ for (const mutation of optimisticMutations) {+ if (isOptimisticMutationReconciled(mutation, remoteById.get(mutation.comment.id))) {+ removeOptimisticMutation(mutation.comment.id);+ }+ }+ }, [optimisticMutations, remoteItems, removeOptimisticMutation]);+ useEffect(() => {+ if (!data || optimisticReplyCountMutations.length === 0) return;+ const remoteCountByRootId = new Map(+ remoteItems.map(({ replyCount, root }) => [root.id, replyCount]),+ );+ const mutationsByRootId = new Map<string, OptimisticTopicCommentReplyCountMutation[]>();+ for (const mutation of optimisticReplyCountMutations) {+ const mutations = mutationsByRootId.get(mutation.rootCommentId) ?? [];+ mutations.push(mutation);+ mutationsByRootId.set(mutation.rootCommentId, mutations);+ }+ for (const [rootCommentId, mutations] of mutationsByRootId) {+ const remoteCount = remoteCountByRootId.get(rootCommentId);+ if (remoteCount !== undefined && areReplyCountMutationsReconciled(mutations, remoteCount)) {+ for (const mutation of mutations) removeOptimisticReplyCountMutation(mutation.id);+ }+ }+ }, [data, optimisticReplyCountMutations, remoteItems, removeOptimisticReplyCountMutation]);+ const remoteClientKeys = new Set(remoteItems.map(({ root }) => topicCommentClientKey(root)));+ const mutationById = new Map(+ optimisticMutations.map((mutation) => [mutation.comment.id, mutation]),+ );+ const items = [+ ...optimisticComments+ .filter(({ comment }) => !remoteClientKeys.has(topicCommentClientKey(comment)))+ .flatMap(({ comment }) => {+ const mutation = mutationById.get(comment.id);+ if (mutation?.kind === 'delete' && mutation.deleteMode === 'hard') return [];+ return [+ {+ replyCount: resolveReplyCount(+ 0,+ optimisticReplyCountMutations.filter(+ ({ rootCommentId }) => rootCommentId === comment.id,+ ),+ ),+ root: mutation?.comment ?? comment,+ },+ ];+ }),+ ...remoteItems.flatMap((thread) => {+ const mutation = mutationById.get(thread.root.id);+ if (mutation?.kind === 'delete' && mutation.deleteMode === 'hard') return [];+ return [+ {+ ...thread,+ replyCount: resolveReplyCount(+ thread.replyCount,+ optimisticReplyCountMutations.filter(+ ({ rootCommentId }) => rootCommentId === thread.root.id,+ ),+ ),+ root: mutation?.comment ?? thread.root,+ },+ ];+ }),+ ];+ const pendingCommentIds = new Set(+ optimisticComments.filter(({ pending }) => pending).map(({ comment }) => comment.id),+ );+ const lastPage = data?.findLast(Boolean);+ const hasLoadedPages = data !== undefined || optimisticComments.length > 0;+ const isInitialError = Boolean(response.error) && !hasLoadedPages;+ const isLoadingInitial = !response.error && response.isLoading && !hasLoadedPages;+ const isLoadingMore =+ !response.error &&+ hasLoadedPages &&+ response.size > 0 &&+ typeof data?.[response.size - 1] === 'undefined';++ return {+ ...response,+ hasMore: !response.error && (lastPage ? lastPage.nextCursor !== null : false),+ isInitialError,+ isLoadingInitial,+ isLoadingMore,+ isRetrying: Boolean(response.error) && response.isValidating,+ items,+ loadMore: () => response.setSize((size) => size + 1),+ pendingCommentIds,+ reload: () => response.mutate(),+ };+};++export const useTopicCommentReplies = (+ rootCommentId?: string | null,+ initialReplyCount?: number,+) => {+ const workspaceId = useActiveWorkspaceId();+ const { cache } = useSWRConfig();+ const optimisticComments = useTopicCommentStore(+ topicCommentSelectors.optimisticReplies(workspaceId, rootCommentId),+ );+ const optimisticMutations = useTopicCommentStore(+ topicCommentSelectors.optimisticReplyMutations(workspaceId, rootCommentId),+ );+ const removeOptimisticComment = useTopicCommentStore((s) => s.removeOptimisticComment);+ const removeOptimisticMutation = useTopicCommentStore((s) => s.removeOptimisticMutation);+ const getKey = useCallback(+ (_index: number, previous: TopicCommentReplyPage | null) => {+ if (!rootCommentId || !workspaceId || previous?.nextCursor === null) return null;+ return topicCommentKeys.replies(+ workspaceId,+ rootCommentId,+ previous?.nextCursor ?? undefined,+ );+ },+ [rootCommentId, workspaceId],+ );+ const firstPageKey =+ rootCommentId && workspaceId+ ? unstable_serialize(topicCommentKeys.replies(workspaceId, rootCommentId))+ : undefined;+ const cachedFirstPage = firstPageKey+ ? (cache.get(firstPageKey)?.data as TopicCommentReplyPage | undefined)+ : undefined;+ const response = useSWRInfinite<TopicCommentReplyPage>(getKey, fetchTopicCommentReplies, {+ fallbackData:+ initialReplyCount === 0+ ? [{ items: [], nextCursor: null }]+ : cachedFirstPage+ ? [cachedFirstPage]+ : undefined,+ revalidateFirstPage: false,+ revalidateOnMount: true,+ });+ const data = response.data;+ useEffect(() => {+ if (!data || optimisticComments.length === 0) return;+ const remoteClientKeys = new Set(+ data.flatMap((page) => page?.items.map(topicCommentClientKey) ?? []),+ );+ for (const { comment, targetKey } of optimisticComments) {+ if (remoteClientKeys.has(topicCommentClientKey(comment))) {+ removeOptimisticComment(targetKey, comment.clientId);+ }+ }+ }, [data, optimisticComments, removeOptimisticComment]);+ const remoteItems = data?.flatMap((page) => page?.items ?? []) ?? [];+ useEffect(() => {+ if (!data || optimisticMutations.length === 0) return;+ const remoteById = new Map(remoteItems.map((comment) => [comment.id, comment]));+ for (const mutation of optimisticMutations) {+ if (isOptimisticMutationReconciled(mutation, remoteById.get(mutation.comment.id))) {+ removeOptimisticMutation(mutation.comment.id);+ }+ }+ }, [optimisticMutations, remoteItems, removeOptimisticMutation]);+ const remoteClientKeys = new Set(remoteItems.map(topicCommentClientKey));+ const mutationById = new Map(+ optimisticMutations.map((mutation) => [mutation.comment.id, mutation]),+ );+ const items = [+ ...remoteItems.flatMap((comment) => {+ const mutation = mutationById.get(comment.id);+ if (mutation?.kind === 'delete' && mutation.deleteMode === 'hard') return [];+ return [mutation?.comment ?? comment];+ }),+ ...optimisticComments+ .filter(({ comment }) => !remoteClientKeys.has(topicCommentClientKey(comment)))+ .flatMap(({ comment }) => {+ const mutation = mutationById.get(comment.id);+ if (mutation?.kind === 'delete' && mutation.deleteMode === 'hard') return [];+ return [mutation?.comment ?? comment];+ }),+ ];+ const pendingCommentIds = new Set(+ optimisticComments.filter(({ pending }) => pending).map(({ comment }) => comment.id),+ );+ const lastPage = data?.findLast(Boolean);+ const hasLoadedPages = data !== undefined || optimisticComments.length > 0;+ const isInitialError = Boolean(response.error) && !hasLoadedPages;+ const isLoadingInitial = !response.error && response.isLoading && !hasLoadedPages;+ const isLoadingMore =+ !response.error &&+ hasLoadedPages &&+ response.size > 0 &&+ typeof data?.[response.size - 1] === 'undefined';++ return {+ ...response,+ hasMore: !response.error && (lastPage ? lastPage.nextCursor !== null : false),+ isInitialError,+ isLoadingInitial,+ isLoadingMore,+ isRetrying: Boolean(response.error) && response.isValidating,+ items,+ loadMore: () => response.setSize((size) => size + 1),+ pendingCommentIds,+ reload: () => response.mutate(),+ };+};++export const useTopicCommentMutations = () => {+ const workspaceId = useActiveWorkspaceId();+ const user = useUserStore(userProfileSelectors.userProfile);+ const [removeOptimisticMutation, upsertOptimisticMutation] = useTopicCommentStore((s) => [+ s.removeOptimisticMutation,+ s.upsertOptimisticMutation,+ ]);+ const [removeOptimisticReplyCountMutation, upsertOptimisticReplyCountMutation] =+ useTopicCommentStore((s) => [+ s.removeOptimisticReplyCountMutation,+ s.upsertOptimisticReplyCountMutation,+ ]);+ const [removeOptimisticComment, upsertOptimisticComment] = useTopicCommentStore((s) => [+ s.removeOptimisticComment,+ s.upsertOptimisticComment,+ ]);+ const [creating, setCreating] = useState(false);+ const [mutatingIds, setMutatingIds] = useState<ReadonlySet<string>>(new Set());++ const create = useCallback(+ async (input: CreateTopicCommentInput, options: { rootReplyCount?: number } = {}) => {+ setCreating(true);+ const targetKey = workspaceId+ ? createTopicCommentDraftKey({+ messageId: input.messageId,+ parentCommentId: input.parentCommentId,+ topicId: input.topicId,+ workspaceId,+ })+ : undefined;+ const now = new Date();+ const optimisticComment: TopicCommentItem | undefined =+ targetKey && user && workspaceId+ ? {+ anchorPreview: null,+ author: {+ avatar: user.avatar ?? null,+ fullName: user.fullName ?? null,+ id: user.id,+ status: 'active',+ username: user.username ?? null,+ },+ authorUserId: user.id,+ canDelete: false,+ canEdit: false,+ canRestore: false,+ clientId: input.clientId,+ content: input.content,+ createdAt: now,+ deletedAt: null,+ editorData: input.editorData ?? null,+ id: `optimistic-topic-comment-${input.clientId}`,+ messageId: input.messageId ?? null,+ moderatedAt: null,+ moderationExpiresAt: null,+ moderationIsOwn: false,+ parentCommentId: input.parentCommentId ?? null,+ topicId: input.topicId,+ updatedAt: now,+ workspaceId,+ }+ : undefined;++ if (targetKey && optimisticComment) {+ upsertOptimisticComment({+ comment: optimisticComment,+ pending: true,+ targetKey,+ });+ }+ const replyCountMutation =+ input.parentCommentId && workspaceId && options.rootReplyCount !== undefined+ ? {+ baselineCount: options.rootReplyCount,+ delta: 1 as const,+ id: input.clientId,+ pending: true,+ rootCommentId: input.parentCommentId,+ topicId: input.topicId,+ workspaceId,+ }+ : undefined;+ if (replyCountMutation) upsertOptimisticReplyCountMutation(replyCountMutation);++ try {+ const result = await topicCommentService.create(input);+ if (targetKey && optimisticComment) {+ if (!result.isDuplicate) {+ void mutate(+ topicCommentKeys.summary(input.topicId),+ (current: TopicCommentSummary | undefined) => {+ if (!current) return current;+ const countByMessage = { ...current.countByMessage };+ if (input.messageId) {+ countByMessage[input.messageId] = (countByMessage[input.messageId] ?? 0) + 1;+ }+ return { countByMessage, total: current.total + 1 };+ },+ { revalidate: true },+ ).catch(() => undefined);+ } else {+ void mutate(topicCommentKeys.summary(input.topicId)).catch(() => undefined);+ }+ upsertOptimisticComment({+ comment: result.comment,+ pending: false,+ targetKey,+ });+ }+ if (replyCountMutation) {+ if (result.isDuplicate) removeOptimisticReplyCountMutation(replyCountMutation.id);+ else upsertOptimisticReplyCountMutation({ ...replyCountMutation, pending: false });+ }+ return result;+ } catch (error) {+ if (targetKey) removeOptimisticComment(targetKey, input.clientId);+ if (replyCountMutation) removeOptimisticReplyCountMutation(replyCountMutation.id);+ throw error;+ } finally {+ setCreating(false);+ }+ },+ [+ removeOptimisticComment,+ removeOptimisticReplyCountMutation,+ upsertOptimisticComment,+ upsertOptimisticReplyCountMutation,+ user,+ workspaceId,+ ],+ );++ const runForId = useCallback(async <T>(id: string, action: () => Promise<T>) => {+ setMutatingIds((current) => new Set(current).add(id));+ try {+ return await action();+ } finally {+ setMutatingIds((current) => {+ const next = new Set(current);+ next.delete(id);+ return next;+ });+ }+ }, []);++ const update = useCallback(+ (input: UpdateTopicCommentInput, currentComment: TopicCommentItem) =>+ runForId(input.id, async () => {+ const previousMutation = useTopicCommentStore.getState().optimisticMutations[input.id];+ const optimisticComment: TopicCommentItem = {+ ...currentComment,+ content: input.content ?? currentComment.content,+ editorData: input.editorData ?? currentComment.editorData,+ updatedAt: new Date(),+ };+ upsertOptimisticMutation({+ comment: optimisticComment,+ kind: 'update',+ pending: true,+ });++ try {+ const result = await topicCommentService.update(input);+ upsertOptimisticMutation({ comment: result, kind: 'update', pending: false });+ void mutate(topicCommentKeys.detail(result.id), result, { revalidate: false }).catch(+ () => undefined,+ );+ return result;+ } catch (error) {+ if (previousMutation) upsertOptimisticMutation(previousMutation);+ else removeOptimisticMutation(input.id);+ throw error;+ }+ }),+ [removeOptimisticMutation, runForId, upsertOptimisticMutation],+ );+ const remove = useCallback(+ (+ comment: TopicCommentItem,+ optimisticDeleteMode: 'hard' | 'soft' = 'hard',+ options: { rootReplyCount?: number } = {},+ ) =>+ runForId(comment.id, async () => {+ const previousMutation = useTopicCommentStore.getState().optimisticMutations[comment.id];+ const createDeletedComment = (mode: 'hard' | 'moderated' | 'soft'): TopicCommentItem =>+ mode === 'moderated'+ ? {+ ...comment,+ canDelete: false,+ canEdit: false,+ canRestore: true,+ moderatedAt: new Date(),+ moderationExpiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),+ moderationIsOwn: false,+ }+ : mode === 'soft'+ ? {+ ...comment,+ canDelete: false,+ canEdit: false,+ canRestore: false,+ content: '',+ deletedAt: new Date(),+ editorData: null,+ updatedAt: new Date(),+ }+ : comment;+ const initialDeleteMode =+ comment.canDelete && !comment.canEdit ? 'moderated' : optimisticDeleteMode;+ upsertOptimisticMutation({+ affectsMessageCount: optimisticDeleteMode === 'hard',+ comment: createDeletedComment(initialDeleteMode),+ deleteMode: initialDeleteMode,+ kind: 'delete',+ pending: true,+ });+ const replyCountMutation =+ comment.parentCommentId && workspaceId && options.rootReplyCount !== undefined+ ? {+ baselineCount: options.rootReplyCount,+ delta: -1 as const,+ id: `delete:${comment.id}`,+ pending: true,+ rootCommentId: comment.parentCommentId,+ topicId: comment.topicId,+ workspaceId,+ }+ : undefined;+ if (replyCountMutation) upsertOptimisticReplyCountMutation(replyCountMutation);++ try {+ const result = await topicCommentService.delete(comment.id);+ const confirmedMutation: OptimisticTopicCommentMutation = {+ affectsMessageCount: optimisticDeleteMode === 'hard',+ comment:+ result.mode === 'moderated' ? result.comment : createDeletedComment(result.mode),+ deleteMode: result.mode,+ kind: 'delete',+ pending: true,+ };+ upsertOptimisticMutation(confirmedMutation);+ void mutate(+ topicCommentKeys.summary(comment.topicId),+ (current: TopicCommentSummary | undefined) => {+ if (!current) return current;+ const countByMessage = { ...current.countByMessage };+ const removesMessageCount =+ result.mode === 'hard' ||+ (result.mode === 'moderated' && optimisticDeleteMode === 'hard');+ if (removesMessageCount && comment.messageId) {+ const nextCount = Math.max(0, (countByMessage[comment.messageId] ?? 0) - 1);+ if (nextCount > 0) countByMessage[comment.messageId] = nextCount;+ else delete countByMessage[comment.messageId];+ }+ return { countByMessage, total: Math.max(0, current.total - 1) };+ },+ { revalidate: true },+ ).catch(() => undefined);+ upsertOptimisticMutation({ ...confirmedMutation, pending: false });+ if (replyCountMutation) {+ upsertOptimisticReplyCountMutation({ ...replyCountMutation, pending: false });+ }+ void mutate(+ topicCommentKeys.detail(comment.id),+ result.mode === 'hard' ? undefined : confirmedMutation.comment,+ { revalidate: false },+ ).catch(() => undefined);+ return result;+ } catch (error) {+ if (previousMutation) upsertOptimisticMutation(previousMutation);+ else removeOptimisticMutation(comment.id);+ if (replyCountMutation) removeOptimisticReplyCountMutation(replyCountMutation.id);+ throw error;+ }+ }),+ [+ removeOptimisticMutation,+ removeOptimisticReplyCountMutation,+ runForId,+ upsertOptimisticMutation,+ upsertOptimisticReplyCountMutation,+ workspaceId,+ ],+ );++ const restore = useCallback(+ (comment: TopicCommentItem, options: { rootReplyCount?: number } = {}) =>+ runForId(comment.id, async () => {+ const previousMutation = useTopicCommentStore.getState().optimisticMutations[comment.id];+ const optimisticComment: TopicCommentItem = {+ ...comment,+ canDelete: true,+ canRestore: false,+ moderatedAt: null,+ moderationExpiresAt: null,+ moderationIsOwn: false,+ };+ upsertOptimisticMutation({+ affectsMessageCount: options.rootReplyCount === 0,+ comment: optimisticComment,+ kind: 'restore',+ pending: true,+ });++ try {+ const result = await topicCommentService.restore(comment.id);+ upsertOptimisticMutation({+ affectsMessageCount: options.rootReplyCount === 0,+ comment: result,+ kind: 'restore',+ pending: false,+ });+ void mutate(+ topicCommentKeys.summary(comment.topicId),+ (current: TopicCommentSummary | undefined) => {+ if (!current) return current;+ const countByMessage = { ...current.countByMessage };+ if (comment.messageId && options.rootReplyCount === 0) {+ countByMessage[comment.messageId] = (countByMessage[comment.messageId] ?? 0) + 1;+ }+ return { countByMessage, total: current.total + 1 };+ },+ { revalidate: true },+ ).catch(() => undefined);+ void mutate(topicCommentKeys.detail(comment.id), result, { revalidate: false }).catch(+ () => undefined,+ );+ return result;+ } catch (error) {+ if (previousMutation) upsertOptimisticMutation(previousMutation);+ else removeOptimisticMutation(comment.id);+ throw error;+ }+ }),+ [removeOptimisticMutation, runForId, upsertOptimisticMutation],+ );++ return { create, creating, mutatingIds, remove, restore, update };+};diff --git a/src/features/TopicComment/useTopicCommentDeepLink.test.ts b/src/features/TopicComment/useTopicCommentDeepLink.test.tsnew file mode 100644index 00000000000..6c25cdfd01d--- /dev/null+++ b/src/features/TopicComment/useTopicCommentDeepLink.test.ts@@ -0,0 +1,64 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useTopicCommentDeepLink } from './useTopicCommentDeepLink';++const mocks = vi.hoisted(() => ({+ location: {+ hash: '#section',+ pathname: '/acme/agent/agent-1/topic-1',+ search: '?comment=reply-1&commentThread=root-1&source=inbox',+ },+ navigate: vi.fn(),+ openTopicCommentThread: vi.fn(),+ openTopicComments: vi.fn(),+}));++vi.mock('react-router', () => ({ useLocation: () => mocks.location }));+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => mocks.navigate,+}));+vi.mock('@/store/chat', () => ({+ useChatStore: {+ getState: () => ({+ openTopicCommentThread: mocks.openTopicCommentThread,+ openTopicComments: mocks.openTopicComments,+ }),+ },+}));++describe('useTopicCommentDeepLink', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.location.search = '?comment=reply-1&commentThread=root-1&source=inbox';+ });++ it('opens the target thread, focuses the linked comment and consumes only its query params', async () => {+ renderHook(() => useTopicCommentDeepLink('topic-1'));++ await waitFor(() => expect(mocks.openTopicComments).toHaveBeenCalledWith('topic-1'));+ expect(mocks.openTopicCommentThread).toHaveBeenCalledWith(+ 'topic-1',+ 'root-1',+ undefined,+ undefined,+ 'reply-1',+ );+ expect(mocks.navigate).toHaveBeenCalledWith(+ '/acme/agent/agent-1/topic-1?source=inbox#section',+ { replace: true },+ );+ });++ it('does nothing without a comment thread target', () => {+ mocks.location.search = '?source=inbox';++ renderHook(() => useTopicCommentDeepLink('topic-1'));++ expect(mocks.openTopicComments).not.toHaveBeenCalled();+ expect(mocks.navigate).not.toHaveBeenCalled();+ });+});diff --git a/src/features/TopicComment/useTopicCommentDeepLink.ts b/src/features/TopicComment/useTopicCommentDeepLink.tsnew file mode 100644index 00000000000..76f2373dd6a--- /dev/null+++ b/src/features/TopicComment/useTopicCommentDeepLink.ts@@ -0,0 +1,39 @@+import { useEffect, useRef } from 'react';+import { useLocation } from 'react-router';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useChatStore } from '@/store/chat';++const COMMENT_QUERY = 'comment';+const COMMENT_THREAD_QUERY = 'commentThread';++/** Opens a notification deep link once topic route hydration has completed. */+export const useTopicCommentDeepLink = (topicId?: string) => {+ const location = useLocation();+ const navigate = useWorkspaceAwareNavigate();+ const handledRef = useRef<string | undefined>(undefined);++ useEffect(() => {+ if (!topicId) return;++ const searchParams = new URLSearchParams(location.search);+ const rootCommentId = searchParams.get(COMMENT_THREAD_QUERY);+ if (!rootCommentId) return;++ const focusCommentId = searchParams.get(COMMENT_QUERY) ?? rootCommentId;+ const deepLinkKey = `${topicId}:${rootCommentId}:${focusCommentId}`;+ if (handledRef.current === deepLinkKey) return;+ handledRef.current = deepLinkKey;++ const { openTopicComments, openTopicCommentThread } = useChatStore.getState();+ openTopicComments(topicId);+ openTopicCommentThread(topicId, rootCommentId, undefined, undefined, focusCommentId);++ searchParams.delete(COMMENT_QUERY);+ searchParams.delete(COMMENT_THREAD_QUERY);+ const search = searchParams.toString();+ navigate(`${location.pathname}${search ? `?${search}` : ''}${location.hash}`, {+ replace: true,+ });+ }, [location.hash, location.pathname, location.search, navigate, topicId]);+};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 32d1823f9f9..674118b9a45 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -134,6 +134,36 @@ export const topicKeys = {]),};+// ---- topic comment ------------------------------------------------------+export const topicCommentKeys = {+ detail: def('topicComment:detail', (commentId: string) => ['topicComment:detail', commentId]),+ replies: def(+ 'topicComment:replies',+ (workspaceId: string | null, rootCommentId: string, cursor?: string) => [+ 'topicComment:replies',+ workspaceId ?? '',+ rootCommentId,+ cursor ?? '',+ ],+ ),+ summary: def('topicComment:summary', (topicId: string) => ['topicComment:summary', topicId]),+ threads: def(+ 'topicComment:threads',+ (workspaceId: string | null, topicId: string, messageId?: string, cursor?: string) => [+ 'topicComment:threads',+ workspaceId ?? '',+ topicId,+ messageId ?? '',+ cursor ?? '',+ ],+ ),+ warmup: def('topicComment:warmup', (workspaceId: string, topicId: string) => [+ 'topicComment:warmup',+ workspaceId,+ topicId,+ ]),+};+// ---- agent --------------------------------------------------------------export const agentKeys = {/** Sidebar agent list. */@@ -1093,6 +1123,7 @@ export const swrKeys = {thread: threadKeys,tool: toolKeys,topic: topicKeys,+ topicComment: topicCommentKeys,topicAction: topicActionKeys,user: userKeys,userMemory: userMemoryKeys,diff --git a/src/routes/(main)/agent/_layout/PortalAutoCollapse.tsx b/src/routes/(main)/agent/_layout/PortalAutoCollapse.tsxindex 5290154061f..e87b0a9678e 100644--- a/src/routes/(main)/agent/_layout/PortalAutoCollapse.tsx+++ b/src/routes/(main)/agent/_layout/PortalAutoCollapse.tsx@@ -11,7 +11,7 @@ import { useGlobalStore } from '@/store/global';* Restores the previous state when Portal closes.*/const PortalAutoCollapse = memo(() => {- const showPortal = useChatStore(chatPortalSelectors.showPortal);+ const showPortal = useChatStore(chatPortalSelectors.showStandalonePortal);const savedShowLeftPanelRef = useRef<boolean | null>(null);useEffect(() => {diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsxindex 12ac395573f..2e736b530c3 100644--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx@@ -5,6 +5,7 @@ import { memo, useLayoutEffect, useRef } from 'react';import { useLocation, useParams, useSearchParams } from 'react-router';import { useClearActiveTopicUnread } from '@/features/Conversation/hooks';+import { useTopicCommentDeepLink } from '@/features/TopicComment/useTopicCommentDeepLink';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useQueryState } from '@/hooks/useQueryParam';import { useChatStore } from '@/store/chat';@@ -35,6 +36,7 @@ const ChatHydration = memo(() => {// switchTopic, so clear any lingering persisted unread once the topic loads.useClearActiveTopicUnread();useFetchTopicLinkedPullRequest(activeAgentId ? routeTopicId : undefined, topicMetadata);+ useTopicCommentDeepLink(routeTopicId);useLayoutEffect(() => {const target = routeTopicId ?? null;diff --git a/src/routes/(main)/agent/features/Conversation/ExposeMainEditor.tsx b/src/routes/(main)/agent/features/Conversation/ExposeMainEditor.tsxindex 771fcadb50c..4645810191e 100644--- a/src/routes/(main)/agent/features/Conversation/ExposeMainEditor.tsx+++ b/src/routes/(main)/agent/features/Conversation/ExposeMainEditor.tsx@@ -1,18 +1,30 @@'use client';-import { memo } from 'react';+import { memo, useEffect } from 'react';import { useConversationStore } from '@/features/Conversation/store';+import { useChatStore } from '@/store/chat';import { useExposeMainEditor } from './useExposeMainEditor';/**- * Renders nothing — mounts the active composer's editor on `window.__mainEditor`.+ * Renders nothing — exposes the active main conversation's imperative handles.* Must live inside ConversationProvider, which is why ConversationArea can't call the hook* directly from its own body.*/const ExposeMainEditor = memo(() => {useExposeMainEditor(useConversationStore((s) => s.editor));+ const scrollToIndex = useConversationStore((s) => s.scrollToIndex);++ useEffect(() => {+ useChatStore.setState({ mainConversationScrollToIndex: scrollToIndex });++ return () => {+ if (useChatStore.getState().mainConversationScrollToIndex === scrollToIndex) {+ useChatStore.setState({ mainConversationScrollToIndex: null });+ }+ };+ }, [scrollToIndex]);return null;});diff --git a/src/routes/(main)/agent/features/Conversation/Header/index.tsx b/src/routes/(main)/agent/features/Conversation/Header/index.tsxindex b88c689e78a..5b80fd4e992 100644--- a/src/routes/(main)/agent/features/Conversation/Header/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/index.tsx@@ -6,6 +6,7 @@ import { memo } from 'react';import NavHeader from '@/features/NavHeader';import OpenInAppButton from '@/features/OpenInAppButton';+import TopicCommentButton from '@/features/TopicComment/TopicCommentButton';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -125,6 +126,7 @@ const Header = memo(() => {{isLocalSystemEnabled && (<OpenInAppButton workingDirectory={effectiveWorkingDirectory} />)}+ <TopicCommentButton /><ShareButton /><TerminalToggle /><WorkingPanelToggle />diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsxindex 2d2a10ae8fd..31f183db1f7 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx@@ -72,6 +72,14 @@ const dropdownMenuState = vi.hoisted(() => ({onOpenChangeComplete: undefined as ((open: boolean) => void) | undefined,}));+const workspace = vi.hoisted(() => ({ id: undefined as string | undefined }));++const chatStore = vi.hoisted(() => ({+ activeTopicId: undefined as string | undefined,+ openTopicComments: vi.fn(),+ portalStack: [] as Array<{ topicId?: string; type: string }>,+}));+const globalStore = vi.hoisted(() => ({updateSystemStatus: vi.fn(),toggleRightPanel: vi.fn(),@@ -135,6 +143,9 @@ vi.mock('../Overview', () => ({</>),}));+vi.mock('@/features/Portal/TopicComments/Sidebar', () => ({+ default: () => <div data-testid="comments" />,+}));vi.mock('@/store/agent', () => ({getAgentStoreState: () => agentStore,@@ -161,7 +172,13 @@ vi.mock('@/store/global/selectors', () => ({},}));vi.mock('@/store/electron', () => ({ useElectronStore: () => undefined }));-vi.mock('@/store/chat', () => ({ useChatStore: () => undefined }));+vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (state: typeof chatStore) => unknown) => selector(chatStore),+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => workspace.id,+}));vi.mock('@/business/client/features/WorkingSidebarTabs', () => ({useBusinessWorkingSidebarTabs: () => businessTabs.current,@@ -305,6 +322,10 @@ beforeEach(() => {paramsSectionState.suspend = false;localStorageState.openTabsByContext = { 'draft:default:none': ['params'] };localStorageState.pinnedTabsByAgent = {};+ workspace.id = undefined;+ chatStore.activeTopicId = undefined;+ chatStore.portalStack = [];+ chatStore.openTopicComments.mockReset();agentStore.activeAgentId = undefined;agentStore.isHeterogeneous = false;agentStore.rawAgencyConfig = undefined;@@ -855,4 +876,24 @@ describe('AgentWorkingSidebar — tab strip', () => {expect(screen.getByRole('button', { name: 'workingPanel.review.title' })).toBeInTheDocument();});});++ it('offers Comments for a workspace topic and opens it in this panel', () => {+ workspace.id = 'workspace-1';+ chatStore.activeTopicId = 'topic-1';++ render(<AgentWorkingSidebar />);+ fireEvent.click(screen.getByRole('button', { name: 'workingPanel.openMenu.title' }));+ const commentsItem = screen.getByRole('button', { name: 'topicComment.title' });++ fireEvent.click(commentsItem);++ expect(chatStore.openTopicComments).toHaveBeenCalledWith('topic-1');+ });++ it('hides Comments when there is no workspace topic', () => {+ render(<AgentWorkingSidebar />);+ fireEvent.click(screen.getByRole('button', { name: 'workingPanel.openMenu.title' }));++ expect(screen.queryByRole('button', { name: 'topicComment.title' })).not.toBeInTheDocument();+ });});diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsxindex 780f4b77aa0..bf5a6973547 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx@@ -12,6 +12,7 @@ import {Globe2Icon,GlobeIcon,LayoutDashboardIcon,+ MessageCircleIcon,PanelRightCloseIcon,PanelsTopLeftIcon,PinIcon,@@ -35,9 +36,11 @@ import {import { useTranslation } from 'react-i18next';import { useBusinessWorkingSidebarTabs } from '@/business/client/features/WorkingSidebarTabs';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';import { isDesktop } from '@/const/version';import { useRepoType } from '@/features/ChatInput/ControlBar/useRepoType';+import TopicCommentsSidebar from '@/features/Portal/TopicComments/Sidebar';import RightPanel from '@/features/RightPanel';import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';import { resolveExecutionTarget } from '@/helpers/executionTarget';@@ -48,6 +51,8 @@ import { useLocalStorageState } from '@/hooks/useLocalStorageState';import { useAgentStore } from '@/store/agent';import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';+import { PortalViewType } from '@/store/chat/slices/portal/initialState';import { useElectronStore } from '@/store/electron';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';@@ -173,7 +178,12 @@ const AgentWorkingSidebar = memo(() => {s.status.workingSidebarTabRequest,]);const activeAgentId = useAgentStore((s) => s.activeAgentId);- const topicId = useChatStore((s) => s.activeTopicId);+ const workspaceId = useActiveWorkspaceId();+ const [topicId, currentPortalView, openTopicComments] = useChatStore((s) => [+ s.activeTopicId,+ chatPortalSelectors.currentView(s),+ s.openTopicComments,+ ]);const isChatMode = useAgentStore((s) =>activeAgentId ? chatConfigByIdSelectors.isChatModeById(activeAgentId)(s) : false,);@@ -235,6 +245,13 @@ const AgentWorkingSidebar = memo(() => {);const businessTabs = useBusinessWorkingSidebarTabs({ activeAgentId, topicId });+ const commentsAvailable = !!workspaceId && !!topicId;+ const currentCommentTopicId =+ currentPortalView?.type === PortalViewType.TopicComments ||+ currentPortalView?.type === PortalViewType.TopicCommentThread+ ? currentPortalView.topicId+ : undefined;+ const isCurrentTopicComments = currentCommentTopicId === topicId;const tabDescriptors = useMemo<SidebarTabDescriptor[]>(() => [{ icon: SkillsIcon, key: 'skills', label: t('workingPanel.resources.filter.skills') },@@ -251,6 +268,9 @@ const AgentWorkingSidebar = memo(() => {{ icon: GlobeIcon, key: 'web', label: t('workingPanel.resources.filter.web') },]),{ icon: BoxesIcon, key: 'works', label: t('workingPanel.works.title') },+ ...(commentsAvailable+ ? [{ icon: MessageCircleIcon, key: 'comments', label: t('topicComment.title') }]+ : []),...(reviewAvailable? [{ icon: ClipboardListIcon, key: 'review', label: t('workingPanel.review.title') }]: []),@@ -275,7 +295,16 @@ const AgentWorkingSidebar = memo(() => {label: tab.label,})),],- [browserAvailable, businessTabs, filesAvailable, isHetero, paramsAvailable, reviewAvailable, t],+ [+ browserAvailable,+ businessTabs,+ commentsAvailable,+ filesAvailable,+ isHetero,+ paramsAvailable,+ reviewAvailable,+ t,+ ],);const availableTabs = useMemo(() => new Map(tabDescriptors.map((tab) => [tab.key, tab])),@@ -349,9 +378,20 @@ const AgentWorkingSidebar = memo(() => {if (tab !== 'overview') {updateOpenedTabs((current) => (current.includes(tab) ? current : [...current, tab]));}+ if (tab === 'comments' && topicId && !isCurrentTopicComments) {+ openTopicComments(topicId);+ return;+ }setWorkingSidebarTab(tab);},- [isAvailableTab, setWorkingSidebarTab, updateOpenedTabs],+ [+ isAvailableTab,+ isCurrentTopicComments,+ openTopicComments,+ setWorkingSidebarTab,+ topicId,+ updateOpenedTabs,+ ],);const openBrowserTab = useCallback(() => {@@ -375,6 +415,25 @@ const AgentWorkingSidebar = memo(() => {? storedTab: 'overview';+ useEffect(() => {+ if (+ activeTab !== 'comments' ||+ !topicId ||+ (!currentCommentTopicId && currentPortalView) ||+ isCurrentTopicComments+ )+ return;++ openTopicComments(topicId);+ }, [+ activeTab,+ currentCommentTopicId,+ currentPortalView,+ isCurrentTopicComments,+ openTopicComments,+ topicId,+ ]);+useEffect(() => {if (!tabRequest || lastTabRequestRef.current === tabRequest.nonce) return;if (tabRequest.tab !== 'overview' && !isAvailableTab(tabRequest.tab)) return;@@ -617,6 +676,7 @@ const AgentWorkingSidebar = memo(() => {'review','files','works',+ 'comments','skills','documents','web',@@ -749,6 +809,14 @@ const AgentWorkingSidebar = memo(() => {onOpenTab={openTab}/></Flexbox>+ {commentsAvailable && (+ <Flexbox+ className={activeTab === 'comments' ? styles.pane : styles.paneHidden}+ style={{ overflow: 'hidden' }}+ >+ <TopicCommentsSidebar />+ </Flexbox>+ )}{paramsAvailable && activeTab === 'params' && (<Flexbox className={styles.pane}><Suspensediff --git a/src/routes/(main)/agent/features/Portal/features/Portal.tsx b/src/routes/(main)/agent/features/Portal/features/Portal.tsxindex 50cff027de8..7b5c1234535 100644--- a/src/routes/(main)/agent/features/Portal/features/Portal.tsx+++ b/src/routes/(main)/agent/features/Portal/features/Portal.tsx@@ -41,7 +41,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({const PortalPanel = memo(({ children }: PropsWithChildren) => {const [showPortal, showToolUI, showArtifactUI, showThread, showTaskDetail, showAgentDetail] =useChatStore((s) => [- chatPortalSelectors.showPortal(s),+ chatPortalSelectors.showStandalonePortal(s),chatPortalSelectors.showPluginUI(s),chatPortalSelectors.showArtifactUI(s),portalThreadSelectors.showThread(s),diff --git a/src/routes/(main)/group/features/Conversation/ChatHydration/index.tsx b/src/routes/(main)/group/features/Conversation/ChatHydration/index.tsxindex 09d6cb413f8..2bfa4147e8a 100644--- a/src/routes/(main)/group/features/Conversation/ChatHydration/index.tsx+++ b/src/routes/(main)/group/features/Conversation/ChatHydration/index.tsx@@ -5,6 +5,7 @@ import { memo, useLayoutEffect, useRef } from 'react';import { useLocation, useParams, useSearchParams } from 'react-router';import { useClearActiveTopicUnread } from '@/features/Conversation/hooks';+import { useTopicCommentDeepLink } from '@/features/TopicComment/useTopicCommentDeepLink';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useQueryState } from '@/hooks/useQueryParam';import { useChatStore } from '@/store/chat';@@ -28,6 +29,7 @@ const ChatHydration = memo(() => {// Route hydration sets activeTopicId directly (below) instead of going through// switchTopic, so clear any lingering persisted unread once the topic loads.useClearActiveTopicUnread();+ useTopicCommentDeepLink(routeTopicId);useLayoutEffect(() => {const target = routeTopicId ?? null;diff --git a/src/routes/(mobile)/chat/features/ChatHeader/index.tsx b/src/routes/(mobile)/chat/features/ChatHeader/index.tsxindex a05d4a884c2..2d56473f952 100644--- a/src/routes/(mobile)/chat/features/ChatHeader/index.tsx+++ b/src/routes/(mobile)/chat/features/ChatHeader/index.tsx@@ -1,8 +1,10 @@'use client';+import { Flexbox } from '@lobehub/ui';import { ChatHeader } from '@lobehub/ui/mobile';import { memo, useState } from 'react';+import TopicCommentButton from '@/features/TopicComment/TopicCommentButton';import { useQueryRoute } from '@/hooks/useQueryRoute';import ShareButton from '@/routes/(main)/agent/features/Conversation/Header/ShareButton';@@ -16,8 +18,13 @@ const MobileHeader = memo(() => {<ChatHeadershowBackButtoncenter={<ChatHeaderTitle />}- right={<ShareButton mobile open={open} setOpen={setOpen} />}style={{ width: '100%' }}+ right={+ <Flexbox horizontal align={'center'} gap={4}>+ <TopicCommentButton mobile />+ <ShareButton mobile open={open} setOpen={setOpen} />+ </Flexbox>+ }onBackClick={() =>// `/agent` index redirects to `..` (mobile home / session list), preserving// workspace scope; the old `?session=` query was never read by the target.diff --git a/src/services/topicComment.ts b/src/services/topicComment.tsnew file mode 100644index 00000000000..f4965271ed9--- /dev/null+++ b/src/services/topicComment.ts@@ -0,0 +1,34 @@+import type {+ CreateTopicCommentInput,+ TopicCommentJson,+ UpdateTopicCommentInput,+} from '@lobechat/types';++import { lambdaClient } from '@/libs/trpc/client';++class TopicCommentService {+ create = (input: CreateTopicCommentInput) => lambdaClient.topicComment.create.mutate(input);++ delete = (id: string) => lambdaClient.topicComment.delete.mutate({ id });++ get = (id: string) => lambdaClient.topicComment.get.query({ id });++ listReplies = (params: { cursor?: string; limit?: number; rootCommentId: string }) =>+ lambdaClient.topicComment.listReplies.query(params);++ listThreads = (params: {+ cursor?: string;+ limit?: number;+ messageId?: string;+ topicId: string;+ }) => lambdaClient.topicComment.listThreads.query(params);++ restore = (id: string) => lambdaClient.topicComment.restore.mutate({ id });++ summary = (topicId: string) => lambdaClient.topicComment.summary.query({ topicId });++ update = (input: UpdateTopicCommentInput & { editorData?: TopicCommentJson }) =>+ lambdaClient.topicComment.update.mutate(input);+}++export const topicCommentService = new TopicCommentService();diff --git a/src/store/chat/slices/agentRun/initialState.ts b/src/store/chat/slices/agentRun/initialState.tsindex 95047f7b695..90df71c18df 100644--- a/src/store/chat/slices/agentRun/initialState.ts+++ b/src/store/chat/slices/agentRun/initialState.ts@@ -1,6 +1,11 @@import { type ChatInputEditor } from '@/features/ChatInput';import type { GatewayConnection } from '@/store/chat/slices/agentRun/actions/transports/gateway/gateway';+export type MainConversationScrollToIndex = (+ index: number,+ options?: { align?: 'start' | 'center' | 'end'; smooth?: boolean },+) => void;+export interface ChatAIChatState {/*** Active Agent Gateway WebSocket connections, keyed by operationId@@ -8,6 +13,10 @@ export interface ChatAIChatState {gatewayConnections: Record<string, GatewayConnection>;inputFiles: File[];inputMessage: string;+ /**+ * Virtual-list navigation exposed by the main conversation for sibling UI such as Portal.+ */+ mainConversationScrollToIndex: MainConversationScrollToIndex | null;mainInputEditor: ChatInputEditor | null;/*** Tool calls currently being executed locally on this client in response to@@ -28,6 +37,7 @@ export const initialAiChatState: ChatAIChatState = {gatewayConnections: {},inputFiles: [],inputMessage: '',+ mainConversationScrollToIndex: null,mainInputEditor: null,pendingClientToolExecutions: {},searchWorkflowLoadingIds: [],diff --git a/src/store/chat/slices/portal/action.test.ts b/src/store/chat/slices/portal/action.test.tsindex c7585e83266..5ba1260847d 100644--- a/src/store/chat/slices/portal/action.test.ts+++ b/src/store/chat/slices/portal/action.test.ts@@ -239,6 +239,40 @@ describe('chatDockSlice', () => {});});+ describe('topic comments', () => {+ it('stacks thread detail on the topic comments list so Back returns to the filter', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.openTopicComments('topic-1', 'message-1');+ result.current.openTopicCommentThread('topic-1', 'comment-1');+ });++ expect(result.current.portalStack).toEqual([+ {+ messageId: 'message-1',+ topicId: 'topic-1',+ type: PortalViewType.TopicComments,+ },+ {+ rootCommentId: 'comment-1',+ topicId: 'topic-1',+ type: PortalViewType.TopicCommentThread,+ },+ ]);++ act(() => result.current.goBack());++ expect(result.current.portalStack).toEqual([+ {+ messageId: 'message-1',+ topicId: 'topic-1',+ type: PortalViewType.TopicComments,+ },+ ]);+ });+ });+describe('openArtifact', () => {it('should push Artifact view and open portal', () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.tsindex b1917f9f11d..e4562332e6e 100644--- a/src/store/chat/slices/portal/action.ts+++ b/src/store/chat/slices/portal/action.ts@@ -1,5 +1,8 @@+import type { TopicCommentItem } from '@lobechat/types';+import { projectFileService } from '@/services/projectFile';import { type ChatStore } from '@/store/chat/store';+import { useGlobalStore } from '@/store/global';import { type StoreSetter } from '@/store/types';import { type PortalArtifact } from '@/types/artifact';@@ -598,6 +601,30 @@ export class ChatPortalActionImpl {this.#get().pushPortalView({ taskId, type: PortalViewType.TaskDetail });};+ openTopicCommentThread = (+ topicId: string,+ rootCommentId: string,+ initialRoot?: TopicCommentItem,+ initialReplyCount?: number,+ focusCommentId?: string,+ ): void => {+ this.#get().pushPortalView({+ ...(focusCommentId ? { focusCommentId } : {}),+ ...(initialReplyCount === undefined ? {} : { initialReplyCount }),+ ...(initialRoot ? { initialRoot } : {}),+ rootCommentId,+ topicId,+ type: PortalViewType.TopicCommentThread,+ });+ };++ openTopicComments = (topicId: string, messageId?: string): void => {+ const { setWorkingSidebarTab, toggleRightPanel } = useGlobalStore.getState();+ toggleRightPanel(true);+ setWorkingSidebarTab('comments');+ this.#get().pushPortalView({ messageId, topicId, type: PortalViewType.TopicComments });+ };+openToolUI = (messageId: string, identifier: string, params?: Record<string, any>): void => {this.#get().pushPortalView({ identifier, messageId, params, type: PortalViewType.ToolUI });};diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.tsindex c35c53a6865..31f38c58d1e 100644--- a/src/store/chat/slices/portal/initialState.ts+++ b/src/store/chat/slices/portal/initialState.ts@@ -1,3 +1,5 @@+import type { TopicCommentItem } from '@lobechat/types';+import { type PortalArtifact } from '@/types/artifact';export enum ArtifactDisplayMode {@@ -22,6 +24,8 @@ export enum PortalViewType {TaskDetail = 'taskDetail',Thread = 'thread',ToolUI = 'toolUI',+ TopicComments = 'topicComments',+ TopicCommentThread = 'topicCommentThread',VerifyReport = 'verifyReport',VerifyResult = 'verifyResult',}@@ -63,6 +67,15 @@ export type PortalViewData =| { startMessageId?: string; threadId?: string; type: PortalViewType.Thread }| { agentId: string; type: PortalViewType.GroupThread }| { taskId: string; type: PortalViewType.TaskDetail }+ | {+ focusCommentId?: string;+ initialReplyCount?: number;+ initialRoot?: TopicCommentItem;+ rootCommentId: string;+ topicId: string;+ type: PortalViewType.TopicCommentThread;+ }+ | { messageId?: string; topicId: string; type: PortalViewType.TopicComments }| { runId: string; type: PortalViewType.VerifyReport }| { checkItemId: string; operationId: string; type: PortalViewType.VerifyResult };diff --git a/src/store/chat/slices/portal/selectors.test.ts b/src/store/chat/slices/portal/selectors.test.tsindex f75fc0ccd90..906bc734756 100644--- a/src/store/chat/slices/portal/selectors.test.ts+++ b/src/store/chat/slices/portal/selectors.test.ts@@ -95,6 +95,78 @@ describe('chatDockSelectors', () => {});});+ describe('topic comments', () => {+ it('extracts list and thread view data only from the active view', () => {+ const listState = createState({+ portalStack: [+ {+ messageId: 'message-1',+ topicId: 'topic-1',+ type: PortalViewType.TopicComments,+ },+ ],+ });++ expect(chatPortalSelectors.topicCommentsView(listState)).toEqual({+ messageId: 'message-1',+ topicId: 'topic-1',+ type: PortalViewType.TopicComments,+ });+ expect(chatPortalSelectors.topicCommentThreadView(listState)).toBeNull();++ const threadState = createState({+ portalStack: [+ {+ rootCommentId: 'comment-1',+ topicId: 'topic-1',+ type: PortalViewType.TopicCommentThread,+ },+ ],+ });+ expect(chatPortalSelectors.topicCommentThreadView(threadState)).toEqual({+ rootCommentId: 'comment-1',+ topicId: 'topic-1',+ type: PortalViewType.TopicCommentThread,+ });+ expect(chatPortalSelectors.topicCommentsView(threadState)).toBeNull();+ });++ it('keeps comment views out of the standalone desktop portal', () => {+ const listState = createState({+ portalStack: [+ {+ topicId: 'topic-1',+ type: PortalViewType.TopicComments,+ },+ ],+ showPortal: true,+ });+ const threadState = createState({+ portalStack: [+ {+ rootCommentId: 'comment-1',+ topicId: 'topic-1',+ type: PortalViewType.TopicCommentThread,+ },+ ],+ showPortal: true,+ });++ expect(chatPortalSelectors.showTopicComments(listState)).toBe(true);+ expect(chatPortalSelectors.showStandalonePortal(listState)).toBe(false);+ expect(chatPortalSelectors.showTopicComments(threadState)).toBe(true);+ expect(chatPortalSelectors.showStandalonePortal(threadState)).toBe(false);+ expect(+ chatPortalSelectors.showStandalonePortal(+ createState({+ portalStack: [{ type: PortalViewType.Notebook }],+ showPortal: true,+ }),+ ),+ ).toBe(true);+ });+ });+describe('canGoBack', () => {it('should return false when stack has 0 or 1 views', () => {expect(chatPortalSelectors.canGoBack(createState())).toBe(false);diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.tsindex 06542894d00..ab7b3143844 100644--- a/src/store/chat/slices/portal/selectors.ts+++ b/src/store/chat/slices/portal/selectors.ts@@ -28,6 +28,13 @@ const stackDepth = (s: ChatStoreState): number => {};const showPortal = (s: ChatStoreState) => s.showPortal;+const showTopicComments = (s: ChatStoreState) => {+ const viewType = currentViewType(s);+ return (+ viewType === PortalViewType.TopicComments || viewType === PortalViewType.TopicCommentThread+ );+};+const showStandalonePortal = (s: ChatStoreState) => showPortal(s) && !showTopicComments(s);// ============== View Type Guards ==============@@ -220,6 +227,10 @@ const taskDetailId = (s: ChatStoreState): string | undefined => {return view?.taskId;};+const topicCommentsView = (s: ChatStoreState) => getViewData(s, PortalViewType.TopicComments);+const topicCommentThreadView = (s: ChatStoreState) =>+ getViewData(s, PortalViewType.TopicCommentThread);+// Tool UI / Plugin selectorsconst currentToolUI = (s: ChatStoreState,@@ -252,6 +263,8 @@ export const chatPortalSelectors = {canGoBack,stackDepth,showPortal,+ showStandalonePortal,+ showTopicComments,// View type guardsshowArtifactUI,@@ -304,6 +317,10 @@ export const chatPortalSelectors = {// Task detail datataskDetailId,+ // Topic comment data+ topicCommentsView,+ topicCommentThreadView,+// Tool UI datacurrentToolUI,toolMessageId,diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex c69c01fe2e3..5c27847b75c 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -40,6 +40,7 @@ export enum GroupSettingsTabs {// business builds may register extra sidebar tabs, so any string key is acceptedexport type WorkingSidebarTab =| 'browser'+ | 'comments'| 'documents'| 'files'| 'overview'diff --git a/src/store/topicComment/action.ts b/src/store/topicComment/action.tsnew file mode 100644index 00000000000..a3538137a0d--- /dev/null+++ b/src/store/topicComment/action.ts@@ -0,0 +1,122 @@+import type { StoreSetter } from '@/store/types';++import {+ createOptimisticTopicCommentKey,+ type OptimisticTopicComment,+ type OptimisticTopicCommentMutation,+ type OptimisticTopicCommentReplyCountMutation,+ type TopicCommentDraft,+} from './initialState';+import type { TopicCommentStore } from './store';++type Setter = StoreSetter<TopicCommentStore>;++export const createTopicCommentSlice = (+ set: Setter,+ get: () => TopicCommentStore,+ _api?: unknown,+) => new TopicCommentActionImpl(set, get, _api);++export class TopicCommentActionImpl {+ readonly #get: () => TopicCommentStore;+ readonly #set: Setter;++ constructor(set: Setter, get: () => TopicCommentStore, _api?: unknown) {+ void _api;+ this.#set = set;+ this.#get = get;+ }++ clearDraft = (key: string, expectedClientId?: string): void => {+ if (expectedClientId && this.#get().drafts[key]?.clientId !== expectedClientId) return;++ const { [key]: _, ...drafts } = this.#get().drafts;+ this.#set({ drafts }, false, 'clearDraft');+ };++ removeOptimisticComment = (targetKey: string, clientId: string): void => {+ const key = createOptimisticTopicCommentKey(targetKey, clientId);+ const { [key]: _, ...optimisticComments } = this.#get().optimisticComments;+ this.#set({ optimisticComments }, false, 'removeOptimisticComment');+ };++ removeOptimisticMutation = (commentId: string): void => {+ const { [commentId]: _, ...optimisticMutations } = this.#get().optimisticMutations;+ this.#set({ optimisticMutations }, false, 'removeOptimisticMutation');+ };++ removeOptimisticReplyCountMutation = (id: string): void => {+ const { [id]: _, ...optimisticReplyCountMutations } = this.#get().optimisticReplyCountMutations;+ this.#set({ optimisticReplyCountMutations }, false, 'removeOptimisticReplyCountMutation');+ };++ setDraft = (key: string, draft: TopicCommentDraft): void => {+ this.#set({ drafts: { ...this.#get().drafts, [key]: draft } }, false, 'setDraft');+ };++ setDraftContent = (+ key: string,+ content: string,+ editorData?: TopicCommentDraft['editorData'],+ ): void => {+ const current = this.#get().drafts[key];+ const clientId =+ current?.clientId && current.content.trim() === content.trim() ? current.clientId : undefined;++ this.#set(+ {+ drafts: {+ ...this.#get().drafts,+ [key]:+ editorData === undefined ? { clientId, content } : { clientId, content, editorData },+ },+ },+ false,+ 'setDraftContent',+ );+ };++ upsertOptimisticComment = (comment: OptimisticTopicComment): void => {+ const key = createOptimisticTopicCommentKey(comment.targetKey, comment.comment.clientId);+ this.#set(+ {+ optimisticComments: {+ ...this.#get().optimisticComments,+ [key]: comment,+ },+ },+ false,+ 'upsertOptimisticComment',+ );+ };++ upsertOptimisticMutation = (mutation: OptimisticTopicCommentMutation): void => {+ this.#set(+ {+ optimisticMutations: {+ ...this.#get().optimisticMutations,+ [mutation.comment.id]: mutation,+ },+ },+ false,+ 'upsertOptimisticMutation',+ );+ };++ upsertOptimisticReplyCountMutation = (+ mutation: OptimisticTopicCommentReplyCountMutation,+ ): void => {+ this.#set(+ {+ optimisticReplyCountMutations: {+ ...this.#get().optimisticReplyCountMutations,+ [mutation.id]: mutation,+ },+ },+ false,+ 'upsertOptimisticReplyCountMutation',+ );+ };+}++export type TopicCommentAction = Pick<TopicCommentActionImpl, keyof TopicCommentActionImpl>;diff --git a/src/store/topicComment/index.ts b/src/store/topicComment/index.tsnew file mode 100644index 00000000000..9cf4b05671f--- /dev/null+++ b/src/store/topicComment/index.ts@@ -0,0 +1,3 @@+export { createTopicCommentDraftKey } from './initialState';+export { topicCommentSelectors } from './selectors';+export { useTopicCommentStore } from './store';diff --git a/src/store/topicComment/initialState.ts b/src/store/topicComment/initialState.tsnew file mode 100644index 00000000000..72b27804740--- /dev/null+++ b/src/store/topicComment/initialState.ts@@ -0,0 +1,61 @@+import type { TopicCommentItem, TopicCommentJson } from '@lobechat/types';++export interface TopicCommentDraft {+ clientId?: string;+ content: string;+ editorData?: TopicCommentJson;+}++export interface OptimisticTopicComment {+ comment: TopicCommentItem;+ pending: boolean;+ targetKey: string;+}++export interface OptimisticTopicCommentMutation {+ affectsMessageCount?: boolean;+ comment: TopicCommentItem;+ deleteMode?: 'hard' | 'moderated' | 'soft';+ kind: 'delete' | 'restore' | 'update';+ pending: boolean;+}++export interface OptimisticTopicCommentReplyCountMutation {+ baselineCount: number;+ delta: -1 | 1;+ id: string;+ pending: boolean;+ rootCommentId: string;+ topicId: string;+ workspaceId: string;+}++export interface TopicCommentState {+ drafts: Record<string, TopicCommentDraft>;+ optimisticComments: Record<string, OptimisticTopicComment>;+ optimisticMutations: Record<string, OptimisticTopicCommentMutation>;+ optimisticReplyCountMutations: Record<string, OptimisticTopicCommentReplyCountMutation>;+}++export const initialState: TopicCommentState = {+ drafts: {},+ optimisticComments: {},+ optimisticMutations: {},+ optimisticReplyCountMutations: {},+};++export const createTopicCommentDraftKey = ({+ messageId,+ parentCommentId,+ topicId,+ workspaceId,+}: {+ messageId?: string;+ parentCommentId?: string;+ topicId: string;+ workspaceId: string;+}) =>+ `${workspaceId}:${topicId}:${parentCommentId ? `reply:${parentCommentId}` : `message:${messageId ?? 'all'}`}`;++export const createOptimisticTopicCommentKey = (targetKey: string, clientId: string) =>+ `${targetKey}:${clientId}`;diff --git a/src/store/topicComment/selectors.ts b/src/store/topicComment/selectors.tsnew file mode 100644index 00000000000..17b4be54c70--- /dev/null+++ b/src/store/topicComment/selectors.ts@@ -0,0 +1,130 @@+import type { TopicCommentStore } from './store';++const draft = (key: string) => (s: TopicCommentStore) => s.drafts[key];+const optimisticMutation = (commentId: string | null | undefined) => (s: TopicCommentStore) =>+ commentId ? s.optimisticMutations[commentId] : undefined;+const optimisticReplyCountMutations =+ (rootCommentId: string | null | undefined) => (s: TopicCommentStore) =>+ rootCommentId+ ? Object.values(s.optimisticReplyCountMutations).filter(+ (mutation) => mutation.rootCommentId === rootCommentId,+ )+ : [];+const optimisticReplyCountMutationsByTopic =+ (workspaceId: string | null | undefined, topicId: string | null | undefined) =>+ (s: TopicCommentStore) =>+ workspaceId && topicId+ ? Object.values(s.optimisticReplyCountMutations).filter(+ (mutation) => mutation.workspaceId === workspaceId && mutation.topicId === topicId,+ )+ : [];+const optimisticReplyMutations =+ (workspaceId: string | null | undefined, rootCommentId: string | null | undefined) =>+ (s: TopicCommentStore) =>+ workspaceId && rootCommentId+ ? Object.values(s.optimisticMutations).filter(+ ({ comment }) =>+ comment.workspaceId === workspaceId && comment.parentCommentId === rootCommentId,+ )+ : [];+const optimisticReplies =+ (workspaceId: string | null | undefined, rootCommentId: string | null | undefined) =>+ (s: TopicCommentStore) =>+ workspaceId && rootCommentId+ ? Object.values(s.optimisticComments)+ .filter(+ ({ comment }) =>+ comment.workspaceId === workspaceId && comment.parentCommentId === rootCommentId,+ )+ .sort(+ (a, b) =>+ new Date(a.comment.createdAt).getTime() - new Date(b.comment.createdAt).getTime(),+ )+ : [];+const optimisticThreadMutations =+ (+ workspaceId: string | null | undefined,+ topicId: string | null | undefined,+ messageId?: string,+ ) =>+ (s: TopicCommentStore) =>+ workspaceId && topicId+ ? Object.values(s.optimisticMutations).filter(+ ({ comment }) =>+ comment.workspaceId === workspaceId &&+ comment.topicId === topicId &&+ !comment.parentCommentId &&+ (!messageId || comment.messageId === messageId),+ )+ : [];+const optimisticThreads =+ (+ workspaceId: string | null | undefined,+ topicId: string | null | undefined,+ messageId?: string,+ ) =>+ (s: TopicCommentStore) =>+ workspaceId && topicId+ ? Object.values(s.optimisticComments)+ .filter(+ ({ comment }) =>+ comment.workspaceId === workspaceId &&+ comment.topicId === topicId &&+ !comment.parentCommentId &&+ (!messageId || comment.messageId === messageId),+ )+ .sort(+ (a, b) =>+ new Date(b.comment.createdAt).getTime() - new Date(a.comment.createdAt).getTime(),+ )+ : [];+const summaryPendingComments =+ (workspaceId: string | null | undefined, topicId: string | null | undefined) =>+ (s: TopicCommentStore) =>+ workspaceId && topicId+ ? Object.values(s.optimisticComments).filter(+ ({ comment, pending }) =>+ pending &&+ comment.workspaceId === workspaceId &&+ comment.topicId === topicId &&+ !comment.deletedAt,+ )+ : [];+const summaryPendingDeletes =+ (workspaceId: string | null | undefined, topicId: string | null | undefined) =>+ (s: TopicCommentStore) =>+ workspaceId && topicId+ ? Object.values(s.optimisticMutations).filter(+ ({ comment, kind, pending }) =>+ pending &&+ kind === 'delete' &&+ comment.workspaceId === workspaceId &&+ comment.topicId === topicId,+ )+ : [];+const summaryPendingRestores =+ (workspaceId: string | null | undefined, topicId: string | null | undefined) =>+ (s: TopicCommentStore) =>+ workspaceId && topicId+ ? Object.values(s.optimisticMutations).filter(+ ({ comment, kind, pending }) =>+ pending &&+ kind === 'restore' &&+ comment.workspaceId === workspaceId &&+ comment.topicId === topicId,+ )+ : [];++export const topicCommentSelectors = {+ draft,+ optimisticMutation,+ optimisticReplyCountMutations,+ optimisticReplyCountMutationsByTopic,+ optimisticReplyMutations,+ optimisticReplies,+ optimisticThreadMutations,+ optimisticThreads,+ summaryPendingComments,+ summaryPendingDeletes,+ summaryPendingRestores,+};diff --git a/src/store/topicComment/store.test.ts b/src/store/topicComment/store.test.tsnew file mode 100644index 00000000000..0472a7b894e--- /dev/null+++ b/src/store/topicComment/store.test.ts@@ -0,0 +1,151 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it } from 'vitest';++import { createTopicCommentDraftKey, topicCommentSelectors, useTopicCommentStore } from '.';++describe('topicCommentStore', () => {+ beforeEach(() => {+ useTopicCommentStore.getState().reset();+ });++ it('scopes drafts by workspace, topic and target', () => {+ const messageKey = createTopicCommentDraftKey({+ messageId: 'message-1',+ topicId: 'topic-1',+ workspaceId: 'workspace-1',+ });+ const replyKey = createTopicCommentDraftKey({+ parentCommentId: 'comment-1',+ topicId: 'topic-1',+ workspaceId: 'workspace-1',+ });+ const { result } = renderHook(() => useTopicCommentStore());++ act(() => {+ result.current.setDraft(messageKey, { clientId: 'retry-id', content: 'Message draft' });+ result.current.setDraft(replyKey, { content: 'Reply draft' });+ });++ expect(topicCommentSelectors.draft(messageKey)(result.current)).toEqual({+ clientId: 'retry-id',+ content: 'Message draft',+ });+ expect(topicCommentSelectors.draft(replyKey)(result.current)).toEqual({+ content: 'Reply draft',+ });+ });++ it('clears only the submitted draft and preserves its retry client id until then', () => {+ const firstKey = 'workspace-1:topic-1:message:all';+ const secondKey = 'workspace-1:topic-2:message:all';+ const { result } = renderHook(() => useTopicCommentStore());++ act(() => {+ result.current.setDraft(firstKey, { clientId: 'retry-id', content: 'First' });+ result.current.setDraft(secondKey, { content: 'Second' });+ result.current.clearDraft(firstKey);+ });++ expect(result.current.drafts[firstKey]).toBeUndefined();+ expect(result.current.drafts[secondKey]).toEqual({ content: 'Second' });+ });++ it('preserves new input when an older in-flight submission succeeds', () => {+ const key = 'workspace-1:topic-1:message:all';+ const { result } = renderHook(() => useTopicCommentStore());++ act(() => {+ result.current.setDraft(key, { clientId: 'submitted-id', content: 'Submitted' });+ result.current.setDraftContent(key, 'Next comment');+ result.current.clearDraft(key, 'submitted-id');+ });++ expect(result.current.drafts[key]).toEqual({ clientId: undefined, content: 'Next comment' });+ });++ it('reuses a client id only while retrying the same content', () => {+ const key = 'workspace-1:topic-1:message:all';+ const { result } = renderHook(() => useTopicCommentStore());++ act(() => {+ result.current.setDraft(key, { clientId: 'retry-id', content: 'Submitted' });+ result.current.setDraftContent(key, 'Submitted ');+ });+ expect(result.current.drafts[key]).toEqual({+ clientId: 'retry-id',+ content: 'Submitted ',+ });++ act(() => {+ result.current.setDraftContent(key, 'Changed');+ });+ expect(result.current.drafts[key]).toEqual({ clientId: undefined, content: 'Changed' });+ });++ it('keeps editor data with a draft so member mentions survive retries', () => {+ const key = 'workspace-1:topic-1:message:all';+ const editorData = {+ root: {+ children: [{ metadata: { id: 'member-1', type: 'member' }, type: 'mention' }],+ },+ };+ const { result } = renderHook(() => useTopicCommentStore());++ act(() => {+ result.current.setDraft(key, {+ clientId: 'retry-id',+ content: '<mention name="Member" id="member-1" />',+ editorData,+ });+ result.current.setDraftContent(key, '<mention name="Member" id="member-1" />', editorData);+ });++ expect(result.current.drafts[key]).toEqual({+ clientId: 'retry-id',+ content: '<mention name="Member" id="member-1" />',+ editorData,+ });+ });++ it('tracks reply-count operations independently and scopes them to their topic and root', () => {+ const { result } = renderHook(() => useTopicCommentStore());++ act(() => {+ result.current.upsertOptimisticReplyCountMutation({+ baselineCount: 2,+ delta: 1,+ id: 'create:reply-1',+ pending: true,+ rootCommentId: 'root-1',+ topicId: 'topic-1',+ workspaceId: 'workspace-1',+ });+ result.current.upsertOptimisticReplyCountMutation({+ baselineCount: 1,+ delta: -1,+ id: 'delete:reply-2',+ pending: false,+ rootCommentId: 'root-2',+ topicId: 'topic-1',+ workspaceId: 'workspace-1',+ });+ });++ expect(topicCommentSelectors.optimisticReplyCountMutations('root-1')(result.current)).toEqual([+ expect.objectContaining({ delta: 1, id: 'create:reply-1' }),+ ]);+ expect(+ topicCommentSelectors.optimisticReplyCountMutationsByTopic(+ 'workspace-1',+ 'topic-1',+ )(result.current),+ ).toHaveLength(2);++ act(() => result.current.removeOptimisticReplyCountMutation('create:reply-1'));++ expect(topicCommentSelectors.optimisticReplyCountMutations('root-1')(result.current)).toEqual(+ [],+ );+ expect(result.current.optimisticReplyCountMutations['delete:reply-2']).toBeDefined();+ });+});diff --git a/src/store/topicComment/store.ts b/src/store/topicComment/store.tsnew file mode 100644index 00000000000..563ec5081ce--- /dev/null+++ b/src/store/topicComment/store.ts@@ -0,0 +1,35 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';+import type { StateCreator } from 'zustand/vanilla';++import { createDevtools } from '../middleware/createDevtools';+import { expose } from '../middleware/expose';+import { flattenActions } from '../utils/flattenActions';+import { type ResetableStore, ResetableStoreAction } from '../utils/resetableStore';+import { createTopicCommentSlice, type TopicCommentAction } from './action';+import { initialState, type TopicCommentState } from './initialState';++export type TopicCommentStore = TopicCommentAction & TopicCommentState & ResetableStore;++class TopicCommentStoreResetAction extends ResetableStoreAction<TopicCommentStore> {+ protected readonly resetActionName = 'resetTopicCommentStore';+}++const createStore: StateCreator<TopicCommentStore, [['zustand/devtools', never]]> = (+ ...parameters: Parameters<StateCreator<TopicCommentStore, [['zustand/devtools', never]]>>+) => ({+ ...initialState,+ ...flattenActions<TopicCommentAction & ResetableStore>([+ createTopicCommentSlice(...parameters),+ new TopicCommentStoreResetAction(...parameters),+ ]),+});++const devtools = createDevtools('topicComment');++export const useTopicCommentStore = createWithEqualityFn<TopicCommentStore>()(+ devtools(createStore),+ shallow,+);++expose('topicComment', useTopicCommentStore);