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(bots): 对已加载旧页上的消息做表情回应后重读那一页

Chrise295aef9a6c3
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
index eed624e6b4..1d01559aad 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -205,7 +205,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
const [stopping, setStopping] = useState(false);
const [planPending, setPlanPending] = useState<PlanPending | null>(null);
const planPendingRef = useRef(false);
- const loadRef = useRef<(additionalSources?: string[]) => void>(() => {});
+ const loadRef = useRef<(additionalSources?: string[], changedIds?: string[]) => void>(() => {});
const scrollRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const stickToBottomRef = useRef(true);
@@ -231,8 +231,8 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
/** Bumped when a read starts (and on delete): re-checks spawned by older reads stop. */
let version = 0;
let inFlight = false;
- let queued: string[] | null = null;
- const run = async (additionalSources: string[]) => {
+ let queued: { sources: string[]; changed: string[] } | null = null;
+ const run = async (additionalSources: string[], changedIds: string[]) => {
inFlight = true;
const current = ++version;
const owner = getDataOwnerGeneration();
@@ -262,8 +262,14 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
return merged === previous ? previous : { kind: 'ready', ...merged };
});
if (shown.kind === 'ready') {
- const targets = quotedOlderOriginals([...shown.older, ...shown.group.messages], result.group.messages);
- if (targets.length > 0) void recheckQuotedOriginals(api, targets, isCurrent);
+ const quoted = quotedOlderOriginals([...shown.older, ...shown.group.messages], result.group.messages);
+ // A message changed here (a reaction) that sits only on an opened older page: the
+ // latest page cannot refresh its copy, so its page is re-read like a quoted original's.
+ const latestIds = new Set(result.group.messages.map((message) => message.id));
+ const changed = shown.older.filter((message) => changedIds.includes(message.id)
+ && !latestIds.has(message.id) && !quoted.some((target) => target.id === message.id));
+ const targets = [...quoted, ...changed].sort((a, b) => b.sequence - a.sequence);
+ if (targets.length > 0) void recheckOlderCopies(api, targets, isCurrent);
}
} else if (result.errorCode === 'NOT_FOUND') {
setState({ kind: 'missing' });
@@ -278,26 +284,30 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
if (queued && !cancelled) {
const next = queued;
queued = null;
- void run(next);
+ void run(next.sources, next.changed);
}
}
};
- /** One read in flight; pushes meanwhile collapse into one follow-up read. */
- const load = (additionalSources: string[] = []) => {
+ /**
+ * One read in flight; pushes meanwhile collapse into one follow-up read. `changedIds` are
+ * messages this client just changed (a reaction): their copies on opened older pages are
+ * re-read, since the latest page does not cover them.
+ */
+ const load = (additionalSources: string[] = [], changedIds: string[] = []) => {
if (inFlight) {
- queued = [...(queued ?? []), ...additionalSources];
+ queued = { sources: [...(queued?.sources ?? []), ...additionalSources], changed: [...(queued?.changed ?? []), ...changedIds] };
return;
}
- void run(additionalSources);
+ void run(additionalSources, changedIds);
};
/**
- * Re-reads the older pages holding quoted originals after a push and updates only messages
- * already loaded; history that was never opened is not fetched. Each read covers at least the
- * newest remaining original, so it ends after at most one read per original. A newer read
- * supersedes this one; a failed read leaves the rest unverified, so their quotes show the
- * snapshot, not the stale copy.
+ * Re-reads the older pages holding quoted originals (and copies this client changed) after a
+ * push and updates only messages already loaded; history that was never opened is not fetched.
+ * Each read covers at least the newest remaining target, so it ends after at most one read per
+ * target. A newer read supersedes this one; a failed read leaves the rest unverified, so their
+ * quotes show the snapshot, not the stale copy.
*/
- const recheckQuotedOriginals = async (
+ const recheckOlderCopies = async (
api: NonNullable<ReturnType<typeof botGroupApi>>,
targets: BotGroupMessageView[],
isCurrent: () => boolean,
@@ -329,7 +339,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
if (covered.length === 0) return;
}
};
- loadRef.current = additionalSources => load(additionalSources);
+ loadRef.current = (additionalSources, changedIds) => load(additionalSources, changedIds);
load();
const unsubscribe =
botGroupApi()?.onBotGroupChanged?.((payload, ownerStamp) => {
@@ -811,7 +821,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
const onPlanAction = useCallback((action: 'start' | 'dismiss', planId: string) => void actionsRef.current.runPlanAction(action, planId), []);
const onEditStep = useCallback((planId: string, step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string) =>
void actionsRef.current.editPlanStep(planId, step, action, botId), []);
- const onChanged = useCallback(() => loadRef.current(), []);
+ const onChanged = useCallback((messageId: string) => loadRef.current([], [messageId]), []);
const onQuote = useCallback((messageId: string) => {
const message = messageByIdRef.current.get(messageId);
if (message) setQuoteDraft(botGroupQuoteFromMessage(message));
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx b/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx
index 017eedb89c..fd3367713c 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx
@@ -229,7 +229,8 @@ export interface BotGroupTimelineItemProps {
onLocateQuote?: (quote: BotGroupQuoteView) => void;
onQuote?: (messageId: string) => void;
onOpenThread?: (messageId: string) => void;
- onChanged: () => void;
+ /** This client changed the message (a reaction): the timeline refreshes its copy. */
+ onChanged: (messageId: string) => void;
highlighted?: boolean;
/** Focusable only as a jump target, so a click elsewhere keeps its usual focus. */
focusable?: boolean;
diff --git a/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx b/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx
index fa07ac6fff..7dca47b964 100644
--- a/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatServerControls.tsx
@@ -20,7 +20,7 @@ const iconClass = 'flex h-8 w-8 shrink-0 items-center justify-center rounded-ful
export { chatErrorKey } from './chatError';
/** Adds or removes the current actor's reaction; the caller re-reads the authoritative message. */
-function useChatReaction(groupId: string | undefined, messageId: string, onChanged: () => void) {
+function useChatReaction(groupId: string | undefined, messageId: string, onChanged: (messageId: string) => void) {
const { t } = useTranslation();
const [busy, setBusy] = useState(false);
const busyRef = useRef(false);
@@ -32,7 +32,7 @@ function useChatReaction(groupId: string | undefined, messageId: string, onChang
const result = await api().react({ groupId, messageId, emoji, present });
if (!isDataOwnerGenerationCurrent(owner)) return;
if (!result.ok) toast.error(t(chatErrorKey(result.errorCode)));
- else onChanged();
+ else onChanged(messageId);
} catch { if (isDataOwnerGenerationCurrent(owner)) toast.error(t(key('requestFailed'))); }
finally { busyRef.current = false; setBusy(false); }
}
@@ -45,7 +45,8 @@ interface ChatMessageActionProps {
onQuote?: () => void;
/** Opens the message's Thread (话题) — 创建话题 before anyone answered, 查看话题 after. */
onReply?: () => void;
- onChanged: () => void;
+ /** The current actor's reaction on `messageId` changed: re-read that message's copy. */
+ onChanged: (messageId: string) => void;
}
/** The reactions under a message's text; each chip toggles the current actor's reaction. */
diff --git a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
index 3aee5dbbb8..1a17d91cf8 100644
--- a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
@@ -81,7 +81,14 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,
const inFlightRef = useRef(false);
const queuedRef = useRef(false);
- const read = useCallback(async (before?: number) => {
+ /** Lowest sequence of the last latest-page read; replies below it live only on opened older pages. */
+ const latestFloorRef = useRef(Number.POSITIVE_INFINITY);
+
+ /**
+ * Reads the latest page, or the page before `before`. `rereadOnly` re-reads an opened page for a
+ * changed copy: it is not the oldest page, so its `hasMore` says nothing about what is loaded.
+ */
+ const read = useCallback(async (before?: number, rereadOnly = false) => {
const owner = getDataOwnerGeneration();
const current = () => aliveRef.current && isDataOwnerGenerationCurrent(owner);
const shown = repliesRef.current;
@@ -93,9 +100,12 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,
setError('');
setExecutionFailures(result.executionFailures ?? []);
setReplies(previous => stabilizeById(previous, mergeBotGroupMessages(previous, result.replies)));
- if (before || shown.length === 0) setHasMore(result.hasMore);
+ if (!before) latestFloorRef.current = result.replies.reduce((min, reply) => Math.min(min, reply.sequence), Number.POSITIVE_INFINITY);
+ if (!rereadOnly && (before || shown.length === 0)) setHasMore(result.hasMore);
} catch { if (current()) setError(t(key('requestFailed'))); }
}, [group.id, rootId, t]);
+ const readRef = useRef(read);
+ readRef.current = read;
/** One refresh in flight; pushes meanwhile collapse into one follow-up read. */
const refresh = useCallback(() => {
if (inFlightRef.current) { queuedRef.current = true; return; }
@@ -144,7 +154,13 @@ export function ChatThreadPanel({ group, rootId, quoteSources = group.messages,
const lastRealSequenceRef = useRef(0);
lastRealSequenceRef.current = realReplies[realReplies.length - 1]?.sequence ?? 0;
- const onChanged = useCallback(() => refreshRef.current(), []);
+ // The root and the latest page come with every refresh; a reply opened through 「加载更早」 sits
+ // below that page, so the page holding it is re-read for its new reaction state.
+ const onChanged = useCallback((messageId: string) => {
+ refreshRef.current();
+ const reply = repliesRef.current.find(candidate => candidate.id === messageId);
+ if (reply && reply.sequence < latestFloorRef.current) void readRef.current(reply.sequence + 1, true);
+ }, []);
const onSendStart = useCallback((message: BotGroupOutgoingMessage) => {
stickToBottomRef.current = true;
setPendingSends((previous) => [
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
index ad928b78c3..5247d37ba4 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -1372,6 +1372,31 @@ describe('BotGroupChatView', () => {
expect(document.body.textContent).not.toContain('很早的原文');
});
+ it('re-reads the opened older page after reacting to a message on it', async () => {
+ const user = userEvent.setup();
+ const older = msg({ id: 'old1', sequence: 1, authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满', content: '很早的消息',
+ reactions: [{ emoji: '👍', count: 1, me: false }] });
+ const latest = msg({ id: 'new1', sequence: 50, content: '最近的消息' });
+ let server = [older];
+ const base = detail({ serverBacked: true, hasMoreBefore: true });
+ mocks.getBotGroup.mockImplementation(async (_id: string, options?: { beforeSequence?: number }) => options?.beforeSequence
+ ? { ok: true, group: { ...base, hasMoreBefore: false, messages: server } }
+ : { ok: true, group: { ...base, messages: [latest] } });
+ const react = vi.fn(async () => { server = [{ ...older, reactions: [{ emoji: '👍', count: 2, me: true }] }]; return { ok: true }; });
+ Object.assign((window.electronAPI as unknown as { maker: { chatServer: Record<string, unknown> } }).maker.chatServer, { react });
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ const chip = await screen.findByRole('button', { name: 'bots.groupChat.server.reactionCount' });
+ expect(chip.getAttribute('aria-pressed')).toBe('false');
+ mocks.getBotGroup.mockClear();
+ await user.click(chip);
+ await waitFor(() => expect(screen.getByRole('button', { name: 'bots.groupChat.server.reactionCount' }).getAttribute('aria-pressed')).toBe('true'));
+ expect(screen.getByRole('button', { name: 'bots.groupChat.server.reactionCount' }).textContent).toContain('2');
+ expect(react).toHaveBeenCalledWith({ groupId: 'g1', messageId: 'old1', emoji: '👍', present: true });
+ // The latest page as always, then only the page holding the changed message.
+ expect(mocks.getBotGroup.mock.calls.map(([, options]) => options?.beforeSequence)).toEqual([undefined, 2]);
+ });
+
describe('quoted originals on older pages after a push', () => {
const original = msg({ id: 'old1', sequence: 1, authorKind: 'bot', authorBotId: 'xiaoman', authorName: '小满', content: '很早的原文' });
const latest = msg({ id: 'q1', sequence: 50, content: '那就这班', quote: quoteOf('old1', { excerpt: '快照摘要', sequence: 1 }) });
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 d94e836c4d..ce6cec3d53 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/ChatServerControls.test.tsx
@@ -211,6 +211,31 @@ describe('chat interaction controls', () => {
expect(mocks.react).toHaveBeenCalledWith({ groupId: 'room', messageId: 'root', emoji: '👍', present: false });
});
+ it('re-reads the opened older Thread page after reacting to a reply on it', async () => {
+ const latest = { ...message, id: 'latest', sequence: 100, content: 'Latest reply', reactions: [] };
+ const older = { ...message, id: 'older', sequence: 4, content: 'Earlier reply', reactions: [{ emoji: '👍', count: 1, me: false }] };
+ let reacted = false;
+ mocks.thread.mockImplementation(async (input: { before?: number }) => input.before
+ // The re-read page's hasMore is not about the oldest loaded page, so it must be ignored.
+ ? { ok: true, root: message, replies: [reacted ? { ...older, reactions: [{ emoji: '👍', count: 2, me: true }] } : older], hasMore: input.before === 5 }
+ : { ok: true, root: message, replies: [latest], hasMore: true });
+ mocks.react.mockImplementation(async () => { reacted = true; return { ok: true }; });
+ render(<ChatThreadPanel group={group} rootId="root" onClose={vi.fn()} />);
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ const earlier = (await screen.findByText('Earlier reply')).closest('article')!;
+ expect(screen.queryByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' })).toBeNull();
+ const chip = within(earlier).getByRole('button', { name: k('reactionCount') });
+ expect(chip.getAttribute('aria-pressed')).toBe('false');
+ fireEvent.click(chip);
+ const earlierChip = () => within(screen.getByText('Earlier reply').closest('article')!).getByRole('button', { name: k('reactionCount') });
+ await waitFor(() => expect(earlierChip().getAttribute('aria-pressed')).toBe('true'));
+ expect(earlierChip().textContent).toContain('2');
+ expect(mocks.react).toHaveBeenCalledWith({ groupId: 'room', messageId: 'older', emoji: '👍', present: true });
+ expect(mocks.thread.mock.calls.map(([input]) => input.before)).toEqual([undefined, 100, undefined, 5]);
+ expect(screen.queryByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' })).toBeNull();
+ expect(screen.getByText('Latest reply')).toBeTruthy();
+ });
+
it('uses the refreshed Thread root reaction state while the main timeline remains stale', async () => {
mocks.thread.mockResolvedValueOnce({ ok: true, root: message, replies: [], hasMore: false })
.mockResolvedValue({ ok: true, root: { ...message, reactions: [{ emoji: '👍', count: 1, me: false }] }, replies: [], hasMore: false });
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index e1b01bcbaa..bd2a5700d6 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -27,6 +27,8 @@
停在旧记录处或窗口在后台时,保留新消息的提醒。
- **消息操作复用统一组件**:复制、分享、引用回复、创建话题、表情回应与时间使用现有消息操作栏,
放在对应作者的正文下方;不另做尺寸与间距不同的群聊操作行。话题(Thread)同样支持复制、分享与表情。
+ 表情回应成功后以服务器为准重读这条消息:它在最新一页就随刷新更新;只在「查看更早」/「加载更早」已打开的
+ 页上时,重读它所在的那一页(只更新已加载的消息,不改变「还有更早」的判断)。
「引用回复」留在当前时间线,「创建话题」打开挂在这条消息下的 Thread,两者不能混用(第 10 节「引用回复」)。
分享复用消息选取和图片导出流程,主群与 Thread 的选区各自独立,导出保留作者和正文,排除操作控件。
- **伙伴在群里还是它自己**:名字、头像、人格、记忆、自有 Skill、模型候选链和工具与平时一致。