Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): 拒绝失效点名目标并保留群聊草稿 (#5675)
Chris Zhange9ea098a650c
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex ede602a137..4887a191ae 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -810,6 +810,89 @@ describe('Chat Server result delivery and refresh', () => {});});++describe('Chat Server directed sends', () => {+ const roomId = '10000000-0000-4000-8000-000000000001';+ const botId = '20000000-0000-4000-8000-000000000001';+ const selfId = '30000000-0000-4000-8000-000000000001';+ const humanId = '40000000-0000-4000-8000-000000000001';+ const rootId = '50000000-0000-4000-8000-000000000001';+ let service: BotGroupChatService;+ let responseMode: 'all' | 'mentioned';+ let members: Array<{ id: string; kind: string; state: string }>;+ beforeEach(() => {+ vi.useFakeTimers();+ fixture.packaged = true; responseMode = 'all';+ fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', status: 'active' }];+ members = [{ id: selfId, kind: 'human', state: 'joined' },+ { id: botId, kind: 'bot', state: 'joined' }, { id: humanId, kind: 'human', state: 'joined' }];+ fixture.handle.mockImplementation((route, method) => {+ if (route === '/me') return { body: { actor: { id: selfId } } };+ if (route === '/actors') return { body: [{ id: botId, kind: 'bot', externalId: 'local-bot', name: 'Bot' }] };+ if (route.endsWith('/members')) return { body: members };+ if (route.endsWith('/snapshot')) return { body: { room: { id: roomId, response_mode: responseMode }, members, messages: [], cursor: '0' } };+ if (route.endsWith('/messages') && method === 'POST') return { body: { id: 'posted-message' } };+ return { body: [] };+ });+ service = withChatServer({ listGroups: async () => ({ ok: true, groups: [] }), dispose: vi.fn() } as unknown as BotGroupChatService,+ { dispatch: vi.fn(), onChanged: vi.fn() } as unknown as BotGroupChatServiceDeps);+ });+ afterEach(() => { service.dispose(); vi.useRealTimers(); vi.clearAllMocks(); });+ const posts = () => fixture.handle.mock.calls.filter(([route, method]) => route.endsWith('/messages') && method === 'POST');+ const send = (entry: string, mentions = { all: false, botIds: ['local-bot'] }) => {+ const input = { groupId: roomId, text: '@Bot hello', clientId: 'directed-send-1', mentions };+ return entry === 'thread' ? service.chatServer!.reply({ ...input, rootId }) : service.sendMessage(input);+ };++ it.each(['main', 'thread'])('rejects a selected bot that left before the %s send instead of posting empty mentions', async entry => {+ await service.chatServer!.ownedBots();+ members[1]!.state = 'left';+ expect(await send(entry)).toMatchObject({ ok: false, errorCode: 'MENTION_UNAVAILABLE' });+ expect(posts()).toEqual([]);+ });++ it.each(['main', 'thread'])('preserves actor/local-bot/human targets and excludes self in %s wire payloads', async entry => {+ for (const all of [false, true]) {+ for (const targets of [[botId], ['local-bot'], [humanId], [selfId], [selfId, humanId, 'local-bot', botId]]) {+ expect(await send(entry, { all, botIds: targets })).toMatchObject({ ok: true });+ const ids = all ? [botId, humanId]+ : [...new Set(targets.map(target => target === 'local-bot' ? botId : target))].filter(target => target !== selfId);+ expect(posts().at(-1)![2]).toMatchObject({ mentions: ids,+ ...(entry === 'thread' ? { threadRootId: rootId } : {}) });+ }+ }+ });++ it.each(['main', 'thread'])('keeps Everyone and ordinary unaddressed %s messages working', async entry => {+ for (const mode of ['all', 'mentioned'] as const) {+ responseMode = mode;+ for (const mentions of [{ all: true, botIds: [] }, { all: false, botIds: [] }]) {+ expect(await send(entry, mentions)).toMatchObject({ ok: true });+ expect(posts().at(-1)![2].mentions).toEqual(mentions.all ? [botId, humanId] : []);+ }+ }+ });++ it.each(['main', 'thread'])('refuses unknown, removed, and mixed stale targets in %s without posting', async entry => {+ for (const state of ['left', 'removed', 'banned', 'invited', 'missing']) {+ members = state === 'missing' ? members.filter(m => m.id !== botId) : members.map(m => m.id === botId ? { ...m, state } : m);+ for (const mentions of [{ all: false, botIds: [botId] }, { all: false, botIds: [humanId, 'local-bot'] },+ { all: true, botIds: [botId] }, { all: false, botIds: [selfId, 'local-bot'] },+ { all: true, botIds: [selfId, 'local-bot'] }, { all: false, botIds: ['unknown-target'] }]) {+ expect(await send(entry, mentions)).toMatchObject({ ok: false, errorCode: 'MENTION_UNAVAILABLE' });+ }+ }+ expect(posts()).toEqual([]);+ });++ it.each(['main', 'thread'])('refuses a departed human target in %s', async entry => {+ members[2]!.state = 'left';+ expect(await send(entry, { all: false, botIds: [humanId] })).toMatchObject({ ok: false, errorCode: 'MENTION_UNAVAILABLE' });+ expect(posts()).toEqual([]);+ });++});+describe('Chat authentication recovery and polling backoff', () => {let service: BotGroupChatService;const denied = (code = 'INVALID_TOKEN') => ({ status: 401, body: { error: { code } } });diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex 99e7f97b05..de0d61b3dc 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -853,14 +853,23 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDif (['PLAN_OPEN','PLAN_CLOSED'].includes(code)) return { ok: false, errorCode: code as 'PLAN_OPEN' | 'PLAN_CLOSED', message: '分工状态已变化,请刷新后重试。' };if (code === 'IMPORT_PENDING') return failure('这个群的历史记录尚未上传完成,稍后会自动重试,其他群可正常使用。');if (code === 'CONVERSATION_NOT_FOUND') return { ok: false, errorCode: 'NOT_FOUND', message: '你已退出此群,或没有访问权限。' };+ if (code === 'MENTION_UNAVAILABLE') return { ok: false, errorCode: 'MENTION_UNAVAILABLE', message: '点名的成员已不可用,请重新选择后发送' };if (code === 'CONVERSATION_ARCHIVED') return { ok: false, errorCode: 'INVALID_PARAMS', message: '本群已归档,不能发送新消息。' };if (['ROLE_REQUIRED', 'ACTOR_NOT_OWNED', 'OWNER_REQUIRED'].includes(code)) return { ok: false, errorCode: 'INVALID_PARAMS', message: '你没有执行此操作的权限。' };return failure('聊天服务暂时无法连接,请稍后重试。');});async function mentionIds(roomId: string, mentions: { all: boolean; botIds: string[] }) {const members = await api<Member[]>(`/conversations/${roomId}/members`);- return members.filter(m => m.state === 'joined' && m.id !== selfId && (mentions.all ||- mentions.botIds.includes(m.id) || mentions.botIds.includes(localBot(m.id)?.id ?? ''))).map(m => m.id);+ const joined = members.filter(m => m.state === 'joined');+ // A stale explicit target must never become an unaddressed message. Check+ // every pick, including mixed valid/stale picks, before expanding Everyone.+ const named = mentions.botIds.map(target => {+ const member = joined.find(m => m.id === target || localBot(m.id)?.id === target);+ if (!member) throw new Error('MENTION_UNAVAILABLE');+ return member.id;+ });+ const recipients = mentions.all ? [...joined.map(m => m.id), ...named] : named;+ return [...new Set(recipients.filter(target => target !== selfId))];}const result = async <T>(fn: () => Promise<T>) => {try { return { ok: true as const, ...await fn() }; }diff --git a/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx b/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsxindex c214d8f40c..7496b0a1b9 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx@@ -66,6 +66,7 @@ import {findBotGroupMentionQuery,insertBotGroupMention,resolveBotGroupMentions,+ retainBotGroupTrackedMentions,type BotGroupTrackedMention,} from './botGroupMentions';import {@@ -157,18 +158,20 @@ export function BotGroupComposer({});const textRef = useRef(text);textRef.current = text;+ const selectionRef = useRef({ start: 0, end: 0 });const attachmentsRef = useRef(attachmentState.attachments);attachmentsRef.current = attachmentState.attachments;const focusInputOnMenuCloseRef = useRef(false);const pendingCaretRef = useRef<number | null>(null);const sendingRef = useRef(false);const stoppingRef = useRef(false);- /** Idempotency key for the text and attachments currently being (re)sent. */+ /** Idempotency key for the text, targets and attachments currently being (re)sent. */const attemptRef = useRef<{text: string;clientId: string;division: boolean;attachments: string;+ mentionSignature: string;} | null>(null);const activeMembers = useMemo(() => members.filter(isActiveBotGroupMember), [members]);@@ -213,7 +216,10 @@ export function BotGroupComposer({const syncCaret = () => {const element = textareaRef.current;- if (element) setCaret(element.selectionStart ?? element.value.length);+ if (element) {+ selectionRef.current = { start: element.selectionStart ?? element.value.length, end: element.selectionEnd ?? element.value.length };+ setCaret(selectionRef.current.start);+ }};const choose = (option: MentionOption | undefined) => {@@ -221,14 +227,13 @@ export function BotGroupComposer({const next = insertBotGroupMention(text, { start: query.start, end: caret }, option.label);pendingCaretRef.current = next.caret;setText(next.text);+ selectionRef.current = { start: next.caret, end: next.caret };setCaret(next.caret);setHighlight(0);- if (option.kind === 'member') {- setTracked((current) => [- ...current.filter((mention) => mention.botId !== option.member.botId),- { botId: option.member.botId, label: option.label },- ]);- }+ setTracked(current => {+ const remaining = retainBotGroupTrackedMentions(text, next.text, { members, allLabels: [allLabel], tracked: current, editStart: query.start, editEnd: caret });+ return option.kind === 'member' ? [...remaining, { botId: option.member.botId, label: option.label, start: query.start }] : remaining;+ });textareaRef.current?.focus();};@@ -243,18 +248,20 @@ export function BotGroupComposer({const signature = botGroupAttachmentSignature(files);// The tag changes what main does with the text, so it is part of the idempotency key;// so are the attachments that go with it.+ const mentions = resolveBotGroupMentions(text, {+ members,+ allLabels: [allLabel],+ tracked,+ });+ const mentionSignature = JSON.stringify([mentions.all, mentions.botIds]);const attempt =attemptRef.current?.text === trimmed &&attemptRef.current.division === division &&- attemptRef.current.attachments === signature+ attemptRef.current.attachments === signature &&+ attemptRef.current.mentionSignature === mentionSignature? attemptRef.current- : { text: trimmed, clientId: crypto.randomUUID(), division, attachments: signature };+ : { text: trimmed, clientId: crypto.randomUUID(), division, attachments: signature, mentionSignature };attemptRef.current = attempt;- const mentions = resolveBotGroupMentions(trimmed, {- members,- allLabels: [allLabel],- tracked,- });const draft = text;sendingRef.current = true;setSending(true);@@ -269,7 +276,10 @@ export function BotGroupComposer({const owner = getDataOwnerGeneration();const restore = () => {// The tag comes back only with its own draft, never onto newly typed text.- if (attempt.division && !textRef.current) setDivision(true);+ if (!textRef.current) {+ if (attempt.division) setDivision(true);+ setTracked(tracked);+ }setText((current) => (current ? current : draft));};try {@@ -497,7 +507,11 @@ export function BotGroupComposer({onChange={(event) => {const value = event.target.value;const nextCaret = event.target.selectionStart ?? value.length;+ const editStart = Math.min(selectionRef.current.start, nextCaret);+ const editEnd = selectionRef.current.end;setText(value);+ setTracked(current => retainBotGroupTrackedMentions(text, value, { members, allLabels: [allLabel], tracked: current, editStart, editEnd }));+ selectionRef.current = { start: nextCaret, end: nextCaret };setCaret(nextCaret);setHighlight(0);// A dismissed picker stays closed only for the `@` it was closed on.diff --git a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsxindex 864a559f54..1cfe5286fc 100644--- a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx+++ b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx@@ -10,7 +10,7 @@ import { ShareMessageCheckbox } from '@/components/chat/ShareMessageCheckbox';import { shareSelectionStore, useShareSelectionActive } from '@/components/chat/shareSelectionStore';import { SHARE_SESSION_ATTR, SHARE_MESSAGE_ATTR } from '@/lib/shareConversationImage';import { getDataOwnerGeneration, isDataOwnerGenerationCurrent, isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';-import type { BotGroupDetail, BotGroupMessageView } from '../../../shared/botGroupChat';+import type { BotGroupDetail, BotGroupMention, BotGroupMessageView } from '../../../shared/botGroupChat';import { resolveBotGroupMentions } from './botGroupMentions';import { refreshBotGroups } from './botGroupStore';import { BotAvatar } from './BotAvatar';@@ -51,7 +51,7 @@ export function ChatThreadPanel({ group, rootId, onClose }: { group: BotGroupDetconst [busy, setBusy] = useState(false);const [error, setError] = useState('');const request = useRef(0);- const attempt = useRef<{ text: string; id: string } | null>(null);+ const attempt = useRef<{ text: string; id: string; mentions: BotGroupMention } | null>(null);const sending = useRef(false);const load = useCallback(async (before?: number) => {const version = ++request.current, owner = getDataOwnerGeneration();@@ -81,10 +81,13 @@ export function ChatThreadPanel({ group, rootId, onClose }: { group: BotGroupDetif (group.archived || sending.current || !text.trim()) return;sending.current = true; setBusy(true); setError('');const owner = getDataOwnerGeneration();- if (!attempt.current || attempt.current.text !== text) attempt.current = { text, id: crypto.randomUUID() };+ if (!attempt.current || attempt.current.text !== text) attempt.current = {+ text, id: crypto.randomUUID(),+ mentions: resolveBotGroupMentions(text, { members: group.members, allLabels: [t('bots.groupChat.mention.all'), '所有人', 'all', 'everyone'] }),+ };try {const result = await api().reply({ groupId: group.id, rootId, text: attempt.current.text, clientId: attempt.current.id,- mentions: resolveBotGroupMentions(text, { members: group.members, allLabels: [t('bots.groupChat.mention.all'), '所有人', 'all', 'everyone'] }) });+ mentions: attempt.current.mentions });if (!isDataOwnerGenerationCurrent(owner)) return;if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); return; }setText(''); attempt.current = null; void loadRef.current(); refreshBotGroups();@@ -109,7 +112,10 @@ export function ChatThreadPanel({ group, rootId, onClose }: { group: BotGroupDet{sharing ? <ShareSelectionBar sessionId={shareScope} barWidth="100%"getContentWidth={() => contentRef.current?.querySelector('article')?.getBoundingClientRect().width ?? 400} /> : <div className="space-y-3 border-t border-[var(--border-default)] p-4">{error && <p role="alert" className="text-13 text-[var(--error-fg)]">{error}</p>}- <Textarea aria-label={t(key('replyPlaceholder'))} placeholder={t(key('replyPlaceholder'))} value={text} onChange={setText}+ <Textarea aria-label={t(key('replyPlaceholder'))} placeholder={t(key('replyPlaceholder'))} value={text} onChange={value => {+ setText(value);+ if (attempt.current?.text !== value) attempt.current = null;+ }}rows={3} maxLength={8000} disabled={busy || group.archived} onKeyDown={e => {if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && e.keyCode !== 229) { e.preventDefault(); void send(); }}} />diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsxindex 8d72194ccd..49f62adedc 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx@@ -558,6 +558,88 @@ describe('BotGroupChatView', () => {expect(mocks.sendBotGroupMessage).not.toHaveBeenCalled();});+ it('keeps a selected target and its draft across roster removal and a rejected retry', async () => {+ const namesakes = [+ { ...detail().members[0]!, botId: 'picked', name: 'Ann' },+ { ...detail().members[1]!, botId: 'other', name: 'Ann' },+ ];+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ members: namesakes }) });+ mocks.sendBotGroupMessage.mockResolvedValue({ ok: false, errorCode: 'MENTION_UNAVAILABLE', message: '' });+ renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ act(() => input.focus());+ fireEvent.change(input, { target: { value: '@', selectionStart: 1 } });+ const options = await screen.findAllByRole('option');+ fireEvent.click(options[1]!);+ expect(input.value).toBe('@Ann ');+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ members: namesakes.slice(1) }) });+ act(() => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));+ await waitFor(() => expect(mocks.getBotGroup).toHaveBeenCalledTimes(2));+ for (let attempt = 1; attempt <= 2; attempt++) {+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(attempt));+ await waitFor(() => expect(input.value).toBe('@Ann '));+ expect(mocks.sendBotGroupMessage.mock.calls.at(-1)![0].mentions).toEqual({ all: false, botIds: ['picked'] });+ }+ expect(mocks.toastError).toHaveBeenCalledWith('bots.groupChat.errors.mentionUnavailable');+ const originalClientId = mocks.sendBotGroupMessage.mock.calls[0]![0].clientId;+ expect(mocks.sendBotGroupMessage.mock.calls[1]![0].clientId).toBe(originalClientId);+ fireEvent.change(input, { target: { value: '@', selectionStart: 1 } });+ const remaining = await screen.findAllByRole('option');+ fireEvent.click(remaining[1]!);+ mocks.sendBotGroupMessage.mockResolvedValue({ ok: true, messageId: 'accepted' });+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(3));+ expect(mocks.sendBotGroupMessage.mock.calls.at(-1)![0].mentions).toEqual({ all: false, botIds: ['other'] });+ expect(mocks.sendBotGroupMessage.mock.calls.at(-1)![0].clientId).not.toBe(originalClientId);+ });++ it('drops a deleted selected mention before a namesake is manually mentioned again', async () => {+ const namesakes = [+ { ...detail().members[0]!, botId: 'picked', name: 'Ann' },+ { ...detail().members[1]!, botId: 'other', name: 'Ann' },+ ];+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ members: namesakes }) });+ renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ act(() => input.focus());+ fireEvent.change(input, { target: { value: '@', selectionStart: 1 } });+ fireEvent.click((await screen.findAllByRole('option'))[1]!);+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ members: namesakes.slice(1) }) });+ act(() => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));+ await waitFor(() => expect(mocks.getBotGroup).toHaveBeenCalledTimes(2));+ fireEvent.change(input, { target: { value: 'hello', selectionStart: 5 } });+ fireEvent.change(input, { target: { value: '@Ann hello', selectionStart: 10 } });+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));+ expect(mocks.sendBotGroupMessage.mock.calls[0]![0].mentions).toEqual({ all: false, botIds: ['other'] });+ });++ it.each(['picked', 'manual'])('removes only the %s token identity when same-name mentions coexist', async removed => {+ const namesakes = [+ { ...detail().members[0]!, botId: 'picked', name: 'Ann' },+ { ...detail().members[1]!, botId: 'other', name: 'Ann' },+ ];+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ members: namesakes }) });+ mocks.sendBotGroupMessage.mockResolvedValue({ ok: false, errorCode: 'MENTION_UNAVAILABLE' });+ renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ act(() => input.focus());+ fireEvent.change(input, { target: { value: ' @', selectionStart: 3 } });+ fireEvent.click((await screen.findAllByRole('option'))[1]!);+ fireEvent.change(input, { target: { value: ' @Ann @Ann', selectionStart: 11 } });+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ members: namesakes.slice(1) }) });+ act(() => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));+ await waitFor(() => expect(mocks.getBotGroup).toHaveBeenCalledTimes(2));+ input.setSelectionRange(removed === 'picked' ? 2 : 6, removed === 'picked' ? 7 : 11);+ fireEvent.select(input);+ fireEvent.change(input, { target: { value: ' @Ann', selectionStart: removed === 'picked' ? 2 : 6 } });+ fireEvent.keyDown(input, { key: 'Escape' });+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));+ expect(mocks.sendBotGroupMessage.mock.calls[0]![0].mentions).toEqual({ all: false, botIds: [removed === 'picked' ? 'other' : 'picked'] });+ });+it('refreshes on a push for this group and shows the unavailable state after delete', async () => {renderView();await screen.findByText('周六 8:10 有票');diff --git a/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsxindex 0351dd350a..068898c4ba 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx@@ -118,6 +118,30 @@ describe('chat interaction controls', () => {expect((await screen.findByRole('textbox', { name: k('inviteLink') }) as HTMLInputElement).value).toBe('cindy://chat-invite/test');});+ it.each([{ members: [] }, { members: [{ botId: 'namesake', name: 'Ann', status: 'active' as const }] }])('keeps a refused directed thread reply after the roster changes to %j', async ({ members }) => {+ mocks.reply.mockResolvedValue({ ok: false, errorCode: 'MENTION_UNAVAILABLE' });+ const view = render(<ChatThreadPanel group={{ ...group, members: [{ botId: 'bot', name: 'Ann', status: 'active' }] } as BotGroupDetail} rootId="root" onClose={vi.fn()} />);+ const input = screen.getByRole('textbox', { name: k('replyPlaceholder') }) as HTMLTextAreaElement;+ fireEvent.change(input, { target: { value: '@Ann hello' } });+ fireEvent.click(screen.getByRole('button', { name: k('sendReply') }));+ expect((await screen.findByRole('alert')).textContent).toBe('bots.groupChat.errors.mentionUnavailable');+ expect(input.value).toBe('@Ann hello');+ expect(mocks.reply).toHaveBeenCalledWith(expect.objectContaining({ mentions: { all: false, botIds: ['bot'] } }));+ const original = mocks.reply.mock.calls[0]![0];+ view.rerender(<Tooltip.Provider><ChatThreadPanel group={{ ...group, members } as BotGroupDetail} rootId="root" onClose={vi.fn()} /></Tooltip.Provider>);+ fireEvent.click(screen.getByRole('button', { name: k('sendReply') }));+ await waitFor(() => expect(mocks.reply).toHaveBeenCalledTimes(2));+ expect(mocks.reply.mock.calls[1]![0]).toEqual(original);+ expect(input.value).toBe('@Ann hello');+ fireEvent.change(input, { target: { value: 'hello' } });+ fireEvent.change(input, { target: { value: '@Ann hello' } });+ mocks.reply.mockResolvedValue({ ok: true, messageId: 'accepted' });+ fireEvent.click(screen.getByRole('button', { name: k('sendReply') }));+ await waitFor(() => expect(mocks.reply).toHaveBeenCalledTimes(3));+ expect(mocks.reply.mock.calls[2]![0].mentions).toEqual({ all: false, botIds: members.map(member => member.botId) });+ expect(mocks.reply.mock.calls[2]![0].clientId).not.toBe(original.clientId);+ });+it('keeps a failed reply draft and reuses its operation id; IME confirmation does not send', async () => {mocks.reply.mockResolvedValueOnce({ ok: false, errorCode: 'REQUEST_TIMEOUT' }).mockResolvedValueOnce({ ok: true, messageId: 'reply' });render(<ChatThreadPanel group={group} rootId="root" onClose={vi.fn()} />);diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botGroupMentions.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botGroupMentions.test.tsindex edfd244fca..c4fda69a1d 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupMentions.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupMentions.test.ts@@ -5,6 +5,7 @@ import {findBotGroupMentionQuery,insertBotGroupMention,resolveBotGroupMentions,+ retainBotGroupTrackedMentions,splitBotGroupMentionSegments,} from '../botGroupMentions';import {@@ -70,12 +71,55 @@ describe('resolveBotGroupMentions', () => {resolveBotGroupMentions('@小满 在吗', {members: duplicates,allLabels: [],- tracked: [{ botId: 'b', label: '小满' }],+ tracked: [{ botId: 'b', label: '小满', start: 0 }],}).botIds,).toEqual(['b']);});});+describe('stale explicit picks', () => {+ it('routes each same-name token independently and clears only the deleted picked occurrence', () => {+ const tracked = [{ botId: 'departed', label: 'Ann', start: 0 }];+ const input = { members: [{ botId: 'current', name: 'Ann' }], allLabels: [], tracked };+ expect(resolveBotGroupMentions('@Ann @Ann', input).botIds).toEqual(['departed', 'current']);+ const firstRemoved = retainBotGroupTrackedMentions('@Ann @Ann', '@Ann', { ...input, editStart: 0 });+ expect(firstRemoved).toEqual([]);+ expect(resolveBotGroupMentions('@Ann', { ...input, tracked: firstRemoved }).botIds).toEqual(['current']);+ const secondRemoved = retainBotGroupTrackedMentions('@Ann @Ann', '@Ann', { ...input, editStart: 4 });+ expect(secondRemoved).toEqual(tracked);+ expect(resolveBotGroupMentions('@Ann', { ...input, tracked: secondRemoved }).botIds).toEqual(['departed']);+ // Pasting the same characters over the picked token creates a manual token.+ expect(retainBotGroupTrackedMentions('@Ann @Ann', '@Ann @Ann', { ...input, editStart: 0, editEnd: 4 })).toEqual([]);+ });++ it('moves a picked identity with edits before it and discards edits inside its token', () => {+ const input = { members: [], allLabels: [], tracked: [{ botId: 'departed', label: 'Ann', start: 3 }] };+ const shifted = retainBotGroupTrackedMentions('hi @Ann', 'hello @Ann', { ...input, editStart: 1 });+ expect(shifted).toEqual([{ botId: 'departed', label: 'Ann', start: 6 }]);+ expect(resolveBotGroupMentions('hello @Ann', { ...input, tracked: shifted }).botIds).toEqual(['departed']);+ expect(retainBotGroupTrackedMentions('hi @Ann', 'hi @Anna', { ...input, editStart: 7 })).toEqual([]);+ expect(retainBotGroupTrackedMentions('hi @Ann', 'hi @An', { ...input, editStart: 6 })).toEqual([]);+ });++ it('retains only picked labels that still form mention tokens after a text edit', () => {+ const tracked = [{ botId: 'departed', label: 'Ann', start: 0 }, { botId: 'picked', label: '小满', start: 11 }];+ const input = { members: [{ botId: 'longer', name: '小满满' }], allLabels: ['所有人'], tracked };+ const draft = '@Ann hello @小满';+ expect(retainBotGroupTrackedMentions(draft, draft, input)).toEqual(tracked);+ expect(retainBotGroupTrackedMentions(draft, '@所有人 @Anna [email protected] @小满满', input)).toEqual([]);+ expect(retainBotGroupTrackedMentions(draft, '@Ann hello', input)).toEqual([tracked[0]]);+ });++ it('retains a selected target after roster removal rather than making it unaddressed or retargeting a namesake', () => {+ const tracked = [{ botId: 'departed', label: 'Ann', start: 0 }];+ for (const current of [[], [{ botId: 'namesake', name: 'Ann' }]]) {+ expect(resolveBotGroupMentions('@Ann hello', { members: current, allLabels: [], tracked })).toEqual({ all: false, botIds: ['departed'] });+ }+ expect(resolveBotGroupMentions('hello', { members: [], allLabels: [], tracked })).toEqual({ all: false, botIds: [] });+ expect(resolveBotGroupMentions('@Anna hello', { members: [], allLabels: [], tracked })).toEqual({ all: false, botIds: [] });+ });+});+describe('mention picker helpers', () => {it('finds the query typed right before the caret', () => {expect(findBotGroupMentionQuery('帮我查一下 @小', 8)).toEqual({ start: 6, query: '小' });diff --git a/apps/desktop/src/renderer/features/bots/chatError.ts b/apps/desktop/src/renderer/features/bots/chatError.tsindex 2ec34ddf7f..8e29a1257f 100644--- a/apps/desktop/src/renderer/features/bots/chatError.ts+++ b/apps/desktop/src/renderer/features/bots/chatError.ts@@ -2,6 +2,7 @@ const key = (name: string) => `bots.groupChat.server.${name}`;export function chatErrorKey(code: string) {if (['INVITATION_NOT_FOUND', 'INVITATION_UNAVAILABLE', 'INVALID_INPUT'].includes(code)) return key('invalidInvite');+ if (code === 'MENTION_UNAVAILABLE') return 'bots.groupChat.errors.mentionUnavailable';if (code === 'LAST_OWNER') return key('settings.lastOwner');if (code === 'REVISION_CONFLICT') return key('settings.conflict');if (['FORBIDDEN', 'ROLE_REQUIRED', 'OWNER_REQUIRED', 'ACTOR_NOT_OWNED', 'IDENTITY_DOMAIN_MISMATCH'].includes(code)) return key('notAllowed');diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 11f487f376..13cc23b0b9 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -8537,6 +8537,7 @@"errors": {"memberLimit": "A group chat needs 2–6 teammates","memberUnavailable": "One of these teammates is unavailable. Choose another and try again.",+ "mentionUnavailable": "A mentioned member is no longer available. Choose who to mention before sending again.","notFound": "This group chat no longer exists","hostNotReady": "Cindy is still getting ready. Try again in a moment.","planOpen": "A work split is underway. Finish or stop it before starting another.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex fc356193f1..1fd97194be 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -8522,6 +8522,7 @@"errors": {"memberLimit": "グループチャットには仲間が 2〜6 人必要です","memberUnavailable": "利用できない仲間がいます。別の仲間を選んで再試行してください",+ "mentionUnavailable": "メンションしたメンバーは現在利用できません。送信する前に選び直してください。","notFound": "このグループチャットはもう存在しません","hostNotReady": "Cindy の準備がまだ終わっていません。しばらくしてから再試行してください","planOpen": "役割分担の途中です。終わるか停止してから新しく始めてください",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 7be98f2876..69c9c5e9ee 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -8522,6 +8522,7 @@"errors": {"memberLimit": "그룹 채팅에는 동료가 2~6명 필요합니다","memberUnavailable": "사용할 수 없는 동료가 있습니다. 다른 동료를 골라 다시 시도하세요",+ "mentionUnavailable": "멘션한 멤버를 더 이상 사용할 수 없습니다. 다시 선택한 후 보내세요.","notFound": "이 그룹 채팅은 더 이상 존재하지 않습니다","hostNotReady": "Cindy가 아직 준비 중입니다. 잠시 후 다시 시도하세요","planOpen": "역할 분담이 진행 중입니다. 끝내거나 중지한 뒤 새로 시작하세요",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 2baffba79c..17d7f5699b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -8522,6 +8522,7 @@"errors": {"memberLimit": "一个群需要 2–6 位伙伴","memberUnavailable": "有伙伴现在不可用,换一位再试",+ "mentionUnavailable": "点名的成员已不可用,请重新选择后发送","notFound": "这个群聊已不存在","hostNotReady": "Cindy 还在准备中,请稍后重试","planOpen": "正在分工,做完或停止后才能安排新的",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex e4e684e05f..09c9d219f7 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -8522,6 +8522,7 @@"errors": {"memberLimit": "一個群聊需要 2–6 位夥伴","memberUnavailable": "有夥伴現在無法使用,換一位再試",+ "mentionUnavailable": "點名的成員已無法使用,請重新選擇後傳送","notFound": "這個群聊已不存在","hostNotReady": "Cindy 還在準備中,請稍後重試","planOpen": "正在分工,做完或停止後才能安排新的",diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsxindex 4f12bd4e1e..237ac4c46f 100644--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx@@ -471,6 +471,44 @@ describe('group composer', () => {expect(h.row.value).toBe('');});+ it.each(['[INVALID_PARAMS] MENTION_UNAVAILABLE', 'MENTION_UNAVAILABLE'])('keeps a stale selected target through a refused send (%s) and lets a new pick replace it', async message => {+ const data = group({ openPlan: null });+ const namesakes = [{ ...data.members[0]!, name: 'Ann' }, { ...data.members[1]!, name: 'Ann' }];+ await render(group({ openPlan: null, members: namesakes }));+ await type('@');+ await click('botGroup.mention.mimi');+ await render(group({ openPlan: null, members: namesakes.slice(1) }));+ h.chat.act.mockRejectedValue(new Error(message));+ for (let retry = 0; retry < 2; retry++) {+ await click('botGroup.composer.send');+ expect(h.chat.act).toHaveBeenLastCalledWith('send', expect.objectContaining({ mentions: { all: false, botIds: ['mimi'] } }));+ expect(h.row.value).toBe('@Ann ');+ }+ expect(h.alert).toHaveBeenCalledWith('groupChat.errors.mentionUnavailable');+ const originalClientId = h.chat.act.mock.calls[0][1].clientId;+ expect(h.chat.act.mock.calls[1][1].clientId).toBe(originalClientId);+ await type('@');+ await click('botGroup.mention.abu');+ h.chat.act.mockResolvedValue({ effects: [] });+ await click('botGroup.composer.send');+ expect(h.chat.act).toHaveBeenLastCalledWith('send', expect.objectContaining({ mentions: { all: false, botIds: ['abu'] } }));+ expect(h.chat.act.mock.calls.at(-1)[1].clientId).not.toBe(originalClientId);+ expect(h.row.value).toBe('');+ });++ it('drops a deleted selected mention before a namesake is manually mentioned again', async () => {+ const data = group({ openPlan: null });+ const namesakes = [{ ...data.members[0]!, name: 'Ann' }, { ...data.members[1]!, name: 'Ann' }];+ await render(group({ openPlan: null, members: namesakes }));+ await type('@');+ await click('botGroup.mention.mimi');+ await render(group({ openPlan: null, members: namesakes.slice(1) }));+ await type('hello');+ await type('@Ann hello');+ await click('botGroup.composer.send');+ expect(h.chat.act).toHaveBeenLastCalledWith('send', expect.objectContaining({ mentions: { all: false, botIds: ['abu'] } }));+ });+it('keeps the current human in the group but excludes it from mention choices and typed mentions', async () => {h.chat.server = true;const data = group({ openPlan: null });@@ -484,6 +522,22 @@ describe('group composer', () => {expect(h.chat.act).toHaveBeenLastCalledWith('send', expect.objectContaining({ mentions: { all: false, botIds: ['abu'] } }));});+ it.each(['picked', 'manual'])('removes only the %s token identity when same-name mentions coexist', async removed => {+ const data = group({ openPlan: null });+ const namesakes = [{ ...data.members[0]!, name: 'Ann' }, { ...data.members[1]!, name: 'Ann' }];+ await render(group({ openPlan: null, members: namesakes }));+ await type(' @');+ await click('botGroup.mention.mimi');+ await type(' @Ann @Ann');+ await render(group({ openPlan: null, members: namesakes.slice(1) }));+ await act(async () => h.row.onSelectionChange({ nativeEvent: { selection: {+ start: removed === 'picked' ? 2 : 6, end: removed === 'picked' ? 7 : 11,+ } } }));+ await type(' @Ann');+ await click('botGroup.composer.send');+ expect(h.chat.act).toHaveBeenLastCalledWith('send', expect.objectContaining({ mentions: { all: false, botIds: [removed === 'picked' ? 'abu' : 'mimi'] } }));+ });+it('sends a 分工 message and keeps the clientId and tag for a retry', async () => {await render(group({ openPlan: null }));expect(byId('botGroup.divisionTag')).toBeNull();diff --git a/apps/mobile/src/__tests__/botGroupRemote.test.ts b/apps/mobile/src/__tests__/botGroupRemote.test.tsindex 4f9de39dc2..1ebd8f0ccf 100644--- a/apps/mobile/src/__tests__/botGroupRemote.test.ts+++ b/apps/mobile/src/__tests__/botGroupRemote.test.ts@@ -149,6 +149,7 @@ describe('actions', () => {['[INVALID_PARAMS] MEMBER_LIMIT', 'MEMBER_LIMIT'],[new Error('[NOT_FOUND] NOT_FOUND'), 'NOT_FOUND'],[new Error('[INVALID_PARAMS] MEMBER_UNAVAILABLE'), 'MEMBER_UNAVAILABLE'],+ [new Error('[INVALID_PARAMS] MENTION_UNAVAILABLE'), 'MENTION_UNAVAILABLE'],[new Error('[NOT_CONNECTED] not online within 1500ms'), null],[new Error('XPLAN_OPEN'), null],])('reads the group error code of %s', (error, code) => {@@ -189,4 +190,14 @@ describe('actions', () => {expect(nextBotGroupSendAttempt(first, '', false, next, ['a2', 'a1']).clientId).toBe('c3');expect(nextBotGroupSendAttempt(first, '', false, next).clientId).toBe('c4');});++ it('reuses an unchanged target intent but gives changed IDs, order or Everyone a new key', () => {+ let serial = 0;+ const next = () => `c${++serial}`;+ const first = nextBotGroupSendAttempt(null, '@Ann', false, next, [], { all: false, botIds: ['picked', 'other'] });+ expect(nextBotGroupSendAttempt(first, '@Ann', false, next, [], { botIds: ['picked', 'other'], all: false })).toBe(first);+ expect(nextBotGroupSendAttempt(first, '@Ann', false, next, [], { all: false, botIds: ['new'] }).clientId).toBe('c2');+ expect(nextBotGroupSendAttempt(first, '@Ann', false, next, [], { all: false, botIds: ['other', 'picked'] }).clientId).toBe('c3');+ expect(nextBotGroupSendAttempt(first, '@Ann', false, next, [], { all: true, botIds: ['picked', 'other'] }).clientId).toBe('c4');+ });});diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsxindex caf100b319..188e6ad9cb 100644--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx@@ -118,6 +118,40 @@ it('resolves everyone using authorized members at send time instead of the displexpect(h.auth.apiFetch).toHaveBeenCalledWith(`/v1/conversations/${id}/messages`, expect.objectContaining({ method: 'POST', body: { operationId: 'fixture-new-member', content: [{ type: 'text', text: 'everyone' }], mentions: [joined] } }));});+it.each([+ ['human', false], ['human', true], ['bot', false], ['bot', true],+] as const)('refuses any unavailable explicit %s target before sending (everyone=%s)', async (kind, all) => {+ const target = '00000000-0000-4000-8000-000000000003';+ const available = '00000000-0000-4000-8000-000000000004';+ const original = h.auth.apiFetch.getMockImplementation()!;+ let membership = 'joined';+ h.auth.apiFetch.mockImplementation(async (path, options) => {+ const value = await original(path, options);+ const members = [{ id: target, kind, state: membership, name: 'Ann', ownerActorId: self, ownerName: '', role: 'member', avatar: null },+ { id: available, kind: 'bot', state: 'joined', name: 'Available', ownerActorId: self, ownerName: '', role: 'member', avatar: null }];+ if (path.endsWith('/members')) return [...value, ...members.filter(member => member.state !== 'missing')];+ return path.endsWith('/snapshot') ? { ...value, members: [...value.members, ...members] } : value;+ });+ showChat = true; await render();+ for (membership of ['left', 'removed', 'banned', 'invited', 'missing']) {+ for (const botIds of [[target], [available, target]]) {+ await act(async () => {+ await expect(chat.act('send', { text: '@Ann hello', clientId: 'fixture-stale-target', mentions: { all, botIds } }))+ .rejects.toThrow('MENTION_UNAVAILABLE');+ });+ expect(chat.online).toBe(true);+ expect(chat.state.kind).toBe('ready');+ expect(h.auth.apiFetch.mock.calls.some(([, options]) => options.method === 'POST')).toBe(false);+ }+ }+ await act(async () => {+ await chat.act('send', { text: '@Available hello', clientId: 'fixture-reselected', mentions: { all, botIds: [available] } });+ });+ expect(h.auth.apiFetch).toHaveBeenCalledWith(`/v1/conversations/${id}/messages`, expect.objectContaining({+ method: 'POST', body: { operationId: 'fixture-reselected', content: [{ type: 'text', text: '@Available hello' }], mentions: [available] },+ }));+});+it('keeps REST sending available after the group WebSocket disconnects', async () => {vi.useFakeTimers();const sockets: any[] = [];diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.tsindex 76d858ef7a..2f9c60dc81 100644--- a/apps/mobile/src/chat/useChatServer.ts+++ b/apps/mobile/src/chat/useChatServer.ts@@ -220,15 +220,22 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {if (!latest || latest.identity !== identity) throw new Error('CHAT_READ_FAILED');try {const mentions = input.mentions as { all: boolean; botIds: string[] };+ const joined = mentions.all || mentions.botIds.length+ ? (await api.client.members(groupId)).filter(member => member.state === 'joined') : [];+ if (!valid() || page.current?.identity !== identity) throw new Error('OWNER_CHANGED');+ // Validate every explicit pick before Everyone expansion; never discard a+ // departed target or submit only the remaining part of the intended list.+ if (mentions.botIds.some(id => !joined.some(member => member.id === id))) throw new Error('MENTION_UNAVAILABLE');const recipients = mentions.all- ? (await api.client.members(groupId)).filter(member => member.state === 'joined').map(member => member.id)+ ? joined.map(member => member.id): mentions.botIds;- if (!valid() || page.current?.identity !== identity) throw new Error('OWNER_CHANGED');await api.client.send(groupId, { clientId: String(input.clientId), text: String(input.text),mentions: { all: false, botIds: recipients.filter(id => id !== latest.self) } });if (valid()) reload();return { effects: [] };} catch (error) {+ // An unavailable mention is a draft correction, not a connectivity failure.+ if (error instanceof Error && error.message === 'MENTION_UNAVAILABLE') throw error;if (valid()) {freshRead.current = false;if (chatAccessLost(error)) loseAccess();diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.jsonindex f640048d59..1018b1ce17 100644--- a/apps/mobile/src/i18n/locales/en/groupChat.json+++ b/apps/mobile/src/i18n/locales/en/groupChat.json@@ -166,6 +166,7 @@"errors": {"memberLimit": "A group chat needs 2–6 teammates","memberUnavailable": "One of these teammates is unavailable. Choose another and try again.",+ "mentionUnavailable": "A mentioned member is no longer available. Choose who to mention before sending again.","notFound": "This group chat no longer exists","hostNotReady": "Cindy is still getting ready. Try again in a moment.","planOpen": "A work split is underway. Finish or stop it before starting another.",diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.jsonindex 2d161ddf5d..998e66598a 100644--- a/apps/mobile/src/i18n/locales/ja/groupChat.json+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json@@ -166,6 +166,7 @@"errors": {"memberLimit": "グループチャットには仲間が 2〜6 人必要です","memberUnavailable": "利用できない仲間がいます。別の仲間を選んで再試行してください",+ "mentionUnavailable": "メンションしたメンバーは現在利用できません。送信する前に選び直してください。","notFound": "このグループチャットはもう存在しません","hostNotReady": "Cindy の準備がまだ終わっていません。しばらくしてから再試行してください","planOpen": "役割分担の途中です。終わるか停止してから新しく始めてください",diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.jsonindex 5951ae232c..70efa6ad20 100644--- a/apps/mobile/src/i18n/locales/ko/groupChat.json+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json@@ -166,6 +166,7 @@"errors": {"memberLimit": "그룹 채팅에는 동료가 2~6명 필요합니다","memberUnavailable": "사용할 수 없는 동료가 있습니다. 다른 동료를 골라 다시 시도하세요",+ "mentionUnavailable": "멘션한 멤버를 더 이상 사용할 수 없습니다. 다시 선택한 후 보내세요.","notFound": "이 그룹 채팅은 더 이상 존재하지 않습니다","hostNotReady": "Cindy가 아직 준비 중입니다. 잠시 후 다시 시도하세요","planOpen": "역할 분담이 진행 중입니다. 끝내거나 중지한 뒤 새로 시작하세요",diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.jsonindex 908b1b9431..2c789ec55d 100644--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json@@ -166,6 +166,7 @@"errors": {"memberLimit": "一个群需要 2–6 位伙伴","memberUnavailable": "有伙伴现在不可用,换一位再试",+ "mentionUnavailable": "点名的成员已不可用,请重新选择后发送","notFound": "这个群聊已不存在","hostNotReady": "Cindy 还在准备中,请稍后重试","planOpen": "正在分工,做完或停止后才能安排新的",diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.jsonindex e9d3f5f478..119f12d356 100644--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json@@ -166,6 +166,7 @@"errors": {"memberLimit": "一個群聊需要 2–6 位夥伴","memberUnavailable": "有夥伴現在無法使用,換一位再試",+ "mentionUnavailable": "點名的成員已無法使用,請重新選擇後傳送","notFound": "這個群聊已不存在","hostNotReady": "Cindy 還在準備中,請稍後重試","planOpen": "正在分工,做完或停止後才能安排新的",diff --git a/apps/mobile/src/session/BotGroupComposer.tsx b/apps/mobile/src/session/BotGroupComposer.tsxindex 1334485ee6..f9d606923a 100644--- a/apps/mobile/src/session/BotGroupComposer.tsx+++ b/apps/mobile/src/session/BotGroupComposer.tsx@@ -3,7 +3,7 @@** 输入 `@` 在输入框上方弹出点名候选,第一项固定是「所有人」。发送时以正文重新解析点名* (与桌面同一套规则,见 @cindy/maker-shared/botGroupMentions),clientId 作为幂等键:同一段- * 文字、同一个「分工」标签、同一批附件重发沿用同一个 clientId。一轮进行中输入框为空且没有+ * 文字、同一批点名目标、同一个「分工」标签、同一批附件重发沿用同一个 clientId。一轮进行中输入框为空且没有* 附件时,发送按钮变成停止;否则照常发送(插话本身就会作废当前一轮)。** 附件与一对一聊天同一套(照片、拍照、文件、iOS 最近照片、粘贴图片,见@@ -26,6 +26,7 @@ import {findBotGroupMentionQuery,insertBotGroupMention,resolveBotGroupMentions,+ retainBotGroupTrackedMentions,type BotGroupTrackedMention,} from '@cindy/maker-shared/botGroupMentions';import {@@ -100,6 +101,7 @@ export function BotGroupComposer({const [stopping, setStopping] = useState(false);const inputRef = useRef<NativeTextInput>(null);const textRef = useRef(text); textRef.current = text;+ const selectionRef = useRef({ start: 0, end: 0 });const sendingRef = useRef(false);const stoppingRef = useRef(false);const attemptRef = useRef<BotGroupSendAttempt | null>(null);@@ -149,14 +151,16 @@ export function BotGroupComposer({if (!query) return;const next = insertBotGroupMention(text, { start: query.start, end: caret }, option.label);setText(next.text);+ selectionRef.current = { start: next.caret, end: next.caret };setCaret(next.caret);setForcedSelection({ start: next.caret, end: next.caret });- if (option.kind === 'member') {- setTracked((current) => [- ...current.filter((mention) => mention.botId !== option.member.botId),- { botId: option.member.botId, label: option.label },- ]);- }+ setTracked(current => {+ const remaining = retainBotGroupTrackedMentions(text, next.text, {+ members: members.map(member => ({ botId: member.botId, name: member.name })),+ allLabels: [allLabel], tracked: current, editStart: query.start, editEnd: caret,+ });+ return option.kind === 'member' ? [...remaining, { botId: option.member.botId, label: option.label, start: query.start }] : remaining;+ });inputRef.current?.focus();};@@ -191,14 +195,14 @@ export function BotGroupComposer({return;}const attachmentIds = attachments.map((attachment) => attachment.id);- // The tag and the attachments change what the host does, so they are part of the idempotency key.- const attempt = nextBotGroupSendAttempt(attemptRef.current, draftText, draftDivision, randomUUID, attachmentIds);- attemptRef.current = attempt;- const mentions = resolveBotGroupMentions(draftText, {+ const mentions = resolveBotGroupMentions(draft, {members: mentionMembers.map((member) => ({ botId: member.botId, name: member.name })),allLabels: [allLabel],tracked: draftTracked,});+ // Targets, tag and attachments are part of the same send intent.+ const attempt = nextBotGroupSendAttempt(attemptRef.current, draftText, draftDivision, randomUUID, attachmentIds, mentions);+ attemptRef.current = attempt;release = tray.holdForSend(attachmentIds);await onSend({ text: attempt.text, mentions, clientId: attempt.clientId, division: attempt.division, attachments });attemptRef.current = null;@@ -317,8 +321,19 @@ export function BotGroupComposer({cursorColor={colors.inputCaret}selectionColor={colors.inputCaret}selection={forcedSelection}- onChangeText={setText}+ onChangeText={(value) => {+ const { start: editStart, end: editEnd } = selectionRef.current;+ setText(value);+ setTracked(current => retainBotGroupTrackedMentions(text, value, {+ members: members.map(member => ({ botId: member.botId, name: member.name })),+ allLabels: [allLabel],+ tracked: current,+ editStart,+ editEnd,+ }));+ }}onSelectionChange={(event) => {+ selectionRef.current = event.nativeEvent.selection;setForcedSelection(undefined);setCaret(event.nativeEvent.selection.end);}}diff --git a/apps/mobile/src/session/botGroupRemote.ts b/apps/mobile/src/session/botGroupRemote.tsindex 31d5b5268b..49af8d74b9 100644--- a/apps/mobile/src/session/botGroupRemote.ts+++ b/apps/mobile/src/session/botGroupRemote.ts@@ -360,6 +360,7 @@ export function botGroupChatDataFromResource(resource: Pick<RemoteResource, 'bloconst ERROR_CODES: readonly BotGroupErrorCode[] = ['MEMBER_LIMIT','MEMBER_UNAVAILABLE',+ 'MENTION_UNAVAILABLE','PLAN_OPEN','PLAN_CLOSED','HOST_NOT_READY',@@ -407,11 +408,13 @@ export interface BotGroupSendAttempt {division: boolean;/** Ids of the attached uploads, in order. */attachmentIds: readonly string[];+ /** Explicit target identity, independent of the displayed names. */+ mentionSignature?: string;clientId: string;}/**- * A retry of the same text with the same 「分工」 tag and the same attachments reuses its+ * A retry of the same text, targets, 「分工」 tag and attachments reuses its* clientId, so the host returns the message it already stored instead of writing it twice.*/export function nextBotGroupSendAttempt(@@ -420,10 +423,14 @@ export function nextBotGroupSendAttempt(division: boolean,newClientId: () => string,attachmentIds: readonly string[] = [],+ mentions?: BotGroupMention,): BotGroupSendAttempt {+ const mentionSignature = mentions === undefined ? undefined : JSON.stringify([mentions.all, mentions.botIds]);return previous && previous.text === text && previous.division === division+ && previous.mentionSignature === mentionSignature&& previous.attachmentIds.length === attachmentIds.length&& previous.attachmentIds.every((attachmentId, index) => attachmentId === attachmentIds[index])? previous- : { text, division, attachmentIds: [...attachmentIds], clientId: newClientId() };+ : { text, division, attachmentIds: [...attachmentIds], clientId: newClientId(),+ ...(mentionSignature === undefined ? {} : { mentionSignature }) };}diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex 0a75a8ebd4..6b28bbd9c6 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -301,6 +301,14 @@ Chris 已明确扩展到多人各带伙伴,并选择「主人按群预先授群主可以是伙伴,主人可代该伙伴管理群;最后群主不能直接退出。个人账号资料、群内昵称、群角色与伙伴归属是四个不同字段,禁止互相覆盖。群内昵称只由本人/伙伴主人修改;个人头像与名字走既有账号服务,Chat Server 只保存受认证的显示投影。+发送主群消息或 Thread 回复时,显式点名的每个目标都必须仍是已加入成员。任一目标失效时拒绝发送并保留原输入,不把非空点名列表过滤为空,也不只发送给混合列表里的有效目标。输入框从候选中选过的目标在成员列表刷新后仍保留为本条草稿的点名意图,由发送入口校验;不把离群目标重新放回成员或候选列表。选择记录绑定到正文中的具体点名,编辑时随未改动的点名移动,删除或覆盖该点名时清除,不被另一个同名点名继承。删除正文里的点名后,草稿恢复普通消息规则。校验后到消息提交之间的成员变化仍由服务端按原始点名与最新授权处理;Thread 不自动点名原消息作者。回归见 `chatServer.test.ts`、`BotGroupChatView.test.tsx` 与 `ChatServerControls.test.tsx`。++同一草稿的点名目标 ID、顺序或所有人标记变化,即使显示名字与正文没变,也必须使用新的 `clientId`。只有正文、点名目标、分工标记和附件均不变时,失败重试才复用原发送尝试。++完成全部显式目标校验后,最终点名列表继续沿用排除当前用户自己的既有规则;主群、Thread 与手机直连均一致,不因显式列表或所有人标记改变。++手机直连入口同样在发送前读取已加入成员、校验全部显式目标,再展开所有人。点名失效沿用本地化提示和草稿恢复,不把群页标为离线;重选当前成员后可以立即继续发送。回归见 `chatServerMobileEntry.test.tsx` 与 `BotGroupChatScreen.test.tsx`。+多人群里的伙伴统一显示为 `伙伴名 (主人昵称)`,例如 `Cindy (Chris)`,便于区分不同人带来的同名伙伴。消息、Thread、成员列表、侧栏摘要与 @ 候选使用同一显示名;后缀仅用于展示,身份、授权和 @ 路由仍依据唯一 ID。已有短名 @ 继续可用,选取完整名字时只点名对应伙伴。当前本地验收与正式切源边界见 [Chat Server 本地联调](../dev-rules/chat-server-local-test.md)。diff --git a/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts b/packages/maker-shared/src/__tests__/botGroupPresentation.test.tsindex 30091c6b78..4fa6392215 100644--- a/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts+++ b/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts@@ -31,6 +31,7 @@ describe('bot group copy variants (shared by desktop and phone)', () => {it('names only the refusals the user can act on', () => {expect(botGroupErrorVariant('PLAN_OPEN')).toBe('planOpen');+ expect(botGroupErrorVariant('MENTION_UNAVAILABLE')).toBe('mentionUnavailable');expect(botGroupErrorVariant('INTERNAL')).toBeNull();expect(botGroupErrorVariant('constructor' as BotGroupErrorCode)).toBeNull();expect(botGroupErrorVariant(undefined)).toBeNull();diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.tsindex 82720ebfbb..63434ab7d7 100644--- a/packages/maker-shared/src/botGroupChat.ts+++ b/packages/maker-shared/src/botGroupChat.ts@@ -249,6 +249,7 @@ export type BotGroupErrorCode =| 'NOT_FOUND'| 'MEMBER_LIMIT'| 'MEMBER_UNAVAILABLE'+ | 'MENTION_UNAVAILABLE'| 'HOST_NOT_READY'/** An explicit 安排分工 while a plan is running or waiting. */| 'PLAN_OPEN'diff --git a/packages/maker-shared/src/botGroupMentions.ts b/packages/maker-shared/src/botGroupMentions.tsindex 7d962ae335..0a7a424460 100644--- a/packages/maker-shared/src/botGroupMentions.ts+++ b/packages/maker-shared/src/botGroupMentions.ts@@ -2,8 +2,8 @@* 群聊输入框里的 @ 点名:纯文本解析,不依赖 React 与 IPC。** 输入框是普通 textarea,点名以 `@名字 ` 的形式留在正文里。发送时以正文为准重新解析- * (手打的 `@小满` 与从候选里选的效果一致),只有「重名」这种正文分辨不了的情况,才用- * 选择候选时记下的 botId 消歧。宿主按解析结果决定谁回答+ * (手打的 `@小满` 与从候选里选的效果一致)。选择候选时记下的 botId 用于消歧,+ * 成员离群后仍保留显式目标,由宿主拒绝失效目标。宿主按解析结果决定谁回答* (docs/product-rules/bot-group-chat.md §4.1)。*/import type { BotGroupMention } from './botGroupChat.js';@@ -20,6 +20,8 @@ export interface BotGroupMentionMember {export interface BotGroupTrackedMention {botId: string;label: string;+ /** UTF-16 index of this picked token's `@` in the untrimmed draft. */+ start: number;}export interface BotGroupMentionQuery {@@ -66,15 +68,6 @@ function buildLabelEntries(const label = raw.trim();if (label) byLabel.set(label, { label, all: true, botIds: [] });}- const memberIds = new Set(members.map((member) => member.botId));- const trackedByLabel = new Map<string, string[]>();- for (const mention of tracked) {- const label = mention.label.trim();- if (!label || !memberIds.has(mention.botId)) continue;- const ids = trackedByLabel.get(label) ?? [];- if (!ids.includes(mention.botId)) ids.push(mention.botId);- trackedByLabel.set(label, ids);- }for (const member of members) {for (const raw of [member.name, member.nickname || member.displayName || '']) {const label = raw.trim();@@ -84,10 +77,11 @@ function buildLabelEntries(byLabel.set(label, entry);}}- // 重名时正文分辨不出是哪一位,才用选择候选时记下的 botId 收窄。- for (const [label, ids] of trackedByLabel) {- const entry = byLabel.get(label);- if (entry && !entry.all) entry.botIds = ids;+ // Keep an explicit pick even after it disappears from the live roster. This+ // records intent, not membership: the host must reject unavailable targets.+ for (const mention of tracked) {+ const label = mention.label.trim();+ if (label && !byLabel.has(label)) byLabel.set(label, { label, all: false, botIds: [] });}// 最长优先:`@小满满` 不能先被 `@小满` 截走。return [...byLabel.values()].sort((a, b) => b.label.length - a.label.length);@@ -123,7 +117,7 @@ function scanMentionTokens(text: string, entries: readonly LabelEntry[]): Mentio/*** Resolve who a group message addresses. Mentions are re-derived from the text- * at send time; a tracked pick only disambiguates members that share a name.+ * at send time; a tracked pick also preserves a stale target for host validation.*/export function resolveBotGroupMentions(text: string,@@ -134,19 +128,54 @@ export function resolveBotGroupMentions(},): BotGroupMention {const entries = buildLabelEntries(input.members, input.allLabels, input.tracked ?? []);- const memberIds = new Set(input.members.map((member) => member.botId));const botIds: string[] = [];let all = false;for (const token of scanMentionTokens(text, entries)) {if (token.entry.all) all = true;- for (const botId of token.entry.botIds) {- if (memberIds.has(botId) && !botIds.includes(botId)) botIds.push(botId);+ const picked = (input.tracked ?? []).filter(mention => !token.entry.all &&+ mention.start === token.start && mention.label.trim() === token.entry.label);+ for (const botId of picked.length ? picked.map(mention => mention.botId) : token.entry.botIds) {+ if (!botIds.includes(botId)) botIds.push(botId);}}// 按正文里点名的先后输出:宿主直接按这个顺序轮流发言(bot-group-chat.md §4.1)。return { all, botIds };}+/** Move intact picked tokens with a text edit; forget tokens the edit replaces. */+export function retainBotGroupTrackedMentions(+ previousText: string,+ text: string,+ input: {+ members: readonly BotGroupMentionMember[];+ allLabels: readonly string[];+ tracked: readonly BotGroupTrackedMention[];+ /** Previous selection start (or new caret after deletion) disambiguates identical tokens. */+ editStart?: number;+ /** Selected text is replaced even when its characters also match the new suffix. */+ editEnd?: number;+ },+): BotGroupTrackedMention[] {+ const prefixLimit = Math.min(previousText.length, text.length, Math.max(0, input.editStart ?? previousText.length));+ let prefix = 0;+ while (prefix < prefixLimit && previousText[prefix] === text[prefix]) prefix++;+ let previousEnd = previousText.length, nextEnd = text.length;+ const suffixLimit = Math.max(prefix, input.editEnd ?? prefix);+ while (previousEnd > suffixLimit && nextEnd > prefix && previousText[previousEnd - 1] === text[nextEnd - 1]) {+ previousEnd--; nextEnd--;+ }+ const delta = text.length - previousText.length;+ const tracked = input.tracked.flatMap(mention => {+ if (mention.start + 1 + mention.label.trim().length <= prefix) return [mention];+ if (mention.start >= previousEnd) return [{ ...mention, start: mention.start + delta }];+ return []; // This particular token was edited or deleted, even if a namesake remains.+ });+ const entries = buildLabelEntries(input.members, input.allLabels, tracked);+ const tokens = scanMentionTokens(text, entries);+ return tracked.filter(mention => tokens.some(token => !token.entry.all &&+ token.start === mention.start && token.entry.label === mention.label.trim()));+}+/** The `@query` being typed right before the caret, if any. */export function findBotGroupMentionQuery(text: string, caret: number): BotGroupMentionQuery | null {const before = text.slice(0, Math.max(0, Math.min(caret, text.length)));diff --git a/packages/maker-shared/src/botGroupPresentation.ts b/packages/maker-shared/src/botGroupPresentation.tsindex 9e57724fbe..718b1d7dcc 100644--- a/packages/maker-shared/src/botGroupPresentation.ts+++ b/packages/maker-shared/src/botGroupPresentation.ts@@ -75,6 +75,7 @@ export function mergeBotGroupMessages(export type BotGroupErrorVariant =| 'memberLimit'| 'memberUnavailable'+ | 'mentionUnavailable'| 'notFound'| 'hostNotReady'| 'planOpen'@@ -83,6 +84,7 @@ export type BotGroupErrorVariant =const ERROR_VARIANTS: ReadonlyMap<string, BotGroupErrorVariant> = new Map<BotGroupErrorCode, BotGroupErrorVariant>([['MEMBER_LIMIT', 'memberLimit'],['MEMBER_UNAVAILABLE', 'memberUnavailable'],+ ['MENTION_UNAVAILABLE', 'mentionUnavailable'],['NOT_FOUND', 'notFound'],['HOST_NOT_READY', 'hostNotReady'],['PLAN_OPEN', 'planOpen'],