🤯 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(channel): invite outsiders into a channel by @mentioning them (#22294)
AmAzing-283c606ed884
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.jsonindex 09c6f63641b..18159a4152c 100644--- a/locales/en-US/channel.json+++ b/locales/en-US/channel.json@@ -106,6 +106,9 @@"membersCount": "Members · {{count}}","membersTitle": "Members","mentionHint": "Mention Agents to choose who replies. Without a mention, every Agent here replies.",+ "mentionInvite.failed": "Couldn't add {{name}} to the channel. Try again.",+ "mentionInvite.failedReason": "Couldn't add {{name}} to the channel: {{reason}}",+ "mentionInvite.section": "Not in this channel · mention to add","moveToTrash": "Move channel to trash","moveToTrashConfirm": "Move “{{title}}” to trash? Replies will stop. You can restore the channel and its history from Trash. Agents and files will be kept.","moveToTrashSuccess": "Channel moved to trash",diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.jsonindex 8662f99d2fb..414f579c3ed 100644--- a/locales/zh-CN/channel.json+++ b/locales/zh-CN/channel.json@@ -106,6 +106,9 @@"membersCount": "成员 · {{count}}","membersTitle": "成员","mentionHint": "@ Agent 可指定谁来回复;不 @ 时,频道里的所有 Agent 都会回复。",+ "mentionInvite.failed": "未能将 {{name}} 加入频道,请重试。",+ "mentionInvite.failedReason": "未能将 {{name}} 加入频道:{{reason}}",+ "mentionInvite.section": "不在频道中 · @ 后将加入","moveToTrash": "移至回收站","moveToTrashConfirm": "将「{{title}}」移至回收站?进行中的回复会停止,你可以在回收站恢复频道和历史消息。Agent 和文件将保留。","moveToTrashSuccess": "频道已移至回收站",diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.tsindex 8428968c7d4..3906af016c7 100644--- a/packages/locales/src/default/channel.ts+++ b/packages/locales/src/default/channel.ts@@ -107,6 +107,9 @@ export default {'conversationEmpty': 'Start the conversation','mentionHint':'Mention Agents to choose who replies. Without a mention, every Agent here replies.',+ 'mentionInvite.failed': "Couldn't add {{name}} to the channel. Try again.",+ 'mentionInvite.failedReason': "Couldn't add {{name}} to the channel: {{reason}}",+ 'mentionInvite.section': 'Not in this channel · mention to add','attachments.upload': 'Attach files','attachments.failed': 'Upload failed. Try again.','attachments.limit': 'Attach up to {{count}} files.',diff --git a/src/features/Channels/ChannelConversation.tsx b/src/features/Channels/ChannelConversation.tsxindex 4dfd2b30fa8..6c787874dd8 100644--- a/src/features/Channels/ChannelConversation.tsx+++ b/src/features/Channels/ChannelConversation.tsx@@ -232,6 +232,7 @@ const Timeline = ({) : (<Composeractivity={<ReplyActivity detail={detail} threadId={threadId} />}+ channel={detail.channel}draftKey={channelDraftKey(channelId, threadId)}key={channelDraftKey(channelId, threadId)}members={activeMembers}diff --git a/src/features/Channels/Composer.tsx b/src/features/Channels/Composer.tsxindex 5b8457ce036..e22999ba543 100644--- a/src/features/Channels/Composer.tsx+++ b/src/features/Channels/Composer.tsx@@ -1,4 +1,4 @@-import type { ChannelPublicMember } from '@lobechat/types';+import type { ChannelListItem, ChannelPublicMember } from '@lobechat/types';import type { ISlashOption } from '@lobehub/editor';import {INSERT_MENTION_COMMAND,@@ -33,17 +33,24 @@ import { userProfileSelectors } from '@/store/user/selectors';import { MemberAvatar } from './MemberAvatar';import { isCurrentUserMember, memberName } from './memberName';import { getMentionGroups } from './mentionGroups';-import { $insertChannelMentionBoundary, channelMentionIds } from './mentions';+import type { ChannelMentionInvite } from './mentions';+import {+ $insertChannelMentionBoundary,+ channelMentionIds,+ channelMentionInvites,+} from './mentions';import { createChannelSendRequest } from './sendRequest';import { styles } from './styles';import { useAttachments } from './useAttachments';import { useComposerDraft } from './useComposerDraft';+import { useMentionInvites } from './useMentionInvites';import type { ChannelReplyTarget } from './useReplyTarget';const plugins = [ReactCodePlugin, ReactListPlugin, ReactLinkHighlightPlugin, ReactMentionPlugin];export function Composer({activity,+ channel,draftKey,members,onSend,@@ -54,6 +61,8 @@ export function Composer({}: {/** Who is replying right now; shown on the line above the input. */activity?: ReactNode;+ /** Lets an @mention invite people and Agents from outside the Channel. */+ channel?: ChannelListItem;/** Where unsent input is kept; see {@link useComposerDraft}. */draftKey: string;members: ChannelPublicMember[];@@ -98,6 +107,7 @@ export function Composer({const memberIds = members.map((member) => member.id);// Mentioning yourself notifies nobody and picks no reply.const mentionable = members.filter((member) => !isCurrentUserMember(member, userId));+ const invites = useMentionInvites(channel, members);const send = async () => {const value = String(editor.getDocument('markdown') || '').trim();const fileIds = attachments.readyFileIds();@@ -105,15 +115,20 @@ export function Composer({sending.current = true;setBusy(true);setError('');+ invites.clearError();const sentRevision = draft.snapshot();- const mentions = channelMentionIds(editor.getDocument('json'), memberIds);- const requestKey = requests.get(`${cacheScope.get()}:${draftKey}`, {- content: value,- fileIds,- mentions,- replyToId: replyTarget?.id,- });+ const document = editor.getDocument('json');try {+ // Mentioned outsiders join first, so the message can address them as members.+ const invited = await invites.resolve(channelMentionInvites(document));+ if (!invited) return;+ const mentions = [...new Set([...channelMentionIds(document, memberIds), ...invited])];+ const requestKey = requests.get(`${cacheScope.get()}:${draftKey}`, {+ content: value,+ fileIds,+ mentions,+ replyToId: replyTarget?.id,+ });await onSend(value, mentions, requestKey, fileIds, replyTarget?.id);requests.complete(requestKey);editor.cleanDocument();@@ -227,10 +242,12 @@ export function Composer({type="text"variant="chat"mentionOption={{- items: async (search) =>- getMentionGroups(+ items: async (search) => {+ const query = search?.matchingString || '';+ const outsiders = await invites.options(query);+ const options = getMentionGroups(mentionable,- search?.matchingString || '',+ query,t('deletedMember'),!!workspaceId,).flatMap<ISlashOption>((group) => {@@ -250,13 +267,28 @@ export function Composer({},]: items;- }),+ });+ return outsiders.length+ ? [+ ...options,+ {+ type: 'section' as const,+ key: 'invite',+ label: t('mentionInvite.section'),+ items: outsiders,+ },+ ]+ : options;+ },markdownWriter: (node) => `@${node.label}`,onSelect: (instance, option) => {instance.dispatchCommand(INSERT_MENTION_COMMAND, {label: String(option.label),metadata: option.metadata,});+ // Choosing someone outside the Channel brings them in right away.+ if (option.metadata?.type === 'channel-invite')+ invites.invite(option.metadata as ChannelMentionInvite);// Leave the decorator's cursor node before the next @ is typed.instance.getLexicalEditor()?.update(() => {const selection = $getSelection();@@ -278,7 +310,8 @@ export function Composer({}}}onKeyDown={({ event }) =>- mentionable.length > 0 && $insertChannelMentionBoundary(event)+ (mentionable.length > 0 || invites.enabled) &&+ $insertChannelMentionBoundary(event)}onPressEnter={({ event }) => {if (event.isComposing || !shouldSendOnEnter(event)) return;@@ -299,11 +332,12 @@ export function Composer({/></div></ChatInput>- {error && (+ {(error || invites.error) && (<span {...stylex.props(styles.error)} role="alert">- {error}+ {error || invites.error}</span>)}+ {invites.agentDrafts}</Flexbox></WideScreenContainer>);diff --git a/src/features/Channels/CreateChannel/EnvironmentFields.tsx b/src/features/Channels/CreateChannel/EnvironmentFields.tsxindex fed3969e2ea..b08d1b8d0fe 100644--- a/src/features/Channels/CreateChannel/EnvironmentFields.tsx+++ b/src/features/Channels/CreateChannel/EnvironmentFields.tsx@@ -8,19 +8,13 @@ import AsyncError from '@/components/AsyncError';import { openPickWorkingDirModal } from '@/features/WorkingDirectory';import type { DeviceListResult } from '@/store/device/useDeviceList';-import type { ChannelAgentIssue } from './agentEnvironment';+import { channelAgentIssueKey } from './agentEnvironment';import type { useChannelAgentDraft } from './useChannelAgentDraft';const styles = stylex.create({directory: { maxWidth: '100%', overflow: 'hidden' },});-/** Device issues of an inherited environment are fixed in the Agent's settings, not here. */-const INHERITED_ISSUES = ['deviceOffline', 'deviceRequired', 'deviceUnavailable'] as const;--const isInheritedIssue = (issue: ChannelAgentIssue): issue is (typeof INHERITED_ISSUES)[number] =>- (INHERITED_ISSUES as readonly ChannelAgentIssue[]).includes(issue);-export const deviceLabel = (device: DeviceListItem) =>device.friendlyName || device.hostname || device.deviceId;@@ -127,9 +121,7 @@ export const EnvironmentIssue = ({role="status"type={checking ? 'secondary' : 'danger'}>- {inherited && isInheritedIssue(draft.issue)- ? t(`environment.inherited.${draft.issue}`)- : t(`environment.${draft.issue}`)}+ {t(channelAgentIssueKey(draft.issue, inherited))}</Text>);};diff --git a/src/features/Channels/CreateChannel/agentEnvironment.ts b/src/features/Channels/CreateChannel/agentEnvironment.tsindex 65615a18556..366e2fdd24c 100644--- a/src/features/Channels/CreateChannel/agentEnvironment.ts+++ b/src/features/Channels/CreateChannel/agentEnvironment.ts@@ -36,6 +36,18 @@ export interface ChannelAgentEnvironment {workspaceScoped?: boolean;}+/** Device issues of an inherited environment are fixed in the Agent's settings, not here. */+const INHERITED_ISSUES = ['deviceOffline', 'deviceRequired', 'deviceUnavailable'] as const;++const isInheritedIssue = (issue: ChannelAgentIssue): issue is (typeof INHERITED_ISSUES)[number] =>+ (INHERITED_ISSUES as readonly ChannelAgentIssue[]).includes(issue);++/** The `channel` locale key that explains an issue. */+export const channelAgentIssueKey = (issue: ChannelAgentIssue, inherited?: boolean) =>+ inherited && isInheritedIssue(issue)+ ? (`environment.inherited.${issue}` as const)+ : (`environment.${issue}` as const);+const getRuntime = ({ agencyConfig, model }: ChannelAgentEnvironment) =>agencyConfig?.heterogeneousProvider?.type ??(isHeterogeneousAgentModelId(model) ? model! : 'native');diff --git a/src/features/Channels/DraftThreadConversation.tsx b/src/features/Channels/DraftThreadConversation.tsxindex 091fa1f76b9..5542a72d5f2 100644--- a/src/features/Channels/DraftThreadConversation.tsx+++ b/src/features/Channels/DraftThreadConversation.tsx@@ -50,6 +50,7 @@ export function DraftThreadConversation({<ArchivedNotice channel={detail.channel} threadId={null} />) : (<Composer+ channel={detail.channel}draftKey={channelDraftKey(detail.channel.id, `draft:${draft.root.id}`)}members={detail.members.filter((member) => member.status === 'active')}placeholder={t('threadComposer')}diff --git a/src/features/Channels/mentionGroups.test.ts b/src/features/Channels/mentionGroups.test.tsindex 4b72dda53a4..39c1762ce9d 100644--- a/src/features/Channels/mentionGroups.test.ts+++ b/src/features/Channels/mentionGroups.test.ts@@ -1,7 +1,7 @@import type { ChannelPublicMember } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import { getMentionGroups } from './mentionGroups';+import { getMentionGroups, matchInviteAgents, MENTION_INVITE_LIMIT } from './mentionGroups';const member = (id: string,@@ -84,3 +84,48 @@ describe('Channel mention groups', () => {expect(getMentionGroups([user, agent], 'zzzzzzz', 'Former member')).toEqual([]);});});++describe('Agents an @mention can invite', () => {+ const outside = [+ { id: 'agt_writer', name: 'Writer' },+ { id: 'agt_review', name: 'Code reviewer' },+ { id: 'agt_lead', name: 'Project writer' },+ { id: 'agt_joined', name: 'Writer two' },+ ];+ const match = (query: string, priorityIds: string[] = []) =>+ matchInviteAgents(outside, {+ exclude: ['agt_joined'],+ nameOf: (agent) => agent.name,+ priorityIds,+ query,+ }).map((agent) => agent.id);++ it('lists nobody until a name is typed', () => {+ expect(match('')).toEqual([]);+ expect(match(' ')).toEqual([]);+ });++ it('matches names case-insensitively and skips Agents already in the Channel', () => {+ expect(match('WRITER')).toEqual(['agt_writer', 'agt_lead']);+ expect(match('zzz')).toEqual([]);+ });++ it("puts the project's own Agents first", () => {+ expect(match('writer', ['agt_lead'])).toEqual(['agt_lead', 'agt_writer']);+ });++ it('caps the suggestions', () => {+ const many = Array.from({ length: MENTION_INVITE_LIMIT + 3 }, (_, index) => ({+ id: `agt_${index}`,+ name: `Helper ${index}`,+ }));+ expect(+ matchInviteAgents(many, {+ exclude: [],+ nameOf: (a) => a.name,+ priorityIds: [],+ query: 'helper',+ }),+ ).toHaveLength(MENTION_INVITE_LIMIT);+ });+});diff --git a/src/features/Channels/mentionGroups.ts b/src/features/Channels/mentionGroups.tsindex e4eafe61f57..d73b18812be 100644--- a/src/features/Channels/mentionGroups.ts+++ b/src/features/Channels/mentionGroups.ts@@ -1,6 +1,7 @@import type { ChannelPublicMember } from '@lobechat/types';import Fuse from 'fuse.js';+import { splitByPriority } from './CreateChannel/projectAgentOrder';import { memberName } from './memberName';/** Keep mention search results grouped, preserving relevance within each actor type. */@@ -28,3 +29,29 @@ export function getMentionGroups(})).filter((group) => group.members.length > 0);}++/** At most this many outsiders of each kind follow the Channel's own members. */+export const MENTION_INVITE_LIMIT = 5;++/**+ * Agents outside the Channel whose name contains the query, the project's own first. An empty+ * query lists none: only a typed name reaches past the Channel's members.+ */+export function matchInviteAgents<T extends { id: string }>(+ agents: T[],+ {+ exclude,+ nameOf,+ priorityIds,+ query,+ }: { exclude: string[]; nameOf: (agent: T) => string; priorityIds: string[]; query: string },+) {+ const search = query.trim().toLocaleLowerCase();+ if (!search) return [];+ const excluded = new Set(exclude);+ const matches = agents.filter(+ (agent) => !excluded.has(agent.id) && nameOf(agent).toLocaleLowerCase().includes(search),+ );+ const { others, priority } = splitByPriority(matches, priorityIds);+ return [...priority, ...others].slice(0, MENTION_INVITE_LIMIT);+}diff --git a/src/features/Channels/mentions.test.ts b/src/features/Channels/mentions.test.tsindex 5642976ee1a..55ecfc8cb5d 100644--- a/src/features/Channels/mentions.test.ts+++ b/src/features/Channels/mentions.test.ts@@ -1,7 +1,11 @@import { $createParagraphNode, $createTextNode, $getRoot, createEditor } from 'lexical';import { describe, expect, it } from 'vitest';-import { $insertChannelMentionBoundary, channelMentionIds } from './mentions';+import {+ $insertChannelMentionBoundary,+ channelMentionIds,+ channelMentionInvites,+} from './mentions';describe('Channel mention boundaries', () => {const insert = (@@ -87,3 +91,34 @@ describe('Channel recipient chips', () => {expect(channelMentionIds({ root: { children: [] } }, ['A', 'B'])).toEqual([]);});});++const inviteChip = (actorType: string, id: string) => ({+ type: 'mention',+ metadata: { actorType, id, name: `Name ${id}`, type: 'channel-invite' },+});+describe('Channel invite chips', () => {+ it('lists each outsider once, ignoring member chips, code and malformed metadata', () => {+ expect(+ channelMentionInvites({+ root: {+ children: [+ inviteChip('user', 'user_b'),+ chip('A'),+ inviteChip('agent', 'agt_a'),+ inviteChip('user', 'user_b'),+ { type: 'code', children: [inviteChip('user', 'user_c')] },+ inviteChip('robot', 'x'),+ inviteChip('agent', ''),+ ],+ },+ }),+ ).toEqual([+ { actorType: 'user', id: 'user_b', name: 'Name user_b', type: 'channel-invite' },+ { actorType: 'agent', id: 'agt_a', name: 'Name agt_a', type: 'channel-invite' },+ ]);+ });++ it('never treats an invite chip as an existing recipient', () => {+ expect(channelMentionIds({ root: { children: [inviteChip('user', 'A')] } }, ['A'])).toEqual([]);+ });+});diff --git a/src/features/Channels/mentions.ts b/src/features/Channels/mentions.tsindex 27e3c1dad97..26c3451fd71 100644--- a/src/features/Channels/mentions.ts+++ b/src/features/Channels/mentions.ts@@ -1,3 +1,5 @@+import type { ChannelMemberActorType } from '@lobechat/types';+import type { UnknownRecord } from '@lobechat/utils/object';import { isRecord } from '@lobechat/utils/object';import { $getSelection, $isRangeSelection, $isTextNode } from 'lexical';@@ -17,10 +19,18 @@ export function $insertChannelMentionBoundary(event: KeyboardEvent): boolean {return true;}-/** Only editor-created member chips select recipients; plain text and code never do. */-export function channelMentionIds(document: unknown, memberIds: string[]): string[] {- const allowed = new Set(memberIds);- const result = new Set<string>();+/** Chip metadata for someone outside the Channel; choosing them invites them in. */+export interface ChannelMentionInvite {+ actorType: ChannelMemberActorType;+ /** The user id of a person, or the Agent id. */+ id: string;+ /** Shown when they cannot be added. */+ name: string;+ type: 'channel-invite';+}++/** Visits the metadata of every editor-created mention chip outside code. */+const visitMentionMetadata = (document: unknown, onMention: (metadata: UnknownRecord) => void) => {const visit = (value: unknown) => {if (Array.isArray(value)) {value.forEach(visit);@@ -29,17 +39,44 @@ export function channelMentionIds(document: unknown, memberIds: string[]): strinif (!isRecord(value)) return;const node = value;if (typeof node.type === 'string' && /code/i.test(node.type)) return;- const metadata = isRecord(node.metadata) ? node.metadata : undefined;+ if (node.type === 'mention' && isRecord(node.metadata)) onMention(node.metadata);+ if (node.root) visit(node.root);+ if (node.children) visit(node.children);+ };+ visit(document);+};++/** Only editor-created member chips select recipients; plain text and code never do. */+export function channelMentionIds(document: unknown, memberIds: string[]): string[] {+ const allowed = new Set(memberIds);+ const result = new Set<string>();+ visitMentionMetadata(document, (metadata) => {if (- node.type === 'mention' &&- metadata?.type === 'channel-member' &&+ metadata.type === 'channel-member' &&typeof metadata.id === 'string' &&allowed.has(metadata.id))result.add(metadata.id);- if (node.root) visit(node.root);- if (node.children) visit(node.children);- };- visit(document);+ });return [...result];}++/** People and Agents mentioned from outside the Channel, once each. */+export function channelMentionInvites(document: unknown): ChannelMentionInvite[] {+ const result = new Map<string, ChannelMentionInvite>();+ visitMentionMetadata(document, (metadata) => {+ if (+ metadata.type === 'channel-invite' &&+ (metadata.actorType === 'agent' || metadata.actorType === 'user') &&+ typeof metadata.id === 'string' &&+ metadata.id+ )+ result.set(`${metadata.actorType}:${metadata.id}`, {+ actorType: metadata.actorType,+ id: metadata.id,+ name: typeof metadata.name === 'string' ? metadata.name : '',+ type: 'channel-invite',+ });+ });+ return [...result.values()];+}diff --git a/src/features/Channels/useMentionInvites.test.ts b/src/features/Channels/useMentionInvites.test.tsnew file mode 100644index 00000000000..7209e894206--- /dev/null+++ b/src/features/Channels/useMentionInvites.test.ts@@ -0,0 +1,235 @@+import type { ChannelListItem, ChannelPublicMember } from '@lobechat/types';+import { act, cleanup, render, renderHook, waitFor } from '@testing-library/react';+import { createElement, Fragment } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { channelService } from '@/services/channel';+import { channelActions } from '@/store/channel';++import type { ChannelMentionInvite } from './mentions';+import { useMentionInvites } from './useMentionInvites';++const { agentDraft } = vi.hoisted(() => ({+ agentDraft: { issue: undefined as string | undefined },+}));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: Record<string, string>) =>+ options ? `${key} ${JSON.stringify(options)}` : key,+ }),+}));+vi.mock('@/components/AgentAvatar', () => ({ default: () => null }));+vi.mock('@/components/Avatar', () => ({ default: () => null }));+vi.mock('@/store/device/useDeviceList', () => ({ useDeviceList: () => ({}) }));+vi.mock('./CreateChannel/useChannelAgentOptions', () => ({+ useChannelAgentOptions: () => ({+ agents: [+ { id: 'agt_writer', title: 'Writer' },+ { id: 'agt_project', title: 'Project writer' },+ { id: 'agt_joined', title: 'Joined writer' },+ ],+ projectAgentIds: ['agt_project'],+ }),+}));+// The invite dialog's environment resolution, settled with the issue the test sets.+vi.mock('./CreateChannel/useChannelAgentDraft', () => ({+ useChannelAgentDraft: (draft: { agentId: string }) => ({+ draft: agentDraft.issue+ ? { ...draft, initialized: false, issue: agentDraft.issue }+ : { ...draft, deviceId: 'dev_1', initialized: true, issue: undefined },+ }),+}));++const channel: ChannelListItem = {+ agentId: null,+ canDelete: true,+ createdAt: new Date(0),+ id: 'chn_abcdefghijkl',+ projectId: null,+ sequence: 0,+ status: 'active',+ title: 'Team',+ workspaceId: 'ws_1',+};++const joinedAgent = {+ actorType: 'agent',+ agentId: 'agt_joined',+ id: 'mem_joined',+ status: 'active',+} as ChannelPublicMember;++const target = (actorType: 'agent' | 'user', id: string): ChannelMentionInvite => ({+ actorType,+ id,+ name: `Name ${id}`,+ type: 'channel-invite',+});++const setup = (current: ChannelListItem = channel, members = [joinedAgent]) => {+ const hook = renderHook(() => useMentionInvites(current, members));+ // Hidden Agent environment resolution mounts beside the editor.+ const drafts = () => createElement(Fragment, null, hook.result.current.agentDrafts);+ const view = render(drafts());+ return { ...hook, rerenderDrafts: () => view.rerender(drafts()) };+};++describe('@mentions that invite people and Agents from outside the Channel', () => {+ beforeEach(() => {+ agentDraft.issue = undefined;+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.spyOn(channelService, 'userCandidates').mockResolvedValue([+ { avatar: null, fullName: 'Writer Lin', userId: 'user_lin', username: 'lin' },+ ]);+ vi.spyOn(channelActions, 'addMember').mockImplementation(async (_, member) =>+ 'userId' in member ? `mem_${member.userId}` : `mem_${member.agent.agentId}`,+ );+ });+ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ });++ it('suggests matching outsiders only once a name is typed', async () => {+ const { result } = setup();+ expect(await result.current.options('')).toEqual([]);+ const options = await result.current.options('writer');+ expect(options.map((option) => option.metadata)).toEqual([+ { actorType: 'user', id: 'user_lin', name: 'Writer Lin', type: 'channel-invite' },+ // The project's own Agent first; Agents already in the Channel are left out.+ { actorType: 'agent', id: 'agt_project', name: 'Project writer', type: 'channel-invite' },+ { actorType: 'agent', id: 'agt_writer', name: 'Writer', type: 'channel-invite' },+ ]);+ expect(channelService.userCandidates).toHaveBeenCalledExactlyOnceWith(channel.id, 'writer');+ });++ it('searches people only for the query typing settled on', async () => {+ const { result } = setup();+ const [first, second] = await Promise.all([+ result.current.options('wri'),+ result.current.options('writer'),+ ]);+ expect(first.filter((option) => option.metadata.actorType === 'user')).toEqual([]);+ expect(second.map((option) => option.metadata.id)).toContain('user_lin');+ expect(channelService.userCandidates).toHaveBeenCalledExactlyOnceWith(channel.id, 'writer');+ });++ it('stops suggesting someone once they joined, even from a cached search', async () => {+ const lin = { actorType: 'user', id: 'mem_lin', status: 'active', userId: 'user_lin' };+ const { result, rerender } = renderHook(({ members }) => useMentionInvites(channel, members), {+ initialProps: { members: [joinedAgent] },+ });+ expect((await result.current.options('writer')).map((o) => o.metadata.id)).toContain(+ 'user_lin',+ );+ rerender({ members: [joinedAgent, lin as ChannelPublicMember] });+ expect((await result.current.options('writer')).map((o) => o.metadata.id)).not.toContain(+ 'user_lin',+ );+ });++ it('leaves an invite chip as plain text where no one can be invited', async () => {+ const { result } = setup({ ...channel, agentId: 'agt_direct' });+ await expect(+ result.current.resolve([target('user', 'user_lin'), target('agent', 'agt_joined')]),+ ).resolves.toEqual(['mem_joined']);+ expect(channelActions.addMember).not.toHaveBeenCalled();+ expect(result.current.error).toBe('');+ });++ it.each([+ ['someone who cannot invite', { canDelete: false }],+ ['an archived Channel', { status: 'archived' as const }],+ ['a direct conversation', { agentId: 'agt_direct' }],+ ])('suggests no outsiders in %s', async (_, patch) => {+ const { result } = setup({ ...channel, ...patch });+ expect(result.current.enabled).toBe(false);+ expect(await result.current.options('writer')).toEqual([]);+ });++ it('offers only Agents in a personal Channel, where people cannot join', async () => {+ const { result } = setup({ ...channel, workspaceId: null });+ const options = await result.current.options('writer');+ expect(options.map((option) => option.metadata.actorType)).toEqual(['agent', 'agent']);+ expect(channelService.userCandidates).not.toHaveBeenCalled();+ });++ it('adds a mentioned person once and resolves the message mention to the new member', async () => {+ const { result } = setup();+ act(() => {+ result.current.invite(target('user', 'user_lin'));+ });+ await expect(result.current.resolve([target('user', 'user_lin')])).resolves.toEqual([+ 'mem_user_lin',+ ]);+ expect(channelActions.addMember).toHaveBeenCalledExactlyOnceWith(channel.id, {+ userId: 'user_lin',+ });+ });++ it('does not re-add someone who is already a member', async () => {+ const { result } = setup();+ await expect(result.current.resolve([target('agent', 'agt_joined')])).resolves.toEqual([+ 'mem_joined',+ ]);+ expect(channelActions.addMember).not.toHaveBeenCalled();+ });++ it("adds an Agent with the invite dialog's environment defaults", async () => {+ const { result, rerenderDrafts } = setup();+ let resolved: Promise<string[] | undefined>;+ act(() => {+ resolved = result.current.resolve([target('agent', 'agt_writer')]);+ });+ rerenderDrafts();+ await expect(resolved!).resolves.toEqual(['mem_agt_writer']);+ expect(channelActions.addMember).toHaveBeenCalledExactlyOnceWith(channel.id, {+ agent: { agentId: 'agt_writer', deviceId: 'dev_1' },+ });+ });++ it('reports an Agent whose environment blocks it, and the message is not sent', async () => {+ agentDraft.issue = 'deviceOffline';+ const { result, rerenderDrafts } = setup();+ let resolved: Promise<string[] | undefined>;+ act(() => {+ resolved = result.current.resolve([target('agent', 'agt_writer')]);+ });+ rerenderDrafts();+ await expect(resolved!).resolves.toBeUndefined();+ expect(channelActions.addMember).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(result.current.error).toContain('environment.inherited.deviceOffline'),+ );+ });++ it('gives up on an Agent whose settings never finish loading', async () => {+ vi.useFakeTimers();+ try {+ agentDraft.issue = 'devicesLoading';+ const { result, rerenderDrafts } = setup();+ let resolved: Promise<string[] | undefined>;+ act(() => {+ resolved = result.current.resolve([target('agent', 'agt_writer')]);+ });+ rerenderDrafts();+ await act(() => vi.advanceTimersByTimeAsync(30_000));+ await expect(resolved!).resolves.toBeUndefined();+ expect(channelActions.addMember).not.toHaveBeenCalled();+ expect(result.current.error).toContain('environment.configurationFailed');+ } finally {+ vi.useRealTimers();+ }+ });++ it('reports a failed add and retries it when the message is sent', async () => {+ vi.mocked(channelActions.addMember).mockRejectedValueOnce(new Error('offline'));+ const { result } = setup();+ await expect(result.current.resolve([target('user', 'user_lin')])).resolves.toBeUndefined();+ await waitFor(() => expect(result.current.error).toContain('mentionInvite.failed'));+ await expect(result.current.resolve([target('user', 'user_lin')])).resolves.toEqual([+ 'mem_user_lin',+ ]);+ expect(channelActions.addMember).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/features/Channels/useMentionInvites.tsx b/src/features/Channels/useMentionInvites.tsxnew file mode 100644index 00000000000..d1d8dfc10a9--- /dev/null+++ b/src/features/Channels/useMentionInvites.tsx@@ -0,0 +1,305 @@+import { DEFAULT_USER_AVATAR } from '@lobechat/const';+import type { ChannelListItem, ChannelPublicMember } from '@lobechat/types';+import { agentDisplayName } from '@lobechat/types';+import type { ISlashMenuOption } from '@lobehub/editor';+import { useLatest } from 'ahooks';+import type { Dispatch, SetStateAction } from 'react';+import { useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import AgentAvatar from '@/components/AgentAvatar';+import Avatar from '@/components/Avatar';+import { useSingleton } from '@/hooks/useSingleton';+import type { ChannelAgentSelection, ChannelPersonOption } from '@/services/channel';+import { channelService } from '@/services/channel';+import { channelActions } from '@/store/channel';+import type { DeviceListResult } from '@/store/device/useDeviceList';+import { useDeviceList } from '@/store/device/useDeviceList';++import { canInviteMembers } from './channelAccess';+import type { ChannelAgentDraft, ChannelAgentIssue } from './CreateChannel/agentEnvironment';+import { channelAgentIssueKey, toChannelAgentSelection } from './CreateChannel/agentEnvironment';+import { getChannelSaveErrorKey } from './CreateChannel/saveError';+import { useChannelAgentDraft } from './CreateChannel/useChannelAgentDraft';+import { useChannelAgentOptions } from './CreateChannel/useChannelAgentOptions';+import { matchInviteAgents, MENTION_INVITE_LIMIT } from './mentionGroups';+import type { ChannelMentionInvite } from './mentions';++/** Like a chosen Agent in the invite dialog: it keeps its own device and directory. */+const INHERITED = { directoryOptional: true };+/** Issues that clear once loading finishes; any other issue blocks the invite. */+const LOADING_ISSUES = new Set<ChannelAgentIssue>(['configurationLoading', 'devicesLoading']);+/** A send waits this long for an Agent's settings and devices before giving up. */+const AGENT_RESOLVE_TIMEOUT_MS = 30_000;+/** Typing pauses this long before people are searched, like the invite dialog. */+const PEOPLE_SEARCH_DEBOUNCE_MS = 200;++class AgentIssueError extends Error {+ constructor(readonly issue: ChannelAgentIssue) {+ super(issue);+ }+}++const inviteKey = ({ actorType, id }: Pick<ChannelMentionInvite, 'actorType' | 'id'>) =>+ `${actorType}:${id}`;++/** Resolves one Agent's environment with the invite dialog's defaults, without showing it. */+const AgentDraft = ({+ devices,+ draft,+ onSettle,+ setDrafts,+}: {+ devices: DeviceListResult;+ draft: ChannelAgentDraft;+ onSettle: (draft: ChannelAgentDraft) => void;+ setDrafts: Dispatch<SetStateAction<ChannelAgentDraft[]>>;+}) => {+ const { draft: resolved } = useChannelAgentDraft(draft, devices, setDrafts, INHERITED);+ const settled = resolved.issue ? !LOADING_ISSUES.has(resolved.issue) : resolved.initialized;+ useEffect(() => {+ if (settled) onSettle(resolved);+ }, [onSettle, resolved, settled]);+ return null;+};++const AgentDrafts = ({+ drafts,+ onSettle,+ setDrafts,+}: {+ drafts: ChannelAgentDraft[];+ onSettle: (draft: ChannelAgentDraft) => void;+ setDrafts: Dispatch<SetStateAction<ChannelAgentDraft[]>>;+}) => {+ const devices = useDeviceList({ refreshInterval: 15_000 });+ return drafts.map((draft) => (+ <AgentDraft+ devices={devices}+ draft={draft}+ key={draft.agentId}+ setDrafts={setDrafts}+ onSettle={onSettle}+ />+ ));+};++/**+ * An @mention can reach people and Agents outside the Channel: typing a name lists the+ * matching workspace members and Agents, and choosing one adds them to the Channel, exactly+ * as the invite dialog would. Only someone who may invite sees them, and never in a direct+ * conversation, which stays one person and one Agent.+ */+export const useMentionInvites = (+ channel: ChannelListItem | undefined,+ members: ChannelPublicMember[],+) => {+ const { t } = useTranslation('channel');+ const enabled = !!channel && !channel.agentId && canInviteMembers(channel);+ const agentOptions = useChannelAgentOptions(+ enabled ? (channel.projectId ?? undefined) : undefined,+ );+ const [drafts, setDrafts] = useState<ChannelAgentDraft[]>([]);+ const [error, setError] = useState('');+ // The editor keeps the mention callbacks it was first given, so they read the latest render.+ const latest = useLatest({ agentOptions, channel, enabled, members });+ const running = useSingleton(() => new Map<string, Promise<string | undefined>>());+ const people = useSingleton(() => new Map<string, Promise<ChannelPersonOption[]>>());+ const latestQuery = useRef('');+ const agentWaiters = useSingleton(+ () =>+ new Map<+ string,+ { reject: (error: unknown) => void; resolve: (agent: ChannelAgentSelection) => void }+ >(),+ );++ const settleAgent = useSingleton(() => (draft: ChannelAgentDraft) => {+ const waiter = agentWaiters.get(draft.agentId);+ if (!waiter) return;+ agentWaiters.delete(draft.agentId);+ setDrafts((current) => current.filter((item) => item.agentId !== draft.agentId));+ if (draft.issue) waiter.reject(new AgentIssueError(draft.issue));+ else waiter.resolve(toChannelAgentSelection(draft));+ });++ const resolveAgent = (agentId: string) =>+ new Promise<ChannelAgentSelection>((resolve, reject) => {+ // Settings or device presence that never finish loading must not hold a send forever.+ const timer = setTimeout(+ () => settleAgent({ agentId, initialized: false, issue: 'configurationFailed' }),+ AGENT_RESOLVE_TIMEOUT_MS,+ );+ agentWaiters.set(agentId, {+ reject: (error) => {+ clearTimeout(timer);+ reject(error);+ },+ resolve: (agent) => {+ clearTimeout(timer);+ resolve(agent);+ },+ });+ setDrafts((current) => [+ ...current.filter((item) => item.agentId !== agentId),+ { agentId, initialized: false, issue: 'configurationLoading' },+ ]);+ });++ /**+ * Each search takes the Channel lock on the server, so only the query typing settled on is+ * searched; an earlier one resolves empty because the editor already dropped it.+ */+ const searchPeople = async (channelId: string, query: string) => {+ const key = `${channelId}:${query}`;+ latestQuery.current = query;+ let result = people.get(key);+ if (!result) {+ await new Promise((resolve) => setTimeout(resolve, PEOPLE_SEARCH_DEBOUNCE_MS));+ if (latestQuery.current !== query) return [];+ result = people.get(key);+ }+ if (!result) {+ result = channelService.userCandidates(channelId, query).catch((cause) => {+ people.delete(key);+ console.error('Failed to search people to mention', cause);+ return [];+ });+ people.set(key, result);+ }+ return result;+ };++ /** Workspace people and Agents outside the Channel whose name matches `query`. */+ const options = async (query: string): Promise<ISlashMenuOption[]> => {+ const { agentOptions, channel, enabled, members } = latest.current;+ const search = query.trim();+ if (!enabled || !channel || !search) return [];+ const agents = matchInviteAgents(agentOptions.agents ?? [], {+ exclude: members.flatMap((member) => (member.agentId ? [member.agentId] : [])),+ nameOf: (agent) => agentDisplayName(agent, t('unnamedAgent')),+ priorityIds: agentOptions.projectAgentIds,+ query: search,+ });+ // People join only workspace Channels.+ // The search result may predate someone joining, so members are filtered here as well.+ const memberUserIds = new Set(members.map((member) => member.userId));+ const persons = channel.workspaceId+ ? (await searchPeople(channel.id, search))+ .filter((person) => !memberUserIds.has(person.userId))+ .slice(0, MENTION_INVITE_LIMIT)+ : [];+ return [+ ...persons.map((person) => {+ const name = person.fullName || person.username || t('person');+ return {+ icon: <Avatar avatar={person.avatar || DEFAULT_USER_AVATAR} size={24} title={name} />,+ key: `invite:${inviteKey({ actorType: 'user', id: person.userId })}`,+ label: name,+ metadata: {+ actorType: 'user',+ id: person.userId,+ name,+ type: 'channel-invite',+ } satisfies ChannelMentionInvite,+ };+ }),+ ...agents.map((agent) => {+ const name = agentDisplayName(agent, t('unnamedAgent'));+ return {+ icon: (+ <AgentAvatar+ agentId={agent.id}+ avatar={typeof agent.avatar === 'string' ? agent.avatar : undefined}+ background={agent.backgroundColor ?? undefined}+ name={name}+ shape={'circle'}+ size={24}+ />+ ),+ key: `invite:${inviteKey({ actorType: 'agent', id: agent.id })}`,+ label: name,+ metadata: {+ actorType: 'agent',+ id: agent.id,+ name,+ type: 'channel-invite',+ } satisfies ChannelMentionInvite,+ };+ }),+ ];+ };++ /**+ * The member `target` already is, or adds them once however often they are mentioned.+ * Undefined where no one can be invited, such as a chip pasted into a direct conversation:+ * like any other chip for a non-member, it then stays plain text.+ */+ const invite = (target: ChannelMentionInvite): Promise<string | undefined> => {+ const { channel, enabled, members } = latest.current;+ const joined = members.find((member) =>+ target.actorType === 'user'+ ? member.actorType === 'user' && member.userId === target.id+ : member.agentId === target.id,+ );+ if (joined) return Promise.resolve(joined.id);+ if (!enabled || !channel) return Promise.resolve(undefined);+ const key = inviteKey(target);+ const pending = running.get(key);+ if (pending) return pending;+ setError('');+ const added = (+ target.actorType === 'user'+ ? channelActions.addMember(channel.id, { userId: target.id })+ : resolveAgent(target.id).then((agent) => channelActions.addMember(channel.id, { agent }))+ )+ .then((memberId) => {+ // Searches cached before the invite would still list them as outside.+ people.clear();+ return memberId;+ })+ .catch((cause: unknown) => {+ console.error('Failed to invite a mentioned member', cause);+ const reasonKey =+ cause instanceof AgentIssueError+ ? channelAgentIssueKey(cause.issue, true)+ : getChannelSaveErrorKey(cause);+ setError(+ reasonKey === 'environment.saveFailed'+ ? t('mentionInvite.failed', { name: target.name })+ : t('mentionInvite.failedReason', { name: target.name, reason: t(reasonKey) }),+ );+ throw cause;+ })+ .finally(() => running.delete(key));+ running.set(key, added);+ return added;+ };++ /**+ * Member ids for the outsiders a message mentions, waiting for invites still in flight and+ * retrying failed ones. Undefined when someone could not join; the error says who.+ */+ const resolve = async (targets: ChannelMentionInvite[]) => {+ const results = await Promise.allSettled(targets.map(invite));+ const ids: string[] = [];+ for (const result of results) {+ if (result.status === 'rejected') return;+ if (result.value) ids.push(result.value);+ }+ return ids;+ };++ return {+ /** Mounts the hidden environment resolution of Agents being invited. */+ agentDrafts: drafts.length > 0 && (+ <AgentDrafts drafts={drafts} setDrafts={setDrafts} onSettle={settleAgent} />+ ),+ clearError: () => setError(''),+ enabled,+ error,+ invite: (target: ChannelMentionInvite) => void invite(target).catch(() => {}),+ options,+ resolve,+ };+};diff --git a/src/store/channel/action.test.ts b/src/store/channel/action.test.tsindex 8c7c63d2350..53355622b2a 100644--- a/src/store/channel/action.test.ts+++ b/src/store/channel/action.test.ts@@ -77,6 +77,23 @@ describe('channelActions after a committed write', () => {).rejects.toThrow('device offline');});+ it('returns the member an @mention invite added, even when the detail refresh fails', async () => {+ vi.mocked(channelService.addUser).mockResolvedValue({ data: { id: 'mem_user' } } as never);+ vi.mocked(channelService.addAgent).mockResolvedValue({ data: { id: 'mem_agent' } } as never);+ vi.mocked(channelService.detail).mockRejectedValue(new Error('offline'));++ await expect(channelActions.addMember('chn_000000000001', { userId: 'user_b' })).resolves.toBe(+ 'mem_user',+ );+ await expect(+ channelActions.addMember('chn_000000000001', { agent: { agentId: 'agt_a' } }),+ ).resolves.toBe('mem_agent');+ expect(channelService.addUser).toHaveBeenCalledExactlyOnceWith('chn_000000000001', 'user_b');+ expect(channelService.addAgent).toHaveBeenCalledExactlyOnceWith('chn_000000000001', {+ agentId: 'agt_a',+ });+ });+// One invite adds people and Agents together; people go first so a failing Agent// cannot block the people who were already chosen.it('adds invited people before Agents and refreshes once', async () => {diff --git a/src/store/channel/action.ts b/src/store/channel/action.tsindex 3cb4da081e4..ad3a2ad2009 100644--- a/src/store/channel/action.ts+++ b/src/store/channel/action.ts@@ -195,6 +195,21 @@ class ChannelActionImpl {await this.#refreshAfterWrite(() => this.refreshDetail({ channelId }));}};+ /**+ * Adds one person or Agent, as an @mention of someone outside the Channel does, and returns+ * the member id the mention resolves to. Idempotent like `addMembers`.+ */+ addMember = async (+ channelId: string,+ member: { agent: ChannelAgentSelection } | { userId: string },+ ) => {+ const { data } =+ 'userId' in member+ ? await channelService.addUser(channelId, member.userId)+ : await channelService.addAgent(channelId, member.agent);+ await this.#refreshAfterWrite(() => this.refreshDetail({ channelId }));+ return data.id;+ };send = async (input: Parameters<typeof channelService.send>[0]) => {const scope = cacheScope.get();const { data } = await channelService.send(input);