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): 减少伙伴刷新误报并避免提示挤动列表

Dash35d42bf9f944
diff --git a/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx b/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx
index 2f8d857552..34340bcea6 100644
--- a/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx
+++ b/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx
@@ -6,7 +6,7 @@ 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),
+ Pressable: ({ children, testID, disabled, onPress, accessibilityLabel }: any) => 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 },
@@ -14,6 +14,7 @@ vi.mock('react-native', () => ({
vi.mock('expo-router/react-navigation', () => ({
NavigationContext: createContext(null), NavigationRouteContext: createContext(null), useIsFocused: () => true,
}));
+vi.mock('expo-router', () => ({ useFocusEffect: () => {} }));
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' } }) }));
@@ -45,6 +46,7 @@ vi.mock('@/session/useTeammateNavigation', () => ({ useTeammateNavigation: () =>
owner: 'owner', teammatesCollapsed: false, lastTeammate: null,
setTeammatesCollapsed: async () => {}, openTeammate: async () => {}, openCreatedTeammate: async () => {} }) }));
import { HomeTeammatesSection } from '../session/HomeTeammatesSection';
+import { CONNECTION_NOTICE_DELAY_MS } from '../components/connectionNoticeDelay';
const item = { key: 'host:bot', host: { deviceId: 'host', deviceName: 'Mac' }, item: {
ref: { collectionId: 'teammates', kind: 'bot', id: 'bot' }, revision: '1', links: [], display: { title: 'Mimi' } } };
@@ -52,24 +54,43 @@ const roster = { items: [item], createTargets: [], groupTargets: [], loading: fa
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()); });
+beforeEach(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); node = document.createElement('div'); root = createRoot(node); vi.clearAllMocks(); vi.useFakeTimers(); roster.error = 'LIST_FAILED'; });
+afterEach(async () => { await act(async () => root.unmount()); vi.useRealTimers(); });
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 () => {
+// Unit regression: a failed background read must not insert a row above cached teammates.
+// The previous test required an immediate alert; now test the real delayed header action.
+it('keeps cached teammates and offers a quiet header retry only for a lasting failure', async () => {
await render(0);
expect(node.textContent).toContain('Mimi');
- expect(byId('home.teammatesError')?.textContent).toBe('devices.companions.stale');
+ expect(byId('home.teammatesRetry')).toBeNull();
+ await act(async () => vi.advanceTimersByTimeAsync(CONNECTION_NOTICE_DELAY_MS));
+ expect(byId('home.teammatesError')).toBeNull();
+ expect(byId('home.teammatesRetry')?.getAttribute('aria-label')).toContain('devices.companions.stale');
+ expect(byId('home.teammatesRetry')?.parentElement).toBe(byId('home.teammatesHeader')?.parentElement);
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);
+ roster.error = null;
+ await render(0);
+ expect(byId('home.teammatesRetry')).toBeNull();
+});
+
+it('never flashes a recovered background error', async () => {
+ await render(0);
+ await act(async () => vi.advanceTimersByTimeAsync(CONNECTION_NOTICE_DELAY_MS - 1));
+ roster.error = null;
+ await render(0);
+ await act(async () => vi.advanceTimersByTimeAsync(CONNECTION_NOTICE_DELAY_MS));
+ expect(byId('home.teammatesRetry')).toBeNull();
+ expect(byId('home.teammatesError')).toBeNull();
+ expect(node.textContent).toContain('Mimi');
});
// Pull-to-refresh lives on the home list; it reaches the section's cloud companions through the key.
diff --git a/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx b/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx
index 6c8f3a3a5f..59a49faf89 100644
--- a/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx
+++ b/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx
@@ -6,7 +6,7 @@ import type { HostedRemoteCollectionItem, RemoteResourceHostTarget } from '@/dev
import { REMOTE_RESOURCE_STARTUP_TIMEOUT_MS } from '@/device-link/remoteResourceAvailability';
const h = vi.hoisted(() => ({
auth: { user: { id: 'owner' }, accountGeneration: 1 }, focused: true,
- link: { connectionEpoch: 1, status: 'online', presenceVersion: 1, getPresenceAvailability: vi.fn(() => true as boolean | null),
+ link: { connectionEpoch: 1, status: 'online', presenceVersion: 1, getPresenceAvailability: vi.fn((_deviceId: string) => true as boolean | null),
invoke: vi.fn(), openLink: vi.fn(), onRemoteResourceChanged: vi.fn((_listener: (deviceId: string, payload: { collectionId: string }) => void) => () => {}), subscribe: vi.fn(), unsubscribe: vi.fn() },
app: { currentState: 'active', listener: null as null | ((state: string) => void) },
translation: { t: (key: string) => key, i18n: { language: 'en' } },
@@ -47,6 +47,23 @@ beforeEach(() => {
});
afterEach(() => { act(() => root?.unmount()); root = undefined; vi.useRealTimers(); });
describe('shared real resource list', () => {
+ // Regression: one sleeping computer raised a section-wide warning on a healthy phone.
+ // Unit: real roster hook, cached offline shard + a successful online shard.
+ it('keeps known offline computers without reporting a failed refresh and reads them on return', async () => {
+ h.cached = [cached(targets[1], 'sleeping')];
+ h.link.getPresenceAvailability.mockImplementation(id => id !== 'pc');
+ h.list.mockResolvedValue({ items: [item('fresh')] });
+ await render();
+ expect(result.items.map(row => row.item.ref.id)).toEqual(['fresh', 'sleeping']);
+ expect(result.error).toBeNull();
+ expect(result.isOnline(targets[1])).toBe(false);
+ expect(h.link.openLink.mock.calls.map(([id]) => id)).toEqual(['mac']);
+ h.link.getPresenceAvailability.mockReturnValue(true);
+ h.link.presenceVersion++;
+ await render();
+ expect(result.items.map(row => row.item.ref.id)).toEqual(['fresh', 'fresh']);
+ expect(result.isOnline(targets[1])).toBe(true);
+ });
it('reconciles deletion from a successful host, retains a failed host as offline, and reports partial failures', async () => {
h.cached = [cached(targets[0], 'deleted'), cached(targets[1], 'offline')];
h.list.mockImplementation(async (_invoke, host) => {
diff --git a/apps/mobile/src/__tests__/useTeammateRoster.test.tsx b/apps/mobile/src/__tests__/useTeammateRoster.test.tsx
index a8f7b0c43c..eba11cb84e 100644
--- a/apps/mobile/src/__tests__/useTeammateRoster.test.tsx
+++ b/apps/mobile/src/__tests__/useTeammateRoster.test.tsx
@@ -42,6 +42,8 @@ it('offers only real online hosts advertising create, including a host with an e
expect(h.link.invoke).toHaveBeenCalledTimes(2); // No extra capability probe or mutation.
expect(result.authoritative).toBe(true);
h.list.isOnline.mockReturnValue(false); await render(); expect(result.createTargets).toEqual([]);
+ // Offline cached shards no longer raise refresh errors, but are still not authoritative.
+ expect(result.authoritative).toBe(false);
});
it('does not treat initial offline discovery as authoritative; recovers on connection', async () => {
h.link.status = 'offline'; await render(); expect(result.authoritative).toBe(false); expect(result.createTargets).toEqual([]);
diff --git a/apps/mobile/src/session/HomeTeammatesSection.tsx b/apps/mobile/src/session/HomeTeammatesSection.tsx
index bea2e8a0e0..d49d2ab7c2 100644
--- a/apps/mobile/src/session/HomeTeammatesSection.tsx
+++ b/apps/mobile/src/session/HomeTeammatesSection.tsx
@@ -16,6 +16,7 @@ import { ChevronDown, ChevronRight, ChevronUp, Plus, RefreshCw, UsersRound } fro
import { resolveRemoteText } from '@cindy/device-link';
import { useAuth } from '@/auth/AuthContext';
import { Text } from '@/components/AppText';
+import { useDelayedConnectionNotice } from '@/components/ConnectionNoticeOverlay';
import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';
import { RemoteCompanionAvatar } from '@/components/RemoteCompanionAvatar';
import { CLOUD_ROW_REVISION, cloudActorForRow, cloudCompanionRows } from '@/chat/cloudCompanion';
@@ -139,12 +140,14 @@ function SectionContent({ shared, active, refreshKey, visible, query, showFooter
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.
+ // Keep cached rows during recovery. A lasting failure only adds a header action,
+ // never a notice row that changes the list's height.
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 showError = useDelayedConnectionNotice(!!error && focused && visible && !search);
const retry = () => {
void roster.refresh();
if (groups.supported) void groups.refresh();
@@ -171,19 +174,17 @@ function SectionContent({ shared, active, refreshKey, visible, query, showFooter
<Text style={[list.projectTitle, styles.headerTitle]} numberOfLines={1}>{title}</Text>
{collapsed || !entries.length ? null : <Text style={[list.projectCount, styles.count]} numberOfLines={1}>{entries.length}</Text>}
</Pressable>
+ {showError ? <Pressable accessibilityRole="button" accessibilityLabel={`${t(errorKey)} ${t('devices.resources.retry')}`}
+ disabled={retrying} onPress={retry} hitSlop={spacing.xs}
+ style={({ pressed }) => [styles.headerAdd, pressed && mobileInteractionStyles.pressed]} testID="home.teammatesRetry">
+ {retrying ? <ActivityIndicator color={colors.textTertiary} /> : <RefreshCw size={iconSize.sm} color={colors.textTertiary} strokeWidth={iconStroke.regular} />}
+ </Pressable> : null}
{/* Folded, the strip's last cell is the create entry; the header keeps only one. */}
{collapsed || !entries.length ? null : create((press, label) => <Pressable accessibilityRole="button" accessibilityLabel={label}
onPress={press} hitSlop={spacing.xs} style={({ pressed }) => [styles.headerAdd, pressed && mobileInteractionStyles.pressed]} testID="home.teammatesCreate">
<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>
@@ -283,9 +284,6 @@ 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).
diff --git a/apps/mobile/src/session/useRemoteResourceList.ts b/apps/mobile/src/session/useRemoteResourceList.ts
index fa96af2a70..f860308313 100644
--- a/apps/mobile/src/session/useRemoteResourceList.ts
+++ b/apps/mobile/src/session/useRemoteResourceList.ts
@@ -88,7 +88,10 @@ export function useRemoteResourceList(collectionId: string, targets: readonly Re
while (offset < selected.length && current()) {
const host = selected[offset++];
try {
- if (status !== 'online' || getPresenceAvailability(host.deviceId) === false) throw new Error(t('devices.resources.hostOffline'));
+ if (status !== 'online') throw new Error(t('devices.resources.hostOffline'));
+ // An explicitly offline peer is an expected cached shard, not a failed
+ // refresh of the whole roster. Presence changes already schedule a read.
+ if (getPresenceAvailability(host.deviceId) === false) continue;
const response = await retryRemoteSyncRead({ signal, isStale: () => !current() }, async () => {
await openLink(host.deviceId);
return listRemoteCollection(invoke, host, collectionId, i18n.language);
diff --git a/apps/mobile/src/session/useTeammateRoster.ts b/apps/mobile/src/session/useTeammateRoster.ts
index 22188fa1a2..5d57dec2fa 100644
--- a/apps/mobile/src/session/useTeammateRoster.ts
+++ b/apps/mobile/src/session/useTeammateRoster.ts
@@ -196,7 +196,8 @@ export function useTeammateRoster(enabled = true) {
// Stable reference (revocation is applied at discovery and again to the listed rows).
groupTargets: ready ? discovery.groupTargets : NO_TARGETS,
createTargets: ready && status === 'online' ? discovery.createTargets.filter((host) => !revoked.has(host.deviceId) && list.isOnline(host)) : NO_TARGETS,
- authoritative: ready && !discovery.loading && !list.loading && !list.syncing && status === 'online' && !discovery.error && (!discovery.targets.length || !list.error),
+ authoritative: ready && !discovery.loading && !list.loading && !list.syncing && status === 'online' && !discovery.error
+ && (!discovery.targets.length || (!list.error && discovery.targets.every(list.isOnline))),
loading: !ready || !discovery.settled || list.loading,
refreshing: list.refreshing,
error: ready ? discovery.error ?? (discovery.targets.length ? list.error : null) : null, refresh };