Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): recover failed bot group refreshes
zcinta0514436dd37647f0
diff --git a/apps/mobile/src/__tests__/useBotGroupChat.test.tsx b/apps/mobile/src/__tests__/useBotGroupChat.test.tsxindex 804c70ed95..840cda39c4 100644--- a/apps/mobile/src/__tests__/useBotGroupChat.test.tsx+++ b/apps/mobile/src/__tests__/useBotGroupChat.test.tsx@@ -4,6 +4,8 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, expect, it, vi } from 'vitest';const h = vi.hoisted(() => ({+ accountGeneration: 1, focused: true,+ appState: { currentState: 'active', listeners: new Set<(state: string) => void>() },listeners: new Set<(deviceId: string, payload: { collectionId: string; resourceRefs?: { id: string; kind: string; collectionId: string }[] }) => void>(),link: {status: 'online', connectionEpoch: 1, presenceVersion: 1,@@ -13,10 +15,10 @@ const h = vi.hoisted(() => ({onRemoteResourceChanged: vi.fn(),},}));-vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) } }));-vi.mock('expo-router', async () => { const { useEffect } = await import('react'); return { useFocusEffect: (effect: () => void) => useEffect(effect, [effect]) }; });+vi.mock('react-native', () => ({ AppState: { get currentState() { return h.appState.currentState; }, addEventListener: (_: string, callback: (state: string) => void) => { h.appState.listeners.add(callback); return { remove: () => h.appState.listeners.delete(callback) }; } } }));+vi.mock('expo-router', async () => { const { useEffect } = await import('react'); return { useFocusEffect: (effect: () => void) => useEffect(() => h.focused ? effect() : undefined, [effect, h.focused]) }; });vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'zh-CN' } }) }));-vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: { id: 'owner' }, accountGeneration: 1 }) }));+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: { id: 'owner' }, accountGeneration: h.accountGeneration }) }));vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));vi.mock('@/device-link/remoteStatus', async () => ({ formatRemoteError: (await import('@cindy/maker-shared/device-link-contract')).formatRemoteError }));@@ -45,12 +47,13 @@ async function push(payload: Parameters<typeof h.listeners extends Set<infer L>}beforeEach(() => {+ h.focused = true; h.accountGeneration = 1; h.appState.currentState = 'active'; h.appState.listeners.clear();vi.clearAllMocks(); h.listeners.clear(); h.link.status = 'online';h.link.getPresenceAvailability.mockReturnValue(true);h.link.onRemoteResourceChanged.mockImplementation((listener) => { h.listeners.add(listener); return () => h.listeners.delete(listener); });h.link.invoke.mockImplementation(async (_deviceId: string, channel: string) => channel === 'maker:remote-resources:get' ? resource('官网') : { effects: [] });});-afterEach(() => { act(() => root?.unmount()); root = undefined; });+afterEach(() => { act(() => root?.unmount()); root = undefined; vi.useRealTimers(); });it('reads the group with the chat primitive and follows its change pushes', async () => {await render();@@ -128,3 +131,98 @@ it('forwards only the measured message to a read-capable host without a re-readexpect(request[2][0]).toMatchObject({ actionId: 'read', input: { messageId: 'seen' } });expect(reads()).toHaveLength(1);});++async function pushRecovery() {+ await act(async () => {+ h.listeners.forEach(listener => listener('mac', { collectionId: 'bot-groups' }));+ await vi.advanceTimersByTimeAsync(150);+ });+}++// #7099: existing push tests required another push after a failed read. Through the production+// hook, a timeout after the last completion push must recover the displayed result (unit tier).+it.each(['[REQUEST_TIMEOUT] timed out', '[SERVICE_ERROR] temporarily unavailable'])('recovers a failed refresh without another push: %s', async message => {+ vi.useFakeTimers();+ await render();+ h.link.invoke.mockRejectedValueOnce(new Error(message)).mockResolvedValue(resource('已完成 · 结果已送达'));+ await pushRecovery();+ expect(result.state).toMatchObject({ kind: 'ready', group: { name: '官网' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });+ expect(result.state).toMatchObject({ kind: 'ready', group: { name: '已完成 · 结果已送达' } });+ const count = reads().length;+ await act(async () => { await vi.advanceTimersByTimeAsync(90_000); });+ expect(reads()).toHaveLength(count);+});++it('keeps first-read and permanent failures manual, and cancels recovery after NOT_FOUND', async () => {+ vi.useFakeTimers();+ h.link.invoke.mockRejectedValue(new Error('[REQUEST_TIMEOUT] timed out'));+ await render();+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });+ expect(result.state.kind).toBe('error'); expect(reads()).toHaveLength(1);+ h.link.invoke.mockResolvedValue(resource('官网'));+ await act(async () => { result.reload(); });+ h.link.invoke.mockRejectedValue(new Error('[PERMISSION_DENIED] denied'));+ await pushRecovery();+ const count = reads().length;+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });+ expect(reads()).toHaveLength(count);+ h.link.invoke.mockRejectedValue(new Error('[REQUEST_TIMEOUT] timed out'));+ await pushRecovery();+ h.link.invoke.mockRejectedValue(new Error('NOT_FOUND'));+ await pushRecovery();+ expect(result.state.kind).toBe('missing');+ const missingCount = reads().length;+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });+ expect(reads()).toHaveLength(missingCount);+});++it('does not recover off-screen or in the background, and resumes on foreground', async () => {+ vi.useFakeTimers();+ await render();+ h.link.invoke.mockRejectedValue(new Error('[REQUEST_TIMEOUT] timed out'));+ await pushRecovery();+ h.focused = false; await render();+ const count = reads().length;+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });+ expect(reads()).toHaveLength(count);+ h.focused = true; await render();+ await act(async () => { h.appState.currentState = 'background'; h.appState.listeners.forEach(fn => fn('background')); });+ const backgroundCount = reads().length;+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });+ expect(reads()).toHaveLength(backgroundCount);+ h.link.invoke.mockResolvedValue(resource('已完成'));+ await act(async () => { h.appState.currentState = 'active'; h.appState.listeners.forEach(fn => fn('active')); });+ expect(result.state).toMatchObject({ kind: 'ready', group: { name: '已完成' } });+});++it('forgets the previous owner recovery and stops reading after unmount', async () => {+ vi.useFakeTimers();+ await render();+ h.link.invoke.mockRejectedValue(new Error('[REQUEST_TIMEOUT] timed out'));+ await pushRecovery();+ h.accountGeneration++; await render();+ const count = reads().length;+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });+ expect(result.state.kind).toBe('error'); expect(reads()).toHaveLength(count);+ h.link.invoke.mockResolvedValue(resource('新账号'));+ await act(async () => { result.reload(); });+ h.link.invoke.mockRejectedValue(new Error('[REQUEST_TIMEOUT] timed out'));+ await pushRecovery();+ act(() => root!.unmount()); root = undefined;+ const unmountedCount = reads().length;+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });+ expect(reads()).toHaveLength(unmountedCount);+});++it('recovers when a queued refresh fails before the first successful state commits', async () => {+ vi.useFakeTimers();+ let finish!: (value: ReturnType<typeof resource>) => void;+ h.link.invoke.mockReturnValueOnce(new Promise(resolve => { finish = resolve; }))+ .mockRejectedValueOnce(new Error('[REQUEST_TIMEOUT] timed out')).mockResolvedValue(resource('最终结果'));+ await render();+ await act(async () => { result.reload(); finish(resource('官网')); });+ expect(result.state).toMatchObject({ kind: 'ready', group: { name: '官网' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });+ expect(result.state).toMatchObject({ kind: 'ready', group: { name: '最终结果' } });+});diff --git a/apps/mobile/src/session/useBotGroupChat.ts b/apps/mobile/src/session/useBotGroupChat.tsindex 59dbedd03e..476c93f8f5 100644--- a/apps/mobile/src/session/useBotGroupChat.ts+++ b/apps/mobile/src/session/useBotGroupChat.ts@@ -11,6 +11,7 @@ import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscriimport { getRemoteResource, invokeRemoteResourceAction, type RemoteResourceHostTarget } from '@/device-link/remoteResources';import { formatRemoteError } from '@/device-link/remoteStatus';import { useRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';+import { isTransientRemoteError } from '@/device-link/remoteRetry';import { BOT_GROUP_CLIENT_PRIMITIVES, botGroupChatDataFromResource, botGroupErrorCode, botGroupResourceRef } from './botGroupRemote';export type BotGroupChatState =@@ -21,6 +22,7 @@ export type BotGroupChatState =/** Pushes for one change arrive in bursts (messages, round, plan); read once per burst. */const PUSH_COALESCE_MS = 150;+const READ_RECOVERY_MS = 30_000;/*** One group as the computer sees it (docs/product-rules/bot-group-chat.md §8). Every change@@ -36,10 +38,15 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string,const identity = JSON.stringify([accountGeneration, host.deviceId, groupId]);const identityRef = useRef(identity); identityRef.current = identity;const [state, setState] = useState<{ identity: string; value: BotGroupChatState }>({ identity, value: { kind: 'loading' } });+ // A queued read may fail before React commits the previous successful snapshot.+ const recovery = useRef({ identity, hasGroup: false });+ if (recovery.current.identity !== identity) recovery.current = { identity, hasGroup: false };+ const recoveryControl = useRef<{ identity: string; clear: () => void; schedule: () => void } | null>(null);const read = useCallback(async (isStale: () => boolean) => {const owner = identity;const valid = () => !isStale() && identityRef.current === owner;+ if (recoveryControl.current?.identity === owner) recoveryControl.current.clear();if (!host.deviceId || !groupId) {setState({ identity: owner, value: { kind: 'missing' } });return;@@ -50,10 +57,12 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string,if (!valid()) return;const group = botGroupChatDataFromResource(resource);if (!group || group.id !== groupId) throw new Error('INVALID_GROUP_DATA');+ recovery.current.hasGroup = true;setState({ identity: owner, value: { kind: 'ready', group } });} catch (error) {if (!valid()) return;if (botGroupErrorCode(error) === 'NOT_FOUND') {+ recovery.current.hasGroup = false;setState({ identity: owner, value: { kind: 'missing' } });return;}@@ -61,6 +70,10 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string,setState((previous) => previous.identity === owner && previous.value.kind === 'ready'? previous: { identity: owner, value: { kind: 'error', message: formatRemoteError(error) } });+ const code = botGroupErrorCode(error);+ if (recovery.current.hasGroup && (isTransientRemoteError(error)+ || code === 'SERVICE_ERROR' || code === 'CHAT_UNAVAILABLE' || code === 'HOST_NOT_READY')+ && recoveryControl.current?.identity === owner) recoveryControl.current.schedule();}}, [groupId, host, i18n.language, identity, invoke, openLink]);@@ -70,6 +83,20 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string,useFocusEffect(useCallback(() => {if (!host.deviceId || !groupId || status !== 'online') return;let timer: ReturnType<typeof setTimeout> | undefined;+ let retryTimer: ReturnType<typeof setTimeout> | undefined;+ const control = {+ identity,+ clear: () => { clearTimeout(retryTimer); retryTimer = undefined; },+ schedule: () => {+ control.clear();+ if (AppState.currentState !== 'active') return;+ retryTimer = setTimeout(() => {+ retryTimer = undefined;+ if (identityRef.current === identity && AppState.currentState === 'active') reload();+ }, READ_RECOVERY_MS);+ },+ };+ recoveryControl.current = control;const schedule = () => {if (timer) return;timer = setTimeout(() => { timer = undefined; if (AppState.currentState === 'active') reload(); }, PUSH_COALESCE_MS);@@ -81,10 +108,16 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string,});// The change push rides the account-level `sessions` topic.const offTopic = startFocusedTopicSubscription({ deviceId: host.deviceId, owner: `bot-group:${groupId}`, topic: 'sessions', subscribe, unsubscribe });- const appState = AppState.addEventListener('change', (value) => { if (value === 'active') reload(); });- reload();- return () => { offPush(); offTopic(); appState.remove(); if (timer) clearTimeout(timer); };- }, [connectionEpoch, groupId, host.deviceId, onRemoteResourceChanged, reload, status, subscribe, unsubscribe]));+ const appState = AppState.addEventListener('change', (value) => {+ control.clear();+ if (value === 'active') reload();+ });+ if (AppState.currentState === 'active') reload();+ return () => {+ offPush(); offTopic(); appState.remove(); if (timer) clearTimeout(timer); control.clear();+ if (recoveryControl.current === control) recoveryControl.current = null;+ };+ }, [connectionEpoch, groupId, host.deviceId, identity, onRemoteResourceChanged, reload, status, subscribe, unsubscribe]));/** Run a group action; rejects with the host's error (see `botGroupErrorCode`). */const act = useCallback(async (actionId: BotGroupRemoteActionId, input?: Record<string, unknown>): Promise<RemoteActionInvokeResponse> => {