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): 连接提示统一悬浮并延迟一秒显示 (#4150)

Dashf914cba1e725
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index 4129b93679..6fd466faa7 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -12,6 +12,7 @@ import { useCallback, useEffect, useMemo, useRef, type ReactElement } from 'reac
import { useTranslation } from 'react-i18next';
import { Alert, AppState, Platform, Pressable, StyleSheet, View } from 'react-native';
import { Text } from '@/components/AppText';
+import { ConnectionNoticeProvider } from '@/components/ConnectionNoticeOverlay';
import {
fontWeight,
radius,
@@ -426,7 +427,7 @@ function RootLayout() {
<StartupSplashOverlay
hidden={endpointGate.status === 'error' || forcedUpdate !== null}
>
- {body}
+ <ConnectionNoticeProvider>{body}</ConnectionNoticeProvider>
</StartupSplashOverlay>
</MobileLoginHandoffProvider>
</LocaleProvider>
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index 0dfdaf699f..a39cbee20b 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -113,6 +113,9 @@ import {
formatRemoteError,
} from '@/device-link/remoteStatus';
import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
+import { ConnectionRecoveryProgress } from '@/components/ConnectionBanner';
+import { ConnectionNoticeOverlay, useDelayedConnectionNotice } from '@/components/ConnectionNoticeOverlay';
+import { resolveConnectionBannerSyncActionVisibility, resolveHomeConnectionFeedback, type HomeConnectionError, type HomeDeviceFailure } from '@/components/connectionBannerVisibility';
import { runIndependentSnapshotReads } from '@/device-link/sessionSnapshotSingleFlight';
import { revokedDevicesStore, useRevokedDevices } from '@/device-link/revokedDevicesStore';
import { useUnresponsiveDevices } from '@/device-link/unresponsiveDevicesStore';
@@ -316,7 +319,7 @@ type ProjectDragSession = {
x: number;
};
type HydrateDeviceSessionsResult = {
- failure: string | null;
+ failure: HomeDeviceFailure | null;
needsRerun?: boolean;
offline: boolean;
superseded: boolean;
@@ -369,6 +372,7 @@ function HomeScreenContent() {
connectionIssue,
invoke,
lastPresenceSnapshot,
+ recoveringDeviceIds,
readDeviceList,
status,
subscribe,
@@ -430,7 +434,7 @@ function HomeScreenContent() {
// 首次网络同步必须等设备筛选偏好恢复,否则单机用户会先按默认“全部”拉一轮所有电脑。
const [homeViewPreferencesHydrated, setHomeViewPreferencesHydrated] = useState(false);
const [refreshing, setRefreshing] = useState(false);
- const [error, setError] = useState<string | null>(null);
+ const [error, setError] = useState<HomeConnectionError>(null);
const [lastSyncedAt, setLastSyncedAt] = useState<number | null>(null);
const [selectedDeviceId, setSelectedDeviceId] = useState<string | null>(null);
const [remoteHomeCollections, setRemoteHomeCollections] = useState<RemoteHomeCollection[]>([]);
@@ -806,7 +810,7 @@ function HomeScreenContent() {
if (offline) markDeviceOffline(device.deviceId);
updateDeviceConnectionState(device.deviceId, 'failed');
return {
- failure: `${device.name}: ${formatRemoteError(err)}`,
+ failure: { deviceId: device.deviceId, deviceName: device.name, error: formatRemoteError(err) },
offline,
superseded: false,
};
@@ -838,6 +842,8 @@ function HomeScreenContent() {
return existing.promise;
}
+ // Mark the hand-off before entering the limiter: reseed can queue behind another peer.
+ updateDeviceConnectionState(device.deviceId, 'syncing');
const promise = hydrateDeviceSessionsOnce(
device,
expectedAccountGeneration,
@@ -869,7 +875,7 @@ function HomeScreenContent() {
() => settle(false),
);
return promise;
- }, [accountGeneration, hydrateDeviceSessionsOnce, isCurrentHomeSyncTarget]);
+ }, [accountGeneration, hydrateDeviceSessionsOnce, isCurrentHomeSyncTarget, updateDeviceConnectionState]);
hydrateDeviceSessionsRef.current = hydrateDeviceSessions;
const probeRevokedDeviceAccess = useCallback(async (
@@ -981,7 +987,7 @@ function HomeScreenContent() {
remoteSessionStore.removeDevice(deviceId);
}
- const failures: string[] = [];
+ const failures: HomeDeviceFailure[] = [];
const offlineDeviceIds = new Set<string>();
const hydrateResults = await runHomeDeviceSyncBatch(syncRows, async (item) => {
const result = await hydrateDeviceSessions(item.device, accountGenerationAtStart);
@@ -1011,7 +1017,7 @@ function HomeScreenContent() {
lastSyncedAtRef.current = now;
setLastSyncedAt(now);
if (selectedDeviceIdRef.current === selectedDeviceIdAtSyncStart) {
- setError(failures.length > 0 ? failures.slice(0, 2).join(';') : null);
+ setError(failures.length > 0 ? failures : null);
}
// loadHome 整轮成功后也回写一次:覆盖「设备全部下线 / 会话清空」的收敛场景——
// 此时没有任何 hydrate 成功,只有这里能把缓存里的陈旧设备清掉。
@@ -1424,8 +1430,8 @@ function HomeScreenContent() {
) return;
const failures = results
.filter((result) => !result.superseded && result.failure)
- .map((result) => result.failure as string);
- if (failures.length > 0) setError(failures.slice(0, 2).join(';'));
+ .map((result) => result.failure as HomeDeviceFailure);
+ if (failures.length > 0) setError(failures);
else if (results.some((result) => !result.superseded)) setError(null);
});
}, [accountGeneration, homeSyncDeviceIds, homeSyncRows, hydrateDeviceSessions, reconcileHomeDeviceSyncScope, selectedDeviceId]);
@@ -1808,7 +1814,10 @@ function HomeScreenContent() {
metricCount: 3,
screenWidth,
});
- const connectionError = describeRemoteError(error);
+ const homeRecoveringDeviceIds = new Set(homeSyncDeviceIds.filter((id) => unresponsiveDevices.has(id)
+ || recoveringDeviceIds.has(id) || rawDeviceConnectionStates[id] === 'syncing'));
+ const homeDeviceUnresponsive = homeSyncDeviceIds.some((id) => unresponsiveDevices.has(id));
+ const { error: connectionError, deviceRecovery: homeDeviceRecovery } = resolveHomeConnectionFeedback(error, homeRecoveringDeviceIds, describeRemoteError);
const initialHomeSettled = deviceIdentityCacheReady && lastSyncedAt !== null;
const initialHomeLoading = !initialHomeSettled && !connectionError;
const initialHomeError = !initialHomeSettled && !!connectionError;
@@ -1839,16 +1848,29 @@ function HomeScreenContent() {
&& (!selectedDeviceId || item.deviceId === selectedDeviceId) && item.sessionCount > 0)
&& !home.deviceFilters.some((item) => item.deviceId !== null
&& (!selectedDeviceId || item.deviceId === selectedDeviceId) && item.available);
- const showConnectionRow = selectedDeviceDisconnected || !!connectionError || status !== 'online' || connectionIssue?.kind === 'unstable';
+ const showConnectionRow = homeRecoveringDeviceIds.size > 0 || selectedDeviceDisconnected || !!connectionError || status !== 'online' || connectionIssue?.kind === 'unstable';
+ const showConnectionNotice = useDelayedConnectionNotice(showConnectionRow);
+ const showHomeSyncAction = resolveConnectionBannerSyncActionVisibility({
+ online: status === 'online',
+ hasActiveIssue: activeConnectionIssue !== null,
+ deviceUnresponsive: homeDeviceRecovery,
+ hasRequestError: connectionError !== null,
+ // loadHome has no outer retry after its bounded REST retries are exhausted.
+ requestErrorAutoRecovering: false,
+ });
+ const showHomeRecoveryProgress = (!activeConnectionIssue
+ || activeConnectionIssue.kind === 'unstable' || activeConnectionIssue.kind === 'replaced')
+ && (status === 'connecting' || homeDeviceRecovery);
const connectionTone = activeConnectionIssue
? 'off'
- : selectedDeviceDisconnected ? 'off' : connectionError ? 'muted' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';
+ : homeDeviceRecovery ? 'busy' : selectedDeviceDisconnected ? 'off' : connectionError ? 'muted' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';
const connectionTitle = activeConnectionIssue
? connectionIssueTitle(activeConnectionIssue.kind)
- : selectedDeviceDisconnected ? t('deviceLink.cachedHistory.title') : connectionError ? t('devices.list.syncFailed') : homeConnectionTitle(status, t);
+ : homeDeviceRecovery ? t(homeDeviceUnresponsive ? 'deviceLink.deviceUnresponsiveTitle' : 'deviceLink.recovery.syncing')
+ : selectedDeviceDisconnected ? t('deviceLink.cachedHistory.title') : connectionError ? t('devices.list.syncFailed') : homeConnectionTitle(status, t);
const connectionCopy = activeConnectionIssue
? connectionIssueHint(activeConnectionIssue.kind)
- : selectedDeviceDisconnected ? t('deviceLink.cachedHistory.hint') : connectionError;
+ : homeDeviceRecovery ? t(homeDeviceUnresponsive ? 'deviceLink.deviceUnresponsiveHint' : 'deviceLink.recovery.syncingHint') : selectedDeviceDisconnected ? t('deviceLink.cachedHistory.hint') : connectionError;
const emptyStateTitle = initialHomeError ? t('devices.list.syncFailed') : home.emptyTitle;
const emptyStateCopy = initialHomeError ? (connectionError ?? t('devices.list.requestFailed')) : home.emptyCopy;
// 无可控制电脑的引导态(landing)可见性,与 ListEmptyComponent 的分支同口径。
@@ -2532,7 +2554,10 @@ function HomeScreenContent() {
/>
) : null}
- {showConnectionRow ? (
+ </View>
+ </HomeChromeFrost>
+ {showConnectionNotice ? (
+ <ConnectionNoticeOverlay>
<View
style={[styles.connectionRow, (connectionError || activeConnectionIssue) && styles.connectionRowError]}
testID="connection.banner"
@@ -2541,7 +2566,7 @@ function HomeScreenContent() {
<Text ellipsizeMode="tail" numberOfLines={1} style={styles.connectionText} testID="connection.title">
{connectionCopy ? `${connectionTitle} · ${connectionCopy}` : connectionTitle}
</Text>
- <Pressable
+ {showHomeSyncAction ? <Pressable
accessibilityLabel={refreshing ? t('devices.list.a11y.syncing') : t('devices.list.a11y.sync')}
accessibilityRole="button"
accessibilityState={{ busy: refreshing || undefined, disabled: refreshing }}
@@ -2555,11 +2580,12 @@ function HomeScreenContent() {
testID="connection.syncButton"
>
<RefreshCw color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
- </Pressable>
+ </Pressable> : showHomeRecoveryProgress ? (
+ <ConnectionRecoveryProgress />
+ ) : null}
</View>
+ </ConnectionNoticeOverlay>
) : null}
- </View>
- </HomeChromeFrost>
</View>
<SectionList
@@ -4420,6 +4446,10 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
alignSelf: 'flex-end',
},
connectionRow: {
+ backgroundColor: colors.surfaceElevated,
+ borderColor: colors.border,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderRadius: radius.container,
alignItems: 'center',
borderBottomColor: colors.border,
borderBottomWidth: StyleSheet.hairlineWidth,
diff --git a/apps/mobile/src/__tests__/connectionNoticeDelay.test.ts b/apps/mobile/src/__tests__/connectionNoticeDelay.test.ts
new file mode 100644
index 0000000000..cb217a51d0
--- /dev/null
+++ b/apps/mobile/src/__tests__/connectionNoticeDelay.test.ts
@@ -0,0 +1,60 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { scheduleConnectionNotice, updateConnectionNoticeVisibility } from '@/components/connectionNoticeDelay';
+
+describe('floating connection notice', () => {
+ afterEach(() => vi.useRealTimers());
+ it('waits one second and cancels a brief outage without flashing', () => {
+ vi.useFakeTimers();
+ const reveal = vi.fn();
+ const cancel = scheduleConnectionNotice(reveal);
+ vi.advanceTimersByTime(999);
+ expect(reveal).not.toHaveBeenCalled();
+ cancel();
+ vi.advanceTimersByTime(1_000);
+ expect(reveal).not.toHaveBeenCalled();
+ const cancelNext = scheduleConnectionNotice(reveal);
+ vi.advanceTimersByTime(999);
+ expect(reveal).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(reveal).toHaveBeenCalledTimes(1);
+ cancelNext();
+ });
+ it('keeps the anchor out of layout and renders touch targets in the root overlay', () => {
+ const overlay = readFileSync('src/components/ConnectionNoticeOverlay.tsx', 'utf8');
+ expect(overlay).toContain('anchor: { height: 0 }');
+ expect(overlay).toContain('pointerEvents="box-none" style={styles.layer}');
+ expect(overlay).toContain('context?.publish(id, null)');
+ const root = readFileSync('app/_layout.tsx', 'utf8');
+ expect(root).toContain('<ConnectionNoticeProvider>{body}</ConnectionNoticeProvider>');
+ const banner = readFileSync('src/components/ConnectionBanner.tsx', 'utf8');
+ expect(banner).toContain("useDelayedConnectionNotice(cachedOnly || active, recovery === 'recovered')");
+ expect(banner).toContain('<ConnectionNoticeOverlay>');
+ });
+ it('holds completion for two seconds only after a visible incident and cancels it on a new outage', () => {
+ vi.useFakeTimers();
+ let visible = false;
+ let cancel: (() => void) | undefined;
+ const update = (active: boolean, completed: boolean) => {
+ cancel?.();
+ cancel = updateConnectionNoticeVisibility(active, completed, visible, (next) => { visible = next; });
+ };
+ update(true, false);
+ vi.advanceTimersByTime(500);
+ update(false, true);
+ vi.advanceTimersByTime(2_000);
+ expect(visible).toBe(false);
+ update(true, false);
+ vi.advanceTimersByTime(1_000);
+ expect(visible).toBe(true);
+ update(false, true);
+ vi.advanceTimersByTime(1_999);
+ expect(visible).toBe(true);
+ update(true, false);
+ vi.advanceTimersByTime(2_000);
+ expect(visible).toBe(true);
+ update(false, true);
+ vi.advanceTimersByTime(2_000);
+ expect(visible).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index c35e203eed..db899c934e 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -3,11 +3,118 @@ import { resolve } from 'node:path';
import { describe, expect, it, vi } from 'vitest';
import { i18n } from '@/i18n';
import { startBoundedStartupRead } from '@/session/mobileHomeStartup';
+import { resolveConnectionBannerSyncActionVisibility, resolveHomeConnectionFeedback } from '@/components/connectionBannerVisibility';
+import { describeRemoteError } from '@/device-link/remoteStatus';
function readSource(relativePath: string): string {
return readFileSync(resolve(process.cwd(), relativePath), 'utf8').replace(/\r\n/g, '\n');
}
+describe('mobile Home connection feedback', () => {
+ it('does not offer manual sync for the device-prefixed unresponsive error shown on Home', () => {
+ expect(resolveConnectionBannerSyncActionVisibility({
+ online: true,
+ hasActiveIssue: false,
+ deviceUnresponsive: true,
+ hasRequestError: true,
+ requestErrorAutoRecovering: false,
+ })).toBe(false);
+ });
+
+ it('wires Home itself to the shared recovery indicator instead of an unconditional retry button', () => {
+ const source = readSource('app/devices/index.tsx');
+ expect(source).toContain('resolveHomeConnectionFeedback(error, homeRecoveringDeviceIds, describeRemoteError)');
+ expect(source).toContain('deviceUnresponsive: homeDeviceRecovery,');
+ expect(source).toContain('const showHomeSyncAction = resolveConnectionBannerSyncActionVisibility(');
+ expect(source).toContain('const showConnectionRow = homeRecoveringDeviceIds.size > 0 ||');
+ expect(source).toContain("homeDeviceRecovery ? t(homeDeviceUnresponsive ? 'deviceLink.deviceUnresponsiveTitle' : 'deviceLink.recovery.syncing')");
+ expect(source).toContain("recoveringDeviceIds.has(id) || rawDeviceConnectionStates[id] === 'syncing'");
+ const hydrate = source.slice(source.indexOf('const hydrateDeviceSessions = useCallback('), source.indexOf('const probeRevokedDeviceAccess'));
+ expect(hydrate.indexOf("updateDeviceConnectionState(device.deviceId, 'syncing')")).toBeLessThan(hydrate.indexOf('const promise = hydrateDeviceSessionsOnce('));
+ expect(source).toContain('useDelayedConnectionNotice(showConnectionRow)');
+ const row = source.slice(source.indexOf('{showConnectionNotice ? ('), source.indexOf('<SectionList'));
+ expect(row).toMatch(/showHomeSyncAction\s*\?\s*<Pressable/);
+ const progress = row.slice(row.indexOf(': showHomeRecoveryProgress ?'));
+ expect(progress).toContain('<ConnectionRecoveryProgress');
+ expect(progress).not.toContain('onPress');
+ expect(progress).not.toContain('<Pressable');
+ });
+});
+
+describe('Home recovery completion', () => {
+ const stale = { deviceId: 'a', deviceName: 'MacBook', error: '[DEVICE_UNRESPONSIVE] circuit open' };
+ const recovering = new Set(['a']);
+ const recovered = new Set<string>();
+ it('tracks ordinary failures through same-device and other-device circuit transitions', () => {
+ const failure = { deviceId: 'a', deviceName: 'Same name', error: '[IPC_ERROR] failed' };
+ const other = { deviceId: 'b', deviceName: 'Same name', error: '[REQUEST_TIMEOUT] failed' };
+ for (const [ids, failures, expectedRecovery, expectedError] of [
+ [[], [failure], false, 'Same name: [IPC_ERROR] failed'],
+ [['a'], [failure], true, 'Same name: [IPC_ERROR] failed'],
+ [['a'], [failure, other], false, 'Same name: [REQUEST_TIMEOUT] failed'],
+ [['a', 'b'], [failure, other], true, 'Same name: [IPC_ERROR] failed;Same name: [REQUEST_TIMEOUT] failed'],
+ [['b'], [failure, other], false, 'Same name: [IPC_ERROR] failed'],
+ [[], [failure], false, 'Same name: [IPC_ERROR] failed'],
+ ] as const) {
+ const feedback = resolveHomeConnectionFeedback([...failures], new Set(ids));
+ expect(feedback).toEqual({ error: expectedError, deviceRecovery: expectedRecovery });
+ expect(resolveConnectionBannerSyncActionVisibility({ online: true, hasActiveIssue: false,
+ deviceUnresponsive: feedback.deviceRecovery, hasRequestError: feedback.error !== null,
+ requestErrorAutoRecovering: false,
+ })).toBe(!expectedRecovery);
+ }
+ });
+ it('expires a recovered device marker while another device is still probing', () => {
+ expect(resolveHomeConnectionFeedback(stale, new Set(['b']))).toEqual({ error: null, deviceRecovery: true });
+ });
+ it('keeps page-level errors independent of a device circuit', () => {
+ expect(resolveHomeConnectionFeedback('[NETWORK_UNAVAILABLE] failed', recovering))
+ .toEqual({ error: '[NETWORK_UNAVAILABLE] failed', deviceRecovery: false });
+ });
+ it.each([
+ [true, true, true],
+ [false, true, true],
+ [true, false, false],
+ [false, false, false],
+ ])('keeps mixed-device recovery independent (circuit=%s, manual=%s)', (circuit, manual, canSync) => {
+ const ordinary = { deviceId: 'b', deviceName: 'Other', error: '[REQUEST_TIMEOUT] failed' };
+ const feedback = resolveHomeConnectionFeedback(manual ? [stale, ordinary] : stale, circuit ? recovering : recovered);
+ expect(feedback.error).toBe(manual ? 'Other: [REQUEST_TIMEOUT] failed' : circuit ? 'MacBook: [DEVICE_UNRESPONSIVE] circuit open' : null);
+ expect(feedback.deviceRecovery).toBe(circuit && !manual);
+ expect(resolveConnectionBannerSyncActionVisibility({ online: true, hasActiveIssue: false,
+ deviceUnresponsive: feedback.deviceRecovery, hasRequestError: feedback.error !== null,
+ requestErrorAutoRecovering: false,
+ })).toBe(canSync);
+ });
+ it('shows background recovery even without a stored request error', () => {
+ expect(resolveHomeConnectionFeedback(null, recovering)).toEqual({ error: null, deviceRecovery: true });
+ });
+ it('clears the stale circuit error once probing succeeds', () => {
+ expect(resolveHomeConnectionFeedback(stale, recovering).error).toBe('MacBook: [DEVICE_UNRESPONSIVE] circuit open');
+ expect(resolveHomeConnectionFeedback(stale, recovered).error).toBeNull();
+ });
+ it('preserves a different device failure in the joined error', () => {
+ expect(resolveHomeConnectionFeedback([stale, { deviceId: 'b', deviceName: 'Other', error: 'denied' }], recovered).error).toBe('Other: denied');
+ });
+ it.each(['REQUEST_TIMEOUT', 'NETWORK_UNAVAILABLE'])('keeps manual retry after %s exhausts bounded retries', (code) => {
+ const error = resolveHomeConnectionFeedback(`[${code}] failed`, recovered).error;
+ expect(resolveConnectionBannerSyncActionVisibility({ online: true, hasActiveIssue: false,
+ deviceUnresponsive: false, hasRequestError: error !== null, requestErrorAutoRecovering: false,
+ })).toBe(true);
+ });
+ it.each(['DEVICE_UNRESPONSIVE', '[DEVICE_UNRESPONSIVE]', 'Mac: [DEVICE_UNRESPONSIVE];Other'])('never classifies the device name %s as an error code', (deviceName) => {
+ const ordinary = { deviceId: 'b', deviceName, error: '[REQUEST_TIMEOUT] failed' };
+ for (const ids of [recovered, recovering]) {
+ const feedback = resolveHomeConnectionFeedback([stale, ordinary], ids, describeRemoteError);
+ expect(feedback.error).toBe(`${deviceName}: ${describeRemoteError(ordinary.error)}`);
+ expect(feedback.deviceRecovery).toBe(false);
+ }
+ });
+ it('classifies all failures before limiting display to two entries', () => {
+ expect(resolveHomeConnectionFeedback([stale, stale, { deviceId: 'c', deviceName: 'Third', error: 'denied' }], recovering).error).toBe('Third: denied');
+ });
+});
+
describe('mobile Home startup reads', () => {
it('returns the local value when the read settles in time', async () => {
const read = startBoundedStartupRead(Promise.resolve('cached'), 'fallback', 100);
@@ -390,8 +497,9 @@ describe('mobile home desktop-first surface', () => {
expect(source).toContain("updateDeviceConnectionState(device.deviceId, 'failed');");
expect(source).toContain("updateDeviceConnectionState(device.deviceId, 'idle');");
expect(source).toContain(
- "const showConnectionRow = selectedDeviceDisconnected || !!connectionError || status !== 'online' || connectionIssue?.kind === 'unstable';",
+ "const showConnectionRow = homeRecoveringDeviceIds.size > 0 || selectedDeviceDisconnected || !!connectionError || status !== 'online' || connectionIssue?.kind === 'unstable';",
);
+ expect(source).toContain('homeSyncDeviceIds.filter((id) => unresponsiveDevices.has(id)');
expect(source).toContain("connectionStates={deviceConnectionStates}");
expect(source).toContain('function DeviceMenuItem');
expect(source).toContain("tone={status === 'online' ? 'ready' : 'off'}");
diff --git a/apps/mobile/src/__tests__/peerRecoveryScheduler.test.ts b/apps/mobile/src/__tests__/peerRecoveryScheduler.test.ts
index 4f75e2c36d..6e034975e1 100644
--- a/apps/mobile/src/__tests__/peerRecoveryScheduler.test.ts
+++ b/apps/mobile/src/__tests__/peerRecoveryScheduler.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
+import { resolveHomeConnectionFeedback } from '@/components/connectionBannerVisibility';
import {
PeerRecoveryOpenIntentRegistry,
PeerRecoveryScheduler,
@@ -18,6 +19,71 @@ async function flush(): Promise<void> {
}
describe('PeerRecoveryScheduler', () => {
+ it('hands recovery off to queued Home hydration without exposing the old manual failure', async () => {
+ const subscribed = deferred<void>();
+ const syncing = new Set<string>();
+ const scheduler = new PeerRecoveryScheduler(async (id) => {
+ await subscribed.promise;
+ // Home reseed marks syncing before its limiter starts the snapshot reads.
+ syncing.add(id);
+ return { retry: false };
+ });
+ const failure = { deviceId: 'a', deviceName: 'Mac', error: '[INVOKE_TIMEOUT] failed' };
+ const feedback = () => resolveHomeConnectionFeedback(failure, new Set([...scheduler.getActiveDeviceIds(), ...syncing]));
+ scheduler.request('a');
+ expect(feedback().deviceRecovery).toBe(true);
+ subscribed.resolve();
+ await flush();
+ expect(scheduler.getActiveDeviceIds().size).toBe(0);
+ expect(feedback().deviceRecovery).toBe(true);
+ syncing.delete('a');
+ // A failed hydrate may retain the ordinary error; only now is manual retry available.
+ expect(feedback().deviceRecovery).toBe(false);
+ expect(resolveHomeConnectionFeedback(null, syncing).error).toBeNull();
+ });
+ it('publishes stable active snapshots across queue, retry, completion and cancellation', async () => {
+ vi.useFakeTimers();
+ try {
+ const first = deferred<{ retry: boolean }>();
+ const scheduler = new PeerRecoveryScheduler(() => first.promise, { maxConcurrent: 1 });
+ const changed = vi.fn();
+ const off = scheduler.subscribe(changed);
+ const initial = scheduler.getActiveDeviceIds();
+ scheduler.requestMany(['a', 'b']);
+ expect([...scheduler.getActiveDeviceIds()]).toEqual(['a', 'b']);
+ expect(initial.size).toBe(0);
+ const active = scheduler.getActiveDeviceIds();
+ first.resolve({ retry: true });
+ await flush();
+ expect(scheduler.getActiveDeviceIds()).toBe(active);
+ scheduler.cancel('a');
+ expect([...scheduler.getActiveDeviceIds()]).toEqual(['b']);
+ scheduler.pause();
+ expect(scheduler.getActiveDeviceIds().size).toBe(0);
+ const calls = changed.mock.calls.length;
+ off();
+ scheduler.clear();
+ expect(changed).toHaveBeenCalledTimes(calls);
+ } finally { vi.useRealTimers(); }
+ });
+
+ it('keeps a re-request visible while a cancelled generation settles', async () => {
+ const old = deferred<{ retry: boolean }>();
+ const next = deferred<{ retry: boolean }>();
+ const run = vi.fn().mockReturnValueOnce(old.promise).mockReturnValueOnce(next.promise);
+ const scheduler = new PeerRecoveryScheduler(run);
+ scheduler.request('a');
+ scheduler.cancel('a');
+ expect(scheduler.getActiveDeviceIds().size).toBe(0);
+ scheduler.request('a');
+ expect(scheduler.getActiveDeviceIds().has('a')).toBe(true);
+ old.resolve({ retry: false });
+ await flush();
+ expect(scheduler.getActiveDeviceIds().has('a')).toBe(true);
+ next.resolve({ retry: false });
+ await flush();
+ expect(scheduler.getActiveDeviceIds().size).toBe(0);
+ });
it('does not let an old forced-open completion clear a newer intent for the same peer', () => {
const intents = new PeerRecoveryOpenIntentRegistry();
const first = intents.request('desktop-a');
diff --git a/apps/mobile/src/components/ConnectionBanner.tsx b/apps/mobile/src/components/ConnectionBanner.tsx
index 1830b74392..fab1c0bac2 100644
--- a/apps/mobile/src/components/ConnectionBanner.tsx
+++ b/apps/mobile/src/components/ConnectionBanner.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react';
+import { ConnectionNoticeOverlay, useDelayedConnectionNotice } from './ConnectionNoticeOverlay';
import { ActivityIndicator, StyleSheet, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { LoaderCircle } from 'lucide-react-native';
@@ -22,18 +22,8 @@ import {
import { fontWeight, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { iconSize, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
-/** 普通断线(无分类 issue)转为可见提示前的静默窗口:健康重连通常 <1s 完成,不闪 banner。 */
-const OFFLINE_BANNER_DELAY_MS = 1_200;
-
-/**
- * 条件挂载 ConnectionBanner 的统一可见性判定:
- * - 请求级 error / 可分类连接问题(鉴权失效、被顶号等)→ 立即显示;
- * - 当前关联设备熔断 open(电脑端未响应,relay 可能仍 online)→ 立即显示;
- * - 普通弱网断线(status 非 online 且无分类 issue)→ 持续超过静默窗口才显示,
- * 既让用户看得到「正在重连」(否则消息流静默停更没有任何信号),又不因
- * 一次快速重连闪一下布局(规则 7:杜绝跳变)。
- * 判定核在 resolveConnectionBannerVisibility(纯函数,单测覆盖)。
- */
+/** Eligibility only. ConnectionBanner owns the shared one-second display delay,
+ * including screens that mount the component unconditionally. */
export function useShowConnectionBanner(
status: DeviceLinkStatus,
error: string | null,
@@ -42,20 +32,9 @@ export function useShowConnectionBanner(
recovery?: 'syncing' | 'recovered',
): boolean {
const offline = status !== 'online' || recovery === 'syncing';
- const showRecovered = recovery !== undefined;
- const [offlineLongEnough, setOfflineLongEnough] = useState(false);
- useEffect(() => {
- if (!offline) {
- if (!showRecovered) { setOfflineLongEnough(false); return; }
- const timer = setTimeout(() => setOfflineLongEnough(false), 2_000);
- return () => clearTimeout(timer);
- }
- const timer = setTimeout(() => setOfflineLongEnough(true), OFFLINE_BANNER_DELAY_MS);
- return () => clearTimeout(timer);
- }, [offline, showRecovered]);
- return (recovery === 'recovered' && offlineLongEnough) || resolveConnectionBannerVisibility({
+ return recovery === 'recovered' || resolveConnectionBannerVisibility({
offline,
- offlineLongEnough,
+ offlineLongEnough: true,
// 熔断已关后屏幕残留的 DEVICE_UNRESPONSIVE 错误按陈旧丢弃(review P1),
// 否则恢复后 banner 会带着"自动重试中"文案常驻到用户手动同步。
hasError: Boolean(resolveEffectiveConnectionError(error, deviceUnresponsive)),
@@ -96,9 +75,9 @@ export function ConnectionBanner({
cachedOnly?: boolean;
}) {
const styles = useThemedStyles(makeStyles);
- const { colors } = useTheme();
- const reduceMotion = useReduceMotionEnabled();
const { t } = useTranslation();
+ const active = useShowConnectionBanner(status, error, issue, deviceUnresponsive, recovery === 'recovered' ? undefined : recovery);
+ const visible = useDelayedConnectionNotice(cachedOnly || active, recovery === 'recovered');
// 链路已 online 说明普通 issue 已过期;unstable 描述跨连接抖动,online 时仍展示。
// issue 优先于请求级 error:链路断因明确时,invoke 失败都是它的下游症状(NOT_CONNECTED)。
const activeIssue = status !== 'online' || issue?.kind === 'unstable' ? issue : null;
@@ -142,7 +121,9 @@ export function ConnectionBanner({
? t('deviceLink.deviceUnresponsiveHint')
: friendlyError ?? (status === 'online' && recovery === 'syncing'
? t('deviceLink.recovery.syncingHint') : relayStatusHint(status, lastSyncedAt));
+ if (!visible) return null;
return (
+ <ConnectionNoticeOverlay>
<View
style={[
styles.root,
@@ -180,25 +161,35 @@ export function ConnectionBanner({
onPress={onSync}
testID="connection.syncButton"
/>
- ) : showRecoveryProgress ? reduceMotion === false ? (
- <ActivityIndicator
- accessibilityLabel={`${title} · ${copy}`}
- color={colors.textSecondary}
- size="small"
- testID="connection.recoveryProgress"
- />
- ) : (
- <LoaderCircle
- accessibilityLabel={`${title} · ${copy}`}
- color={colors.textSecondary}
- size={iconSize.action}
- testID="connection.recoveryProgressStatic"
- />
+ ) : showRecoveryProgress ? (
+ <ConnectionRecoveryProgress />
) : null}
</View>
+ </ConnectionNoticeOverlay>
);
}
+/** Shared by the Home connection row and detail banners; never a press target. */
+export function ConnectionRecoveryProgress() {
+ const { colors } = useTheme();
+ const reduceMotion = useReduceMotionEnabled();
+ return <View accessible={false} accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
+ {reduceMotion === false ? (
+ <ActivityIndicator
+ color={colors.textSecondary}
+ size="small"
+ testID="connection.recoveryProgress"
+ />
+ ) : (
+ <LoaderCircle
+ color={colors.textSecondary}
+ size={iconSize.action}
+ testID="connection.recoveryProgressStatic"
+ />
+ )}
+ </View>;
+}
+
function ConnectionSyncButton({
compact,
loading,
@@ -230,6 +221,10 @@ function ConnectionSyncButton({
const makeStyles = (colors: ThemeColors) => StyleSheet.create({
root: {
+ backgroundColor: colors.surfaceElevated,
+ borderRadius: radius.container,
+ borderColor: colors.border,
+ borderWidth: StyleSheet.hairlineWidth,
alignItems: 'center',
borderBottomColor: colors.border,
borderBottomWidth: StyleSheet.hairlineWidth,
@@ -248,8 +243,6 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
borderColor: colors.border,
borderRadius: radius.container,
borderWidth: StyleSheet.hairlineWidth,
- marginHorizontal: spacing.lg,
- marginTop: spacing.sm,
minHeight: 42,
paddingHorizontal: spacing.md,
},
diff --git a/apps/mobile/src/components/ConnectionNoticeOverlay.tsx b/apps/mobile/src/components/ConnectionNoticeOverlay.tsx
new file mode 100644
index 0000000000..379e978bca
--- /dev/null
+++ b/apps/mobile/src/components/ConnectionNoticeOverlay.tsx
@@ -0,0 +1,71 @@
+import { createContext, useCallback, useContext, useEffect, useId, useMemo, useRef, useState, type ReactNode, type RefObject } from 'react';
+import { StyleSheet, View, useWindowDimensions } from 'react-native';
+import { useFocusEffect } from 'expo-router';
+import { spacing } from '@/theme/tokens';
+import { updateConnectionNoticeVisibility } from './connectionNoticeDelay';
+
+/** Each continuous incident gets one delay; clearing it cancels pending display. */
+export function useDelayedConnectionNotice(active: boolean, completed = false): boolean {
+ const [ready, setReady] = useState(false);
+ useEffect(() => {
+ return updateConnectionNoticeVisibility(active, completed, ready, setReady);
+ }, [active, completed, ready]);
+ return (active || completed) && ready;
+}
+
+type Notice = { top: number; children: ReactNode };
+const NoticeContext = createContext<{ publish: (id: string, notice: Notice | null) => void; host: RefObject<View | null> } | null>(null);
+
+/** Render outside clipped headers, with real touch bounds and no modal input capture. */
+export function ConnectionNoticeProvider({ children }: { children: ReactNode }) {
+ const host = useRef<View>(null);
+ const [notices, setNotices] = useState(new Map<string, Notice>());
+ const publish = useCallback((id: string, notice: Notice | null) => {
+ setNotices((current) => {
+ if (!notice && !current.has(id)) return current;
+ const next = new Map(current);
+ if (notice) next.set(id, notice); else next.delete(id);
+ return next;
+ });
+ }, []);
+ const value = useMemo(() => ({ publish, host }), [publish]);
+ return <NoticeContext.Provider value={value}>
+ <View ref={host} collapsable={false} style={styles.host}>
+ {children}
+ <View pointerEvents="box-none" style={styles.layer}>
+ {[...notices].map(([id, notice]) => <View key={id} style={[styles.overlay, { top: notice.top }]}>{notice.children}</View>)}
+ </View>
+ </View>
+ </NoticeContext.Provider>;
+}
+
+/** Only the zero-height measuring anchor participates in the screen layout. */
+export function ConnectionNoticeOverlay({ children }: { children: ReactNode }) {
+ const context = useContext(NoticeContext);
+ const id = useId();
+ const anchor = useRef<View>(null);
+ const [top, setTop] = useState<number | null>(null);
+ const [focused, setFocused] = useState(false);
+ useFocusEffect(useCallback(() => {
+ setFocused(true);
+ return () => setFocused(false);
+ }, []));
+ const { width, height } = useWindowDimensions();
+ const measure = useCallback(() => {
+ if (context?.host.current) anchor.current?.measureLayout(context.host.current, (_x, y) => setTop(y + spacing.sm));
+ }, [context]);
+ useEffect(() => { measure(); }, [measure, width, height, focused]);
+ useEffect(() => {
+ if (focused && top !== null) context?.publish(id, { top, children });
+ else context?.publish(id, null);
+ return () => context?.publish(id, null);
+ }, [children, focused, id, context, top]);
+ return <View ref={anchor} collapsable={false} pointerEvents="none" onLayout={measure} style={styles.anchor} />;
+}
+
+const styles = StyleSheet.create({
+ host: { flex: 1 },
+ layer: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, zIndex: 20 },
+ anchor: { height: 0 },
+ overlay: { position: 'absolute', left: spacing.md, right: spacing.md },
+});
diff --git a/apps/mobile/src/components/connectionBannerVisibility.ts b/apps/mobile/src/components/connectionBannerVisibility.ts
index 3583dfb27c..2c89799d80 100644
--- a/apps/mobile/src/components/connectionBannerVisibility.ts
+++ b/apps/mobile/src/components/connectionBannerVisibility.ts
@@ -50,6 +50,31 @@ export function resolveConnectionBannerSyncActionVisibility(input: {
* (banner 的 unresponsive 分支优先,error 本就不会被展示)。
* hook 与组件都要用同一份结果,否则会出现「可见但无内容可渲染」的空壳。
*/
+export type HomeDeviceFailure = { deviceId: string; deviceName: string; error: string };
+export type HomeConnectionError = string | HomeDeviceFailure | HomeDeviceFailure[] | null;
+
+/** A recovering device must not mask another device's actionable failure on Home. */
+export function resolveHomeConnectionFeedback(
+ error: HomeConnectionError,
+ recoveringDeviceIds: ReadonlySet<string>,
+ describe: (error: string) => string | null = (error) => error,
+) {
+ const failures = error === null ? [] : typeof error === 'string'
+ ? [{ deviceId: '', deviceName: '', error }] : Array.isArray(error) ? error : [error];
+ // Classify only the raw error's leading code, before adding user-controlled names.
+ const manualFailures = failures.filter((failure) => !recoveringDeviceIds.has(failure.deviceId)
+ && !/^\[DEVICE_UNRESPONSIVE\](?:\s|$)/.test(failure.error));
+ const effectiveFailures = manualFailures.length > 0 ? manualFailures
+ : failures.filter((failure) => recoveringDeviceIds.has(failure.deviceId));
+ return {
+ error: effectiveFailures.slice(0, 2).map((failure) => {
+ const message = describe(failure.error);
+ return failure.deviceName ? `${failure.deviceName}: ${message}` : message;
+ }).join(';') || null,
+ deviceRecovery: recoveringDeviceIds.size > 0 && manualFailures.length === 0,
+ };
+}
+
export function resolveEffectiveConnectionError(
error: string | null,
deviceUnresponsive: boolean,
diff --git a/apps/mobile/src/components/connectionNoticeDelay.ts b/apps/mobile/src/components/connectionNoticeDelay.ts
new file mode 100644
index 0000000000..10a53cb838
--- /dev/null
+++ b/apps/mobile/src/components/connectionNoticeDelay.ts
@@ -0,0 +1,22 @@
+export const CONNECTION_NOTICE_DELAY_MS = 1_000;
+
+/** Cancelling on recovery or unmount prevents brief incidents from flashing a notice. */
+export function scheduleConnectionNotice(reveal: () => void): () => void {
+ const timer = setTimeout(reveal, CONNECTION_NOTICE_DELAY_MS);
+ return () => clearTimeout(timer);
+}
+
+/** Completion may linger only if the preceding incident was already visible. */
+export function updateConnectionNoticeVisibility(
+ active: boolean,
+ completed: boolean,
+ visible: boolean,
+ setVisible: (visible: boolean) => void,
+): (() => void) | undefined {
+ if (active) return visible ? undefined : scheduleConnectionNotice(() => setVisible(true));
+ if (completed && visible) {
+ const timer = setTimeout(() => setVisible(false), 2_000);
+ return () => clearTimeout(timer);
+ }
+ setVisible(false);
+}
diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.ts
index 6f824e452c..88a7b76f49 100644
--- a/apps/mobile/src/debug/visualMock.ts
+++ b/apps/mobile/src/debug/visualMock.ts
@@ -151,6 +151,7 @@ export function createVisualMockDeviceLinkContext(): DeviceLinkContextValue {
?? (MOBILE_VISUAL_MOCK_REALDATA_URL ? VISUAL_MOCK_REALDATA_DEVICE_NAME : VISUAL_MOCK_DEVICE_NAME);
return {
status: 'online',
+ recoveringDeviceIds: new Set(),
readDeviceList: async () => ({ devices: visualMockDevices() }),
connectionIssue: null,
presenceVersion: 1,
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 4b3d064de1..5d7e991374 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -30,7 +30,7 @@ import {
type RemoteResourceChangedPayload,
type Topic,
} from '@cindy/device-link';
-import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';
import { deviceLinkWsUrl, DEVICE_LINK_API_BASE_URL } from '@/config/env';
import { MOBILE_VISUAL_MOCK_ENABLED } from '@/config/env';
import { useAuth } from '@/auth/AuthContext';
@@ -151,6 +151,8 @@ import { createVisualMockDeviceLinkContext, seedVisualMockStore } from '@/debug/
export interface DeviceLinkContextValue {
status: DeviceLinkStatus;
+ /** Peers with queued, running, or retrying recovery work. Read-only UI projection. */
+ recoveringDeviceIds: ReadonlySet<string>;
/** 连接层可分类的失败原因(鉴权失效/被顶号/超限/版本不符);null = 无异常 */
connectionIssue: DeviceLinkConnectionIssue | null;
presenceVersion: number;
@@ -351,6 +353,10 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
},
);
}
+ const recoveringDeviceIds = useSyncExternalStore(
+ peerRecoverySchedulerRef.current.subscribe,
+ peerRecoverySchedulerRef.current.getActiveDeviceIds,
+ );
const presenceWipeTimersRef = useRef(
new Map<string, PresenceWipeTimerEntry>(),
);
@@ -1345,6 +1351,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const value = useMemo<DeviceLinkContextValue>(() => ({
status,
+ recoveringDeviceIds,
connectionIssue,
presenceVersion,
connectionEpoch,
@@ -1362,6 +1369,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
onRemoteResourceChanged: subscribeRemoteResourceChanged,
}), [
closeLink,
+ recoveringDeviceIds,
connectionEpoch,
connectionIssue,
getPresenceAvailability,
diff --git a/apps/mobile/src/device-link/peerRecoveryScheduler.ts b/apps/mobile/src/device-link/peerRecoveryScheduler.ts
index efe8565e96..f8687b2f67 100644
--- a/apps/mobile/src/device-link/peerRecoveryScheduler.ts
+++ b/apps/mobile/src/device-link/peerRecoveryScheduler.ts
@@ -93,6 +93,28 @@ export class PeerRecoveryScheduler {
private readonly queued = new Set<string>();
private active = 0;
private paused = false;
+ private activeDeviceIds: ReadonlySet<string> = new Set();
+ private readonly listeners = new Set<() => void>();
+
+ /** Cached read-only UI projection; it never schedules recovery work. */
+ getActiveDeviceIds = (): ReadonlySet<string> => this.activeDeviceIds;
+
+ subscribe = (listener: () => void): (() => void) => {
+ this.listeners.add(listener);
+ return () => { this.listeners.delete(listener); };
+ };
+
+ private publishActiveDeviceIds(): void {
+ const next = new Set<string>();
+ for (const [deviceId, entry] of this.entries) {
+ if (entry.phase !== 'idle' || entry.rerun) next.add(deviceId);
+ }
+ if (next.size === this.activeDeviceIds.size && [...next].every((id) => this.activeDeviceIds.has(id))) return;
+ this.activeDeviceIds = next;
+ for (const listener of this.listeners) {
+ try { listener(); } catch { /* UI observers must not affect recovery scheduling. */ }
+ }
+ }
constructor(
run: (deviceId: string) => Promise<PeerRecoveryResult>,
@@ -125,6 +147,7 @@ export class PeerRecoveryScheduler {
// serialized behind it so one peer never has two recovery runs in flight.
if (entry.running) {
entry.rerun = true;
+ this.publishActiveDeviceIds();
return;
}
this.enqueue(deviceId, entry);
@@ -150,6 +173,7 @@ export class PeerRecoveryScheduler {
if (index >= 0) this.queue.splice(index, 1);
}
entry.phase = 'idle';
+ this.publishActiveDeviceIds();
}
/**
@@ -215,6 +239,7 @@ export class PeerRecoveryScheduler {
entry.phase = 'queued';
this.queued.add(deviceId);
this.queue.push(deviceId);
+ this.publishActiveDeviceIds();
this.drain();
}
@@ -292,6 +317,7 @@ export class PeerRecoveryScheduler {
this.enqueue(deviceId, entry);
}
this.drain();
+ this.publishActiveDeviceIds();
}
}