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(desktop): 群聊刷新失败后自动补读

zcinta051426f44fe94ee4
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
index de0a57abae..16b2acc0ef 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -145,6 +145,8 @@ const QUOTE_HIGHLIGHT_MS = 2000;
const STICK_TO_BOTTOM_PX = 48;
/** Read marks follow scrolling at most this often (leading edge, plus one trailing mark). */
const ACKNOWLEDGE_THROTTLE_MS = 150;
+/** Match the phone's direct-chat recovery without polling healthy timelines. */
+const TIMELINE_READ_RECOVERY_MS = 30_000;
const NO_IDS: ReadonlySet<string> = new Set();
/**
@@ -257,7 +259,24 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: boo
let version = 0;
let inFlight = false;
let queued: { sources: string[]; changed: string[] } | null = null;
+ // A queued read can finish before React commits the previous successful snapshot.
+ let hasTimeline = stateRef.current.kind === 'ready';
+ let retryTimer: ReturnType<typeof setTimeout> | undefined;
+ const clearRetry = () => {
+ clearTimeout(retryTimer);
+ retryTimer = undefined;
+ };
+ const retryRead = (owner: ReturnType<typeof getDataOwnerGeneration>, sources: string[], changed: string[]) => {
+ // A first read already has an explicit retry; keep the visible history on a failed refresh.
+ if (!hasTimeline) return;
+ clearRetry();
+ retryTimer = setTimeout(() => {
+ retryTimer = undefined;
+ if (!cancelled && isDataOwnerGenerationCurrent(owner)) load(sources, changed);
+ }, TIMELINE_READ_RECOVERY_MS);
+ };
const run = async (additionalSources: string[], changedIds: string[]) => {
+ clearRetry();
inFlight = true;
const current = ++version;
const readToken = beginBotGroupTimelineRead();
@@ -283,6 +302,7 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: boo
: await api.getBotGroup(groupId, direct ? { conversationKind: 'direct' } : undefined);
if (!isApplicable()) return;
if (result.ok) {
+ hasTimeline = true;
readOwner.current = owner;
const shown = stateRef.current;
setState((previous) => {
@@ -317,14 +337,21 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: boo
}
}
} else if (result.errorCode === 'NOT_FOUND') {
+ hasTimeline = false;
discardOutbox();
setState({ kind: 'missing' });
} else {
// Keep a timeline that is already on screen; only a first read fails loudly.
setState((previous) => (previous.kind === 'ready' ? previous : { kind: 'error' }));
+ if (['REQUEST_TIMEOUT', 'SERVICE_ERROR', 'CHAT_UNAVAILABLE', 'HOST_NOT_READY', 'INTERNAL'].includes(result.errorCode)) {
+ retryRead(owner, additionalSources, changedIds);
+ }
}
} catch {
- if (isApplicable()) setState((previous) => (previous.kind === 'ready' ? previous : { kind: 'error' }));
+ if (isApplicable()) {
+ setState((previous) => (previous.kind === 'ready' ? previous : { kind: 'error' }));
+ retryRead(owner, additionalSources, changedIds);
+ }
} finally {
inFlight = false;
if (queued && !cancelled) {
@@ -393,6 +420,7 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: boo
if (payload.change === 'deleted' || (payload.change === 'list' && payload.listState?.hidden)) {
cancelled = true;
queued = null;
+ clearRetry();
// Unsent attachments go with the group (staged copies included).
discardDraft(botGroupAttachmentScope(groupId));
discardOutbox();
@@ -407,6 +435,7 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: boo
return () => {
cancelled = true;
queued = null;
+ clearRetry();
version += 1;
loadRef.current = () => {};
unsubscribe();
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 85f374d2fd..77123309d5 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -1450,6 +1450,11 @@ describe('BotGroupChatView', () => {
renderView();
expect(await screen.findByText('bots.groupChat.loadFailedTitle')).toBeTruthy();
expect(screen.getByTestId('content-header').textContent).toContain('周末出游');
+ vi.useFakeTimers();
+ try {
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(1);
+ } finally { vi.useRealTimers(); }
fireEvent.click(screen.getByRole('button', { name: /bots.retry/ }));
expect(await screen.findByText('周六 8:10 有票')).toBeTruthy();
});
@@ -1475,6 +1480,94 @@ describe('BotGroupChatView', () => {
expect(await screen.findByText('bots.groupChat.unavailableTitle')).toBeTruthy();
});
+ describe('failed timeline read recovery', () => {
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ mocks.ownerGeneration = { dataOwnerId: 'account-a', generation: 1 };
+ });
+
+ // The completion push is already consumed: no later event can rescue the stale page.
+ // Exercise the real timeline component, including its single-flight read queue.
+ it.each(['response', 'exception'] as const)('recovers completed work without another push after a failed %s', async (failure) => {
+ const running = plan({ status: 'running', currentStep: 0,
+ steps: [{ ...plan().steps[0]!, status: 'running' }, plan().steps[1]!] });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: withPlan(running) });
+ renderView();
+ await screen.findByText('bots.groupChat.header.stepRunning:咪咪');
+ vi.useFakeTimers();
+ if (failure === 'response') mocks.getBotGroup.mockResolvedValueOnce({ ok: false, errorCode: 'REQUEST_TIMEOUT', message: '' });
+ else mocks.getBotGroup.mockRejectedValueOnce(new Error('read failed'));
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: withPlan(plan({ status: 'done' }),
+ [msg({ id: 'result', sequence: 11, content: '分工结果已就绪' })]) });
+ await act(async () => { mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'plan' })); });
+ expect(screen.getByText('bots.groupChat.header.stepRunning:咪咪')).toBeTruthy();
+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
+ expect(screen.getByText('分工结果已就绪')).toBeTruthy();
+ expect(screen.queryByText('bots.groupChat.header.stepRunning:咪咪')).toBeNull();
+ const reads = mocks.getBotGroup.mock.calls.length;
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(reads);
+ });
+
+ it('keeps recovery reads serialized and lets a newer push cancel the pending retry', async () => {
+ renderView();
+ await screen.findByText('周六 8:10 有票');
+ vi.useFakeTimers();
+ mocks.getBotGroup.mockResolvedValue({ ok: false, errorCode: 'REQUEST_TIMEOUT', message: '' });
+ await act(async () => { mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })); });
+ let finish!: (value: { ok: true; group: BotGroupDetail }) => void;
+ mocks.getBotGroup.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(3);
+ await act(async () => { await vi.advanceTimersByTimeAsync(90_000); });
+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(3);
+ await act(async () => { finish({ ok: true, group: detail() }); });
+ mocks.getBotGroup.mockResolvedValueOnce({ ok: false, errorCode: 'SERVICE_ERROR', message: '' });
+ await act(async () => { mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })); });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: [msg({ content: '推送已恢复' })] }) });
+ await act(async () => { mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })); });
+ expect(screen.getByText('推送已恢复')).toBeTruthy();
+ const reads = mocks.getBotGroup.mock.calls.length;
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(reads);
+ });
+
+ it('recovers a failed queued refresh before the initial snapshot has rendered', async () => {
+ let first!: (value: { ok: true; group: BotGroupDetail }) => void;
+ mocks.getBotGroup.mockImplementationOnce(() => new Promise(resolve => { first = resolve; }));
+ mocks.getBotGroup.mockResolvedValueOnce({ ok: false, errorCode: 'REQUEST_TIMEOUT', message: '' });
+ renderView();
+ vi.useFakeTimers();
+ await act(async () => {
+ mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'plan' }));
+ first({ ok: true, group: detail() });
+ });
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ messages: [msg({ content: '排队读取已恢复' })] }) });
+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
+ expect(screen.getByText('排队读取已恢复')).toBeTruthy();
+ });
+
+ it.each(['unmount', 'delete', 'owner', 'not-found'] as const)('stops pending recovery after %s', async (boundary) => {
+ const view = renderView();
+ await screen.findByText('周六 8:10 有票');
+ vi.useFakeTimers();
+ mocks.getBotGroup.mockResolvedValue({ ok: false, errorCode: 'REQUEST_TIMEOUT', message: '' });
+ await act(async () => { mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })); });
+ if (boundary === 'unmount') view.unmount();
+ else if (boundary === 'delete') act(() => { mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'deleted' })); });
+ else if (boundary === 'owner') mocks.ownerGeneration = { dataOwnerId: 'account-b', generation: 2 };
+ else {
+ mocks.getBotGroup.mockResolvedValue({ ok: false, errorCode: 'NOT_FOUND', message: '' });
+ await act(async () => { mocks.pushes.forEach(push => push({ groupId: 'g1', change: 'messages' })); });
+ expect(screen.getByText('bots.groupChat.unavailableTitle')).toBeTruthy();
+ }
+ const reads = mocks.getBotGroup.mock.calls.length;
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(reads);
+ });
+ });
+
describe('乐观显示', () => {
/** A send main has not answered yet; the test decides when and how. */
function pendingSend() {