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): 避免伙伴列表重复渲染和预览解析

elfcv37770f250a37
diff --git a/apps/mobile/src/__tests__/TeammateList.test.tsx b/apps/mobile/src/__tests__/TeammateList.test.tsx
index bbc7fc2ecd..025e7f13ed 100644
--- a/apps/mobile/src/__tests__/TeammateList.test.tsx
+++ b/apps/mobile/src/__tests__/TeammateList.test.tsx
@@ -2,16 +2,20 @@
import { act, 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(() => ({ awaiting: new Set<string>() }));
+const h = vi.hoisted(() => ({ awaiting: new Set<string>(), unread: new Set<string>(),
+ listeners: new Set<() => void>(), rowRenders: [] as string[] }));
vi.mock('react-native', () => ({
View: ({ children, testID, style }: any) => el('div', { 'data-testid': testID, style: Object.assign({}, ...[style].flat().filter(Boolean)) }, children),
- Pressable: ({ children, testID, accessibilityLabel, disabled, onPress, style }: any) => el('button', { 'data-testid': testID, 'aria-label': accessibilityLabel, disabled, onClick: onPress,
- style: Object.assign({}, ...[typeof style === 'function' ? style({ pressed: false }) : style].flat().filter(Boolean)) }, children),
+ Pressable: ({ children, testID, accessibilityLabel, disabled, onPress, style }: any) => {
+ if (testID?.startsWith('teammates.item.')) h.rowRenders.push(testID);
+ return el('button', { 'data-testid': testID, 'aria-label': accessibilityLabel, disabled, onClick: onPress,
+ style: Object.assign({}, ...[typeof style === 'function' ? style({ pressed: false }) : style].flat().filter(Boolean)) }, children);
+ },
StyleSheet: { create: (v: unknown) => v, hairlineWidth: 1 },
}));
vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ invoke: async () => ({ blocks: [] }) }) }));
vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: {
- subscribe: () => () => {},
+ subscribe: (listener: () => void) => { h.listeners.add(listener); return () => { h.listeners.delete(listener); }; },
getSessionLiveActivity: (id: string) => h.awaiting.has(id) ? { phase: 'needs-interaction' } : null,
getPendingInteractions: () => [],
} }));
@@ -34,10 +38,11 @@ vi.mock('@/theme', async () => {
return { ...tokens, useThemedStyles: (factory: (value: typeof colors) => unknown) => factory(colors), useTheme: () => ({ colors }) };
});
vi.mock('@/session/WorkingStatusText', () => ({ WorkingStatusText: ({ text }: any) => el('span', null, text) }));
-vi.mock('@/device-link/remoteResourceCache', () => ({ isRemoteResourceUnread: () => false }));
+vi.mock('@/device-link/remoteResourceCache', () => ({ isRemoteResourceUnread: (_owner: string, _device: string, id: string) => h.unread.has(id) }));
vi.mock('@/session/sessionList', () => ({ formatRemoteSessionSidebarTime: () => '' }));
vi.mock('@/utils/useMinuteNow', () => ({ useMinuteNow: () => Date.now() }));
import { useTeammateEntries, useTeammateRowRenderer } from '../session/TeammateList';
+import * as markdown from '../session/messageMarkdown';
/** The task home section's rows: the same entries and row renderer, without the section chrome. */
function Rows(props: Parameters<typeof useTeammateRowRenderer>[0]) {
const entries = useTeammateEntries(props.items, props.groups?.items);
@@ -48,8 +53,8 @@ const item = { key: 'host:bot', host: { deviceId: 'host', deviceName: 'Computer
ref: { collectionId: 'teammates', kind: 'bot', id: 'bot' }, revision: '1', links: [], display: { title: 'Mimi', preview: 'Last reply' },
} };
let root: Root; let node: HTMLDivElement;
-beforeEach(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); node = document.createElement('div'); root = createRoot(node); });
-afterEach(async () => { await act(async () => root.unmount()); });
+beforeEach(() => { h.rowRenders = []; h.awaiting.clear(); h.unread.clear(); Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); node = document.createElement('div'); root = createRoot(node); });
+afterEach(async () => { await act(async () => root.unmount()); vi.restoreAllMocks(); });
async function render(online = true) {
await act(async () => root.render(el(Rows, { items: [item], isOnline: () => online, onSelect: vi.fn() })));
}
@@ -173,3 +178,63 @@ it('keeps a cloud companion quiet while its main computer looks offline: no offl
expect(node.textContent).not.toContain('devices.resources.hostOffline');
expect(node.querySelector('[data-testid="teammate.connection"] [data-testid="status-dot"]')).toBeNull();
});
+
+/**
+ * Performance regression through the production row renderer (unit, no timing budget):
+ * existing visual cases never refresh a roster with new-but-equal objects/callbacks.
+ * Two rows and one changed reply suffice to expose unnecessary native-row renders;
+ * clicking the retained row must still navigate with the latest resource and handler.
+ */
+it('only redraws the changed teammate after a roster refresh and opens the latest resource', async () => {
+ const parse = vi.spyOn(markdown, 'parseMobileMarkdownInlines');
+ const second = { ...item, key: 'host:second', item: { ...item.item,
+ ref: { ...item.item.ref, id: 'second' }, display: { title: 'Aster', preview: 'Unchanged' } } };
+ const firstSelect = vi.fn();
+ await act(async () => root.render(el(Rows, { items: [item, second], isOnline: () => true, onSelect: firstSelect })));
+ h.rowRenders = [];
+ parse.mockClear();
+ const fresh = structuredClone([item, second]);
+ // A new revision/link is navigation data, even when no visible field changed.
+ fresh[1].item.revision = '2';
+ fresh[1].item.links = [{ rel: 'conversation', target: { kind: 'session', sessionId: 'latest' } }] as any;
+ const latestSelect = vi.fn();
+ await act(async () => root.render(el(Rows, { items: fresh, isOnline: () => true, onSelect: latestSelect })));
+ expect(h.rowRenders).toEqual([]);
+ expect(parse).not.toHaveBeenCalled();
+ fresh[0] = { ...fresh[0], item: { ...fresh[0].item, display: { title: 'Mimi', preview: '**New reply**' } } };
+ await act(async () => root.render(el(Rows, { items: [...fresh], isOnline: () => true, onSelect: latestSelect })));
+ expect(h.rowRenders).toEqual(['teammates.item.host.bot']);
+ expect(parse).toHaveBeenCalledExactlyOnceWith('**New reply**');
+ expect(node.textContent).toContain('New reply');
+ expect(node.textContent).toContain('Unchanged');
+ await act(async () => node.querySelector<HTMLButtonElement>('[data-testid="teammates.item.host.second"]')!.click());
+ expect(latestSelect).toHaveBeenCalledExactlyOnceWith(fresh[1]);
+ expect(firstSelect).not.toHaveBeenCalled();
+ // The ordering helper deduplicates by retaining the last resource snapshot.
+ const duplicate = { ...fresh[1], item: { ...fresh[1].item, revision: '3' } };
+ await act(async () => root.render(el(Rows, { items: [...fresh, duplicate], isOnline: () => true, onSelect: latestSelect })));
+ await act(async () => node.querySelector<HTMLButtonElement>('[data-testid="teammates.item.host.second"]')!.click());
+ expect(latestSelect).toHaveBeenLastCalledWith(duplicate);
+});
+
+// A retained row must still reflect live interaction, read acknowledgement and
+// connectivity changes; none changes the cached preview's Markdown input.
+it('updates waiting, unread and connection states without reparsing the reply', async () => {
+ const parse = vi.spyOn(markdown, 'parseMobileMarkdownInlines');
+ const waiting = { ...item, item: { ...item.item,
+ links: [{ rel: 'conversation', target: { kind: 'session' as const, sessionId: 's1' } }] } };
+ const props = { items: [waiting], isOnline: () => true, onSelect: vi.fn() };
+ await act(async () => root.render(el(Rows, props)));
+ parse.mockClear();
+ await act(async () => { h.awaiting.add('s1'); h.listeners.forEach(listener => listener()); });
+ expect(node.textContent).toContain('devices.companions.awaiting · Last reply');
+ h.unread.add('bot');
+ await act(async () => root.render(el(Rows, { ...props })));
+ expect(node.querySelector('[data-testid="companion.row.unread"]')).not.toBeNull();
+ h.unread.clear();
+ await act(async () => root.render(el(Rows, { ...props, isOnline: () => false })));
+ expect(node.querySelector('[data-testid="companion.row.unread"]')).toBeNull();
+ expect(node.textContent).toContain('devices.resources.hostOffline · Last reply');
+ expect(node.textContent).not.toContain('devices.companions.awaiting');
+ expect(parse).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/session/TeammateList.tsx b/apps/mobile/src/session/TeammateList.tsx
index 7d7094fbed..5f700ddab5 100644
--- a/apps/mobile/src/session/TeammateList.tsx
+++ b/apps/mobile/src/session/TeammateList.tsx
@@ -1,5 +1,5 @@
import { readWorkingPhase } from '@cindy/maker-shared';
-import { useCallback, useMemo, useSyncExternalStore } from 'react';
+import { memo, useCallback, useLayoutEffect, useMemo, useRef, useSyncExternalStore } from 'react';
import { View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { resolveRemoteText } from '@cindy/device-link';
@@ -69,10 +69,22 @@ export function useTeammateEntries(items: readonly HostedRemoteCollectionItem[],
/** The teammate / group row of the task home's teammate section. */
export function useTeammateRowRenderer({ items, isOnline, connectionState, quietPresence, onSelect, groups }: TeammateRowOptions) {
- const { t, i18n } = useTranslation();
+ const { i18n } = useTranslation();
const { user } = useAuth();
const now = useMinuteNow();
const awaiting = useAwaitingSessions(items);
+ // Resource refreshes replace objects and navigation closures even when the row
+ // looks identical. Keep presses current without invalidating every visible row.
+ const selection = useRef({ items, onSelect });
+ useLayoutEffect(() => { selection.current = { items, onSelect }; }, [items, onSelect]);
+ const select = useCallback((key: string) => {
+ const current = selection.current;
+ // orderedTeammates keeps the last copy of a repeated identity.
+ for (let index = current.items.length - 1; index >= 0; index--) {
+ const row = current.items[index];
+ if (row.key === key) { current.onSelect(row); return; }
+ }
+ }, []);
const duplicateNames = useMemo(() => {
const names = new Map<string, number>();
for (const row of items) {
@@ -84,15 +96,9 @@ export function useTeammateRowRenderer({ items, isOnline, connectionState, quiet
const renderBot = (row: HostedRemoteCollectionItem, last: boolean) => {
const display = row.item.display;
const title = resolveRemoteText(display.title, i18n.language);
- const preview = display.preview ? parseMobileMarkdownInlines(resolveRemoteText(display.preview, i18n.language))
- .map(inline => inline.type === 'image' ? inline.alt : inline.text).join('').replace(/\s+/g, ' ').trim() : '';
const online = isOnline(row.host);
const connected = connectionState ? connectionState(row.host) : online;
- // Desktop BotsSidebar: the cached reply stays readable offline; then the description, then an invitation.
- const subtitle = display.subtitle ? resolveRemoteText(display.subtitle, i18n.language).replace(/\s+/g, ' ').trim() : '';
- const summary = preview || subtitle || t('devices.companions.startChat');
const generating = online && !!display.generation;
- const workingCopy = generating ? t(`devices.companions.working.${readWorkingPhase(display.generation!.phase) ?? 'processing'}`) : '';
const attention = display.status?.tone === 'warning' || display.status?.tone === 'critical'
? resolveRemoteText(display.status.label, i18n.language) : '';
const sessionId = conversationSessionId(row);
@@ -102,33 +108,16 @@ export function useTeammateRowRenderer({ items, isOnline, connectionState, quiet
const timestamp = display.timestamp;
const time = timestamp !== undefined && Number.isFinite(new Date(timestamp).getTime())
? formatRemoteSessionSidebarTime(new Date(timestamp).toISOString(), now) : '';
- const quiet = !!quietPresence?.(row);
- const connection = quiet ? ''
- : connected === false ? t('devices.resources.hostOffline') : connected === null ? t('devices.resources.connectionUnknown') : '';
- const prefix = attention || (waiting ? t('devices.companions.awaiting') : '');
- return <CompanionListRow key={`bot:${row.key}`} testID={`teammates.item.${row.host.deviceId}.${row.item.ref.id}`}
- accessibilityLabel={[title, ambiguous ? row.host.deviceName : '', connection, prefix, generating ? workingCopy : summary, time,
- unread ? t('devices.companions.unread') : ''].filter(Boolean).join(', ')}
- avatar={<>
- <View style={connected === false && !quiet ? { opacity: OFFLINE_AVATAR_OPACITY } : undefined}>
- <RemoteCompanionAvatar avatar={display.avatar} deviceId={row.host.deviceId} name={title} online={connected === true} size={COMPANION_ROW_AVATAR_SIZE} framed />
- </View>
- <CompanionPresenceRing active={generating} />
- {quiet ? null : <CompanionPresenceDot connected={connected} />}
- </>}
- title={title}
- device={ambiguous ? row.host.deviceName : undefined}
- trailing={generating ? { kind: 'working' } : { kind: 'time', text: time }}
- preview={generating
- ? <TeammateGenerationLabel deviceId={row.host.deviceId} botId={row.item.ref.id} generation={display.generation!} />
- : connection ? `${connection} · ${summary}` : summary}
- previewTone={connection ? 'tertiary' : 'secondary'}
- previewPrefix={connection ? undefined : prefix || undefined}
- previewPrefixTestID={attention ? 'teammate.attention' : undefined}
- unread={unread}
- unreadLabel={t('devices.companions.unread')}
- last={last}
- onPress={() => onSelect(row)} />;
+ return <TeammateRow key={`bot:${row.key}`} rowKey={row.key} deviceId={row.host.deviceId} botId={row.item.ref.id}
+ title={title} device={ambiguous ? row.host.deviceName : undefined}
+ rawPreview={!generating && display.preview ? resolveRemoteText(display.preview, i18n.language) : ''}
+ subtitle={display.subtitle ? resolveRemoteText(display.subtitle, i18n.language) : ''}
+ avatarKind={display.avatar?.kind} avatarValue={display.avatar?.value}
+ avatarFallback={display.avatar?.fallbackText} avatarColor={display.avatar?.color}
+ generating={generating} phase={generating ? display.generation!.phase : ''}
+ startedAt={generating ? display.generation!.startedAt : null}
+ connected={connected} quiet={!!quietPresence?.(row)} attention={attention} waiting={waiting}
+ unread={unread} time={time} last={last} onSelect={select} />;
};
return (entry: TeammateListEntry, last: boolean) => {
if (entry.kind === 'bot' || !groups) return renderBot(entry.row, last);
@@ -136,3 +125,53 @@ export function useTeammateRowRenderer({ items, isOnline, connectionState, quiet
onPress={() => groups.onSelect(entry.row)} />;
};
}
+
+interface TeammateRowProps {
+ rowKey: string; deviceId: string; botId: string; title: string; device?: string;
+ rawPreview: string; subtitle: string;
+ avatarKind?: string; avatarValue?: string; avatarFallback?: string; avatarColor?: string;
+ generating: boolean; phase: string; startedAt: number | null;
+ connected: boolean | null; quiet: boolean; attention: string; waiting: boolean;
+ unread: boolean; time: string; last: boolean;
+ onSelect(key: string): void;
+}
+
+// Only display primitives cross this boundary: fresh host/resource objects and
+// unrelated home updates must not reparse previews or redraw native row content.
+const TeammateAvatar = memo(RemoteCompanionAvatar);
+const TeammateRow = memo(function TeammateRow({ rowKey, deviceId, botId, title, device, rawPreview, subtitle,
+ avatarKind, avatarValue, avatarFallback, avatarColor, generating, phase, startedAt,
+ connected, quiet, attention, waiting, unread, time, last, onSelect }: TeammateRowProps) {
+ const { t } = useTranslation();
+ const preview = useMemo(() => rawPreview ? parseMobileMarkdownInlines(rawPreview)
+ .map(inline => inline.type === 'image' ? inline.alt : inline.text).join('').replace(/\s+/g, ' ').trim() : '', [rawPreview]);
+ const avatar = useMemo(() => avatarKind === undefined ? undefined : {
+ kind: avatarKind, value: avatarValue ?? '', fallbackText: avatarFallback ?? '', color: avatarColor,
+ }, [avatarKind, avatarValue, avatarFallback, avatarColor]);
+ const press = useCallback(() => onSelect(rowKey), [onSelect, rowKey]);
+ // Cached replies stay readable offline, followed by the description or invitation.
+ const summary = preview || subtitle.replace(/\s+/g, ' ').trim() || t('devices.companions.startChat');
+ const workingCopy = generating ? t(`devices.companions.working.${readWorkingPhase(phase) ?? 'processing'}`) : '';
+ const connection = quiet ? '' : connected === false ? t('devices.resources.hostOffline')
+ : connected === null ? t('devices.resources.connectionUnknown') : '';
+ const prefix = attention || (waiting ? t('devices.companions.awaiting') : '');
+ return <CompanionListRow testID={`teammates.item.${deviceId}.${botId}`}
+ accessibilityLabel={[title, device, connection, prefix, generating ? workingCopy : summary, time,
+ unread ? t('devices.companions.unread') : ''].filter(Boolean).join(', ')}
+ avatar={<>
+ <View style={connected === false && !quiet ? { opacity: OFFLINE_AVATAR_OPACITY } : undefined}>
+ <TeammateAvatar avatar={avatar} deviceId={deviceId} name={title} online={connected === true} size={COMPANION_ROW_AVATAR_SIZE} framed />
+ </View>
+ <CompanionPresenceRing active={generating} />
+ {quiet ? null : <CompanionPresenceDot connected={connected} />}
+ </>}
+ title={title} device={device}
+ trailing={generating ? { kind: 'working' } : { kind: 'time', text: time }}
+ preview={generating ? <TeammateGenerationLabel deviceId={deviceId} botId={botId} generation={{ phase, startedAt }} />
+ : connection ? `${connection} · ${summary}` : summary}
+ previewTone={connection ? 'tertiary' : 'secondary'}
+ previewPrefix={connection ? undefined : prefix || undefined}
+ previewPrefixTestID={attention ? 'teammate.attention' : undefined}
+ unread={unread} unreadLabel={t('devices.companions.unread')}
+ last={last} onPress={press} />;
+});