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): 普通同步使用延迟标题动画,异常保留悬浮提示 (#4191)

Dashe80bfccabed2
diff --git a/apps/mobile/app/automations/[deviceId].tsx b/apps/mobile/app/automations/[deviceId].tsx
index fe22f9568e..ae8ffe0cb1 100644
--- a/apps/mobile/app/automations/[deviceId].tsx
+++ b/apps/mobile/app/automations/[deviceId].tsx
@@ -14,7 +14,7 @@ import { SafeAreaView } from 'react-native-safe-area-context';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
import { mobilePresentationLocalizer } from '@/i18n/presentationLocalizer';
-import { ConnectionBanner } from '@/components/ConnectionBanner';
+import { ConnectionBanner, useShowConnectionBanner } from '@/components/ConnectionBanner';
import { useUnresponsiveDevices } from '@/device-link/unresponsiveDevicesStore';
import { goBackGuarded } from '@/utils/backGuard';
import {
@@ -802,9 +802,11 @@ export default function AutomationsScreen() {
}
}, [busyAction, deviceId, maker, openLink, subscribe, syncRuns]);
+ const showConnectionBanner = useShowConnectionBanner(status, error, connectionIssue, deviceUnresponsive);
return (
<SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.safeArea} testID="automations.screen">
<SimpleStackHeader
+ syncing={!showConnectionBanner && (loading || runsLoading || status === 'connecting')}
action={{
label: t('devices.common.create'),
onPress: busyAction ? undefined : startCreateSchedule,
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsx
index 7cf9221fa7..65142151ff 100644
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@ -665,6 +665,7 @@ function DeviceDetailScreenContent() {
return (
<SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.safeArea} testID="deviceDetail.screen">
<SimpleStackHeader
+ syncing={!showConnectionBanner && (loading || status === 'connecting')}
backTestID="deviceDetail.backButton"
eyebrow={t('devices.detail.automationScope.eyebrow')}
onBack={() => goBackGuarded(router)}
@@ -729,6 +730,7 @@ function DeviceDetailScreenContent() {
return (
<SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.safeArea} testID="deviceDetail.screen">
<SimpleStackHeader
+ syncing={!showConnectionBanner && (loading || status === 'connecting')}
action={{
label: t('devices.common.create'),
// 在这个项目里建新对话:预填 workingDir。
@@ -851,6 +853,7 @@ function DeviceDetailScreenContent() {
return (
<SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.safeArea} testID="deviceDetail.screen">
<SimpleStackHeader
+ syncing={!showConnectionBanner && (loading || status === 'connecting')}
action={{
label: t('devices.common.create'),
onPress: () => guardedPush({
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index a39cbee20b..c9a88dd4e5 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -115,7 +115,8 @@ import {
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 { resolveConnectionBannerVisibility, resolveConnectionBannerSyncActionVisibility, resolveHomeConnectionFeedback, type HomeConnectionError, type HomeDeviceFailure } from '@/components/connectionBannerVisibility';
+import { QuietSyncIndicator } from '@/components/QuietSyncIndicator';
import { runIndependentSnapshotReads } from '@/device-link/sessionSnapshotSingleFlight';
import { revokedDevicesStore, useRevokedDevices } from '@/device-link/revokedDevicesStore';
import { useUnresponsiveDevices } from '@/device-link/unresponsiveDevicesStore';
@@ -1844,12 +1845,21 @@ function HomeScreenContent() {
}, [home.deviceFilters, home.selectedDeviceId, initialHomeSettled, selectedDeviceId]);
// 连接层失败原因比请求级 error 更根因:unstable 在 online 时也需保持可见。
const activeConnectionIssue = status !== 'online' || connectionIssue?.kind === 'unstable' ? connectionIssue : null;
- const selectedDeviceDisconnected = home.deviceFilters.some((item) => item.deviceId !== null
+ const selectedDeviceDisconnected = status !== 'connecting' && home.deviceFilters.some((item) => item.deviceId !== null
&& (!selectedDeviceId || item.deviceId === selectedDeviceId) && item.sessionCount > 0)
&& !home.deviceFilters.some((item) => item.deviceId !== null
&& (!selectedDeviceId || item.deviceId === selectedDeviceId) && item.available);
- const showConnectionRow = homeRecoveringDeviceIds.size > 0 || selectedDeviceDisconnected || !!connectionError || status !== 'online' || connectionIssue?.kind === 'unstable';
+ const showConnectionRow = selectedDeviceDisconnected || resolveConnectionBannerVisibility({
+ offline: status !== 'online',
+ connecting: status === 'connecting',
+ offlineLongEnough: true,
+ hasError: !!connectionError,
+ hasIssue: activeConnectionIssue !== null,
+ hasUnstableIssue: activeConnectionIssue?.kind === 'unstable',
+ deviceUnresponsive: homeDeviceUnresponsive,
+ });
const showConnectionNotice = useDelayedConnectionNotice(showConnectionRow);
+ const quietSyncing = !showConnectionRow && (refreshing || homeRecoveringDeviceIds.size > 0 || status === 'connecting');
const showHomeSyncAction = resolveConnectionBannerSyncActionVisibility({
online: status === 'online',
hasActiveIssue: activeConnectionIssue !== null,
@@ -2458,6 +2468,7 @@ function HomeScreenContent() {
>
{nativeHomeHeader ? (
<HomeNativeStackHeader
+ syncing={quietSyncing}
displayA11y={t('devices.list.a11y.openDisplaySettings')}
displayActions={homeDisplayPullDownActions}
menuA11y={t('devices.list.a11y.openMenu')}
@@ -2515,6 +2526,7 @@ function HomeScreenContent() {
<View style={styles.headerTitleCluster}>
<Text style={styles.headerTitle} numberOfLines={1}>{selectedDeviceLabel}</Text>
<ChevronDown color={colors.textSecondary} size={iconSize.xs} strokeWidth={iconStroke.medium} />
+ <QuietSyncIndicator active={quietSyncing} />
</View>
</Pressable>
</NativePullDownMenu>
diff --git a/apps/mobile/app/files/[sessionId].tsx b/apps/mobile/app/files/[sessionId].tsx
index a3992da5fe..7255e04068 100644
--- a/apps/mobile/app/files/[sessionId].tsx
+++ b/apps/mobile/app/files/[sessionId].tsx
@@ -49,6 +49,7 @@ import { SafeAreaView } from 'react-native-safe-area-context';
import { Text, TextInput } from '@/components/AppText';
import { ScreenBackButton } from '@/components/MobilePrimitives';
import { ConnectionBanner, useShowConnectionBanner } from '@/components/ConnectionBanner';
+import { QuietSyncIndicator } from '@/components/QuietSyncIndicator';
import { useUnresponsiveDevices } from '@/device-link/unresponsiveDevicesStore';
import { goBackGuarded } from '@/utils/backGuard';
import { useAuth } from '@/auth/AuthContext';
@@ -759,6 +760,7 @@ export default function RemoteFileBrowserScreen() {
<View style={styles.titleChevronChip}>
<ChevronDown color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
</View>
+ <QuietSyncIndicator active={!showConnectionBanner && (loading || status === 'connecting')} />
</Pressable>
<Pressable
accessibilityLabel={t('files.browser.a11ySearch')}
@@ -786,7 +788,6 @@ export default function RemoteFileBrowserScreen() {
<Text numberOfLines={1} style={styles.sectionLabel}>
{deviceName}{isRoot ? t('files.browser.workdirSuffix') : ''}
</Text>
- {loading && !refreshing ? <ActivityIndicator color={colors.textTertiary} size="small" /> : null}
</View>
) : null}
@@ -1500,6 +1501,8 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
minWidth: 0,
},
title: {
+ flexShrink: 1,
+ minWidth: 0,
color: colors.textPrimary,
fontSize: typeScale.body,
fontWeight: fontWeight.semibold,
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 647156d527..dbc002d49e 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -80,6 +80,8 @@ import { useGuardedBack } from '@/utils/useGuardedBack';
import { useGuardedPush } from '@/utils/useGuardedPush';
import { DEVICE_LINK_API_BASE_URL, MOBILE_VISUAL_MOCK_ENABLED } from '@/config/env';
import { ConnectionBanner, useShowConnectionBanner } from '@/components/ConnectionBanner';
+import { QuietSyncIndicator } from '@/components/QuietSyncIndicator';
+import { hasSessionEntryPreviewMismatch } from '@/session/sessionEntrySyncIndicator';
import { resolveEffectiveConnectionError } from '@/components/connectionBannerVisibility';
import { PaperPlaneIcon } from '@/components/PaperPlaneIcon';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
@@ -1024,6 +1026,9 @@ export default function SessionScreen() {
const unresponsiveDevices = useUnresponsiveDevices();
const maker = useMobileMakerTransport(deviceId);
const remoteHistoryAvailable = status === 'online' && getPresenceAvailability(deviceId) === true;
+ // Unknown presence while connecting is loading, not evidence of a lost computer.
+ const showCachedHistoryNotice = status !== 'connecting'
+ && (status !== 'online' || getPresenceAvailability(deviceId) === false);
const historyView = useRemoteHistoryView(deviceId, sessionId, maker,
() => messageScreenFocusedRef.current && messageAppActiveRef.current, remoteHistoryAvailable);
useEffect(() => {
@@ -2070,7 +2075,6 @@ export default function SessionScreen() {
bannerError,
connectionIssue,
isDeviceUnresponsive,
- contentRecoveryState,
);
const hasCurrentSession = currentSession !== null;
const currentAgentKind = useMemo(
@@ -4263,9 +4267,16 @@ export default function SessionScreen() {
prefix: renderWindow.prefix,
};
}, [renderItems, renderWindow.prefix, sessionId]);
- // 后台静默刷新:仅在首次加载、还没有任何内容(messages 为空)时显示"正在同步";已有内容
- // (重开已看过的会话,messages 还在内存)时后台对账一律静默,不再弹同步提示打扰用户。
- const showSyncingIndicator = loading && !hasRenderedMessages;
+ // Known stale entry content bypasses the quiet delay; routine sync stays subtle.
+ const showSyncingIndicator = !showConnectionBanner && !showCachedHistoryNotice
+ && (loading || historyView.snapshot.loading || status === 'connecting' || contentRecoveryState === 'syncing');
+ const showSyncingImmediately = showSyncingIndicator && hasSessionEntryPreviewMismatch(
+ sessionId,
+ remoteSessionStore.getSessionMessagePreview(sessionId),
+ currentSession?.preview,
+ messages,
+ historyView.snapshot,
+ );
const diffCount = renderWindow.diffCount;
const searchHits = useMemo(
() => searchOpen && searchQuery.trim()
@@ -8805,6 +8816,7 @@ export default function SessionScreen() {
<ShareSelectAllButton busy={conversationShareBusy} shareableIds={allShareableIds} />
) : undefined}
syncing={showSyncingIndicator}
+ syncingImmediately={showSyncingImmediately}
messageCount={Math.max(messages.length, currentSession?._count?.messages ?? 0)}
messageOnly={sessionManagedByHost}
onBack={goBackToHome}
@@ -8845,10 +8857,10 @@ export default function SessionScreen() {
|| (connectionError ? t('session.screen.sessionNotSynced') : (deviceName || t('session.screen.conversationFallback')))}
/>
- {showConnectionBanner || !remoteHistoryAvailable ? (
+ {showConnectionBanner || showCachedHistoryNotice ? (
<ConnectionBanner
density="compact"
- cachedOnly={!remoteHistoryAvailable}
+ cachedOnly={showCachedHistoryNotice}
deviceUnresponsive={isDeviceUnresponsive}
error={bannerError}
requestErrorAutoRecovering={bannerRetriesHistory ? false : undefined}
@@ -9600,6 +9612,7 @@ function SessionHeaderBar({
shareSelectionLeadingInset,
shareSelectAllNode,
syncing,
+ syncingImmediately,
messageCount,
messageOnly,
onBack,
@@ -9626,6 +9639,7 @@ function SessionHeaderBar({
/** 分享选择模式下替换头部动作区。 */
shareSelectAllNode?: ReactNode;
syncing: boolean;
+ syncingImmediately: boolean;
messageCount: number;
/** Host-managed canonical Sessions expose conversation controls only. */
messageOnly: boolean;
@@ -9678,7 +9692,6 @@ function SessionHeaderBar({
} satisfies Record<SessionActionStripActionId, () => void>;
const notice = compactSessionHeaderNotice({
isDeviceAccessRevoked,
- syncing,
pendingCount,
queuePaused,
readOnlyReason,
@@ -9734,6 +9747,7 @@ function SessionHeaderBar({
<Text numberOfLines={1} style={styles.sessionHeaderTitle} testID="session.title">
{title}
</Text>
+ <QuietSyncIndicator active={syncing} immediate={syncingImmediately} />
</View>
{notice ? (
<Text numberOfLines={1} style={styles.sessionHeaderNotice} testID="session.headerNotice">
@@ -9838,22 +9852,19 @@ function sessionHeaderActionIcon(actionId: SessionActionStripActionId): SessionH
function compactSessionHeaderNotice({
isDeviceAccessRevoked,
- syncing,
pendingCount,
queuePaused,
readOnlyReason,
session,
}: {
isDeviceAccessRevoked: boolean;
- syncing: boolean;
pendingCount: number;
queuePaused: boolean;
readOnlyReason?: string | null;
session: RemoteSession | null;
}): string | null {
if (isDeviceAccessRevoked) return i18n.t('session.screen.accessRevoked');
- if (!session) return syncing ? i18n.t('session.screen.syncingSession') : null;
- if (syncing) return i18n.t('session.screen.syncing');
+ if (!session) return null;
if (pendingCount > 0) return i18n.t('session.screen.pendingCount', { num: pendingCount });
// readOnlyReason 现在传入的是 composer 只读 reason:worker(只读)→「只读模式」;Lead(可聊天)→ 不显示。
if (readOnlyReason) return i18n.t('session.screen.readOnlyMode');
@@ -11355,6 +11366,7 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
minWidth: 0,
},
sessionHeaderTitle: {
+ flexShrink: 1,
color: colors.textPrimary,
fontSize: typeScale.body,
fontWeight: fontWeight.semibold,
diff --git a/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts b/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts
index bbccfc9384..041e9304ee 100644
--- a/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts
+++ b/apps/mobile/src/__tests__/connectionBannerVisibility.test.ts
@@ -15,6 +15,16 @@ const base = {
};
describe('resolveConnectionBannerVisibility', () => {
+ it('normal connecting stays quiet, but real failures still surface during connecting', () => {
+ const connecting = { ...base, offline: true, connecting: true, offlineLongEnough: true };
+ expect(resolveConnectionBannerVisibility(connecting)).toBe(false);
+ expect(resolveConnectionBannerVisibility({ ...connecting, hasError: true })).toBe(true);
+ expect(resolveConnectionBannerVisibility({ ...connecting, hasIssue: true })).toBe(true);
+ expect(resolveConnectionBannerVisibility({ ...connecting, deviceUnresponsive: true })).toBe(true);
+ expect(resolveConnectionBannerVisibility({ ...connecting, hasUnstableIssue: true })).toBe(true);
+ expect(resolveConnectionBannerVisibility({ ...connecting, connecting: false })).toBe(true);
+ expect(resolveConnectionBannerVisibility(base)).toBe(false);
+ });
it('连接正常且无错误时不显示(不渲染常驻状态条)', () => {
expect(resolveConnectionBannerVisibility(base)).toBe(false);
});
diff --git a/apps/mobile/src/__tests__/connectionNoticeDelay.test.ts b/apps/mobile/src/__tests__/connectionNoticeDelay.test.ts
index cb217a51d0..9daae5fc4d 100644
--- a/apps/mobile/src/__tests__/connectionNoticeDelay.test.ts
+++ b/apps/mobile/src/__tests__/connectionNoticeDelay.test.ts
@@ -4,17 +4,17 @@ import { scheduleConnectionNotice, updateConnectionNoticeVisibility } from '@/co
describe('floating connection notice', () => {
afterEach(() => vi.useRealTimers());
- it('waits one second and cancels a brief outage without flashing', () => {
+ it('waits three seconds and cancels a brief outage without flashing', () => {
vi.useFakeTimers();
const reveal = vi.fn();
const cancel = scheduleConnectionNotice(reveal);
- vi.advanceTimersByTime(999);
+ vi.advanceTimersByTime(2_999);
expect(reveal).not.toHaveBeenCalled();
cancel();
- vi.advanceTimersByTime(1_000);
+ vi.advanceTimersByTime(3_000);
expect(reveal).not.toHaveBeenCalled();
const cancelNext = scheduleConnectionNotice(reveal);
- vi.advanceTimersByTime(999);
+ vi.advanceTimersByTime(2_999);
expect(reveal).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(reveal).toHaveBeenCalledTimes(1);
@@ -28,32 +28,61 @@ describe('floating connection notice', () => {
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('useDelayedConnectionNotice(cachedOnly || active)');
expect(banner).toContain('<ConnectionNoticeOverlay>');
});
- it('holds completion for two seconds only after a visible incident and cancels it on a new outage', () => {
+ it('keeps immediate feedback visible through preview alignment until the active interval ends', () => {
vi.useFakeTimers();
let visible = false;
let cancel: (() => void) | undefined;
- const update = (active: boolean, completed: boolean) => {
+ const update = (active: boolean, immediate = false) => {
cancel?.();
- cancel = updateConnectionNoticeVisibility(active, completed, visible, (next) => { visible = next; });
+ cancel = updateConnectionNoticeVisibility(active, visible, (next) => { visible = next; }, immediate);
};
- update(true, false);
+ update(true);
+ vi.advanceTimersByTime(100);
+ update(true, true);
+ expect(visible).toBe(true);
+ vi.advanceTimersByTime(400);
+ update(true); // Preview aligned, but other content is still synchronizing.
+ expect(visible).toBe(true);
+ vi.advanceTimersByTime(3_000);
+ expect(visible).toBe(true);
+ update(false);
+ expect(visible).toBe(false);
+ update(true);
+ vi.advanceTimersByTime(2_999);
+ expect(visible).toBe(false);
+ vi.advanceTimersByTime(1);
+ expect(visible).toBe(true);
+ update(false);
+ vi.runAllTimers();
+ expect(visible).toBe(false);
+ });
+ it('clears immediately on completion and delays each new incident independently', () => {
+ vi.useFakeTimers();
+ let visible = false;
+ let cancel: (() => void) | undefined;
+ const update = (active: boolean) => {
+ cancel?.();
+ cancel = updateConnectionNoticeVisibility(active, visible, (next) => { visible = next; });
+ };
+ update(true);
vi.advanceTimersByTime(500);
- update(false, true);
+ update(false);
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);
+ update(true);
+ vi.advanceTimersByTime(3_000);
expect(visible).toBe(true);
- update(true, false);
- vi.advanceTimersByTime(2_000);
+ update(false);
+ expect(visible).toBe(false);
+ update(true);
+ vi.advanceTimersByTime(2_999);
+ expect(visible).toBe(false);
+ vi.advanceTimersByTime(1);
expect(visible).toBe(true);
- update(false, true);
+ update(false);
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 db899c934e..90f2979b8f 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -26,7 +26,8 @@ describe('mobile Home connection feedback', () => {
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('const showConnectionRow = selectedDeviceDisconnected || resolveConnectionBannerVisibility(');
+ expect(source).toContain('deviceUnresponsive: homeDeviceUnresponsive,');
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'));
@@ -497,7 +498,7 @@ 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 = homeRecoveringDeviceIds.size > 0 || selectedDeviceDisconnected || !!connectionError || status !== 'online' || connectionIssue?.kind === 'unstable';",
+ 'const showConnectionRow = selectedDeviceDisconnected || resolveConnectionBannerVisibility(',
);
expect(source).toContain('homeSyncDeviceIds.filter((id) => unresponsiveDevices.has(id)');
expect(source).toContain("connectionStates={deviceConnectionStates}");
diff --git a/apps/mobile/src/__tests__/sessionEntrySyncIndicator.test.ts b/apps/mobile/src/__tests__/sessionEntrySyncIndicator.test.ts
new file mode 100644
index 0000000000..b1aeba565b
--- /dev/null
+++ b/apps/mobile/src/__tests__/sessionEntrySyncIndicator.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+import type { HistoryViewSnapshot } from '@cindy/maker-shared/message-window';
+import type { RemoteMessage } from '@/session/types';
+import { hasSessionEntryPreviewMismatch } from '@/session/sessionEntrySyncIndicator';
+
+const message = (content: string, role: RemoteMessage['role'] = 'assistant', time = 1): RemoteMessage => ({
+ id: String(time), clientId: String(time), sessionId: 's', role, content,
+ toolUseId: null, agentMeta: null, createdAt: new Date(time).toISOString(),
+});
+const history: HistoryViewSnapshot<RemoteMessage> = {
+ items: [], details: new Map(), expanded: new Set(), nextCursor: null,
+ hasMore: false, loading: true, ready: false, error: null,
+};
+
+describe('immediate entry synchronization', () => {
+ it('shows immediately for a known different Home preview and stops when aligned', () => {
+ expect(hasSessionEntryPreviewMismatch('s', 'New answer', null, [message('Old answer')], history)).toBe(true);
+ expect(hasSessionEntryPreviewMismatch('s', 'New answer', null, [message('New\nanswer')], history)).toBe(false);
+ });
+ it('shows missing content immediately only when Home already has a preview', () => {
+ expect(hasSessionEntryPreviewMismatch('s', undefined, 'Known content', [], history)).toBe(true);
+ expect(hasSessionEntryPreviewMismatch('s', undefined, undefined, [], history)).toBe(false);
+ });
+ it('handles plain server previews without mistaking truncation or rich formatting for stale content', () => {
+ expect(hasSessionEntryPreviewMismatch('s', undefined, 'New answer', [message('Old answer')], history)).toBe(true);
+ expect(hasSessionEntryPreviewMismatch('s', undefined, 'Long answer', [message('Long answer continued')], history)).toBe(false);
+ expect(hasSessionEntryPreviewMismatch('s', undefined, 'Answer continued', [message('Answer')], history)).toBe(true);
+ expect(hasSessionEntryPreviewMismatch('s', undefined, 'Answer', [message('**Answer**')], history)).toBe(false);
+ expect(hasSessionEntryPreviewMismatch('s', undefined, 'Answer', [message('- Answer')], history)).toBe(false);
+ });
+ it('does not mistake deferred work prose for missing messages even with a later tool row', () => {
+ const folded: HistoryViewSnapshot<RemoteMessage> = { ...history, ready: true, items: [{
+ type: 'work', key: 'w', summary: {
+ key: 'w', firstMessageId: '2', lastMessageId: '2', startedAtMs: 2, endedAtMs: 2,
+ isStreaming: false, messageCount: 1, toolCount: 0, revision: 'r',
+ },
+ }] };
+ expect(hasSessionEntryPreviewMismatch('s', 'Folded answer', null,
+ [message('Earlier answer'), message('tool', 'tool_result', 3)], folded)).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts
index 542fccf0c9..7366f026a5 100644
--- a/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts
@@ -23,10 +23,11 @@ describe('mobile session header desktop-first surface', () => {
expect(source).not.toContain('sessionHeaderIconBadgeText');
expect(source).not.toContain('badge={');
expect(source).not.toContain("if (queueCount > 0) return `队列 ${queueCount}`;");
- expect(source).toContain("if (!session) return syncing ? i18n.t('session.screen.syncingSession') : null;\n if (syncing) return i18n.t('session.screen.syncing');");
- // 后台静默刷新:同步提示由 showSyncingIndicator gate —— 仅首次加载、还没有任何内容时显示,
- // 已有 messages(重开已看过的会话)时后台对账静默,不再弹"正在同步"。
- expect(source).toContain('const showSyncingIndicator = loading && !hasRenderedMessages;');
+ expect(source).toContain('if (!session) return null;');
+ // Routine work uses the trailing title indicator, without an extra subtitle.
+ expect(source).toContain('const showSyncingIndicator = !showConnectionBanner && !showCachedHistoryNotice');
+ expect(source).toContain('<QuietSyncIndicator active={syncing} immediate={syncingImmediately} />');
+ expect(source).not.toContain("if (syncing) return i18n.t('session.screen.syncing');");
expect(source).toContain("if (queuePaused) return i18n.t('session.screen.queuePausedNotice');\n return null;");
expect(source).toContain('attention ? (');
});
diff --git a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts
index 2517943cdd..c14dc2455a 100644
--- a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts
@@ -44,8 +44,8 @@ describe('mobile session main layer desktop-first noise budget', () => {
// banner 渲染条件(useShowConnectionBanner):请求级 / transport hold error、可分类连接问题、
// 目标设备熔断 open(电脑端未响应)立即显示;普通弱网断线经防闪窗口后也显示,不再彻底静默。
- expect(routeSource).toContain('{showConnectionBanner || !remoteHistoryAvailable ? (');
- expect(routeSource).toContain('cachedOnly={!remoteHistoryAvailable}');
+ expect(routeSource).toContain('{showConnectionBanner || showCachedHistoryNotice ? (');
+ expect(routeSource).toContain('cachedOnly={showCachedHistoryNotice}');
expect(source.replace(/\r\n/g, '\n'))
.toContain('useShowConnectionBanner(\n status,\n bannerError,');
expect(routeSource).not.toContain('connectionError || (loading && !currentSession)');
diff --git a/apps/mobile/src/components/ConnectionBanner.tsx b/apps/mobile/src/components/ConnectionBanner.tsx
index fab1c0bac2..2b2b4a3939 100644
--- a/apps/mobile/src/components/ConnectionBanner.tsx
+++ b/apps/mobile/src/components/ConnectionBanner.tsx
@@ -22,18 +22,18 @@ import {
import { fontWeight, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { iconSize, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
-/** Eligibility only. ConnectionBanner owns the shared one-second display delay,
+/** Eligibility only. ConnectionBanner owns the shared three-second display delay,
* including screens that mount the component unconditionally. */
export function useShowConnectionBanner(
status: DeviceLinkStatus,
error: string | null,
issue: DeviceLinkConnectionIssue | null,
deviceUnresponsive = false,
- recovery?: 'syncing' | 'recovered',
): boolean {
- const offline = status !== 'online' || recovery === 'syncing';
- return recovery === 'recovered' || resolveConnectionBannerVisibility({
+ const offline = status !== 'online';
+ return resolveConnectionBannerVisibility({
offline,
+ connecting: status === 'connecting',
offlineLongEnough: true,
// 熔断已关后屏幕残留的 DEVICE_UNRESPONSIVE 错误按陈旧丢弃(review P1),
// 否则恢复后 banner 会带着"自动重试中"文案常驻到用户手动同步。
@@ -76,8 +76,8 @@ export function ConnectionBanner({
}) {
const styles = useThemedStyles(makeStyles);
const { t } = useTranslation();
- const active = useShowConnectionBanner(status, error, issue, deviceUnresponsive, recovery === 'recovered' ? undefined : recovery);
- const visible = useDelayedConnectionNotice(cachedOnly || active, recovery === 'recovered');
+ const active = useShowConnectionBanner(status, error, issue, deviceUnresponsive);
+ const visible = useDelayedConnectionNotice(cachedOnly || active);
// 链路已 online 说明普通 issue 已过期;unstable 描述跨连接抖动,online 时仍展示。
// issue 优先于请求级 error:链路断因明确时,invoke 失败都是它的下游症状(NOT_CONNECTED)。
const activeIssue = status !== 'online' || issue?.kind === 'unstable' ? issue : null;
diff --git a/apps/mobile/src/components/ConnectionNoticeOverlay.tsx b/apps/mobile/src/components/ConnectionNoticeOverlay.tsx
index 379e978bca..b2882074d8 100644
--- a/apps/mobile/src/components/ConnectionNoticeOverlay.tsx
+++ b/apps/mobile/src/components/ConnectionNoticeOverlay.tsx
@@ -5,12 +5,12 @@ 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 {
+export function useDelayedConnectionNotice(active: boolean, immediate = false): boolean {
const [ready, setReady] = useState(false);
useEffect(() => {
- return updateConnectionNoticeVisibility(active, completed, ready, setReady);
- }, [active, completed, ready]);
- return (active || completed) && ready;
+ return updateConnectionNoticeVisibility(active, ready, setReady, immediate);
+ }, [active, ready, immediate]);
+ return active && (immediate || ready);
}
type Notice = { top: number; children: ReactNode };
diff --git a/apps/mobile/src/components/MobilePrimitives.tsx b/apps/mobile/src/components/MobilePrimitives.tsx
index eaaff5533f..d1a557d301 100644
--- a/apps/mobile/src/components/MobilePrimitives.tsx
+++ b/apps/mobile/src/components/MobilePrimitives.tsx
@@ -15,6 +15,7 @@ import {
type ViewStyle,
} from 'react-native';
import { Text } from '@/components/AppText';
+import { QuietSyncIndicator } from '@/components/QuietSyncIndicator';
import { fontWeight, iconSize, iconStroke, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
@@ -335,6 +336,7 @@ export function ScreenHeader({
subtitle,
title,
titleTestID,
+ syncing,
}: {
action?: MainWindowAction;
backTestID?: string;
@@ -346,6 +348,7 @@ export function ScreenHeader({
subtitle?: string | null;
title: string;
titleTestID?: string;
+ syncing?: boolean;
}) {
const styles = useThemedStyles(makeStyles);
const compact = density === 'compact';
@@ -360,9 +363,12 @@ export function ScreenHeader({
) : null}
<View style={styles.headerText}>
{eyebrow ? <Text style={styles.eyebrow}>{eyebrow}</Text> : null}
- <Text numberOfLines={1} style={[styles.headerTitle, compact && styles.headerTitleCompact]} testID={titleTestID}>
+ <View style={{ flexDirection: 'row', alignItems: 'center' }}>
+ <Text numberOfLines={1} style={[styles.headerTitle, compact && styles.headerTitleCompact, { flexShrink: 1 }]} testID={titleTestID}>
{title}
</Text>
+ {syncing !== undefined ? <QuietSyncIndicator active={syncing} /> : null}
+ </View>
{subtitle ? (
<Text numberOfLines={1} style={styles.headerSubtitle}>
{subtitle}
diff --git a/apps/mobile/src/components/QuietSyncIndicator.tsx b/apps/mobile/src/components/QuietSyncIndicator.tsx
new file mode 100644
index 0000000000..a8afaa771d
--- /dev/null
+++ b/apps/mobile/src/components/QuietSyncIndicator.tsx
@@ -0,0 +1,41 @@
+import { useEffect, useRef } from 'react';
+import { Animated, Easing } from 'react-native';
+import { LoaderCircle } from 'lucide-react-native';
+import { useTranslation } from 'react-i18next';
+import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';
+import { iconSize, iconStroke, useTheme } from '@/theme';
+import { motionDuration } from '@/theme/tokens';
+import { useDelayedConnectionNotice } from './ConnectionNoticeOverlay';
+
+/** Same working glyph and cadence as the task list; no idle placeholder. */
+export function QuietSyncIndicator({ active, immediate = false }: { active: boolean; immediate?: boolean }) {
+ const visible = useDelayedConnectionNotice(active, immediate);
+ const reduceMotion = useReduceMotionEnabled();
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ const rotation = useRef(new Animated.Value(0)).current;
+ useEffect(() => {
+ if (!visible || reduceMotion !== false) return;
+ const loop = Animated.loop(Animated.timing(rotation, {
+ toValue: 1,
+ duration: motionDuration.spinnerCycle,
+ easing: Easing.linear,
+ useNativeDriver: true,
+ isInteraction: false,
+ }));
+ loop.start();
+ return () => { loop.stop(); rotation.setValue(0); };
+ }, [visible, reduceMotion, rotation]);
+ if (!visible) return null;
+ const rotate = rotation.interpolate({ inputRange: [0, 1], outputRange: ['0deg', '360deg'] });
+ return <Animated.View
+ pointerEvents="none"
+ style={{ flexShrink: 0, transform: [{ rotate }] }}
+ accessible
+ accessibilityLabel={t('deviceLink.recovery.syncing')}
+ accessibilityState={{ busy: true }}
+ testID="connection.quietSync"
+ >
+ <LoaderCircle color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ </Animated.View>;
+}
diff --git a/apps/mobile/src/components/connectionBannerVisibility.ts b/apps/mobile/src/components/connectionBannerVisibility.ts
index 2c89799d80..801cfad0c1 100644
--- a/apps/mobile/src/components/connectionBannerVisibility.ts
+++ b/apps/mobile/src/components/connectionBannerVisibility.ts
@@ -1,15 +1,17 @@
/**
* connectionBannerVisibility.ts — ConnectionBanner 可见性判定的决策核。
* 纯函数(不依赖 React / react-native),node 可单测;useShowConnectionBanner
- * 只负责喂时间维度的 offlineLongEnough,判定逻辑全在这里:
- * - 请求级 error / 可分类连接问题(鉴权失效、被顶号等)→ 立即显示;
- * - 关联设备熔断 open(电脑端未响应)→ 立即显示——relay 可能仍 online,
+ * 只负责传入状态,浮窗统一经过三秒防闪延迟:
+ * - 没有故障证据的 connecting / 内容同步 / 同步完成 → 标题轻量反馈,不弹浮窗;
+ * - 请求级 error / 可分类连接问题(鉴权失效、被顶号等)→ 具备浮窗展示资格;
+ * - 关联设备熔断 open(电脑端未响应)→ 具备浮窗展示资格——relay 可能仍 online,
* 只看 status 的旧判定对「进程活着但内部卡死」的半死态完全失明
* (2026-07 事故:presence 恒 online,banner 一直不出现,用户零信号);
* - 普通弱网断线 → 持续超过防闪窗口才显示(规则 7:杜绝跳变)。
*/
export function resolveConnectionBannerVisibility(input: {
offline: boolean;
+ connecting?: boolean;
offlineLongEnough: boolean;
hasError: boolean;
hasIssue: boolean;
@@ -19,7 +21,7 @@ export function resolveConnectionBannerVisibility(input: {
return input.hasError
|| input.deviceUnresponsive
|| input.hasUnstableIssue
- || (input.offline && (input.hasIssue || input.offlineLongEnough));
+ || (input.offline && (input.hasIssue || (!input.connecting && input.offlineLongEnough)));
}
/**
diff --git a/apps/mobile/src/components/connectionNoticeDelay.ts b/apps/mobile/src/components/connectionNoticeDelay.ts
index 10a53cb838..fb0c19f204 100644
--- a/apps/mobile/src/components/connectionNoticeDelay.ts
+++ b/apps/mobile/src/components/connectionNoticeDelay.ts
@@ -1,4 +1,4 @@
-export const CONNECTION_NOTICE_DELAY_MS = 1_000;
+export const CONNECTION_NOTICE_DELAY_MS = 3_000;
/** Cancelling on recovery or unmount prevents brief incidents from flashing a notice. */
export function scheduleConnectionNotice(reveal: () => void): () => void {
@@ -6,17 +6,17 @@ export function scheduleConnectionNotice(reveal: () => void): () => void {
return () => clearTimeout(timer);
}
-/** Completion may linger only if the preceding incident was already visible. */
+/** Clear immediately when work or an incident ends; no completion notification. */
export function updateConnectionNoticeVisibility(
active: boolean,
- completed: boolean,
visible: boolean,
setVisible: (visible: boolean) => void,
+ immediate = false,
): (() => void) | undefined {
- if (active) return visible ? undefined : scheduleConnectionNotice(() => setVisible(true));
- if (completed && visible) {
- const timer = setTimeout(() => setVisible(false), 2_000);
- return () => clearTimeout(timer);
+ if (active && immediate) {
+ setVisible(true);
+ return;
}
+ if (active) return visible ? undefined : scheduleConnectionNotice(() => setVisible(true));
setVisible(false);
}
diff --git a/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx b/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx
index a6c782a597..ec16f1b15a 100644
--- a/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx
+++ b/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx
@@ -1,4 +1,5 @@
import { Stack } from "expo-router";
+import { QuietSyncIndicator } from '@/components/QuietSyncIndicator';
import { ChevronDown, Ellipsis, Menu, Monitor } from "lucide-react-native";
import { Pressable, StyleSheet, View } from "react-native";
import { Text } from "@/components/AppText";
@@ -36,6 +37,7 @@ export function HomeNativeStackHeader({
onSelectScope,
scopeActions,
showRemoteGuide,
+ syncing = false,
title,
titleA11y,
}: {
@@ -51,6 +53,7 @@ export function HomeNativeStackHeader({
onSelectScope(id: string): void;
scopeActions: readonly NativePullDownAction[];
showRemoteGuide: boolean;
+ syncing?: boolean;
title: string;
titleA11y: string;
}) {
@@ -85,6 +88,7 @@ export function HomeNativeStackHeader({
size={iconSize.xs}
strokeWidth={iconStroke.medium}
/>
+ <QuietSyncIndicator active={syncing} />
</View>
</Pressable>
</NativePullDownMenu>
diff --git a/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx b/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx
index 07c22941a2..67c2f62cb0 100644
--- a/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx
+++ b/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx
@@ -1,4 +1,5 @@
import { Stack } from "expo-router";
+import { QuietSyncIndicator } from '@/components/QuietSyncIndicator';
import type { ReactNode } from "react";
import { Platform, StyleSheet, View } from "react-native";
import type { Edge } from "react-native-safe-area-context";
@@ -41,6 +42,7 @@ export function SimpleStackHeader({
subtitle,
title,
titleTestID,
+ syncing,
}: {
action?: MainWindowAction;
right?: ReactNode;
@@ -50,6 +52,7 @@ export function SimpleStackHeader({
subtitle?: string | null;
title: string;
titleTestID?: string;
+ syncing?: boolean;
}) {
const { colors } = useTheme();
const styles = useThemedStyles(makeNativeTitleStyles);
@@ -65,6 +68,7 @@ export function SimpleStackHeader({
subtitle={subtitle}
title={title}
titleTestID={titleTestID}
+ syncing={syncing}
/>
);
}
@@ -82,6 +86,7 @@ export function SimpleStackHeader({
<Text numberOfLines={1} style={styles.title}>
{title}
</Text>
+ {syncing !== undefined ? <QuietSyncIndicator active={syncing} /> : null}
</View>
),
headerLeft: onBack
@@ -104,10 +109,12 @@ export function SimpleStackHeader({
const makeNativeTitleStyles = (colors: ThemeColors) =>
StyleSheet.create({
wrap: {
+ flexDirection: 'row',
alignItems: "center",
maxWidth: 220,
},
title: {
+ flexShrink: 1,
color: colors.textPrimary,
fontSize: typeScale.body,
fontWeight: fontWeight.medium,
diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
index ae10cd4bf6..99f3e4f2a8 100644
--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
@@ -43,6 +43,10 @@ vi.mock("react-native", async () => {
);
};
return {
+ AccessibilityInfo: {
+ isReduceMotionEnabled: async () => false,
+ addEventListener: () => ({ remove() {} }),
+ },
View: view("div"),
Modal: (p: any) => p.visible ? createElement("div", {}, p.children) : null,
Pressable: view("button"),
diff --git a/apps/mobile/src/session/sessionEntrySyncIndicator.ts b/apps/mobile/src/session/sessionEntrySyncIndicator.ts
new file mode 100644
index 0000000000..d4a6f8ec69
--- /dev/null
+++ b/apps/mobile/src/session/sessionEntrySyncIndicator.ts
@@ -0,0 +1,37 @@
+import { buildSessionMessagePreviewIndex } from '@cindy/maker-shared/session-list';
+import { historyWorkSummaries, type HistoryViewSnapshot } from '@cindy/maker-shared/message-window';
+import type { RemoteMessage } from './types';
+
+const inline = (text: string | null | undefined) => (text ?? '').replace(/\s+/g, ' ').trim();
+
+/** Presentation only: unknown or folded content is not evidence of stale history. */
+export function hasSessionEntryPreviewMismatch(
+ sessionId: string,
+ homeLoadedPreview: string | undefined,
+ homePreview: string | null | undefined,
+ messages: readonly RemoteMessage[],
+ history: HistoryViewSnapshot<RemoteMessage>,
+): boolean {
+ const expected = inline(homeLoadedPreview ?? homePreview);
+ if (!expected) return false;
+ const latest = messages.findLast((message) =>
+ buildSessionMessagePreviewIndex([sessionId], () => [message]).has(sessionId));
+ if (historyWorkSummaries(history.items).some((work) =>
+ !history.details.get(work.key)?.complete
+ && work.endedAtMs >= (latest ? Date.parse(latest.createdAt) : 0))) return false;
+ if (!messages.length) return true;
+
+ if (homeLoadedPreview !== undefined) {
+ const actual = inline(buildSessionMessagePreviewIndex([sessionId], () => messages).get(sessionId));
+ return !!actual && actual !== expected;
+ }
+
+ // Server previews are plain user/assistant text, capped at 140 characters.
+ // Rich/structured messages have a different projection; leave those on the
+ // ordinary delay instead of guessing that formatting means stale content.
+ const row = messages.findLast((message) => message.role === 'user' || message.role === 'assistant');
+ if (!row || typeof row.content !== 'string'
+ || /[\[\]{}<>*`#_~\\&]|^\s*(?:[-+] |\d+[.)] )/m.test(row.content)) return false;
+ const actual = inline(row.content);
+ return !!actual && !actual.startsWith(expected);
+}