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。

perf(mobile): 缩小伙伴头像条的刷新范围

elfcv19bdc72fbb5c
diff --git a/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx b/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx
index f5d6532b90..48eee375b5 100644
--- a/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx
+++ b/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx
@@ -3,11 +3,17 @@ 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 () => {}), push: vi.fn(),
- cloudActor: null as null | { id: string }, createOptions: null as any, collapsed: false, unread: false }));
+ openTeammate: vi.fn(async (_row: unknown) => {}),
+ cloudActor: null as null | { id: string }, createOptions: null as any, collapsed: false, unread: false,
+ cacheRevision: 0, cacheListeners: new Set<() => void>(), unreadIds: new Set<string>(),
+ stripRenders: [] as string[], avatarRenders: [] as string[], identityReads: 0 }));
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, accessibilityLabel }: any) => el('button', { 'data-testid': testID, disabled, onClick: onPress, 'aria-label': accessibilityLabel }, children),
+ Pressable: ({ children, testID, disabled, onPress, accessibilityLabel }: any) => {
+ if (testID?.startsWith('home.teammatesStrip.bot.')) h.stripRenders.push(testID);
+ return el('button', { 'data-testid': testID, disabled, onClick: onPress, 'aria-label': accessibilityLabel }, children);
+ },
ActivityIndicator: () => el('i', { 'data-testid': 'spinner' }),
Keyboard: { dismiss: () => {} },
StyleSheet: { create: (v: unknown) => v, hairlineWidth: 1 },
@@ -20,19 +26,27 @@ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => k
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('@/components/RemoteCompanionAvatar', () => ({ RemoteCompanionAvatar: ({ name, avatar }: any) => {
+ h.avatarRenders.push(name);
+ return el('i', { 'data-testid': `avatar.${name}` }, avatar?.value);
+} }));
vi.mock('@/chat/cloudCompanion', () => ({ CLOUD_ROW_REVISION: 'cloud', cloudActorForRow: () => h.cloudActor, cloudCompanionRows: (items: unknown) => items }));
vi.mock('@/session/teammateNavigation', () => ({ cloudCompanionRoute: () => '/cloud-chat' }));
vi.mock('@/session/botGroupNavigation', () => ({ botGroupRoute: () => '/group-chat' }));
vi.mock('@/chat/useCloudCompanion', () => ({ useCloudCompanionHome: () => ({ supported: true, actors: [], deviceNames: {}, refresh: h.cloudRefresh }) }));
-vi.mock('@/device-link/remoteResourceCache', () => ({ isRemoteResourceUnread: () => h.unread, remoteResourceCacheRevision: () => 0, subscribeRemoteResourceCache: () => () => {} }));
+vi.mock('@/device-link/remoteResourceCache', () => ({
+ isRemoteResourceUnread: (_owner: string, _device: string, id: string) => h.unread || h.unreadIds.has(id),
+ remoteResourceCacheRevision: () => h.cacheRevision,
+ subscribeRemoteResourceCache: (listener: () => void) => { h.cacheListeners.add(listener); return () => { h.cacheListeners.delete(listener); }; },
+}));
vi.mock('@/utils/useGuardedPush', () => ({ useGuardedPush: () => h.push }));
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/BotGroupAvatars', () => ({ BotGroupDuoAvatar: () => null,
+ useBotGroupIdentities: () => { h.identityReads++; return () => ({}); } }));
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 }));
@@ -50,7 +64,7 @@ vi.mock('@/session/TeammateList', () => ({
}));
vi.mock('@/session/useTeammateNavigation', () => ({ useTeammateNavigation: () => ({
owner: 'owner', teammatesCollapsed: h.collapsed, lastTeammate: null,
- setTeammatesCollapsed: async () => {}, openTeammate: async () => {}, openCreatedTeammate: async () => {} }) }));
+ setTeammatesCollapsed: async () => {}, openTeammate: h.openTeammate, openCreatedTeammate: async () => {} }) }));
import { HomeTeammatesSection } from '../session/HomeTeammatesSection';
import { CONNECTION_NOTICE_DELAY_MS } from '../components/connectionNoticeDelay';
@@ -60,7 +74,9 @@ const roster = { items: [item], createTargets: [], groupTargets: [], loading: fa
isOnline: () => true, connectionState: undefined, refresh: vi.fn(async () => {}) };
const groups = { items: [] as any[], 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(); h.cloudActor = null; vi.useFakeTimers(); roster.error = 'LIST_FAILED'; h.collapsed = false; h.unread = false; groups.items = []; });
+beforeEach(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); node = document.createElement('div'); root = createRoot(node); vi.clearAllMocks(); h.cloudActor = null; vi.useFakeTimers(); roster.error = 'LIST_FAILED'; h.collapsed = false; h.unread = false; groups.items = [];
+ h.cacheRevision = 0; h.unreadIds.clear(); h.stripRenders = []; h.avatarRenders = []; h.identityReads = 0;
+});
afterEach(async () => { await act(async () => root.unmount()); vi.useRealTimers(); });
const render = (refreshKey: number, overrides: Partial<Parameters<typeof HomeTeammatesSection>[0]> = {}) => act(async () => root.render(el(HomeTeammatesSection, {
context: { navigation: null, route: null, shared: { roster, groups } } as any, active: true, refreshKey,
@@ -145,3 +161,50 @@ it.each(['cloud', 'group', 'created-group'] as const)('defers the %s route until
routeAfterClose?.();
expect(h.push).toHaveBeenCalledExactlyOnceWith(kind === 'cloud' ? '/cloud-chat' : '/group-chat');
});
+
+// Unit performance regression through the real home section: the old strip
+// subscribes ordinary bots to group identities and rerenders all cells on every
+// unrelated cache/parent update. Count work, then verify real unread/avatar/navigation
+// updates; no native FPS or wall-time claim is inferred from this synthetic load.
+// One bot plus one unrelated notification is the minimal trigger; 50 x 10
+// exercises the representative repeated-refresh load without a timing assertion.
+it('keeps a 50-companion strip quiet through ten refreshes and updates only the affected cell', async () => {
+ h.collapsed = true;
+ const items = Array.from({ length: 50 }, (_, index) => ({ ...item, key: `host:bot${index}`,
+ item: { ...item.item, ref: { ...item.item.ref, id: `bot${index}` }, display: { title: `Bot ${index}`, avatar: undefined as any } } }));
+ const show = (rows: typeof items) => render(0, { context: {
+ navigation: null, route: null, shared: { roster: { ...roster, items: rows }, groups },
+ } } as any);
+ await show(items);
+ expect(h.avatarRenders).toHaveLength(50);
+ h.stripRenders = []; h.avatarRenders = []; h.identityReads = 0;
+ let latest = items;
+ for (let index = 0; index < 10; index++) {
+ latest = structuredClone(items);
+ latest[17].item.revision = String(index + 2);
+ await show(latest);
+ await act(async () => { h.cacheRevision++; h.cacheListeners.forEach(listener => listener()); });
+ }
+ expect(h.stripRenders).toHaveLength(0);
+ expect(h.avatarRenders).toHaveLength(0);
+ expect(h.identityReads).toBe(0);
+ await act(async () => { h.unreadIds.add('bot17'); h.cacheRevision++; h.cacheListeners.forEach(listener => listener()); });
+ expect(h.stripRenders).toEqual(['home.teammatesStrip.bot.host.bot17']);
+ expect(byId('home.teammatesStrip.bot.host.bot17')?.querySelector('[data-testid="home.teammatesStrip.unread"]')).not.toBeNull();
+ expect(h.avatarRenders).toHaveLength(0);
+ h.stripRenders = [];
+ await act(async () => { h.unreadIds.clear(); h.cacheRevision++; h.cacheListeners.forEach(listener => listener()); });
+ expect(h.stripRenders).toEqual(['home.teammatesStrip.bot.host.bot17']);
+ expect(byId('home.teammatesStrip.bot.host.bot17')?.querySelector('[data-testid="home.teammatesStrip.unread"]')).toBeNull();
+ expect(h.avatarRenders).toHaveLength(0);
+ h.stripRenders = [];
+ latest[17] = { ...latest[17], item: { ...latest[17].item, display: {
+ ...latest[17].item.display, avatar: { kind: 'emoji', value: '🤖', fallbackText: 'B' },
+ } } };
+ await show([...latest]);
+ expect(h.stripRenders).toEqual(['home.teammatesStrip.bot.host.bot17']);
+ expect(h.avatarRenders).toEqual(['Bot 17']);
+ expect(byId('avatar.Bot 17')?.textContent).toBe('🤖');
+ await act(async () => byId('home.teammatesStrip.bot.host.bot17')!.click());
+ expect(h.openTeammate).toHaveBeenCalledExactlyOnceWith(latest[17]);
+});
diff --git a/apps/mobile/src/session/HomeTeammatesSection.tsx b/apps/mobile/src/session/HomeTeammatesSection.tsx
index 123f9162d4..3db578c5c2 100644
--- a/apps/mobile/src/session/HomeTeammatesSection.tsx
+++ b/apps/mobile/src/session/HomeTeammatesSection.tsx
@@ -8,7 +8,7 @@
* Android 把首页列表挂到根节点渲染(ResidentHomeList),所以名册与路由的导航上下文要在路由里取,
* 再由本段重新提供。
*/
-import { useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore, type ReactElement } from 'react';
+import { memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactElement } from 'react';
import { ActivityIndicator, Keyboard, Pressable, ScrollView, StyleSheet, View } from 'react-native';
import { NavigationContext, NavigationRouteContext, useIsFocused } from 'expo-router/react-navigation';
import { useTranslation } from 'react-i18next';
@@ -227,9 +227,61 @@ function SectionContent({ shared, active, refreshKey, visible, query, showFooter
return <>{body}{creator.sheets}</>;
}
-function StripCell({ entry, online, connected, quiet, onPress }: {
+interface StripCellProps {
entry: TeammateListEntry; online: boolean; connected: boolean | null; quiet: boolean; onPress(): void;
+}
+
+function StripCell({ entry, online, connected, quiet, onPress }: StripCellProps) {
+ const { i18n } = useTranslation();
+ const currentPress = useRef(onPress);
+ useLayoutEffect(() => { currentPress.current = onPress; }, [onPress]);
+ const press = useCallback(() => currentPress.current(), []);
+ if (entry.kind === 'group') return <GroupStripCell entry={entry} online={online} connected={connected} quiet={quiet} onPress={press} />;
+ const { row } = entry;
+ const { display } = row.item;
+ return <BotStripCell deviceId={row.host.deviceId} botId={row.item.ref.id}
+ title={resolveRemoteText(display.title, i18n.language)} lastReplyAt={display.lastReplyAt}
+ avatarKind={display.avatar?.kind} avatarValue={display.avatar?.value}
+ avatarFallback={display.avatar?.fallbackText} avatarColor={display.avatar?.color}
+ connected={connected} quiet={quiet} working={online && !!display.generation} onPress={press} />;
+}
+
+const StripAvatar = memo(RemoteCompanionAvatar);
+const BotStripCell = memo(function BotStripCell({ deviceId, botId, title, lastReplyAt,
+ avatarKind, avatarValue, avatarFallback, avatarColor, connected, quiet, working, onPress }: {
+ deviceId: string; botId: string; title: string; lastReplyAt?: number;
+ avatarKind?: string; avatarValue?: string; avatarFallback?: string; avatarColor?: string;
+ connected: boolean | null; quiet: boolean; working: boolean; onPress(): void;
}) {
+ const { t } = useTranslation();
+ const styles = useThemedStyles(makeStyles);
+ const { user } = useAuth();
+ // Observe this companion's receipt, not the cache's global revision. Other
+ // rosters and read acknowledgements need not rerender every strip avatar.
+ const readUnread = useCallback(() => isRemoteResourceUnread(user?.id ?? '', deviceId, botId, lastReplyAt),
+ [user?.id, deviceId, botId, lastReplyAt]);
+ const unread = useSyncExternalStore(subscribeRemoteResourceCache, readUnread);
+ const avatar = useMemo(() => avatarKind === undefined ? undefined : {
+ kind: avatarKind, value: avatarValue ?? '', fallbackText: avatarFallback ?? '', color: avatarColor,
+ }, [avatarKind, avatarValue, avatarFallback, avatarColor]);
+ const dimmed = connected === false && !quiet;
+ const offline = dimmed ? t('devices.resources.hostOffline') : '';
+ return <Pressable accessibilityRole="button" disabled={false} accessibilityState={{ disabled: false }}
+ accessibilityLabel={[title, offline, working ? t('groupChat.list.running') : '', unread ? t('devices.companions.unread') : ''].filter(Boolean).join(', ')}
+ onPress={onPress} style={({ pressed }) => [styles.cell, pressed && mobileInteractionStyles.pressed]}
+ testID={`home.teammatesStrip.bot.${deviceId}.${botId}`}>
+ <View style={styles.cellAvatar}>
+ <View style={dimmed ? { opacity: OFFLINE_AVATAR_OPACITY } : undefined}>
+ <StripAvatar avatar={avatar} deviceId={deviceId} name={title} online={connected === true} size={STRIP_AVATAR_SIZE} framed />
+ </View>
+ <CompanionPresenceRing active={working} />
+ {unread ? <View style={styles.unreadRing} testID="home.teammatesStrip.unread"><View style={styles.unreadDot} /></View> : null}
+ </View>
+ <Text style={[styles.cellName, unread && styles.cellNameUnread]} numberOfLines={1}>{title}</Text>
+ </Pressable>;
+});
+
+function GroupStripCell({ entry, online, connected, quiet, onPress }: StripCellProps) {
const { t, i18n } = useTranslation();
const styles = useThemedStyles(makeStyles);
const { user } = useAuth();