π€― 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
π fix(task): make agent @mentions in task comments work (#21646)
Lobehub Coder0a79c5586424
diff --git a/apps/cli/src/commands/task/lifecycle.ts b/apps/cli/src/commands/task/lifecycle.tsindex 46c2b1a85a4..65de75b3148 100644--- a/apps/cli/src/commands/task/lifecycle.ts+++ b/apps/cli/src/commands/task/lifecycle.ts@@ -255,7 +255,10 @@ export function registerLifecycleCommands(task: Command) {task.command('comment <id>').description('Add a comment to a task')- .requiredOption('-m, --message <text>', 'Comment content')+ .requiredOption(+ '-m, --message <text>',+ 'Comment content (markdown). Mention a member with <mention name="Name" id="user_xxx" /> to notify them (ids from `lh workspace members`); a plain "@Name" is only text',+ ).action(async (id: string, options: { message: string }) => {const client = await getTrpcClient();const topicId = process.env.LOBEHUB_TOPIC_ID?.trim() || undefined;diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.commentNotifications.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.commentNotifications.integration.test.tsnew file mode 100644index 00000000000..6637de3c66b--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/integration/task.commentNotifications.integration.test.ts@@ -0,0 +1,313 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { getTestDB } from '@lobechat/database/test-utils';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { taskRouter } from '../../task';+import { cleanupTestUser, createTestContext, createTestUser } from './setup';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return testDB;+ }),+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));++vi.mock('@/business/server/task/notifyTaskAssigned', () => ({+ notifyTaskAssigned: vi.fn().mockResolvedValue(undefined),+}));++// Mock the comment-notification business slot (default impl is a no-op).+const mockNotifyTaskCommentActivity = vi.fn().mockResolvedValue(undefined);+vi.mock('@/business/server/task/notifyTaskCommentActivity', () => ({+ notifyTaskCommentActivity: (...args: unknown[]) => mockNotifyTaskCommentActivity(...args),+}));++// Notifications are retained past the response through `after()`; run that+// work eagerly here and flush it before asserting on the slot above.+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));+};++describe('Task Router comment notifications', () => {+ let serverDB: LobeChatDatabase;+ let userId: string;+ let otherUserId: string | undefined;+ let caller: ReturnType<typeof taskRouter.createCaller>;++ beforeEach(async () => {+ vi.clearAllMocks();+ serverDB = await getTestDB();+ testDB = serverDB;+ userId = await createTestUser(serverDB);+ caller = taskRouter.createCaller(createTestContext(userId));+ });++ afterEach(async () => {+ await cleanupTestUser(serverDB, userId);+ if (otherUserId) await cleanupTestUser(serverDB, otherUserId);+ otherUserId = undefined;+ });++ const mentionNode = (userId: string) => ({+ label: 'Member',+ metadata: { id: userId, type: 'member' },+ type: 'mention',+ });+ const editorDataWith = (...userIds: string[]) => ({+ root: { children: [{ children: userIds.map(mentionNode), type: 'paragraph' }] },+ });++ const setupWorkspace = async () => {+ const workspaceId = 'task-comment-notify-workspace';+ const { workspaces, workspaceMembers } = await import('@/database/schemas');+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Task Comment Notify Workspace',+ primaryOwnerId: userId,+ slug: workspaceId,+ });+ await serverDB.insert(workspaceMembers).values([+ { role: 'owner', userId, workspaceId },+ { role: 'member', userId: otherUserId!, workspaceId },+ ]);+ return {+ wsCaller: taskRouter.createCaller({ ...createTestContext(userId), workspaceId }),+ wsOtherCaller: taskRouter.createCaller({+ ...createTestContext(otherUserId!),+ workspaceId,+ }),+ workspaceId,+ };+ };++ it('should ping the task creator and @mentioned members on a new member comment', async () => {+ otherUserId = await createTestUser(serverDB);+ const { wsCaller, wsOtherCaller, workspaceId } = await setupWorkspace();+ const task = await wsCaller.create({ instruction: 'Discuss', name: 'Discuss' });++ // The creator commenting on their own task with no mentions pings nobody.+ await wsCaller.addComment({ content: 'note to self', id: task.data.id });+ await flushAfterResponse();+ expect(mockNotifyTaskCommentActivity).not.toHaveBeenCalled();++ // Another member commenting pings the creator as ambient activity.+ const comment = await wsOtherCaller.addComment({ content: 'hello', id: task.data.id });+ await flushAfterResponse();+ expect(mockNotifyTaskCommentActivity).toHaveBeenCalledTimes(1);+ expect(mockNotifyTaskCommentActivity).toHaveBeenCalledWith({+ actorUserId: otherUserId,+ commentId: comment.data.id,+ recipients: [{ kind: 'commented', userId }],+ taskId: task.data.id,+ workspaceId,+ });++ // The creator @mentioning the other member pings them as mentioned;+ // unknown ids and self-mentions are dropped.+ const mentioned = await wsCaller.addComment({+ content: '@Member look',+ editorData: editorDataWith(otherUserId!, userId, 'not-a-member'),+ id: task.data.id,+ });+ await flushAfterResponse();+ expect(mockNotifyTaskCommentActivity).toHaveBeenLastCalledWith({+ actorUserId: userId,+ commentId: mentioned.data.id,+ recipients: [{ kind: 'mentioned', userId: otherUserId }],+ taskId: task.data.id,+ workspaceId,+ });+ });++ it('should upgrade the assignee to mentioned; agent notes ping only their @mentions', async () => {+ otherUserId = await createTestUser(serverDB);+ const { wsCaller, workspaceId } = await setupWorkspace();+ const task = await wsCaller.create({+ assigneeUserId: otherUserId,+ instruction: 'Assigned',+ });+ await flushAfterResponse();+ mockNotifyTaskCommentActivity.mockClear();++ await wsCaller.addComment({ content: 'ping', id: task.data.id });+ await flushAfterResponse();+ expect(mockNotifyTaskCommentActivity).toHaveBeenLastCalledWith(+ expect.objectContaining({+ recipients: [{ kind: 'commented', userId: otherUserId }],+ workspaceId,+ }),+ );++ await wsCaller.addComment({+ content: '@Member',+ editorData: editorDataWith(otherUserId!),+ id: task.data.id,+ });+ await flushAfterResponse();+ expect(mockNotifyTaskCommentActivity).toHaveBeenLastCalledWith(+ expect.objectContaining({ recipients: [{ kind: 'mentioned', userId: otherUserId }] }),+ );++ const { agents } = await import('@/database/schemas');+ const wsAgentId = 'agt_task_comment_ws';+ await serverDB+ .insert(agents)+ .values({ id: wsAgentId, slug: wsAgentId, userId, workspaceId })+ .onConflictDoNothing();+ mockNotifyTaskCommentActivity.mockClear();+ const agentNote = async (content: string) => {+ await wsCaller.addComment({ authorAgentId: wsAgentId, content, id: task.data.id });+ await flushAfterResponse();+ };+ await agentNote('Agent progress note');+ expect(mockNotifyTaskCommentActivity).not.toHaveBeenCalled();+ await agentNote(`Done <mention name="M" id="${otherUserId}" />`);+ expect(mockNotifyTaskCommentActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ actorAgentId: wsAgentId,+ recipients: [{ kind: 'mentioned', userId: otherUserId }],+ }),+ );++ // The agent wrote it, so the member it runs for can be @mentioned too;+ // a tag quoted inside a code span is not a mention.+ mockNotifyTaskCommentActivity.mockClear();+ await agentNote(+ `Review please <mention name="Owner" id="${userId}" />, syntax: \`<mention id="${otherUserId}" />\``,+ );+ expect(mockNotifyTaskCommentActivity).toHaveBeenCalledTimes(1);+ expect(mockNotifyTaskCommentActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ actorAgentId: wsAgentId,+ actorUserId: userId,+ recipients: [{ kind: 'mentioned', userId }],+ }),+ );++ // Editing the agent note to add a markdown mention pings only the new one,+ // attributed to the member who made the edit.+ const note = await wsCaller.addComment({+ authorAgentId: wsAgentId,+ content: 'Status update',+ id: task.data.id,+ });+ await flushAfterResponse();+ mockNotifyTaskCommentActivity.mockClear();+ await wsCaller.updateComment({+ commentId: note.data.id,+ content: `Status update <mention name="M" id="${otherUserId}" />`,+ });+ await flushAfterResponse();+ expect(mockNotifyTaskCommentActivity).toHaveBeenCalledWith({+ actorUserId: userId,+ commentId: note.data.id,+ recipients: [{ kind: 'mentioned', userId: otherUserId }],+ taskId: task.data.id,+ workspaceId,+ });+ expect(mockNotifyTaskCommentActivity.mock.lastCall?.[0]).not.toHaveProperty('actorAgentId');+ });++ it('should only ping newly added mentions when a comment is edited', async () => {+ otherUserId = await createTestUser(serverDB);+ const thirdUserId = await createTestUser(serverDB);+ const { wsCaller, workspaceId } = await setupWorkspace();+ const { workspaceMembers } = await import('@/database/schemas');+ await serverDB+ .insert(workspaceMembers)+ .values({ role: 'member', userId: thirdUserId, workspaceId });+ const task = await wsCaller.create({ instruction: 'Edit mentions' });+ const comment = await wsCaller.addComment({+ content: '@Member',+ editorData: editorDataWith(otherUserId!),+ id: task.data.id,+ });+ await flushAfterResponse();+ mockNotifyTaskCommentActivity.mockClear();++ // Keeping the same mention does not re-notify.+ await wsCaller.updateComment({+ commentId: comment.data.id,+ content: '@Member edited',+ editorData: editorDataWith(otherUserId!),+ });+ await flushAfterResponse();+ expect(mockNotifyTaskCommentActivity).not.toHaveBeenCalled();++ // Adding a new mention pings only the new member.+ await wsCaller.updateComment({+ commentId: comment.data.id,+ content: '@Member @Third',+ editorData: editorDataWith(otherUserId!, thirdUserId),+ });+ await flushAfterResponse();+ expect(mockNotifyTaskCommentActivity).toHaveBeenCalledTimes(1);+ expect(mockNotifyTaskCommentActivity).toHaveBeenCalledWith({+ actorUserId: userId,+ commentId: comment.data.id,+ recipients: [{ kind: 'mentioned', userId: thirdUserId }],+ taskId: task.data.id,+ workspaceId,+ });++ // A content-only edit without new mention tags does not notify.+ await wsCaller.updateComment({ commentId: comment.data.id, content: 'plain' });+ await flushAfterResponse();+ expect(mockNotifyTaskCommentActivity).toHaveBeenCalledTimes(1);+ });++ it('should never notify members who cannot open a private task', async () => {+ otherUserId = await createTestUser(serverDB);+ const thirdUserId = await createTestUser(serverDB);+ const { wsCaller, workspaceId } = await setupWorkspace();+ const { workspaceMembers } = await import('@/database/schemas');+ await serverDB+ .insert(workspaceMembers)+ .values({ role: 'member', userId: thirdUserId, workspaceId });+ // A private task is visible to its creator only (assigning it to another+ // member is rejected upstream), yet the creator can still @mention anyone.+ const task = await wsCaller.create({+ instruction: 'Secret',+ name: 'Secret',+ visibility: 'private',+ });++ // The mention must not leak the task's title and link to a member who+ // cannot open it β neither on a new comment nor on an edit.+ const comment = await wsCaller.addComment({+ content: '@Member',+ editorData: editorDataWith(otherUserId!),+ id: task.data.id,+ });+ await flushAfterResponse();+ expect(mockNotifyTaskCommentActivity).not.toHaveBeenCalled();++ await wsCaller.updateComment({+ commentId: comment.data.id,+ content: '@Member @Third',+ editorData: editorDataWith(otherUserId!, thirdUserId),+ });+ await flushAfterResponse();+ expect(mockNotifyTaskCommentActivity).not.toHaveBeenCalled();+ });++ it('should never notify in personal mode', async () => {+ const task = await caller.create({ instruction: 'Personal' });+ await caller.addComment({+ content: '@someone',+ editorData: editorDataWith('someone'),+ id: task.data.id,+ });+ await flushAfterResponse();+ expect(mockNotifyTaskCommentActivity).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.tsindex 6641612e56d..fd841161570 100644--- a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts@@ -625,221 +625,6 @@ describe('Task Router Integration', () => {});});- describe('comment notifications', () => {- const mentionNode = (userId: string) => ({- label: 'Member',- metadata: { id: userId, type: 'member' },- type: 'mention',- });- const editorDataWith = (...userIds: string[]) => ({- root: { children: [{ children: userIds.map(mentionNode), type: 'paragraph' }] },- });-- const setupWorkspace = async () => {- const workspaceId = 'task-comment-notify-workspace';- const { workspaces, workspaceMembers } = await import('@/database/schemas');- await serverDB.insert(workspaces).values({- id: workspaceId,- name: 'Task Comment Notify Workspace',- primaryOwnerId: userId,- slug: workspaceId,- });- await serverDB.insert(workspaceMembers).values([- { role: 'owner', userId, workspaceId },- { role: 'member', userId: otherUserId!, workspaceId },- ]);- return {- wsCaller: taskRouter.createCaller({ ...createTestContext(userId), workspaceId }),- wsOtherCaller: taskRouter.createCaller({- ...createTestContext(otherUserId!),- workspaceId,- }),- workspaceId,- };- };-- it('should ping the task creator and @mentioned members on a new member comment', async () => {- otherUserId = await createTestUser(serverDB);- const { wsCaller, wsOtherCaller, workspaceId } = await setupWorkspace();- const task = await wsCaller.create({ instruction: 'Discuss', name: 'Discuss' });-- // The creator commenting on their own task with no mentions pings nobody.- await wsCaller.addComment({ content: 'note to self', id: task.data.id });- await flushAfterResponse();- expect(mockNotifyTaskCommentActivity).not.toHaveBeenCalled();-- // Another member commenting pings the creator as ambient activity.- const comment = await wsOtherCaller.addComment({ content: 'hello', id: task.data.id });- await flushAfterResponse();- expect(mockNotifyTaskCommentActivity).toHaveBeenCalledTimes(1);- expect(mockNotifyTaskCommentActivity).toHaveBeenCalledWith({- actorUserId: otherUserId,- commentId: comment.data.id,- recipients: [{ kind: 'commented', userId }],- taskId: task.data.id,- workspaceId,- });-- // The creator @mentioning the other member pings them as mentioned;- // unknown ids and self-mentions are dropped.- const mentioned = await wsCaller.addComment({- content: '@Member look',- editorData: editorDataWith(otherUserId!, userId, 'not-a-member'),- id: task.data.id,- });- await flushAfterResponse();- expect(mockNotifyTaskCommentActivity).toHaveBeenLastCalledWith({- actorUserId: userId,- commentId: mentioned.data.id,- recipients: [{ kind: 'mentioned', userId: otherUserId }],- taskId: task.data.id,- workspaceId,- });- });-- it('should upgrade the assignee to mentioned and skip agent-authored comments', async () => {- otherUserId = await createTestUser(serverDB);- const { wsCaller, workspaceId } = await setupWorkspace();- const task = await wsCaller.create({- assigneeUserId: otherUserId,- instruction: 'Assigned',- });- await flushAfterResponse();- mockNotifyTaskCommentActivity.mockClear();-- await wsCaller.addComment({ content: 'ping', id: task.data.id });- await flushAfterResponse();- expect(mockNotifyTaskCommentActivity).toHaveBeenLastCalledWith(- expect.objectContaining({- recipients: [{ kind: 'commented', userId: otherUserId }],- workspaceId,- }),- );-- await wsCaller.addComment({- content: '@Member',- editorData: editorDataWith(otherUserId!),- id: task.data.id,- });- await flushAfterResponse();- expect(mockNotifyTaskCommentActivity).toHaveBeenLastCalledWith(- expect.objectContaining({ recipients: [{ kind: 'mentioned', userId: otherUserId }] }),- );-- // Agent-authored progress notes never ping members, even with mentions.- const { agents } = await import('@/database/schemas');- const wsAgentId = 'agt_task_comment_ws';- await serverDB- .insert(agents)- .values({ id: wsAgentId, slug: wsAgentId, userId, workspaceId })- .onConflictDoNothing();- await flushAfterResponse();- mockNotifyTaskCommentActivity.mockClear();- await wsCaller.addComment({- authorAgentId: wsAgentId,- content: 'Agent progress note',- editorData: editorDataWith(otherUserId!),- id: task.data.id,- });- await flushAfterResponse();- expect(mockNotifyTaskCommentActivity).not.toHaveBeenCalled();- });-- it('should only ping newly added mentions when a comment is edited', async () => {- otherUserId = await createTestUser(serverDB);- const thirdUserId = await createTestUser(serverDB);- const { wsCaller, workspaceId } = await setupWorkspace();- const { workspaceMembers } = await import('@/database/schemas');- await serverDB- .insert(workspaceMembers)- .values({ role: 'member', userId: thirdUserId, workspaceId });- const task = await wsCaller.create({ instruction: 'Edit mentions' });- const comment = await wsCaller.addComment({- content: '@Member',- editorData: editorDataWith(otherUserId!),- id: task.data.id,- });- await flushAfterResponse();- mockNotifyTaskCommentActivity.mockClear();-- // Keeping the same mention does not re-notify.- await wsCaller.updateComment({- commentId: comment.data.id,- content: '@Member edited',- editorData: editorDataWith(otherUserId!),- });- await flushAfterResponse();- expect(mockNotifyTaskCommentActivity).not.toHaveBeenCalled();-- // Adding a new mention pings only the new member.- await wsCaller.updateComment({- commentId: comment.data.id,- content: '@Member @Third',- editorData: editorDataWith(otherUserId!, thirdUserId),- });- await flushAfterResponse();- expect(mockNotifyTaskCommentActivity).toHaveBeenCalledTimes(1);- expect(mockNotifyTaskCommentActivity).toHaveBeenCalledWith({- actorUserId: userId,- commentId: comment.data.id,- recipients: [{ kind: 'mentioned', userId: thirdUserId }],- taskId: task.data.id,- workspaceId,- });-- // Content-only edits never notify.- await wsCaller.updateComment({ commentId: comment.data.id, content: 'plain' });- await flushAfterResponse();- expect(mockNotifyTaskCommentActivity).toHaveBeenCalledTimes(1);- });-- it('should never notify members who cannot open a private task', async () => {- otherUserId = await createTestUser(serverDB);- const thirdUserId = await createTestUser(serverDB);- const { wsCaller, workspaceId } = await setupWorkspace();- const { workspaceMembers } = await import('@/database/schemas');- await serverDB- .insert(workspaceMembers)- .values({ role: 'member', userId: thirdUserId, workspaceId });- // A private task is visible to its creator only (assigning it to another- // member is rejected upstream), yet the creator can still @mention anyone.- const task = await wsCaller.create({- instruction: 'Secret',- name: 'Secret',- visibility: 'private',- });-- // The mention must not leak the task's title and link to a member who- // cannot open it β neither on a new comment nor on an edit.- const comment = await wsCaller.addComment({- content: '@Member',- editorData: editorDataWith(otherUserId!),- id: task.data.id,- });- await flushAfterResponse();- expect(mockNotifyTaskCommentActivity).not.toHaveBeenCalled();-- await wsCaller.updateComment({- commentId: comment.data.id,- content: '@Member @Third',- editorData: editorDataWith(otherUserId!, thirdUserId),- });- await flushAfterResponse();- expect(mockNotifyTaskCommentActivity).not.toHaveBeenCalled();- });-- it('should never notify in personal mode', async () => {- const task = await caller.create({ instruction: 'Personal' });- await caller.addComment({- content: '@someone',- editorData: editorDataWith('someone'),- id: task.data.id,- });- await flushAfterResponse();- expect(mockNotifyTaskCommentActivity).not.toHaveBeenCalled();- });- });-describe('review config', () => {it('should set and retrieve review rubrics', async () => {const task = await caller.create({ instruction: 'Test' });diff --git a/apps/server/src/routers/lambda/task/comments.ts b/apps/server/src/routers/lambda/task/comments.tsindex 56388677ada..46aee2866f7 100644--- a/apps/server/src/routers/lambda/task/comments.ts+++ b/apps/server/src/routers/lambda/task/comments.ts@@ -8,31 +8,37 @@ import type { LobeChatDatabase } from '@/database/type';import { router } from '@/libs/trpc/lambda';import { assertAssigneeAgentBelongsToUser } from '@/server/services/task/patchValidation';import {- extractMentionedUserIds,+ extractCommentMentionedUserIds,filterActiveWorkspaceMemberIds,- validateMentionedUserIds,+ validateTaskCommentMentionedUserIds,} from '@/server/utils/commentMentions';import { after } from '@/server/utils/scheduleAfterResponse';import { resolveOrThrow, taskProcedureWrite } from './procedures';/**- * Recipients of a new member comment on a task: the creator and the member- * assignee as ambient `commented` pings, upgraded to `mentioned` when the- * comment @mentions them. The actor never appears in the result.+ * Recipients of a new comment on a task. A member comment pings the creator+ * and the member assignee as ambient `commented` activity, upgraded to+ * `mentioned` when the comment @mentions them, and never the member who wrote+ * it. An agent-authored progress note only pings the members it explicitly+ * @mentions β including the member the agent runs for, since the agent, not+ * that member, wrote it.*/function collectTaskCommentRecipients(params: {actorUserId: string;+ isAgentAuthored: boolean;mentionedUserIds: string[];task: { assigneeUserId: string | null; createdByUserId: string };}): TaskCommentActivityRecipient[] {- const { actorUserId, mentionedUserIds, task } = params;+ const { actorUserId, isAgentAuthored, mentionedUserIds, task } = params;const byUserId = new Map<string, TaskCommentActivityRecipient['kind']>();- for (const userId of [task.createdByUserId, task.assigneeUserId]) {- if (userId) byUserId.set(userId, 'commented');+ if (!isAgentAuthored) {+ for (const userId of [task.createdByUserId, task.assigneeUserId]) {+ if (userId) byUserId.set(userId, 'commented');+ }}for (const userId of mentionedUserIds) byUserId.set(userId, 'mentioned');- byUserId.delete(actorUserId);+ if (!isAgentAuthored) byUserId.delete(actorUserId);return [...byUserId].map(([userId, kind]) => ({ kind, userId }));}@@ -124,15 +130,18 @@ export const commentsRouter = router({input.authorAgentId,);// Resolve @mentions before the insert so an invalid editorData never- // leaves a comment behind that nobody was told about.- const mentionedUserIds =- ctx.workspaceId && !input.authorAgentId- ? await validateMentionedUserIds(- ctx.serverDB,- { actorUserId: ctx.userId, workspaceId: ctx.workspaceId },- input.editorData,- )- : [];+ // leaves a comment behind that nobody was told about. Markdown-only+ // comments (CLI, agent tools) mention through `<mention id="β¦" />`.+ const mentionedUserIds = ctx.workspaceId+ ? await validateTaskCommentMentionedUserIds(+ ctx.serverDB,+ {+ excludeUserId: input.authorAgentId ? undefined : ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ input,+ )+ : [];const comment = await model.addComment({authorAgentId: input.authorAgentId,authorUserId: input.authorAgentId ? undefined : ctx.userId,@@ -146,10 +155,11 @@ export const commentsRouter = router({// Member comment ping (Linear-style): the task creator and the member// assignee learn about new discussion; @mentioned members get the// stronger "mentioned" notification instead. Agent-authored progress- // notes stay silent β they are not a conversation between members.- if (ctx.workspaceId && !input.authorAgentId) {+ // notes only reach the members they explicitly @mention.+ if (ctx.workspaceId) {const recipients = collectTaskCommentRecipients({actorUserId: ctx.userId,+ isAgentAuthored: Boolean(input.authorAgentId),mentionedUserIds,task,});@@ -157,6 +167,7 @@ export const commentsRouter = router({notifyCommentActivityBestEffort({ serverDB: ctx.serverDB, taskModel: model, workspaceId: ctx.workspaceId },{+ actorAgentId: input.authorAgentId,actorUserId: ctx.userId,commentId: comment.id,recipients,@@ -212,14 +223,16 @@ export const commentsRouter = router({throw new TRPCError({ code: 'NOT_FOUND', message: 'Comment not found' });}// Only members @mentioned for the first time by this edit are pinged;- // mentions kept from the previous revision were already notified.+ // mentions kept from the previous revision were already notified. The+ // edit carries no agent identity, so it is attributed to the member+ // making it even when an agent wrote the original comment.let addedMentionUserIds: string[] = [];- if (workspaceId && !previous.authorAgentId && input.editorData !== undefined) {- const previousMentions = new Set(extractMentionedUserIds(previous.editorData));- const nextMentions = await validateMentionedUserIds(+ if (workspaceId) {+ const previousMentions = new Set(extractCommentMentionedUserIds(previous));+ const nextMentions = await validateTaskCommentMentionedUserIds(ctx.serverDB,- { actorUserId: ctx.userId, workspaceId },- input.editorData,+ { excludeUserId: ctx.userId, workspaceId },+ input,);addedMentionUserIds = nextMentions.filter((id) => !previousMentions.has(id));}diff --git a/apps/server/src/utils/__tests__/commentMentions.test.ts b/apps/server/src/utils/__tests__/commentMentions.test.tsindex 1e18f3ec74a..d60fb5f3e37 100644--- a/apps/server/src/utils/__tests__/commentMentions.test.ts+++ b/apps/server/src/utils/__tests__/commentMentions.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from 'vitest';-import { extractMentionedUserIds } from '../commentMentions';+import {+ extractCommentMentionedUserIds,+ extractMarkdownMentionedUserIds,+ extractMentionedUserIds,+} from '../commentMentions';const mention = (id: unknown, type = 'member') => ({label: 'Alex',@@ -35,3 +39,54 @@ describe('extractMentionedUserIds', () => {expect(extractMentionedUserIds({ root: null })).toEqual([]);});});++describe('extractMarkdownMentionedUserIds', () => {+ it('returns ids from serialized mention tags, deduplicated', () => {+ const content =+ 'Hi <mention name="Arvin" id="user-1" />, cc <mention id="user-2" name="Lin"/> and <mention name="Arvin" id="user-1" />';++ expect(extractMarkdownMentionedUserIds(content)).toEqual(['user-1', 'user-2']);+ });++ it('ignores plain @names, tags without an id and non-string input', () => {+ expect(extractMarkdownMentionedUserIds('@Arvin please review')).toEqual([]);+ expect(extractMarkdownMentionedUserIds('<mention name="Arvin" />')).toEqual([]);+ expect(extractMarkdownMentionedUserIds('<mention name="A" data-id="user-1" />')).toEqual([]);+ expect(extractMarkdownMentionedUserIds('<mention name="A" id="user-1">')).toEqual([]);+ expect(extractMarkdownMentionedUserIds(undefined)).toEqual([]);+ });++ it('accepts unquoted ids, as left by shell quoting of `lh task comment -m "β¦"`', () => {+ // What the CLI receives for: -m "<mention name="Arvin" id="user_1" /> done"+ expect(extractMarkdownMentionedUserIds('<mention name=Arvin id=user_1 /> done')).toEqual([+ 'user_1',+ ]);+ });++ it('accepts single-quoted ids and skips tags quoted in code', () => {+ const content = [+ "Hi <mention name='Arvin' id='user-1' />",+ 'Syntax: `<mention name="X" id="user-2" />`',+ '```',+ '<mention name="Y" id="user-3" />',+ '```',+ '~~~',+ '<mention name="Z" id="user-4" />',+ '~~~',+ '',+ ' <mention name="W" id="user-5" />',+ ].join('\n');++ expect(extractMarkdownMentionedUserIds(content)).toEqual(['user-1']);+ });+});++describe('extractCommentMentionedUserIds', () => {+ it('prefers the rich-text snapshot and falls back to markdown tags', () => {+ const content = '<mention name="B" id="user-2" />';+ const editorData = { root: { children: [mention('user-1')] } };++ expect(extractCommentMentionedUserIds({ content, editorData })).toEqual(['user-1']);+ expect(extractCommentMentionedUserIds({ content, editorData: null })).toEqual(['user-2']);+ });+});diff --git a/apps/server/src/utils/commentMentions.ts b/apps/server/src/utils/commentMentions.tsindex 68435442915..de6bf0032da 100644--- a/apps/server/src/utils/commentMentions.ts+++ b/apps/server/src/utils/commentMentions.ts@@ -1,5 +1,8 @@import { pickNonEmptyString, toRecord } from '@lobechat/utils/object';import { and, eq, inArray, isNull } from 'drizzle-orm';+import remarkParse from 'remark-parse';+import { unified } from 'unified';+import { visit } from 'unist-util-visit';import { workspaceMembers } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';@@ -31,6 +34,54 @@ export const extractMentionedUserIds = (editorData: unknown): string[] => {return [...userIds];};+// Self-closing only, like the renderer: `<mention id="β¦">` never renders as one.+const MARKDOWN_MENTION_TAG = /<mention(\s[^>]*)\/>/gi;+// Same attribute forms the renderer accepts. Unquoted values matter: a shell+// strips the inner quotes of `lh task comment -m "<mention id="β¦" />"`.+const TAG_ATTRIBUTE = /([\w-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+)))?/g;++const readMentionId = (attributes: string): string | undefined => {+ for (const [, key, doubleQuoted, singleQuoted, unquoted] of attributes.matchAll(TAG_ATTRIBUTE)) {+ if (key.toLowerCase() === 'id') return (doubleQuoted ?? singleQuoted ?? unquoted)?.trim();+ }+};++/**+ * Collect the member ids referenced by serialized `<mention name="β¦" id="β¦" />`+ * tags in a markdown comment body. This is the form the comment editor writes+ * for a mention, and the only way a markdown-only author (CLI, agent tools)+ * can address a member.+ */+export const extractMarkdownMentionedUserIds = (content: unknown): string[] => {+ if (typeof content !== 'string' || !content.includes('<mention')) return [];++ const userIds = new Set<string>();+ // Only raw HTML and prose can hold a mention; any code context (fenced,+ // indented, inline) renders literally, so the parsed tree skips it.+ visit(unified().use(remarkParse).parse(content), ['html', 'text'], (node) => {+ const { value } = node as { value?: unknown };+ if (typeof value !== 'string') return;+ for (const [, attributes] of value.matchAll(MARKDOWN_MENTION_TAG)) {+ const userId = readMentionId(attributes);+ if (userId) userIds.add(userId);+ }+ });+ return [...userIds];+};++/**+ * Mention candidates of a comment revision. The rich-text snapshot is the+ * source of truth when present (its markdown is derived from it); a+ * markdown-only revision falls back to its serialized mention tags.+ */+export const extractCommentMentionedUserIds = (comment: {+ content?: unknown;+ editorData?: unknown;+}): string[] =>+ comment.editorData+ ? extractMentionedUserIds(comment.editorData)+ : extractMarkdownMentionedUserIds(comment.content);+/*** Keep only the ids that are active members of the Workspace, preserving* order and dropping duplicates. Shared by the mention validator and by every@@ -74,3 +125,20 @@ export const validateMentionedUserIds = async (scope.workspaceId,extractMentionedUserIds(editorData).filter((id) => id !== scope.actorUserId),);++/**+ * Task-comment counterpart of `validateMentionedUserIds`: the revision may+ * only carry markdown (see `extractCommentMentionedUserIds`), and+ * `excludeUserId` is optional because an agent writing on a member's behalf+ * may @mention that member.+ */+export const validateTaskCommentMentionedUserIds = async (+ db: LobeChatDatabase,+ scope: { excludeUserId?: string; workspaceId: string },+ comment: { content?: unknown; editorData?: unknown },+): Promise<string[]> =>+ filterActiveWorkspaceMemberIds(+ db,+ scope.workspaceId,+ extractCommentMentionedUserIds(comment).filter((id) => id !== scope.excludeUserId),+ );diff --git a/packages/builtin-skills/src/task/SKILL.md b/packages/builtin-skills/src/task/SKILL.mdindex d3d33bfdfff..7e052d9e325 100644--- a/packages/builtin-skills/src/task/SKILL.md+++ b/packages/builtin-skills/src/task/SKILL.md@@ -47,7 +47,7 @@ You are executing a task within the LobeHub task system. Use the `lh task` CLI v- **Check your task first**: Use `lh task view` to understand the full instruction and context- **Use task documents**: Store outputs and deliverables as task documents-- **Report progress**: Use `lh task comment` to log key milestones+- **Report progress**: Use `lh task comment` to log key milestones. To notify a member who needs to act, mention them with `<mention name="Name" id="user_xxx" />`, taking the id from `lh workspace members` (never guess it); a plain "@Name" is only text. Each mention sends a notification, so do not @ people in routine progress notes.- **Respect dependencies**: Check `lh task tree` to understand task ordering- **Complete when done**: Use `lh task complete` when all deliverables are ready- **Automation tasks are the exception β NEVER complete them**: a task with automation (heartbeat or schedule β shown as an `Automation:` line in the task context) is a recurring loop, and this run is one tick of it. NEVER run `lh task complete` (or set a terminal status via `lh task edit --status`) on that task: a terminal status permanently disarms the loop β no future tick will fire and nothing recovers it. A tick with nothing to do, or whose condition is not met yet, is still a successful run; just finish your turn and the next tick is armed automatically. Only the user retires a recurring task.diff --git a/packages/builtin-skills/src/task/references/commands.md b/packages/builtin-skills/src/task/references/commands.mdindex 826729e2dc2..503a7bc77cc 100644--- a/packages/builtin-skills/src/task/references/commands.md+++ b/packages/builtin-skills/src/task/references/commands.md@@ -27,7 +27,7 @@- `lh task resume <id>` - Resume paused task- `lh task complete <id>` - Mark as completed- `lh task cancel <id>` - Cancel task-- `lh task comment <id> -m <message>` - Add comment+- `lh task comment <id> -m <message>` - Add comment. To notify a member who needs to act, mention them with `<mention name="Name" id="user_xxx" />`, taking the id from `lh workspace members` (never guess it); a plain "@Name" is only text. Each mention sends a notification, so do not @ people in routine progress notes.- `lh task sort <parentId> <id1> <id2> ...` - Reorder subtasks- `lh task heartbeat <id>` - Send manual heartbeat- `lh task watchdog` - Detect and fail stuck tasksdiff --git a/packages/builtin-tool-task/src/manifest.ts b/packages/builtin-tool-task/src/manifest.tsindex c4b24107108..c493584998d 100644--- a/packages/builtin-tool-task/src/manifest.ts+++ b/packages/builtin-tool-task/src/manifest.ts@@ -196,7 +196,8 @@ export const TaskManifest: BuiltinToolManifest = {parameters: {properties: {content: {- description: 'Comment content to add to the task.',+ description:+ 'Comment content to add to the task (markdown). To notify a workspace member who needs to act, mention them with <mention name="Name" id="user_xxx" />, resolving the id with listWorkspaceMembers first (never guess it); a plain "@Name" is only text.',type: 'string',},identifier: {@@ -220,7 +221,8 @@ export const TaskManifest: BuiltinToolManifest = {type: 'string',},content: {- description: 'Updated comment content.',+ description:+ 'Updated comment content (markdown). Newly added <mention name="Name" id="user_xxx" /> tags notify those members; resolve ids with listWorkspaceMembers.',type: 'string',},},diff --git a/packages/business-server/src/task/notifyTaskCommentActivity.ts b/packages/business-server/src/task/notifyTaskCommentActivity.tsindex b729ac15ba3..e1588bcfb59 100644--- a/packages/business-server/src/task/notifyTaskCommentActivity.ts+++ b/packages/business-server/src/task/notifyTaskCommentActivity.ts@@ -6,7 +6,13 @@ export interface TaskCommentActivityRecipient {}export interface NotifyTaskCommentActivityParams {- /** The member who wrote / edited the comment β never notified. */+ /**+ * The agent that wrote the comment on `actorUserId`'s behalf. When set, the+ * notification is attributed to the agent and `actorUserId` is an ordinary+ * recipient (an agent may @mention the member it runs for).+ */+ actorAgentId?: string;+ /** The member who wrote / edited the comment β never notified unless `actorAgentId` is set. */actorUserId: string;commentId: string;/** Deduplicated by userId; `mentioned` wins over `commented` for the same member. */diff --git a/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx b/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsxindex ae673bcfeb6..54b8a6bee7d 100644--- a/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/CommentCard.tsx@@ -23,6 +23,7 @@ import { useTaskStore } from '@/store/task';import { isOptimisticActivityId } from '@/store/task/slices/detail/optimisticActivity';import { styles } from '../shared/style';+import { commentMarkdownProps } from './commentMarkdown';// Keep saved comments visually consistent with the editor: render FileNodes// as the Linear-style card on its own row instead of the default inline pill.@@ -191,7 +192,7 @@ const CommentCard = memo<CommentCardProps>(({ activity }) => {/>)}{!isEditing && !activity.editorData && (- <Markdown fontSize={14} variant={'chat'}>+ <Markdown fontSize={14} variant={'chat'} {...commentMarkdownProps}>{content}</Markdown>)}diff --git a/src/features/AgentTasks/AgentTaskDetail/commentMarkdown.tsx b/src/features/AgentTasks/AgentTaskDetail/commentMarkdown.tsxnew file mode 100644index 00000000000..86f589e7452--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/commentMarkdown.tsx@@ -0,0 +1,43 @@+import { type MarkdownProps } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';++import { MENTION_TAG } from '@/const/plugin';+import { createRemarkSelfClosingTagPlugin } from '@/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin';++const styles = stylex.create({+ mention: {+ color: cssVar.colorInfo,+ wordBreak: 'break-word',+ },+});++interface CommentMentionProps {+ node?: { properties?: { id?: string; name?: string } };+}++/**+ * Markdown-only comments (CLI, agent tools) carry member mentions as the same+ * `<mention name="β¦" id="β¦" />` tag the comment editor serializes. Render it+ * like the rich-text mention instead of dropping it as raw HTML.+ */+const CommentMention = memo<CommentMentionProps>(({ node }) => {+ const { id, name } = node?.properties || {};+ if (!name && !id) return null;++ const { className, style } = stylex.props(styles.mention);+ return (+ <span className={`editor_mention ${className ?? ''}`} style={style}>+ @{name || id}+ </span>+ );+});++CommentMention.displayName = 'TaskCommentMention';++export const commentMarkdownProps = {+ components: { [MENTION_TAG]: CommentMention },+ // Inline code stays literal, matching the server: a quoted tag is not a mention.+ remarkPlugins: [createRemarkSelfClosingTagPlugin(MENTION_TAG, { inlineCode: false })],+} satisfies Partial<MarkdownProps>;diff --git a/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.test.tsindex 680f5d6b3c6..ab15fbe354d 100644--- a/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts+++ b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts@@ -344,4 +344,15 @@ describe('createRemarkSelfClosingTagPlugin', () => {expect(paragraphChildren[2].type).toBe('text');expect(paragraphChildren[2].value).toBe(' in your code.');});++ it('keeps backtick-wrapped tags literal when inlineCode is disabled', () => {+ const markdown = `Syntax: \`<${tagName} name="config.json" path="/app/config.json" />\``;+ const processor = unified()+ .use(remarkParse)+ .use(createRemarkSelfClosingTagPlugin(tagName, { inlineCode: false }));+ const tree: any = processor.runSync(processor.parse(markdown));++ expect(collectNodesByType(tree, tagName)).toHaveLength(0);+ expect(collectNodesByType(tree, 'inlineCode')).toHaveLength(1);+ });});diff --git a/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.ts b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.tsindex bfa5f02b56a..766b047d88a 100644--- a/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.ts+++ b/src/features/Conversation/Markdown/plugins/remarkPlugins/createRemarkSelfClosingTagPlugin.ts@@ -23,8 +23,16 @@ const parseAttributes = (attributeString: string): Record<string, string | boolereturn attributes;};+export interface RemarkSelfClosingTagOptions {+ /**+ * Also turn an exact backtick-wrapped tag into a tag node. Defaults to true;+ * disable it where inline code must stay literal (e.g. quoted syntax).+ */+ inlineCode?: boolean;+}+export const createRemarkSelfClosingTagPlugin =- (tagName: string): Plugin<[], any> =>+ (tagName: string, options: RemarkSelfClosingTagOptions = {}): Plugin<[], any> =>() => {// Regex for the specific tag, ensure it matches the entire string for HTML check// Allow trailing whitespace after /> to handle cases where markdown parsers include it@@ -189,6 +197,8 @@ export const createRemarkSelfClosingTagPlugin =}});+ if (options.inlineCode === false) return;+// 3. Visit inlineCode nodes (backtick-wrapped tags like `<localFile ... />`)// @ts-ignorevisit(tree, 'inlineCode', (node: any, index: number, parent) => {