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): 过期读取失败也重新读取;迟到的旧页贴回一并核对;定位不到的贴回不再提供重复贴回

Dashd077961bd091
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreads.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreads.test.ts
index 68e84fd914..8b90a8e086 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreads.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreads.test.ts
@@ -212,6 +212,24 @@ describe('late reads after a reset or invalidation', () => {
expect(io.message).toHaveBeenCalledTimes(2);
expect(projection.shareSources(room, [share], []).get(sourceId)?.revision).toBe(2);
});
+
+ it.each(['reset', 'invalidate'] as const)('asks for a fresh read when a read started before %s fails', async (clear) => {
+ const io = makeIo();
+ const projection = createThreadProjection(io);
+ let fail!: (error: Error) => void;
+ io.message.mockReturnValueOnce(new Promise((_, reject) => { fail = reject; })).mockResolvedValue(reply(sourceId, rootA));
+ projection.shareSources(room, [share], []);
+ // An unrelated edit: the refresh it causes skips the read still in flight.
+ if (clear === 'reset') projection.reset(); else projection.invalidate(room, 'another-message');
+ expect(projection.shareSources(room, [share], []).has(sourceId)).toBe(false);
+ fail(new Error('offline'));
+ await projection.settled();
+ expect(io.filled).toHaveBeenCalledWith(room);
+ projection.shareSources(room, [share], []);
+ await projection.settled();
+ expect(io.message).toHaveBeenCalledTimes(2);
+ expect(projection.shareSources(room, [share], []).get(sourceId)?.id).toBe(sourceId);
+ });
});
describe('reply summaries', () => {
diff --git a/apps/desktop/src/main/maker-ipc/chatServerThreads.ts b/apps/desktop/src/main/maker-ipc/chatServerThreads.ts
index 65ab0bbc66..071d2e650c 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerThreads.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerThreads.ts
@@ -107,12 +107,13 @@ export function createThreadProjection<M extends ThreadMessage>(io: {
const task = (async () => {
let wrote = false;
await eachLimited(items, async ({ cacheKey, item }) => {
+ // A read that outlived a reset or invalidation, whether it succeeded or failed, is
+ // dropped, and the reader is asked to read again: the refresh in between skipped it.
try {
const store = await read(item);
retryAt.delete(cacheKey); settledRetry(roomId, cacheKey);
- // A copy that outlived a reset is dropped, but the reader still needs a fresh read.
if (store) { if (generation === started) store(); wrote = true; }
- } catch { if (generation === started) scheduleRetry(roomId, cacheKey); }
+ } catch { if (generation === started) scheduleRetry(roomId, cacheKey); else wrote = true; }
finally { inFlight.delete(cacheKey); }
});
if (wrote) io.filled(roomId);
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
index 0c9c67bdd5..0e09a9407e 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -166,7 +166,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
const [continuing, setContinuing] = useState(false);
const [planPending, setPlanPending] = useState<PlanPending | null>(null);
const planPendingRef = useRef(false);
- const loadRef = useRef<(additionalSources?: string[]) => void>(() => {});
+ const loadRef = useRef<(merging?: readonly BotGroupMessageView[]) => void>(() => {});
const scrollRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const stickToBottomRef = useRef(true);
@@ -182,7 +182,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
let requestVersion = 0;
// Follow-up reads for older shares one refresh could not check; bounded per chain.
let shareFollowUps = 0;
- const load = async (additionalSources: string[] = []) => {
+ const load = async (merging: readonly BotGroupMessageView[] = []) => {
const version = ++requestVersion;
const owner = getDataOwnerGeneration();
const api = botGroupApi();
@@ -195,10 +195,12 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
try {
const displayed = stateRef.current;
const shown = displayed.kind === 'ready' && displayed.group.id === groupId;
+ // An older page merged just before this read may not be on `displayed` yet.
+ const shownOlder = shown ? mergeBotGroupMessages(displayed.older, merging) : [];
const sourceMessageIds = [...new Set([...(shown
- ? mergeBotGroupMessages(displayed.older, displayed.group.messages).map(message => message.id) : []), ...additionalSources])];
+ ? mergeBotGroupMessages(shownOlder, displayed.group.messages).map(message => message.id) : []), ...merging.map(message => message.id)])];
// Older pages are not re-read, so their shares ask for the reply's current state.
- const shownShares = shown ? botGroupShownShares(displayed.older, displayed.group.threadShareVersion) : [];
+ const shownShares = shown ? botGroupShownShares(shownOlder, displayed.group.threadShareVersion) : [];
const result = sourceMessageIds.length || shownShares.length
? await api.getBotGroup(groupId, { sourceMessageIds, ...(shownShares.length ? { shownShares } : {}) })
: await api.getBotGroup(groupId);
@@ -216,7 +218,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
olderHasMore: result.group.hasMoreBefore,
},
);
- const older = shown ? applyBotGroupThreadShareUpdates(displayed.older, result.group) : [];
+ const older = applyBotGroupThreadShareUpdates(shownOlder, result.group);
const unchecked = staleBotGroupShares(older, result.group.threadShareVersion).length;
const total = older.filter(message => message.threadShare).length;
if (!unchecked) shareFollowUps = 0;
@@ -234,7 +236,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
if (isCurrent()) setState((previous) => (previous.kind === 'ready' ? previous : { kind: 'error' }));
}
};
- loadRef.current = additionalSources => void load(additionalSources);
+ loadRef.current = merging => void load(merging);
void load();
const unsubscribe =
botGroupApi()?.onBotGroupChanged?.((payload, ownerStamp) => {
@@ -475,8 +477,9 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {
olderHasMore: result.group.hasMoreBefore,
};
});
- // A push may have refreshed before these sources were displayed. Reconcile their current state too.
- if (newerRefresh) loadRef.current(result.group.messages.map(message => message.id));
+ // A push may have refreshed before this page was displayed: reconcile its sources and
+ // shares too. The page goes along because the merge above may not be committed yet.
+ if (newerRefresh) loadRef.current(result.group.messages);
} catch {
toast.error(t('bots.groupChat.timeline.loadEarlierFailed'));
} finally {
diff --git a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
index 2a0f8e0e7f..e922db7384 100644
--- a/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
+++ b/apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx
@@ -62,10 +62,11 @@ function ThreadMessage({ group, message, shareScope, sharing, shared, posting, o
if (message.kind === 'notice' && isBotGroupRuntimeFailureCode(message.runtimeFailureCode)) return <BotGroupRuntimeFailureNotice name={message.authorName || member?.name || ''} code={message.runtimeFailureCode} />;
// A share as a thread root shows the same quote as the main chat, in every state.
const share = message.threadShare;
- const postAction = onPost && !message.deleted && message.kind === 'message' ? shared?.bySelf && onReveal
- ? { key: 'reveal-in-main', label: t(key('thread.viewInMain')), icon: <CornerDownRight size={14} strokeWidth={2} className="shrink-0" />, onSelect: onReveal }
- : { key: 'post-to-main', label: t(key('thread.postToMain')), disabled: posting, icon: <MessageSquareShare size={14} strokeWidth={2} className="shrink-0" />, onSelect: onPost }
- : undefined;
+ // Once the reader has posted it, posting again can only meet the same share: offer the
+ // jump when that share can be located, and nothing otherwise.
+ const postAction = !onPost || message.deleted || message.kind !== 'message' ? undefined
+ : shared?.bySelf ? onReveal && { key: 'reveal-in-main', label: t(key('thread.viewInMain')), icon: <CornerDownRight size={14} strokeWidth={2} className="shrink-0" />, onSelect: onReveal }
+ : { key: 'post-to-main', label: t(key('thread.postToMain')), disabled: posting, icon: <MessageSquareShare size={14} strokeWidth={2} className="shrink-0" />, onSelect: onPost };
return <article {...{ [SHARE_SESSION_ATTR]: shareScope, [SHARE_MESSAGE_ATTR]: message.id }}
className={`relative flex min-w-0 gap-2.5 ${sharing ? 'ml-10' : ''}`}>
{sharing && <ShareMessageCheckbox clientId={message.id} />}
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 4a42c0f8b1..0801def61b 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -2021,6 +2021,31 @@ describe('thread share follow-ups', () => {
expect(await screen.findByRole('menuitem', { name: t('viewInMain') })).toBeTruthy();
});
+ it('stops offering to post a reply whose existing share cannot be located', async () => {
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [msg({ id: 'u1', content: '去哪玩' })] }) });
+ mocks.thread.mockResolvedValue({ ok: true, root: msg({ id: 'u1', content: '去哪玩' }), hasMore: false,
+ replies: [msg({ id: 'alice-reply', authorKind: 'user', isSelf: false, authorName: 'Alice', content: 'Alice says hi' })] });
+ // The server already has this person's share but could not say which message it is.
+ mocks.shareToMain.mockResolvedValue({ ok: true, messageId: null, alreadyShared: true });
+ const user = userEvent.setup();
+ renderView();
+ await user.click(await screen.findByRole('button', { name: 'bots.groupChat.server.reply' }));
+ const reply = (await within(await screen.findByRole('complementary')).findByText('Alice says hi')).closest('article')!;
+ fireEvent.pointerDown(within(reply).getByRole('button', { name: 'chat.messageActionBar.moreActions' }), { button: 0, ctrlKey: false });
+ await user.click(await screen.findByRole('menuitem', { name: t('postToMain') }));
+ const badge = await within(reply).findByRole('button', { name: t('postedBySelf') });
+ expect((badge as HTMLButtonElement).disabled).toBe(true);
+ // With nothing else to offer for this reply, the menu itself may be gone.
+ const more = within(reply).queryByRole('button', { name: 'chat.messageActionBar.moreActions' });
+ if (more) {
+ fireEvent.pointerDown(more, { button: 0, ctrlKey: false });
+ await screen.findAllByRole('menuitem');
+ }
+ expect(screen.queryByRole('menuitem', { name: t('postToMain') })).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: t('viewInMain') })).toBeNull();
+ expect(mocks.shareToMain).toHaveBeenCalledTimes(1);
+ });
+
it('keeps every failed main-chat copy retryable, across switching threads', async () => {
mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, messages: [msg({ id: 'u1', content: 'A' }), msg({ id: 'u2', sequence: 2, content: 'B' })] }) });
mocks.reply.mockResolvedValueOnce({ ok: true, messageId: 'first' }).mockResolvedValueOnce({ ok: true, messageId: 'second' });
@@ -2074,6 +2099,29 @@ describe('shares on older pages', () => {
expect(mocks.getBotGroup).toHaveBeenLastCalledWith('g1', expect.objectContaining({
shownShares: [{ id: 'old-share', messageId: 'old-reply', threadRootId: 'old-root', sharerId: 'alice-actor' }] }));
});
+
+ it('checks the shares of an older page that lands after an edit refreshed the timeline', async () => {
+ const share = { messageId: 'old-reply', threadRootId: 'old-root', status: 'available' as const, authorKind: 'bot' as const, authorBotId: 'xiaoman', authorName: '小满',
+ sharedByAuthor: false, content: '编辑前的原文', attachments: [], createdAt: 1, edited: false, version: 1 };
+ const oldShare = msg({ id: 'old-share', sequence: 1, authorKind: 'user', isSelf: false, authorBotId: 'alice-actor', authorName: 'Alice', content: '↪ 卡片文字', threadShare: share });
+ const latest = detail({ serverBacked: true, hasMoreBefore: true, threadShareVersion: 1, messages: [msg({ id: 'new', sequence: 50, content: '最新' })] });
+ let finish!: (result: { ok: true; group: BotGroupDetail }) => void;
+ mocks.getBotGroup
+ .mockResolvedValueOnce({ ok: true, group: latest })
+ .mockReturnValueOnce(new Promise(resolve => { finish = resolve; }))
+ .mockResolvedValueOnce({ ok: true, group: { ...latest, threadShareVersion: 2 } })
+ .mockImplementation(async (_groupId: string, options?: { shownShares?: Array<{ id: string }> }) => ({ ok: true, group: { ...latest, threadShareVersion: 2,
+ ...(options?.shownShares?.some(item => item.id === 'old-share')
+ ? { threadShareUpdates: { 'old-share': { ...share, content: '编辑后的原文', edited: true, version: 2 } } } : {}) } }));
+ renderView();
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));
+ // The reply is edited while that page is on its way; the push refresh finishes first.
+ await act(async () => mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })));
+ await waitFor(() => expect(mocks.getBotGroup).toHaveBeenCalledTimes(3));
+ await act(async () => finish({ ok: true, group: { ...latest, hasMoreBefore: false, messages: [oldShare] } }));
+ expect(await screen.findByText('编辑后的原文')).toBeTruthy();
+ expect(screen.queryByText('编辑前的原文')).toBeNull();
+ });
});
describe('more older shares than one refresh re-reads', () => {