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(mobile): 首页刷新同时恢复伙伴段,读取失败时提示并可重试

Chris9e4f173f7340
diff --git a/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx b/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx
new file mode 100644
index 0000000000..2f8d857552
--- /dev/null
+++ b/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx
@@ -0,0 +1,81 @@
+// @vitest-environment jsdom
+import { act, createContext, createElement as el } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+const h = vi.hoisted(() => ({ cloudRefresh: vi.fn(async () => {}) }));
+vi.mock('react-native', () => ({
+ View: ({ children, testID }: any) => el('div', { 'data-testid': testID }, children),
+ ScrollView: ({ children, testID }: any) => el('div', { 'data-testid': testID }, children),
+ Pressable: ({ children, testID, disabled, onPress }: any) => el('button', { 'data-testid': testID, disabled, onClick: onPress }, children),
+ ActivityIndicator: () => el('i', { 'data-testid': 'spinner' }),
+ Keyboard: { dismiss: () => {} },
+ StyleSheet: { create: (v: unknown) => v, hairlineWidth: 1 },
+}));
+vi.mock('expo-router/react-navigation', () => ({
+ NavigationContext: createContext(null), NavigationRouteContext: createContext(null), useIsFocused: () => true,
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }) }));
+vi.mock('lucide-react-native', () => ({ ChevronDown: () => null, ChevronRight: () => null, ChevronUp: () => null, Plus: () => null, RefreshCw: () => null, UsersRound: () => null }));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: { id: 'owner' } }) }));
+vi.mock('@/components/AppText', () => ({ Text: ({ children, testID }: any) => el('span', { 'data-testid': testID }, children) }));
+vi.mock('@/components/RemoteCompanionAvatar', () => ({ RemoteCompanionAvatar: () => null }));
+vi.mock('@/chat/cloudCompanion', () => ({ CLOUD_ROW_REVISION: 'cloud', cloudActorForRow: () => null, cloudCompanionRows: (items: unknown) => items }));
+vi.mock('@/chat/useCloudCompanion', () => ({ useCloudCompanionHome: () => ({ supported: true, actors: [], deviceNames: {}, refresh: h.cloudRefresh }) }));
+vi.mock('@/device-link/remoteResourceCache', () => ({ isRemoteResourceUnread: () => false, remoteResourceCacheRevision: () => 0, subscribeRemoteResourceCache: () => () => {} }));
+vi.mock('@/utils/useGuardedPush', () => ({ useGuardedPush: () => () => {} }));
+vi.mock('@/theme', async () => {
+ const tokens = await import('@/theme/tokens');
+ const colors = tokens.lightColors;
+ return { ...tokens, useThemedStyles: (factory: (value: typeof colors) => unknown) => factory(colors), useTheme: () => ({ colors }) };
+});
+vi.mock('@/session/BotGroupAvatars', () => ({ BotGroupDuoAvatar: () => null, useBotGroupIdentities: () => () => ({}) }));
+vi.mock('@/session/BotGroupList', () => ({ OFFLINE_AVATAR_OPACITY: 0.45 }));
+vi.mock('@/session/CompanionListRow', () => ({ COMPANION_ROW_AVATAR_SIZE: 44, COMPANION_ROW_DOT_SIZE: 10 }));
+vi.mock('@/session/CompanionPresenceRing', () => ({ CompanionPresenceRing: () => null }));
+vi.mock('@/session/HomeRosterContext', () => ({ useHomeRoster: () => null }));
+vi.mock('@/session/HomeListVisuals', () => ({ homeListStyles: () => ({}) }));
+vi.mock('@/session/listDisclosureTransition', () => ({ DisclosureItem: ({ children, testID }: any) => el('div', { 'data-testid': testID }, children) }));
+vi.mock('@/session/TeammateCreateController', () => ({ useTeammateCreateController: () => ({
+ renderTrigger: (trigger: unknown) => trigger, press: () => {}, label: 'create', sheets: null }) }));
+vi.mock('@/session/TeammateList', () => ({
+ useTeammateEntries: (items: any[]) => items.map(row => ({ kind: 'bot', row })),
+ useTeammateRowRenderer: () => (entry: any) => el('div', { key: entry.row.key }, entry.row.item.display.title),
+}));
+vi.mock('@/session/useTeammateNavigation', () => ({ useTeammateNavigation: () => ({
+ owner: 'owner', teammatesCollapsed: false, lastTeammate: null,
+ setTeammatesCollapsed: async () => {}, openTeammate: async () => {}, openCreatedTeammate: async () => {} }) }));
+import { HomeTeammatesSection } from '../session/HomeTeammatesSection';
+
+const item = { key: 'host:bot', host: { deviceId: 'host', deviceName: 'Mac' }, item: {
+ ref: { collectionId: 'teammates', kind: 'bot', id: 'bot' }, revision: '1', links: [], display: { title: 'Mimi' } } };
+const roster = { items: [item], createTargets: [], groupTargets: [], loading: false, refreshing: false, error: 'LIST_FAILED' as string | null,
+ isOnline: () => true, connectionState: undefined, refresh: vi.fn(async () => {}) };
+const groups = { items: [], supported: true, refreshing: false, error: null, isOnline: () => true, refresh: vi.fn(async () => {}) };
+let root: Root; let node: HTMLDivElement;
+beforeEach(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); node = document.createElement('div'); root = createRoot(node); vi.clearAllMocks(); });
+afterEach(async () => { await act(async () => root.unmount()); });
+const render = (refreshKey: number) => act(async () => root.render(el(HomeTeammatesSection, {
+ context: { navigation: null, route: null, shared: { roster, groups } } as any, active: true, refreshKey,
+ visible: true, query: '', showFooter: false, runDisclosure: (apply: () => void) => apply(), prepareDisclosure: () => {},
+})));
+const byId = (id: string) => node.querySelector<HTMLElement>(`[data-testid="${id}"]`);
+
+// The retired teammate page showed read failures with a retry; the home section must not lose them.
+it('keeps cached teammates, names a failed read and retries every teammate source', async () => {
+ await render(0);
+ expect(node.textContent).toContain('Mimi');
+ expect(byId('home.teammatesError')?.textContent).toBe('devices.companions.stale');
+ h.cloudRefresh.mockClear();
+ await act(async () => byId('home.teammatesRetry')!.click());
+ expect(roster.refresh).toHaveBeenCalledTimes(1);
+ expect(groups.refresh).toHaveBeenCalledTimes(1);
+ expect(h.cloudRefresh).toHaveBeenCalledTimes(1);
+});
+
+// Pull-to-refresh lives on the home list; it reaches the section's cloud companions through the key.
+it('re-reads cloud companions on each manual home refresh', async () => {
+ await render(0);
+ h.cloudRefresh.mockClear();
+ await render(1);
+ expect(h.cloudRefresh).toHaveBeenCalledTimes(1);
+});
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index 08802ea2b3..54e2733ddc 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -785,8 +785,10 @@ describe('mobile home desktop-first surface', () => {
expect(source).toContain('markPresenceFresh(presenceFreshnessRef.current, lastPresenceSnapshot.deviceId);');
expect(source).toContain('collectFreshPresenceDeviceIds(presenceFreshnessRef.current, presenceEpochAtFetchStart)');
expect(source).toContain('progressViewOffset={residentList.enabled ? 0 : chromeHeight}');
- expect(source).toContain('onRefresh={() => void loadHome({ visible: true })}');
- expect(source).toContain('onPress={() => void loadHome({ visible: true })}');
+ // 下拉刷新与同步按钮都走可见的 loadHome,并一起刷新伙伴段。
+ expect(source).toMatch(/const refreshHome = useCallback\(\(\) => \{\n void loadHome\(\{ visible: true \}\);/);
+ expect(source).toContain('onRefresh={refreshHome}');
+ expect(source).toContain('onPress={refreshHome}');
expect(source).toContain('patchDeviceViewsWithPresence(');
expect(source).toContain('result.becameControllable');
expect(source).toContain('remoteSessionStore.registerReseedHandler(item.device.deviceId');
diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsx
index aa9f8e6042..6d0444f5bb 100644
--- a/apps/mobile/src/session/HomeSurface.tsx
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@ -474,6 +474,8 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = false
const residentList = useResidentHomeList(embedded);
// Captured here: Android draws the list above the route, outside its roster and navigation context.
const teammatesSectionContext = useHomeTeammatesSectionContext();
+ // Bumped by a manual home refresh so the teammate section also re-reads its cloud companions.
+ const [teammatesRefreshKey, setTeammatesRefreshKey] = useState(0);
const activeHomeSession = useContext(ActiveHomeSession);
const rememberTask = rememberRecentTask;
const viewSession = getHomeViewSession();
@@ -1306,6 +1308,15 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = false
if (visible && homeAccountGenerationRef.current === accountGenerationAtStart) setRefreshing(false);
});
}, [accountGeneration, readDeviceList, deviceIdentityCacheReady, homeCacheUserId, hydrateDeviceSessions, reconcileDeviceViews, reconcileHomeDeviceSyncScope, revokedDevices, softInvalidateDeviceMirror]);
+ // A manual refresh also recovers the teammate section: roster, group chats and cloud companions.
+ const homeRoster = teammatesSectionContext.shared;
+ const refreshHome = useCallback(() => {
+ void loadHome({ visible: true });
+ if (embedded || !homeRoster) return;
+ void homeRoster.roster.refresh();
+ if (homeRoster.groups.supported) void homeRoster.groups.refresh();
+ setTeammatesRefreshKey(key => key + 1);
+ }, [embedded, homeRoster, loadHome]);
loadHomeRef.current = loadHome;
// 冷启动先画缓存:上次 loadHome 成功的设备+会话快照种入 store,先把列表画出来(消除首屏强制
@@ -2955,7 +2966,7 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = false
}}
sections={sections}
ListHeaderComponent={<>
- {embedded ? null : <HomeTeammatesSection context={teammatesSectionContext} active={active}
+ {embedded ? null : <HomeTeammatesSection context={teammatesSectionContext} active={active} refreshKey={teammatesRefreshKey}
visible={indexedSearch.activeFilterCount === 0 && statusFilter !== 'archived' && !showRemoteGuide}
query={searchQuery}
// Shared group and project blocks draw their own full-width top line.
@@ -3036,7 +3047,7 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = false
<RefreshControl
progressViewOffset={residentList.enabled ? 0 : chromeHeight}
refreshing={refreshing}
- onRefresh={() => void loadHome({ visible: true })}
+ onRefresh={refreshHome}
tintColor={colors.textSecondary}
/>
}
@@ -3327,7 +3338,7 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = false
disabled={refreshing}
// 视觉 28pt,hitSlop 把命中区补到 44pt(§5 触控目标)。
hitSlop={(navigationChrome.target - CONNECTION_ICON_BUTTON_SIZE) / 2}
- onPress={() => void loadHome({ visible: true })}
+ onPress={refreshHome}
style={({ pressed }) => [
styles.connectionIconButton,
pressed && styles.pressed,
diff --git a/apps/mobile/src/session/HomeTeammatesSection.tsx b/apps/mobile/src/session/HomeTeammatesSection.tsx
index 3e1abb14c5..bea2e8a0e0 100644
--- a/apps/mobile/src/session/HomeTeammatesSection.tsx
+++ b/apps/mobile/src/session/HomeTeammatesSection.tsx
@@ -9,10 +9,10 @@
* 再由本段重新提供。
*/
import { useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore, type ReactElement } from 'react';
-import { Keyboard, Pressable, ScrollView, StyleSheet, View } from 'react-native';
+import { ActivityIndicator, Keyboard, Pressable, ScrollView, StyleSheet, View } from 'react-native';
import { NavigationContext, NavigationRouteContext, useIsFocused } from 'expo-router/react-navigation';
import { useTranslation } from 'react-i18next';
-import { ChevronDown, ChevronRight, ChevronUp, Plus, UsersRound } from 'lucide-react-native';
+import { ChevronDown, ChevronRight, ChevronUp, Plus, RefreshCw, UsersRound } from 'lucide-react-native';
import { resolveRemoteText } from '@cindy/device-link';
import { useAuth } from '@/auth/AuthContext';
import { Text } from '@/components/AppText';
@@ -57,10 +57,12 @@ export function useHomeTeammatesSectionContext() {
return useMemo(() => ({ navigation, route, shared }), [navigation, route, shared]);
}
-export function HomeTeammatesSection({ context, active, visible, query, showFooter, runDisclosure, prepareDisclosure }: {
+export function HomeTeammatesSection({ context, active, refreshKey, visible, query, showFooter, runDisclosure, prepareDisclosure }: {
context: ReturnType<typeof useHomeTeammatesSectionContext>;
/** The home is the screen in front. */
active: boolean;
+ /** Changes on each manual home refresh; the section then re-reads its cloud companions. */
+ refreshKey: number;
/** Hidden while filtering or browsing archived tasks; the hooks stay mounted. */
visible: boolean;
/** The home search text: lists every matching teammate, expanded, without create entries. */
@@ -73,14 +75,14 @@ export function HomeTeammatesSection({ context, active, visible, query, showFoot
const { navigation, route, shared } = context;
if (!shared) return null;
return <NavigationContext.Provider value={navigation}><NavigationRouteContext.Provider value={route}>
- <SectionContent shared={shared} active={active} visible={visible} query={query} showFooter={showFooter}
+ <SectionContent shared={shared} active={active} refreshKey={refreshKey} visible={visible} query={query} showFooter={showFooter}
runDisclosure={runDisclosure} prepareDisclosure={prepareDisclosure} />
</NavigationRouteContext.Provider></NavigationContext.Provider>;
}
-function SectionContent({ shared, active, visible, query, showFooter, runDisclosure, prepareDisclosure }: {
+function SectionContent({ shared, active, refreshKey, visible, query, showFooter, runDisclosure, prepareDisclosure }: {
shared: NonNullable<ReturnType<typeof useHomeRoster>>;
- active: boolean; visible: boolean; query: string; showFooter: boolean;
+ active: boolean; refreshKey: number; visible: boolean; query: string; showFooter: boolean;
runDisclosure(apply: () => void): void; prepareDisclosure(): void;
}) {
const { t, i18n } = useTranslation();
@@ -97,7 +99,7 @@ function SectionContent({ shared, active, visible, query, showFooter, runDisclos
[cloud.actors, cloud.deviceNames, cloud.supported, roster.items]);
const listedCompanions = roster.items.map(row => `${row.key}\t${row.item.revision}`).sort().join('\n');
const refreshCloud = cloud.refresh;
- useEffect(() => { if (cloud.supported) void refreshCloud(); }, [cloud.supported, listedCompanions, refreshCloud]);
+ useEffect(() => { if (cloud.supported) void refreshCloud(); }, [cloud.supported, listedCompanions, refreshCloud, refreshKey]);
const cloudActor = (row: HostedRemoteCollectionItem) => cloud.supported && row.item.revision === CLOUD_ROW_REVISION ? cloudActorForRow(cloud.actors, row) : null;
const quietPresence = (row: HostedRemoteCollectionItem) => cloud.supported && !!cloudActorForRow(cloud.actors, row);
const showGroups = groups.supported || groups.items.length > 0;
@@ -137,8 +139,19 @@ function SectionContent({ shared, active, visible, query, showFooter, runDisclos
preferredDeviceId: navigation.lastTeammate?.deviceId,
onCreated: (host, ref) => { void navigation.openCreatedTeammate(host, ref); },
onGroupCreated: (host, groupId) => push(botGroupRoute(host, groupId)) });
+ // Read failures keep the cached rows and say so, with the same retry as a home pull-to-refresh.
+ const error = groups.error ?? roster.error;
+ const errorKey = error === 'CHAT_ENDPOINT_UNAVAILABLE' ? 'groupChat.server.endpointUnavailable'
+ : error === 'CHAT_LIST_FAILED' ? 'groupChat.server.loadFailed'
+ : entries.length ? 'devices.companions.stale' : 'devices.resources.loadFailed';
+ const retrying = roster.refreshing || groups.refreshing;
+ const retry = () => {
+ void roster.refresh();
+ if (groups.supported) void groups.refresh();
+ if (cloud.supported) void refreshCloud();
+ };
// A first read with nothing cached stays out of the way instead of flashing an empty section.
- const shown = visible && (search ? entries.length > 0 : !(!entries.length && (!canCreate || roster.loading)));
+ const shown = visible && (search ? entries.length > 0 : !!error || !(!entries.length && (!canCreate || roster.loading)));
const title = t('devices.companions.title');
const create = (trigger: (press: () => void, label: string) => ReactElement) => showCreate
? creator.renderTrigger(trigger(creator.press, creator.label)) : null;
@@ -164,6 +177,13 @@ function SectionContent({ shared, active, visible, query, showFooter, runDisclos
<Plus color={colors.textSecondary} size={iconSize.action} strokeWidth={iconStroke.regular} />
</Pressable>)}
</View>
+ {error && !search ? <View style={styles.noticeRow}>
+ <Text accessibilityRole="alert" style={styles.notice} testID="home.teammatesError">{t(errorKey)}</Text>
+ <Pressable accessibilityRole="button" accessibilityLabel={t('devices.resources.retry')} disabled={retrying}
+ onPress={retry} style={({ pressed }) => [styles.retry, pressed && mobileInteractionStyles.pressed]} testID="home.teammatesRetry">
+ {retrying ? <ActivityIndicator color={colors.textSecondary} /> : <RefreshCw size={iconSize.sm} color={colors.textSecondary} strokeWidth={iconStroke.regular} />}
+ </Pressable>
+ </View> : null}
{!entries.length ? <DisclosureItem exit>{create((press, label) => <Pressable accessibilityRole="button" accessibilityLabel={label} onPress={press}
style={({ pressed }) => [styles.addRow, pressed && mobileInteractionStyles.pressed]} testID="home.teammatesAdd">
<View style={[styles.addCircle, styles.addCircleRow]}><Plus color={colors.textSecondary} size={iconSize.action} strokeWidth={iconStroke.regular} /></View>
@@ -263,6 +283,9 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
addCircle: { borderRadius: radius.pill, borderWidth: 1, borderStyle: 'dashed', borderColor: colors.borderStrong, alignItems: 'center', justifyContent: 'center' },
addCircleStrip: { width: STRIP_AVATAR_SIZE, height: STRIP_AVATAR_SIZE },
addCircleRow: { width: COMPANION_ROW_AVATAR_SIZE, height: COMPANION_ROW_AVATAR_SIZE },
+ noticeRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, paddingLeft: spacing.lg, paddingRight: spacing.sm },
+ notice: { flex: 1, color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
+ retry: { minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' },
addRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.md, height: ADD_ROW_HEIGHT, paddingLeft: spacing.lg, paddingRight: spacing.lg },
addText: { flexShrink: 1, color: colors.textSecondary, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.regular },
// Text column of the rows above (16 inset + 44 avatar + 12 gap).