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): retry failed group sidebar refreshes

xdb060383198eb
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botGroupStore.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botGroupStore.test.ts
index 30be947bd6..2020d269c2 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupStore.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupStore.test.ts
@@ -2,11 +2,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { BotGroupChangedPayload, BotGroupSummary } from '../../../../shared/botGroupChat';
-import { getBotGroupListSnapshot, resetBotGroupStoreForTests, startBotGroupSync, subscribeBotGroups } from '../botGroupStore';
+import { getBotGroupListSnapshot, refreshBotGroups, resetBotGroupStoreForTests, startBotGroupSync, subscribeBotGroups } from '../botGroupStore';
+const dataOwner = vi.hoisted(() => ({ generation: 1 }));
vi.mock('@/contexts/dataOwnerGeneration', () => ({
- getDataOwnerGeneration: () => 1,
- isDataOwnerGenerationCurrent: () => true,
+ getDataOwnerGeneration: () => dataOwner.generation,
+ isDataOwnerGenerationCurrent: (owner: number) => owner === dataOwner.generation,
isDataOwnerPushCurrent: () => true,
}));
@@ -20,6 +21,7 @@ const listBotGroups = vi.fn();
beforeEach(() => {
vi.useFakeTimers();
+ dataOwner.generation = 1;
resetBotGroupStoreForTests();
listBotGroups.mockReset().mockResolvedValue({ ok: true, groups: [summary('周末出游')] });
Object.defineProperty(window, 'electronAPI', {
@@ -34,6 +36,30 @@ afterEach(() => {
});
describe('group list mirror', () => {
+ // Unit regression: the public sync entry must recover a completed companion's
+ // sidebar state after its final push triggers a failed read. Previously only
+ // successful push bursts were covered; no later push should be required.
+ it.each(['response', 'exception'])('recovers a stale running row after a failed %s without another push', async failure => {
+ const running: BotGroupSummary = { ...summary('工作测试群'), speakingBotIds: ['Lucky'],
+ openPlan: { id: 'plan', status: 'running', currentStep: 3, stepCount: 4, currentBotName: 'Lucky', currentStepStatus: 'running' } };
+ listBotGroups.mockResolvedValueOnce({ ok: true, groups: [running] });
+ const stop = startBotGroupSync();
+ await vi.advanceTimersByTimeAsync(0);
+ if (failure === 'response') listBotGroups.mockResolvedValueOnce({ ok: false });
+ else listBotGroups.mockRejectedValueOnce(new Error('disconnected'));
+ push({ groupId: 'g1', change: 'messages' });
+ await vi.advanceTimersByTimeAsync(300);
+ expect(getBotGroupListSnapshot().groups[0]!.speakingBotIds).toEqual(['Lucky']);
+ listBotGroups.mockResolvedValue({ ok: true, groups: [{ ...running, speakingBotIds: [], openPlan: null }] });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(getBotGroupListSnapshot().groups[0]!.speakingBotIds).toEqual([]);
+ expect(getBotGroupListSnapshot().groups[0]!.openPlan).toBeNull();
+ expect(listBotGroups).toHaveBeenCalledTimes(3);
+ await vi.advanceTimersByTimeAsync(60000);
+ expect(listBotGroups).toHaveBeenCalledTimes(3);
+ stop();
+ });
+
it('reads once per burst of pushes and keeps the snapshot when nothing changed', async () => {
const stop = startBotGroupSync();
await vi.runAllTimersAsync();
@@ -56,4 +82,102 @@ describe('group list mirror', () => {
unsubscribe();
stop();
});
+
+ it('backs off repeated failures and resets the delay after an unchanged successful read', async () => {
+ const stop = startBotGroupSync();
+ await vi.advanceTimersByTimeAsync(0);
+ listBotGroups.mockResolvedValue({ ok: false });
+ push({ groupId: 'g1', change: 'plan' });
+ await vi.advanceTimersByTimeAsync(300);
+ for (const delay of [1000, 2000, 4000, 8000, 16000, 30000, 30000]) {
+ const calls = listBotGroups.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(delay - 1);
+ expect(listBotGroups).toHaveBeenCalledTimes(calls);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(listBotGroups).toHaveBeenCalledTimes(calls + 1);
+ }
+ listBotGroups.mockResolvedValue({ ok: true, groups: [summary('周末出游')] });
+ await vi.advanceTimersByTimeAsync(30000);
+ const recovered = getBotGroupListSnapshot();
+ listBotGroups.mockRejectedValueOnce(new Error('disconnected again'));
+ refreshBotGroups();
+ await vi.advanceTimersByTimeAsync(0);
+ const calls = listBotGroups.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(listBotGroups).toHaveBeenCalledTimes(calls + 1);
+ expect(getBotGroupListSnapshot().groups).toEqual(recovered.groups);
+ stop();
+ });
+
+ it('lets a new push recover immediately and cancels the pending retry', async () => {
+ listBotGroups.mockResolvedValueOnce({ ok: false });
+ const stop = startBotGroupSync();
+ await vi.advanceTimersByTimeAsync(0);
+ push({ groupId: 'g1', change: 'messages' });
+ await vi.advanceTimersByTimeAsync(300);
+ expect(getBotGroupListSnapshot().groups[0]!.name).toBe('周末出游');
+ await vi.advanceTimersByTimeAsync(60000);
+ expect(listBotGroups).toHaveBeenCalledTimes(2);
+ stop();
+ });
+
+ it('coalesces pushes during a retry and never overlaps list requests', async () => {
+ let finish!: (result: unknown) => void;
+ listBotGroups.mockResolvedValueOnce({ ok: false })
+ .mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ const stop = startBotGroupSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ for (let i = 0; i < 5; i++) push({ groupId: 'g1', change: 'messages' });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(listBotGroups).toHaveBeenCalledTimes(2);
+ finish({ ok: false });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(getBotGroupListSnapshot().groups[0]!.name).toBe('周末出游');
+ await vi.advanceTimersByTimeAsync(60000);
+ expect(listBotGroups).toHaveBeenCalledTimes(3);
+ stop();
+ });
+
+ it.each(['pending retry', 'in-flight failure'])('stops retrying after the last surface unmounts (%s)', async stage => {
+ let fail!: (error: Error) => void;
+ if (stage === 'in-flight failure') listBotGroups.mockImplementationOnce(() => new Promise((_resolve, reject) => { fail = reject; }));
+ else listBotGroups.mockResolvedValueOnce({ ok: false });
+ const stop = startBotGroupSync();
+ await vi.advanceTimersByTimeAsync(0);
+ stop();
+ if (stage === 'in-flight failure') fail(new Error('disconnected'));
+ await vi.advanceTimersByTimeAsync(60000);
+ expect(listBotGroups).toHaveBeenCalledTimes(1);
+ expect(getBotGroupListSnapshot().groups).toEqual([]);
+ });
+
+ it('keeps the shared retry until the last surface unmounts', async () => {
+ listBotGroups.mockResolvedValue({ ok: false });
+ const stopFirst = startBotGroupSync();
+ await vi.advanceTimersByTimeAsync(0);
+ const stopSecond = startBotGroupSync();
+ await vi.advanceTimersByTimeAsync(0);
+ stopFirst();
+ listBotGroups.mockResolvedValue({ ok: true, groups: [summary('已恢复')] });
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(getBotGroupListSnapshot().groups[0]!.name).toBe('已恢复');
+ stopSecond();
+ });
+
+ it.each(['pending retry', 'in-flight failure'])('discards old-owner retries and late failures (%s)', async stage => {
+ let fail!: (error: Error) => void;
+ if (stage === 'in-flight failure') listBotGroups.mockImplementationOnce(() => new Promise((_resolve, reject) => { fail = reject; }));
+ else listBotGroups.mockResolvedValueOnce({ ok: false });
+ const stop = startBotGroupSync();
+ await vi.advanceTimersByTimeAsync(0);
+ dataOwner.generation = 2;
+ if (stage === 'in-flight failure') fail(new Error('old owner disconnected'));
+ await vi.advanceTimersByTimeAsync(60000);
+ expect(listBotGroups).toHaveBeenCalledTimes(1);
+ expect(getBotGroupListSnapshot().groups).toEqual([]);
+ refreshBotGroups();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(getBotGroupListSnapshot().groups[0]!.name).toBe('周末出游');
+ stop();
+ });
});
diff --git a/apps/desktop/src/renderer/features/bots/botGroupStore.ts b/apps/desktop/src/renderer/features/bots/botGroupStore.ts
index c54f58669a..a609d7c100 100644
--- a/apps/desktop/src/renderer/features/bots/botGroupStore.ts
+++ b/apps/desktop/src/renderer/features/bots/botGroupStore.ts
@@ -43,6 +43,8 @@ const visibleGroups = (groups: readonly BotGroupSummary[]) => groups.filter(grou
let inFlight: Promise<void> | null = null;
let refreshQueued = false;
let pushTimer: ReturnType<typeof setTimeout> | null = null;
+let retryTimer: ReturnType<typeof setTimeout> | null = null;
+let readFailures = 0;
let syncUsers = 0;
/** Pushes within this window collapse into one list read. */
const PUSH_REFRESH_DELAY_MS = 300;
@@ -70,6 +72,8 @@ function ensureOwner(): void {
inFlight = null;
refreshQueued = false;
cancelPushRefresh();
+ cancelRetryRefresh();
+ readFailures = 0;
snapshot = EMPTY_SNAPSHOT;
personalList.clear();
}
@@ -79,6 +83,24 @@ function cancelPushRefresh(): void {
pushTimer = null;
}
+function cancelRetryRefresh(): void {
+ if (retryTimer !== null) clearTimeout(retryTimer);
+ retryTimer = null;
+}
+
+/** A failed final push must recover even when the room has no more activity. */
+function scheduleRetryRefresh(): void {
+ if (syncUsers === 0 || retryTimer !== null) return;
+ const requestOwner = owner;
+ const requestGeneration = generation;
+ const delay = Math.min(30000, 1000 * 2 ** Math.min(readFailures++, 5));
+ retryTimer = setTimeout(() => {
+ retryTimer = null;
+ if (syncUsers === 0 || requestGeneration !== generation || !isDataOwnerGenerationCurrent(requestOwner)) return;
+ refreshBotGroups();
+ }, delay);
+}
+
/** A push changed something: read the list once the burst has settled. */
function schedulePushRefresh(): void {
if (pushTimer !== null) return;
@@ -102,6 +124,7 @@ export function refreshBotGroups(): void {
refreshQueued = true;
return;
}
+ cancelRetryRefresh();
const requestOwner = owner;
const requestGeneration = generation;
const isCurrent = () =>
@@ -111,13 +134,18 @@ export function refreshBotGroups(): void {
// Every change kind re-reads the list, including 'plan' (open-plan status in the row).
const result = await api.listBotGroups();
if (!isCurrent()) return;
+ if (result.ok) readFailures = 0;
+ else scheduleRetryRefresh();
if (result.ok) seedBotGroupReadState(visibleGroups(result.groups));
// An unchanged list keeps its snapshot: subscribers (sidebar, Dock badge) do not re-render.
if (result.ok && snapshot.loaded && JSON.stringify(visibleGroups(result.groups)) === JSON.stringify(snapshot.groups)) return;
// 失败时保留上一份列表:侧栏不因一次读失败把所有群清空。
applySnapshot(result.ok ? { groups: visibleGroups(result.groups), loaded: true } : { ...snapshot, loaded: true });
} catch {
- if (isCurrent()) applySnapshot({ ...snapshot, loaded: true });
+ if (isCurrent()) {
+ scheduleRetryRefresh();
+ applySnapshot({ ...snapshot, loaded: true });
+ }
}
})();
inFlight = request;
@@ -160,6 +188,8 @@ export function startBotGroupSync(): () => void {
unsubscribePush?.();
unsubscribePush = null;
cancelPushRefresh();
+ cancelRetryRefresh();
+ readFailures = 0;
}
};
}
@@ -245,6 +275,8 @@ export function resetBotGroupStoreForTests(): void {
inFlight = null;
refreshQueued = false;
cancelPushRefresh();
+ cancelRetryRefresh();
+ readFailures = 0;
owner = getDataOwnerGeneration();
snapshot = EMPTY_SNAPSHOT;
listeners.clear();