Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(chat): re-read reactors only for the message whose reactions changed

Dash3ed7b043c82f
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
index 8d88b99e07..e83c8731b2 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -1091,13 +1091,16 @@ describe('Chat Server result delivery and refresh', () => {
const recovered = await service.getGroup(roomId);
expect(recovered.ok && recovered.group.messages[0].attachments[0].name).toBe('report.pdf');
});
- it('versions the room’s reactions on realtime reaction changes and resets, even when counts are unchanged', async () => {
+ it('versions only the changed message on realtime reaction changes and the whole room on resets', async () => {
const message = { id: execution.source_message_id, seq: '1', authorId: selfId, author: { kind: 'human', name: 'Me' },
content: [{ type: 'text', text: 'Hi' }], createdAt: new Date().toISOString(), deleted: false, threadRootId: null,
reactions: [{ emoji: '👍', count: 1, me: false }] };
fixture.handle.mockImplementation(route => route.includes('/messages?') ? { body: [message] } : response(route));
- const revision = async () => { const r = await service.getGroup(roomId); return r.ok ? r.group.reactionRevision : undefined; };
- expect(await revision()).toBe(0);
+ const revisions = async () => {
+ const r = await service.getGroup(roomId);
+ return r.ok ? { room: r.group.reactionRevision, messages: r.group.reactionRevisions } : undefined;
+ };
+ expect(await revisions()).toEqual({ room: 0, messages: {} });
await vi.advanceTimersByTimeAsync(2000);
const socket = fixture.sockets[0];
// One member removes 👍 and another adds it in one batch: same count, different reactor.
@@ -1106,15 +1109,18 @@ describe('Chat Server result delivery and refresh', () => {
{ type: 'reaction.changed', entityId: message.id, data: { emoji: '👍', present: true } },
{ type: 'message.updated', entityId: message.id },
] }));
- expect(await revision()).toBe(1);
- // Other changes do not invalidate reactor reads.
- socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '6', changes: [{ type: 'message.updated', entityId: message.id }] }));
- expect(await revision()).toBe(1);
- // A reset skips whatever changed while disconnected: the room counts as changed once.
+ expect(await revisions()).toEqual({ room: 0, messages: { [message.id]: 2 } });
+ // A reaction elsewhere leaves this message's version alone; other changes do not invalidate reactor reads.
+ socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: '6', changes: [
+ { type: 'reaction.changed', entityId: 'other-message', data: { emoji: '🎉', present: true } },
+ { type: 'message.updated', entityId: message.id },
+ ] }));
+ expect(await revisions()).toEqual({ room: 0, messages: { [message.id]: 2, 'other-message': 1 } });
+ // A reset skips whatever changed while disconnected: the whole room counts as changed once.
Object.defineProperty(socket, 'readyState', { value: 1 });
socket.emit('message', JSON.stringify({ type: 'scope_error', scope: `conversation:${roomId}`, error: { code: 'RESET_REQUIRED' } }));
await vi.advanceTimersByTimeAsync(0);
- expect(await revision()).toBe(2);
+ expect(await revisions()).toEqual({ room: 1, messages: {} });
});
it('refreshes a reset room and resumes realtime from the authorized snapshot cursor', async () => {
await service.getGroup(roomId);
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 50f42c50d2..cf639ce024 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -181,10 +181,16 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
let companion: CompanionCloudRuntime | undefined;
let companionSelf: string | null = null;
let actorsStale = false;
- // Who reacted can change while counts stay the same. Any realtime reaction change, or a reset that
- // skipped events, versions the whole room, so every loaded page and the Thread see it on refresh.
- const reactionRevisions = new Map<string, number>();
- const bumpReactions = (roomId: string) => reactionRevisions.set(roomId, (reactionRevisions.get(roomId) ?? 0) + 1);
+ // Who reacted can change while counts stay the same. A realtime reaction change versions only its
+ // message; a reset that skipped events versions the whole room (and makes per-message versions moot).
+ // Both ride on the group, so every loaded page and the Thread see them on refresh.
+ const reactionRevisions = new Map<string, { room: number; messages: Record<string, number> }>();
+ const bumpMessageReactions = (roomId: string, messageId: string) => {
+ const revisions = reactionRevisions.get(roomId) ?? { room: 0, messages: {} };
+ revisions.messages[messageId] = (revisions.messages[messageId] ?? 0) + 1;
+ reactionRevisions.set(roomId, revisions);
+ };
+ const resetReactions = (roomId: string) => reactionRevisions.set(roomId, { room: (reactionRevisions.get(roomId)?.room ?? 0) + 1, messages: {} });
let profiles: Array<typeof botProfiles.$inferSelect> = [];
const workspaces = () => chatServerWorkspaces(config.baseUrl, selfId, current);
const planning = new Map<string, { botId: string; controller: AbortController }>();
@@ -561,7 +567,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
if (event.scope.startsWith('conversation:')) {
const roomId = event.scope.slice(13);
if (rooms.has(roomId)) advanceRoom(roomId, event.cursor);
- if ((event.changes ?? []).some((change: { type?: unknown }) => change.type === 'reaction.changed')) bumpReactions(roomId);
+ for (const change of event.changes ?? []) if (change.type === 'reaction.changed' && typeof change.entityId === 'string') {
+ bumpMessageReactions(roomId, change.entityId);
+ }
changed(roomId);
for (const run of running.values()) if (run.execution.conversation_id === roomId) void checkLease(run);
}
@@ -577,7 +585,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
void api<Snapshot>(`/conversations/${roomId}/snapshot`).then(value => {
if (!current() || socket !== ws || ws.readyState !== WebSocket.OPEN) return;
if (rooms.has(roomId)) advanceRoom(roomId, value.cursor);
- bumpReactions(roomId);
+ resetReactions(roomId);
changed(roomId);
ws.send(JSON.stringify({ type: 'subscribe', scope: event.scope, after: value.cursor }));
}).catch(() => ws.close());
@@ -732,7 +740,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const messages = summaryOnly ? [] : (await messageViews(roomId, page, s.members)).sort((a, b) => a.sequence - b.sequence);
const last = s.messages[0];
const lastView = last ? messageView(last, s.members) : null;
- return { serverBacked: true, reactionRevision: reactionRevisions.get(roomId) ?? 0, migrationPending: [...upgradeErrors.keys()].some(source => upgradedGroups.get(source) === roomId), archived: s.room.archived, selfActorId: selfId, topic: s.room.topic, description: s.room.description, revision: s.room.revision, canInvite: s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), id: s.room.id, name: s.room.name, replyMode: s.room.response_mode, speakingMode: s.room.speaking_mode,
+ return { serverBacked: true, reactionRevision: reactionRevisions.get(roomId)?.room ?? 0, reactionRevisions: { ...reactionRevisions.get(roomId)?.messages }, migrationPending: [...upgradeErrors.keys()].some(source => upgradedGroups.get(source) === roomId), archived: s.room.archived, selfActorId: selfId, topic: s.room.topic, description: s.room.description, revision: s.room.revision, canInvite: s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), id: s.room.id, name: s.room.name, replyMode: s.room.response_mode, speakingMode: s.room.speaking_mode,
members: s.members.filter(m => m.state === 'joined').map(m => {
const p = localBot(m.id);
return { botId: p?.id ?? m.id, actorId: m.id, actorKind: m.kind, isSelf: m.id === selfId,
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
index 5eb5c33249..8a8cd7cc09 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -73,7 +73,7 @@ import { BotGroupAvatarStack } from './BotGroupAvatars';
import { botGroupAttachmentScope, splitBotGroupMessageAttachments } from './botGroupAttachments';
import { BotGroupComposer } from './BotGroupComposer';
import { BotGroupQuoteBlock } from './BotGroupQuote';
-import { ChatInviteButton, ChatMessageActions } from './ChatServerControls';
+import { ChatInviteButton, ChatMessageActions, messageReactionRevision } from './ChatServerControls';
import { animateThreadPanelWidth, ChatThreadPanel } from './ChatThreadPanel';
import { BotGroupPendingInteraction } from './BotGroupPendingInteraction';
import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';
@@ -840,7 +840,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
quoteDisplay={message.quote ? resolveBotGroupQuote(message.quote, quoteSources) : undefined}
onLocateQuote={message.quote ? () => void locateQuoted(message.quote!) : undefined}
actions={message.kind === 'message' ? <ChatMessageActions
- groupId={group.serverBacked ? group.id : undefined} shareScope={shareScope} message={message} members={group.members} reactionRevision={group.reactionRevision}
+ groupId={group.serverBacked ? group.id : undefined} shareScope={shareScope} message={message} members={group.members} reactionRevision={messageReactionRevision(group, message.id)}
align={message.authorKind === 'user' && message.isSelf !== false ? 'right' : 'left'}
onQuote={group.serverBacked && !group.archived && isBotGroupMessageQuotable(message)
? () => setQuoteDraft(botGroupQuoteFromMessage(message)) : undefined}
diff --git a/apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx b/apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx
index d43f1222c6..80be78df36 100644
--- a/apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx
@@ -36,12 +36,12 @@ function reactorNames(reactors: ChatReactor[], t: TFunction, language: string) {
* and actors without one fall back to an initial, never an invented identity.
*/
export function ChatReactionButton({ groupId, messageId, reaction, revision = 0, members, disabled, onToggle }: {
- groupId?: string; messageId: string; reaction: Reaction; revision?: number; members?: BotGroupMemberView[]; disabled: boolean; onToggle: () => void;
+ groupId?: string; messageId: string; reaction: Reaction; revision?: string | number; members?: BotGroupMemberView[]; disabled: boolean; onToggle: () => void;
}) {
const { t, i18n } = useTranslation();
const [loaded, setLoaded] = useState<Loaded | null>(null);
// Changes on every add/remove, local or remote — including a same-count swap of who reacted,
- // which only the realtime reaction revision reveals.
+ // which only the message's realtime reaction revision reveals.
const summary = `${reaction.count}:${reaction.me}:${revision}`;
const wantsAvatars = !!groupId && reaction.count > 0 && reaction.count <= REACTION_AVATAR_LIMIT;
// Only badges near the viewport read, so opening a long history does not fire one read per badge.
diff --git a/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx b/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx
index 424541e00c..54c8003d95 100644
--- a/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx
@@ -11,7 +11,7 @@ import { Tip } from '@/components/ui/tooltip';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { toast } from '@/lib/toast';
-import type { BotGroupMemberView, BotGroupMessageView } from '../../../shared/botGroupChat';
+import type { BotGroupDetail, BotGroupMemberView, BotGroupMessageView } from '../../../shared/botGroupChat';
const key = (name: string) => `bots.groupChat.server.${name}`;
const api = () => window.electronAPI.maker.chatServer;
@@ -19,12 +19,16 @@ const emojiChoices = ['👍', '❤️', '😂', '🎉', '👀', '🙏', '✅', '
const iconClass = 'flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)] disabled:opacity-50';
export { chatErrorKey } from './chatError';
+/** A message's reaction version: the room's reset version plus the message's own realtime changes. */
+export const messageReactionRevision = (group: Pick<BotGroupDetail, 'reactionRevision' | 'reactionRevisions'>, messageId: string) =>
+ `${group.reactionRevision ?? 0}:${group.reactionRevisions?.[messageId] ?? 0}`;
+
/**
* `onQuote` is 引用回复: a new main-timeline message that quotes this one. `onReply` opens the
* message's Thread (话题) — 创建话题 before anyone answered, 查看话题 after.
*/
export function ChatMessageActions({ groupId, shareScope, message, members, reactionRevision, align = message.isSelf ? 'right' : 'left', onQuote, onReply, onChanged }: {
- groupId?: string; shareScope: string; message: BotGroupMessageView; members?: BotGroupMemberView[]; reactionRevision?: number; align?: 'left' | 'right'; onQuote?: () => void; onReply?: () => void; onChanged: () => void;
+ groupId?: string; shareScope: string; message: BotGroupMessageView; members?: BotGroupMemberView[]; reactionRevision?: string | number; align?: 'left' | 'right'; onQuote?: () => void; onReply?: () => void; onChanged: () => void;
}) {
const { t } = useTranslation();
const [busy, setBusy] = useState(false);
diff --git a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
index 389f883905..2726e0aff5 100644
--- a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
@@ -18,7 +18,7 @@ import { mergeBotGroupMessages, projectBotGroupExecutionFailures } from './botGr
import { BotAvatar } from './BotAvatar';
import { BotGroupQuoteBlock } from './BotGroupQuote';
import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';
-import { ChatMessageActions, chatErrorKey } from './ChatServerControls';
+import { ChatMessageActions, chatErrorKey, messageReactionRevision } from './ChatServerControls';
const key = (name: string) => `bots.groupChat.server.${name}`;
const api = () => window.electronAPI.maker.chatServer;
@@ -46,7 +46,7 @@ function ThreadMessage({ group, message, quoteSources, shareScope, sharing, onCh
<div className="break-words text-14 leading-relaxed text-[var(--text-primary)]">
<MarkdownRenderer workingDir="" content={message.content} allowPrivilegedLinks={false} />
</div>
- <ChatMessageActions groupId={group.id} shareScope={shareScope} message={message} members={group.members} reactionRevision={group.reactionRevision} align="left" onChanged={onChanged} />
+ <ChatMessageActions groupId={group.id} shareScope={shareScope} message={message} members={group.members} reactionRevision={messageReactionRevision(group, message.id)} align="left" onChanged={onChanged} />
</div>
</article>;
}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx
index ce527ab9d4..dfb85bebae 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { StrictMode, type ReactNode } from 'react';
-import { cleanup, fireEvent, render as renderUI, screen, waitFor, within } from '@testing-library/react';
+import { act, cleanup, fireEvent, render as renderUI, screen, waitFor, within } from '@testing-library/react';
import { Tooltip } from '@/components/ui/tooltip';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ChatInviteButton, ChatJoinButton, ChatMessageActions } from '../ChatServerControls';
@@ -145,12 +145,24 @@ describe('chat interaction controls', () => {
expect(mocks.react).toHaveBeenCalledWith({ groupId: 'room', messageId: 'root', emoji: '👍', present: false });
});
- it('re-reads Thread reactors when the room reaction revision changes, even if the page is not reloaded', async () => {
- const view = render(<ChatThreadPanel group={{ ...group, reactionRevision: 1 }} rootId="root" onClose={vi.fn()} />);
+ it('re-reads Thread reactors only when this message or the whole room changed, even if the page is not reloaded', async () => {
+ const thread = (revisions: Pick<BotGroupDetail, 'reactionRevision' | 'reactionRevisions'>) =>
+ <ChatThreadPanel group={{ ...group, ...revisions }} rootId="root" onClose={vi.fn()} />;
+ const view = render(thread({ reactionRevision: 0, reactionRevisions: { root: 1 } }));
+ const rerender = (revisions: Pick<BotGroupDetail, 'reactionRevision' | 'reactionRevisions'>) =>
+ view.rerender(<Tooltip.Provider>{thread(revisions)}</Tooltip.Provider>);
await screen.findByRole('button', { name: k('reactionCount') });
await waitFor(() => expect(mocks.reactors).toHaveBeenCalledTimes(1));
- view.rerender(<Tooltip.Provider><ChatThreadPanel group={{ ...group, reactionRevision: 2 }} rootId="root" onClose={vi.fn()} /></Tooltip.Provider>);
+ // Someone reacted to another message: this badge keeps its reactors.
+ rerender({ reactionRevision: 0, reactionRevisions: { root: 1, other: 1 } });
+ await act(async () => {});
+ expect(mocks.reactors).toHaveBeenCalledTimes(1);
+ // Who reacted to this message changed.
+ rerender({ reactionRevision: 0, reactionRevisions: { root: 2, other: 1 } });
await waitFor(() => expect(mocks.reactors).toHaveBeenCalledTimes(2));
+ // A reset counts every message as changed.
+ rerender({ reactionRevision: 1, reactionRevisions: {} });
+ await waitFor(() => expect(mocks.reactors).toHaveBeenCalledTimes(3));
});
it('uses the refreshed Thread root reaction state while the main timeline remains stale', async () => {
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 78d4ccdb32..cec68fed73 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -365,9 +365,9 @@ Desktop 主群与 Thread 的表情回应徽标参考 Telegram:某个表情的
不额外读取名单。只有接近可视区域的徽标才读取回应者,打开长历史不会逐个徽标发请求。名单按 Actor ID 去重,由主进程读取
Chat Server 既有的回应者接口直到最后一页(离群成员保留回应,总数可超过群人数上限)并按群成员投影命名;
读取只读,不触发伙伴资料同步等任何写入。加载期间按人数预留头像位,不撑动消息;读取失败或名单与人数暂不一致时
-如实显示数字。回应数、自己的状态或群内的实时回应事件(含人数不变、只换了人的情况)变化时重新读取;回应版本按群计,
-已加载的更早消息页与话题里的徽标也会随之更新;实时连接断开期间,
-只换人不换数的变化要到重连回放后才更新,无法回放而重置时,所有回应都按已变化重新读取。回应者是否在群、叫什么,
+如实显示数字。回应数、自己的状态或这条消息的实时回应事件(含人数不变、只换了人的情况)变化时重新读取;
+回应版本按消息记在群详情上,已加载的更早消息页与话题里的徽标也会随之更新,别的消息被回应不会让它重新读取;
+实时连接断开期间,只换人不换数的变化要到重连回放后才更新,无法回放而重置时,整个群的回应都按已变化重新读取。回应者是否在群、叫什么,
始终按最新的群成员资料双向投影:改昵称、离群或重新加入都会立即更新,离群后沿用读取时的名字并标注不在群中。点击仍是添加/取消回应。回归见 `ChatReactionButton.test.tsx`
与 `chatServer.test.ts`;手机端暂不显示回应。
diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.ts
index 5a4f3625f5..dc57673b2c 100644
--- a/packages/maker-shared/src/botGroupChat.ts
+++ b/packages/maker-shared/src/botGroupChat.ts
@@ -313,8 +313,10 @@ export interface BotGroupSummary {
}
export interface BotGroupDetail extends BotGroupSummary {
- /** Room-wide; bumped by realtime reaction changes and resets, so a same-count change of who reacted is noticed. */
+ /** Room-wide; bumped when a reset skipped realtime events, so every message's reactors count as changed. */
reactionRevision?: number;
+ /** Per message id; bumped by realtime reaction changes, so a same-count change of who reacted is noticed. */
+ reactionRevisions?: Record<string, number>;
/** Oldest first. */
messages: BotGroupMessageView[];
/** Authorized current failures, independent of message pagination. Local/older hosts omit this. */