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): 区分本机网络故障与远程电脑离线

Dash2566477421aa
diff --git a/apps/mobile/src/__tests__/connectionBannerRecovery.test.tsx b/apps/mobile/src/__tests__/connectionBannerRecovery.test.tsx
index b8acddbe79..f67d7d9dc4 100644
--- a/apps/mobile/src/__tests__/connectionBannerRecovery.test.tsx
+++ b/apps/mobile/src/__tests__/connectionBannerRecovery.test.tsx
@@ -1,25 +1,41 @@
// @vitest-environment jsdom
-import { act, createElement } from 'react';
+import { act, createElement, type ReactNode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { useDelayedConnectionNotice } from '@/components/ConnectionNoticeOverlay';
-import { useShowConnectionBanner } from '@/components/ConnectionBanner';
+import { ConnectionBanner, useShowConnectionBanner } from '@/components/ConnectionBanner';
+import { localNetworkStore } from '@/device-link/localNetworkStatus';
+import { i18n } from '@/i18n';
import type { DeviceLinkStatus } from '@cindy/device-link';
vi.mock('expo-router', () => ({ useFocusEffect: () => {} }));
-vi.mock('react-native', () => ({ ActivityIndicator: () => null, View: () => null, StyleSheet: { create: (s: unknown) => s } }));
+vi.mock('react-native', () => ({
+ ActivityIndicator: () => null,
+ View: ({ children }: { children: ReactNode }) => createElement('div', null, children),
+ StyleSheet: { create: (s: unknown) => s },
+}));
+vi.mock('@/components/ConnectionNoticeOverlay', async (importOriginal) => ({
+ ...await importOriginal<typeof import('@/components/ConnectionNoticeOverlay')>(),
+ ConnectionNoticeOverlay: ({ children }: { children: ReactNode }) => children,
+}));
vi.mock('lucide-react-native', () => ({ LoaderCircle: () => null }));
vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => true }));
-vi.mock('@/components/AppText', () => ({ Text: () => null }));
+vi.mock('@/components/AppText', () => ({
+ Text: ({ children, testID }: { children: ReactNode; testID: string }) => createElement('span', { 'data-testid': testID }, children),
+}));
vi.mock('@/components/MobilePrimitives', () => ({ MainWindowActionButton: () => null, StatusDot: () => null }));
-vi.mock('@/theme', () => ({ fontWeight: {}, useTheme: () => ({}), useThemedStyles: () => ({}) }));
+vi.mock('@/theme', () => ({ fontWeight: {}, useTheme: () => ({ colors: {} }), useThemedStyles: () => ({}) }));
let root: Root;
+let container: HTMLDivElement;
let visible = false;
-beforeEach(() => {
+beforeEach(async () => {
+ localNetworkStore.update();
+ await i18n.changeLanguage('zh-CN');
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
vi.useFakeTimers();
- root = createRoot(document.createElement('div'));
+ container = document.createElement('div');
+ root = createRoot(container);
});
afterEach(() => { act(() => root.unmount()); vi.useRealTimers(); });
function Probe({ status, error, unresponsive }: {
@@ -34,6 +50,30 @@ function render(status: DeviceLinkStatus, recovery?: 'syncing' | 'recovered', er
}
const advance = (ms: number) => act(() => vi.advanceTimersByTime(ms));
+// Unit regression: render the real banner, replacing only native views/placement.
+// Existing tests covered delay but missed phone outages overriding stale host errors.
+function banner(status: DeviceLinkStatus, cachedOnly = false, deviceUnresponsive = false) {
+ act(() => root.render(createElement(ConnectionBanner, {
+ status, cachedOnly, deviceUnresponsive, loading: false, error: null,
+ lastSyncedAt: null, onSync: () => {},
+ })));
+ advance(3_000);
+ return container.querySelector('[data-testid="connection.title"]')?.textContent;
+}
+it('shows phone network loss even while relay still looks online, and clears on recovery', () => {
+ act(() => localNetworkStore.update({ type: 'NONE', isConnected: false }));
+ expect(banner('online', false, true)).toBe('手机网络不可用');
+ expect(banner('online', true)).toBe('手机网络不可用');
+ banner('online');
+ act(() => localNetworkStore.update({ type: 'WIFI', isConnected: true }));
+ expect(container.textContent).toBe('');
+});
+it('distinguishes service loss, confirmed offline computer and unattributed timeout', () => {
+ expect(banner('stopped', true)).toBe('暂时连不上服务');
+ expect(banner('online', true)).toBe('电脑未连接');
+ expect(banner('online', false, true)).toBe('连接暂无响应');
+});
+
it('keeps repeated online task loads quiet, even when content takes several seconds', () => {
for (let visit = 0; visit < 3; visit++) {
render('online', 'syncing'); advance(5_000); expect(visible).toBe(false);
diff --git a/apps/mobile/src/__tests__/filesConnectionBanner.test.ts b/apps/mobile/src/__tests__/filesConnectionBanner.test.ts
index a35e4adf6d..79c0c790a7 100644
--- a/apps/mobile/src/__tests__/filesConnectionBanner.test.ts
+++ b/apps/mobile/src/__tests__/filesConnectionBanner.test.ts
@@ -11,7 +11,9 @@ const banner = ts.createSourceFile('banner.tsx', readFileSync(resolve(process.cw
const hook = banner.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === 'useShowConnectionBanner');
if (!hook) throw new Error('Missing production banner eligibility function');
const hookCode = ts.transpileModule(hook.getText(banner).replace(/^export /, ''), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
-const useShowConnectionBanner = new Function('resolveConnectionBannerVisibility', 'resolveEffectiveConnectionError', hookCode + '\nreturn useShowConnectionBanner;')(resolveConnectionBannerVisibility, resolveEffectiveConnectionError);
+// This expression fixture has no native network; live network transitions are
+// exercised through the real component in connectionBannerRecovery.test.tsx.
+const useShowConnectionBanner = new Function('resolveConnectionBannerVisibility', 'resolveEffectiveConnectionError', 'useLocalNetworkStatus', hookCode + '\nreturn useShowConnectionBanner;')(resolveConnectionBannerVisibility, resolveEffectiveConnectionError, () => 'unknown');
let visibility: ts.Expression | undefined, render: ts.Expression | undefined, footer: ts.Expression | undefined;
function visit(node: ts.Node) {
if (ts.isVariableDeclaration(node) && node.name.getText(page) === 'showConnectionBanner') visibility = node.initializer;
diff --git a/apps/mobile/src/__tests__/historyViewProvider.test.tsx b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
index 96f2e3f7b7..082753b294 100644
--- a/apps/mobile/src/__tests__/historyViewProvider.test.tsx
+++ b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
@@ -16,6 +16,7 @@ import { isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';
import { DeviceLinkProvider, useDeviceLink, type DeviceLinkContextValue } from '../device-link/DeviceLinkContext';
import { acquireDeviceSendSlot, resetDeviceResponsivenessTracking, settleDeviceSend, unresponsiveDevicesStore } from '../device-link/unresponsiveDevicesStore';
import { revokedDevicesStore } from '../device-link/revokedDevicesStore';
+import { localNetworkStore, type NetworkState } from '../device-link/localNetworkStatus';
const auth = vi.hoisted(() => ({
isAuthenticated: true,
@@ -29,6 +30,7 @@ const networkEvents = vi.hoisted(() => ({
state: 'active',
app: (_next: string) => {},
network: (_next: { type?: string; isConnected?: boolean; isInternetReachable?: boolean }) => {},
+ read: vi.fn<() => Promise<{ type?: string; isConnected?: boolean; isInternetReachable?: boolean }>>(),
}));
vi.mock('react-native', () => ({
Platform: { OS: 'android' },
@@ -39,7 +41,7 @@ vi.mock('react-native', () => ({
},
},
}));
-vi.mock('expo-network', () => ({ addNetworkStateListener: (listener: typeof networkEvents.network) => {
+vi.mock('expo-network', () => ({ getNetworkStateAsync: networkEvents.read, addNetworkStateListener: (listener: typeof networkEvents.network) => {
networkEvents.network = listener; return { remove() {} };
} }));
vi.mock('expo-secure-store', () => ({
@@ -126,6 +128,7 @@ async function readHistory() {
}
beforeEach(async () => {
+ networkEvents.read.mockReset().mockRejectedValue(new Error('native lookup unavailable'));
networkEvents.state = 'active';
auth.accountGeneration = 1;
auth.apiFetch.mockReset();
@@ -455,6 +458,60 @@ describe('Provider shared-task relay compatibility', () => {
describe('Provider network recovery priority', () => {
const wifi = { type: 'WIFI', isConnected: true, isInternetReachable: true };
+ it('refreshes native state on foreground and ignores snapshots older than a network event', async () => {
+ networkEvents.read.mockResolvedValueOnce({ type: 'NONE', isConnected: false });
+ await act(async () => networkEvents.app('active'));
+ expect(localNetworkStore.getSnapshot().status).toBe('unavailable');
+ let complete!: (network: NetworkState) => void;
+ networkEvents.read.mockReturnValueOnce(new Promise(resolve => { complete = resolve; }));
+ await act(async () => networkEvents.app('active'));
+ await act(async () => {
+ networkEvents.network(wifi);
+ complete({ type: 'NONE', isConnected: false });
+ });
+ expect(localNetworkStore.getSnapshot().status).toBe('available');
+ });
+
+ it.each([
+ [{ type: 'WIFI', isConnected: true, isInternetReachable: false }, 'unavailable'],
+ [{ type: 'UNKNOWN', isConnected: false, isInternetReachable: false }, 'unknown'],
+ ] as const)('uses native evidence without turning lookup failures into phone outages (%j)', async (network, expected) => {
+ await act(async () => networkEvents.network(network));
+ expect(localNetworkStore.getSnapshot().status).toBe(expected);
+ });
+
+ // Regression: phone route loss used to count as three host failures. Existing
+ // recovery tests only checked reconnect calls, not the visible host verdict.
+ // Unit tier: real provider/native event boundary, no network or real timers.
+ it('does not blame either computer for timeouts spanning a phone outage', async () => {
+ resetDeviceResponsivenessTracking();
+ await act(async () => networkEvents.network(wifi));
+ const devices = ['host-a', 'host-b'];
+ const pending = devices.map(device => Array.from({ length: 3 }, () => acquireDeviceSendSlot(device)));
+ await act(async () => {
+ networkEvents.network({ type: 'NONE', isConnected: false, isInternetReachable: false });
+ networkEvents.network(wifi);
+ devices.forEach((device, index) => {
+ pending[index].forEach(slot => settleDeviceSend(device, slot, 'timeout'));
+ });
+ });
+ expect([...unresponsiveDevicesStore.getSnapshot()]).toEqual([]);
+ });
+
+ it('ignores requests issued offline, then counts new failures after recovery', async () => {
+ resetDeviceResponsivenessTracking();
+ await act(async () => networkEvents.network({ type: 'NONE', isConnected: false }));
+ const pending = Array.from({ length: 3 }, () => acquireDeviceSendSlot('host'));
+ await act(async () => networkEvents.network(wifi));
+ pending.forEach(slot => settleDeviceSend('host', slot, 'timeout'));
+ expect(unresponsiveDevicesStore.has('host')).toBe(false);
+ const fresh = Array.from({ length: 3 }, () => acquireDeviceSendSlot('host'));
+ await act(async () => fresh.forEach(slot => settleDeviceSend('host', slot, 'timeout')));
+ expect(unresponsiveDevicesStore.has('host')).toBe(true);
+ await act(async () => networkEvents.network({ type: 'NONE', isConnected: false }));
+ expect(unresponsiveDevicesStore.has('host')).toBe(false);
+ });
+
it('replaces an online socket on physical route changes and retains probes for equal hints', async () => {
const client = transport.clients[0];
await act(async () => {
diff --git a/apps/mobile/src/components/ConnectionBanner.tsx b/apps/mobile/src/components/ConnectionBanner.tsx
index c89182a587..aee339e1d2 100644
--- a/apps/mobile/src/components/ConnectionBanner.tsx
+++ b/apps/mobile/src/components/ConnectionBanner.tsx
@@ -6,13 +6,13 @@ import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';
import { Text } from '@/components/AppText';
import type { DeviceLinkConnectionIssue, DeviceLinkStatus } from '@cindy/device-link';
import {
- connectionIssueHint,
- connectionIssueTitle,
+ connectionHealthCopy,
describeRemoteError,
isAutoRecoveringRemoteError,
relayStatusHint,
relayStatusLabel,
} from '@/device-link/remoteStatus';
+import { useLocalNetworkStatus } from '@/device-link/localNetworkStatus';
import { MainWindowActionButton, StatusDot } from '@/components/MobilePrimitives';
import {
resolveConnectionBannerSyncActionVisibility,
@@ -30,8 +30,9 @@ export function useShowConnectionBanner(
issue: DeviceLinkConnectionIssue | null,
deviceUnresponsive = false,
): boolean {
+ const network = useLocalNetworkStatus();
const offline = status !== 'online';
- return resolveConnectionBannerVisibility({
+ return network === 'unavailable' || resolveConnectionBannerVisibility({
offline,
connecting: status === 'connecting',
offlineLongEnough: true,
@@ -76,6 +77,8 @@ export function ConnectionBanner({
}) {
const styles = useThemedStyles(makeStyles);
const { t } = useTranslation();
+ const network = useLocalNetworkStatus();
+ const networkUnavailable = network === 'unavailable';
const active = useShowConnectionBanner(status, error, issue, deviceUnresponsive);
const visible = useDelayedConnectionNotice(cachedOnly || active);
// 链路已 online 说明普通 issue 已过期;unstable 描述跨连接抖动,online 时仍展示。
@@ -83,44 +86,38 @@ export function ConnectionBanner({
const activeIssue = status !== 'online' || issue?.kind === 'unstable' ? issue : null;
// 熔断 open 优先于请求级 error:open 期间的请求失败绝大多数就是熔断快速失败本身,
// 状态级提示(未响应 + 自动重试中)比单次请求的错误原文更能解释现状。
- const showUnresponsive = !cachedOnly && !activeIssue && deviceUnresponsive;
+ const showUnresponsive = !cachedOnly && !activeIssue && !networkUnavailable && status === 'online' && deviceUnresponsive;
// 熔断已关后残留的 DEVICE_UNRESPONSIVE 错误是陈旧快照,按 null 处理(与
// useShowConnectionBanner 同一判定,否则会出现可见但无内容的空壳 banner)。
const effectiveError = resolveEffectiveConnectionError(error, deviceUnresponsive);
- const friendlyError = cachedOnly || activeIssue || showUnresponsive ? null : describeRemoteError(effectiveError);
+ const deviceDisconnected = cachedOnly || Boolean(effectiveError?.includes('DEVICE_OFFLINE'));
+ const healthCopy = connectionHealthCopy({
+ network, status, issue: activeIssue,
+ deviceDisconnected,
+ deviceUnresponsive: showUnresponsive,
+ });
+ const friendlyError = healthCopy ? null : describeRemoteError(effectiveError);
const autoRecoveringRequest = requestErrorAutoRecovering ?? isAutoRecoveringRemoteError(effectiveError);
- const showRecoveryProgress = !cachedOnly && (!activeIssue || activeIssue.kind === 'unstable' || activeIssue.kind === 'replaced')
+ const showRecoveryProgress = !networkUnavailable && !deviceDisconnected && (!activeIssue || activeIssue.kind === 'unstable' || activeIssue.kind === 'replaced')
&& (status === 'connecting' || deviceUnresponsive || recovery === 'syncing'
|| (friendlyError !== null && autoRecoveringRequest));
- const showSyncAction = !cachedOnly && resolveConnectionBannerSyncActionVisibility({
+ const showSyncAction = !networkUnavailable && !cachedOnly && resolveConnectionBannerSyncActionVisibility({
online: status === 'online',
hasActiveIssue: activeIssue !== null,
deviceUnresponsive: showUnresponsive,
hasRequestError: friendlyError !== null,
requestErrorAutoRecovering: autoRecoveringRequest,
});
- const tone = cachedOnly ? 'off' : activeIssue
+ const tone = networkUnavailable || deviceDisconnected ? 'off' : activeIssue
? 'off'
: showUnresponsive
? 'busy'
: friendlyError ? 'muted' : recovery === 'syncing' ? 'busy' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';
const compact = density === 'compact';
- const title = cachedOnly && !activeIssue ? t('deviceLink.cachedHistory.title') : activeIssue
- ? activeIssue.kind === 'unstable'
- ? t('deviceLink.unstableTitle')
- : connectionIssueTitle(activeIssue.kind)
- : showUnresponsive
- ? t('deviceLink.deviceUnresponsiveTitle')
- : friendlyError ? t('deviceLink.syncFailed') : status === 'online' && recovery
- ? t(`deviceLink.recovery.${recovery}`) : relayStatusLabel(status);
- const copy = cachedOnly && !activeIssue ? t('deviceLink.cachedHistory.hint') : activeIssue
- ? activeIssue.kind === 'unstable'
- ? t('deviceLink.unstableHint')
- : connectionIssueHint(activeIssue.kind)
- : showUnresponsive
- ? t('deviceLink.deviceUnresponsiveHint')
- : friendlyError ?? (status === 'online' && recovery === 'syncing'
- ? t('deviceLink.recovery.syncingHint') : relayStatusHint(status, lastSyncedAt));
+ const title = healthCopy?.title ?? (friendlyError ? t('deviceLink.syncFailed') : status === 'online' && recovery
+ ? t(`deviceLink.recovery.${recovery}`) : relayStatusLabel(status));
+ const copy = healthCopy?.hint ?? friendlyError ?? (status === 'online' && recovery === 'syncing'
+ ? t('deviceLink.recovery.syncingHint') : relayStatusHint(status, lastSyncedAt));
if (!visible) return null;
return (
<ConnectionNoticeOverlay>
@@ -133,7 +130,7 @@ export function ConnectionBanner({
]}
testID="connection.banner"
>
- <StatusDot tone={tone} pulsing={!cachedOnly && !activeIssue && (status === 'connecting' || showUnresponsive || recovery === 'syncing')} />
+ <StatusDot tone={tone} pulsing={!networkUnavailable && !cachedOnly && !activeIssue && (status === 'connecting' || showUnresponsive || recovery === 'syncing')} />
<View style={[styles.textBlock, compact && styles.textBlockCompact]}>
<Text
ellipsizeMode="tail"
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index dbcbb2ceb4..90daea796f 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -172,6 +172,7 @@ import { prepareVisualMockDeviceLinkContext } from '@/debug/visualMock';
import { meterDeviceLinkInvokes, recordDeviceLinkPush } from '@/debug/deviceLinkTraffic';
import { decodeGzipBase64TextBounded } from '@/utils/gzipBase64';
import { jankMetricsEnabled, recordInvokeSent, recordPushHandled } from '@/debug/jankMetrics';
+import { localNetworkStore, type NetworkState } from '@/device-link/localNetworkStatus';
export interface DeviceLinkContextValue {
status: DeviceLinkStatus;
@@ -1357,10 +1358,12 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
report: (event) => mobileDebugLog('debug', 'device-link', 'background lifecycle', event),
});
noteAppLifecycleState(AppState.currentState);
+ let refreshNetworkState = () => {};
const sub = AppState.addEventListener('change', (next) => {
// 先于下面的恢复动作记账:回前台后 rehydrate 新发的请求属于新生命周期。
noteAppLifecycleState(next);
if (next === 'active') {
+ refreshNetworkState();
diagnostics.foreground();
const resumingFromBackground = backgroundReleaseInFlightRef.current;
backgroundReleaseInFlightRef.current = false;
@@ -1399,10 +1402,18 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// existing heartbeat fallback if the optional runtime module is unavailable.
let disposed = false;
let networkSubscription: { remove(): void } | undefined;
- let previousNetwork: { type?: string; isConnected?: boolean; isInternetReachable?: boolean } | undefined;
- void import('expo-network').then(({ addNetworkStateListener }) => {
+ let previousNetwork: NetworkState | undefined;
+ void import('expo-network').then(({ addNetworkStateListener, getNetworkStateAsync }) => {
if (disposed) return;
- networkSubscription = addNetworkStateListener((network) => {
+ let networkRevision = 0;
+ const onNetworkState = (network: NetworkState) => {
+ if (disposed) return;
+ networkRevision += 1;
+ localNetworkStore.update(network);
+ if (localNetworkStore.getSnapshot().status === 'unavailable') {
+ // A phone-wide outage is not evidence against any individual computer.
+ resetDeviceResponsivenessTracking();
+ }
const urgent = previousNetwork !== undefined && (
previousNetwork.type !== network.type
|| previousNetwork.isConnected !== network.isConnected
@@ -1427,7 +1438,16 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
}
if (AppState.currentState !== 'active' || network.isConnected === false) return;
recoverNetwork(urgent);
- });
+ };
+ networkSubscription = addNetworkStateListener(onNetworkState);
+ refreshNetworkState = () => {
+ if (typeof getNetworkStateAsync !== 'function') return;
+ const revision = ++networkRevision;
+ void getNetworkStateAsync().then((network) => {
+ if (!disposed && revision === networkRevision) onNetworkState(network);
+ }).catch(() => { /* Keep listener evidence when the native lookup fails. */ });
+ };
+ refreshNetworkState();
}).catch(() => {
console.warn('[device-link] network listener unavailable; using heartbeat recovery');
});
@@ -1437,6 +1457,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
diagnostics.background();
recoveryDiagnostics.delete(client);
networkSubscription?.remove();
+ localNetworkStore.update();
sub.remove();
backgroundConnection.dispose();
backgroundTransitions.current.clear();
diff --git a/apps/mobile/src/device-link/localNetworkStatus.ts b/apps/mobile/src/device-link/localNetworkStatus.ts
new file mode 100644
index 0000000000..bdb171cc3b
--- /dev/null
+++ b/apps/mobile/src/device-link/localNetworkStatus.ts
@@ -0,0 +1,31 @@
+import { useSyncExternalStore } from 'react';
+
+export type LocalNetworkStatus = 'unknown' | 'available' | 'unavailable';
+export type NetworkState = { type?: string; isConnected?: boolean; isInternetReachable?: boolean };
+
+let snapshot: { status: LocalNetworkStatus } = { status: 'unknown' };
+const listeners = new Set<() => void>();
+
+/** Native network evidence only; a failed computer request cannot change this. */
+export const localNetworkStore = {
+ getSnapshot: () => snapshot,
+ subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+ },
+ update(network?: NetworkState) {
+ // UNKNOWN may be a native lookup failure, including spurious false flags.
+ const status: LocalNetworkStatus = !network?.type || network.type === 'UNKNOWN'
+ ? 'unknown'
+ : network.type === 'NONE' || network.isConnected === false || network.isInternetReachable === false
+ ? 'unavailable'
+ : network.isConnected === true ? 'available' : 'unknown';
+ if (status === snapshot.status) return;
+ snapshot = { status };
+ for (const listener of listeners) listener();
+ },
+};
+
+export function useLocalNetworkStatus(): LocalNetworkStatus {
+ return useSyncExternalStore(localNetworkStore.subscribe, localNetworkStore.getSnapshot).status;
+}
diff --git a/apps/mobile/src/device-link/remoteStatus.ts b/apps/mobile/src/device-link/remoteStatus.ts
index d707049648..c5901b2e75 100644
--- a/apps/mobile/src/device-link/remoteStatus.ts
+++ b/apps/mobile/src/device-link/remoteStatus.ts
@@ -3,7 +3,8 @@ import {
isDeviceUnresponsiveRemoteError,
isTransientRemoteError,
} from '@cindy/maker-shared/device-link-contract';
-import type { DeviceLinkConnectionIssueKind, DeviceLinkStatus } from '@cindy/device-link';
+import type { DeviceLinkConnectionIssue, DeviceLinkConnectionIssueKind, DeviceLinkStatus } from '@cindy/device-link';
+import type { LocalNetworkStatus } from '@/device-link/localNetworkStatus';
import { i18n } from '@/i18n';
export {
@@ -40,6 +41,33 @@ export function connectionIssueHint(kind: DeviceLinkConnectionIssueKind): string
return i18n.t(CONNECTION_ISSUE_COPY_KEYS[kind].hint);
}
+/** Shared by Home and detail banners. Only native evidence blames the phone;
+ * only an online service's device verdict blames the computer. */
+export function connectionHealthCopy(input: {
+ network: LocalNetworkStatus;
+ status: DeviceLinkStatus;
+ issue: DeviceLinkConnectionIssue | null;
+ deviceDisconnected?: boolean;
+ deviceUnresponsive?: boolean;
+}): { title: string; hint: string } | null {
+ if (input.network === 'unavailable') {
+ return { title: i18n.t('deviceLink.localNetwork.title'), hint: i18n.t('deviceLink.localNetwork.hint') };
+ }
+ if (input.issue && (input.status !== 'online' || input.issue.kind === 'unstable')) {
+ return { title: connectionIssueTitle(input.issue.kind), hint: connectionIssueHint(input.issue.kind) };
+ }
+ if (input.status !== 'online') {
+ return { title: i18n.t('deviceLink.serviceConnection.title'), hint: i18n.t('deviceLink.serviceConnection.hint') };
+ }
+ if (input.deviceDisconnected) {
+ return { title: i18n.t('deviceLink.cachedHistory.title'), hint: i18n.t('deviceLink.cachedHistory.hint') };
+ }
+ if (input.deviceUnresponsive) {
+ return { title: i18n.t('deviceLink.deviceUnresponsiveTitle'), hint: i18n.t('deviceLink.deviceUnresponsiveHint') };
+ }
+ return null;
+}
+
export function relayStatusLabel(status: DeviceLinkStatus): string {
return i18n.t(`deviceLink.relay.label.${status}`);
}
@@ -197,4 +225,3 @@ export function describeRemoteComposerBlockingError(error: string | null): strin
if (!COMPOSER_BLOCKING_MARKERS.some((marker) => error.includes(marker))) return null;
return localizedStableRemoteError(error);
}
-
diff --git a/apps/mobile/src/device-link/unresponsiveDevicesStore.ts b/apps/mobile/src/device-link/unresponsiveDevicesStore.ts
index 85963ea8f2..2eba8f2091 100644
--- a/apps/mobile/src/device-link/unresponsiveDevicesStore.ts
+++ b/apps/mobile/src/device-link/unresponsiveDevicesStore.ts
@@ -10,6 +10,7 @@
import { useSyncExternalStore } from 'react';
import { DeviceLinkError, type DeviceLinkErrorCode } from '@cindy/device-link';
import { revokedDevicesStore } from '@/device-link/revokedDevicesStore';
+import { localNetworkStore } from '@/device-link/localNetworkStatus';
import {
createDeviceResponsivenessBreaker,
type BreakerSendSlot,
@@ -132,7 +133,9 @@ export function createDeviceSendCohort(deviceId: string): number {
*/
let appActive = true;
let appLifecycleEpoch = 0;
-const slotLifecycle = new WeakMap<BreakerSendSlot, { epoch: number; active: boolean }>();
+const slotLifecycle = new WeakMap<BreakerSendSlot, {
+ epoch: number; active: boolean; network: ReturnType<typeof localNetworkStore.getSnapshot>;
+}>();
export function noteAppLifecycleState(state: string): void {
const active = state === 'active';
@@ -141,9 +144,10 @@ export function noteAppLifecycleState(state: string): void {
appLifecycleEpoch += 1;
}
-function spansAppSuspension(slot: BreakerSendSlot): boolean {
+function spansLocalInterruption(slot: BreakerSendSlot): boolean {
const issued = slotLifecycle.get(slot);
- return issued !== undefined && (!issued.active || issued.epoch !== appLifecycleEpoch);
+ return issued !== undefined && (!issued.active || issued.epoch !== appLifecycleEpoch
+ || issued.network.status === 'unavailable' || issued.network !== localNetworkStore.getSnapshot());
}
export function acquireDeviceSendSlot(
@@ -153,7 +157,7 @@ export function acquireDeviceSendSlot(
): BreakerSendSlot {
const slot = breaker.acquire(deviceId, cohort, options);
if (slot.decision === 'reject') throw createDeviceUnresponsiveError(deviceId);
- slotLifecycle.set(slot, { epoch: appLifecycleEpoch, active: appActive });
+ slotLifecycle.set(slot, { epoch: appLifecycleEpoch, active: appActive, network: localNetworkStore.getSnapshot() });
return slot;
}
@@ -165,9 +169,9 @@ export function settleDeviceSend(
// 撤权竞态防护(review P1):撤权时桌面端发 link-close(revoked) 但不 resolve
// 在途请求,它们随后超时——这不是"设备无响应",是访问被收回。已撤权设备的
// 超时一律降级为不定论,不再计入熔断,避免 unresponsive 状态与撤权状态并存。
- // 跨越 App 挂起的超时同理降级(见 noteAppLifecycleState)。
+ // 跨越 App 挂起或手机网络状态变化的超时同理降级;离线时发出的请求也不计数。
const effective = outcome === 'timeout'
- && (revokedDevicesStore.has(deviceId) || spansAppSuspension(slot))
+ && (revokedDevicesStore.has(deviceId) || spansLocalInterruption(slot))
? 'inconclusive'
: outcome;
breaker.settle(deviceId, slot, effective);
diff --git a/apps/mobile/src/i18n/locales/en/deviceLink.json b/apps/mobile/src/i18n/locales/en/deviceLink.json
index 1dbfdc45fb..c1a312bbfc 100644
--- a/apps/mobile/src/i18n/locales/en/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/en/deviceLink.json
@@ -12,8 +12,16 @@
"resync": "Resync",
"resyncing": "Resyncing",
"syncShort": "Sync",
- "deviceUnresponsiveTitle": "Computer not responding",
- "deviceUnresponsiveHint": "Your computer isn't answering right now. Retrying automatically.",
+ "deviceUnresponsiveTitle": "No response yet",
+ "deviceUnresponsiveHint": "No reply received yet. Retrying automatically.",
+ "localNetwork": {
+ "title": "Phone network unavailable",
+ "hint": "Check your phone’s network. Reconnection is automatic when it recovers."
+ },
+ "serviceConnection": {
+ "title": "Cannot reach the service",
+ "hint": "Your phone cannot reach the service right now. Reconnecting automatically."
+ },
"connectStep1": "Install and open {{appName}} on your computer",
"connectStep2": "Sign in with the same account as your phone",
"connectStep3": "Under Settings → Remote Access, turn on \"Allow same-account devices to control this computer\"",
@@ -63,7 +71,7 @@
"remoteDisabled": "The remote computer has disabled remote control.",
"channelNotAllowed": "The current desktop version doesn't support this remote capability.",
"accessRevoked": "This computer has revoked mobile access.",
- "deviceUnresponsive": "The computer isn't responding. Automatic retry is in progress; try again shortly.",
+ "deviceUnresponsive": "No reply received yet. Retrying automatically.",
"versionMismatch": "The service protocol version doesn't match. Update the app and try again.",
"payloadTooLarge": "This transfer is too large. Split it into smaller parts and try again.",
"mediaFetchFailed": "The file couldn't be fetched from the computer. Try again later.",
diff --git a/apps/mobile/src/i18n/locales/ja/deviceLink.json b/apps/mobile/src/i18n/locales/ja/deviceLink.json
index f8534d7995..fbbe43b888 100644
--- a/apps/mobile/src/i18n/locales/ja/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/ja/deviceLink.json
@@ -12,8 +12,16 @@
"resync": "再同期",
"resyncing": "再同期しています",
"syncShort": "同期",
- "deviceUnresponsiveTitle": "パソコンが応答していません",
- "deviceUnresponsiveHint": "パソコンが一時的に応答していません。自動的に再試行しています。",
+ "deviceUnresponsiveTitle": "まだ応答がありません",
+ "deviceUnresponsiveHint": "まだ応答を受信していません。自動で再試行しています。",
+ "localNetwork": {
+ "title": "スマートフォンのネットワークが使えません",
+ "hint": "スマートフォンのネットワークを確認してください。復旧すると自動で接続します。"
+ },
+ "serviceConnection": {
+ "title": "サービスに接続できません",
+ "hint": "スマートフォンからサービスに接続できません。自動で再接続しています。"
+ },
"connectStep1": "パソコンに {{appName}} をインストールして起動する",
"connectStep2": "スマートフォンと同じアカウントでログインする",
"connectStep3": "「設定 → リモート接続」で「同じアカウントのデバイスにこのパソコンの操作を許可」をオンにする",
@@ -63,7 +71,7 @@
"remoteDisabled": "リモートのパソコンでリモート操作が無効になっています。",
"channelNotAllowed": "現在のデスクトップ版はこのリモート機能に対応していません。",
"accessRevoked": "このコンピューターはモバイルからのアクセスを取り消しました。",
- "deviceUnresponsive": "コンピューターが応答していません。自動再試行中です。しばらくしてから再試行してください。",
+ "deviceUnresponsive": "まだ応答を受信していません。自動で再試行しています。",
"versionMismatch": "サービスのプロトコルバージョンが一致しません。アプリを更新して再試行してください。",
"payloadTooLarge": "転送内容が大きすぎます。分割して再試行してください。",
"mediaFetchFailed": "コンピューターからファイルを取得できませんでした。後でもう一度お試しください。",
diff --git a/apps/mobile/src/i18n/locales/ko/deviceLink.json b/apps/mobile/src/i18n/locales/ko/deviceLink.json
index cf4b87c6f9..51a10c3feb 100644
--- a/apps/mobile/src/i18n/locales/ko/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/ko/deviceLink.json
@@ -12,8 +12,16 @@
"resync": "다시 동기화",
"resyncing": "다시 동기화하는 중",
"syncShort": "동기화",
- "deviceUnresponsiveTitle": "컴퓨터가 응답하지 않습니다",
- "deviceUnresponsiveHint": "컴퓨터가 일시적으로 응답하지 않습니다. 자동으로 다시 시도하고 있습니다.",
+ "deviceUnresponsiveTitle": "아직 응답이 없습니다",
+ "deviceUnresponsiveHint": "아직 응답을 받지 못했습니다. 자동으로 다시 시도하고 있습니다.",
+ "localNetwork": {
+ "title": "휴대폰 네트워크를 사용할 수 없습니다",
+ "hint": "휴대폰 네트워크를 확인해 주세요. 복구되면 자동으로 연결됩니다."
+ },
+ "serviceConnection": {
+ "title": "서비스에 연결할 수 없습니다",
+ "hint": "휴대폰에서 서비스에 연결할 수 없습니다. 자동으로 다시 연결하고 있습니다."
+ },
"connectStep1": "컴퓨터에 {{appName}}을(를) 설치하고 실행하세요",
"connectStep2": "휴대폰과 동일한 계정으로 로그인하세요",
"connectStep3": "'설정 → 원격 연결'에서 '동일 계정 기기의 이 컴퓨터 제어 허용'을 켜세요",
@@ -63,7 +71,7 @@
"remoteDisabled": "원격 컴퓨터에서 원격 제어를 껐습니다.",
"channelNotAllowed": "현재 데스크톱 버전은 이 원격 기능을 지원하지 않습니다.",
"accessRevoked": "이 컴퓨터가 모바일 접근 권한을 취소했습니다.",
- "deviceUnresponsive": "컴퓨터가 응답하지 않습니다. 자동 재시도 중이니 잠시 후 다시 시도하세요.",
+ "deviceUnresponsive": "아직 응답을 받지 못했습니다. 자동으로 다시 시도하고 있습니다.",
"versionMismatch": "서비스 프로토콜 버전이 일치하지 않습니다. 앱을 업데이트한 후 다시 시도하세요.",
"payloadTooLarge": "전송 내용이 너무 큽니다. 나누어 다시 시도하세요.",
"mediaFetchFailed": "컴퓨터에서 파일을 가져오지 못했습니다. 나중에 다시 시도하세요.",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json b/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json
index f5e064bdab..e6cdc8da8e 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json
@@ -12,8 +12,16 @@
"resync": "重新同步",
"resyncing": "正在重新同步",
"syncShort": "同步",
- "deviceUnresponsiveTitle": "电脑端未响应",
- "deviceUnresponsiveHint": "电脑暂时没有回应请求,正在自动重试。",
+ "deviceUnresponsiveTitle": "连接暂无响应",
+ "deviceUnresponsiveHint": "请求尚未收到回应,正在自动重试。",
+ "localNetwork": {
+ "title": "手机网络不可用",
+ "hint": "请检查手机网络,恢复后会自动连接。"
+ },
+ "serviceConnection": {
+ "title": "暂时连不上服务",
+ "hint": "手机暂时连不上服务,正在自动重连。"
+ },
"connectStep1": "在电脑上安装并打开 {{appName}}",
"connectStep2": "用与手机相同的账号登录",
"connectStep3": "在「设置 → 远程连接」中开启「允许同账号设备控制本机」",
@@ -63,7 +71,7 @@
"remoteDisabled": "远程电脑已关闭允许远程控制。",
"channelNotAllowed": "当前电脑端版本不支持这个远程能力。",
"accessRevoked": "这台电脑已撤销手机访问权限。",
- "deviceUnresponsive": "电脑端未响应,正在自动重试,请稍后再试。",
+ "deviceUnresponsive": "请求尚未收到回应,正在自动重试。",
"versionMismatch": "与服务端协议版本不一致,请升级 App 后重试。",
"payloadTooLarge": "这次传输的内容过大,请拆分后重试。",
"mediaFetchFailed": "获取电脑端文件失败,可以稍后重试。",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/deviceLink.json b/apps/mobile/src/i18n/locales/zh-TW/deviceLink.json
index 8a1a1bf6f2..92185541e1 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/deviceLink.json
@@ -12,8 +12,16 @@
"resync": "重新同步",
"resyncing": "正在重新同步",
"syncShort": "同步",
- "deviceUnresponsiveTitle": "電腦端未響應",
- "deviceUnresponsiveHint": "電腦暫時沒有回應請求,正在自動重試。",
+ "deviceUnresponsiveTitle": "連線暫無回應",
+ "deviceUnresponsiveHint": "請求尚未收到回應,正在自動重試。",
+ "localNetwork": {
+ "title": "手機網路無法使用",
+ "hint": "請檢查手機網路,恢復後會自動連線。"
+ },
+ "serviceConnection": {
+ "title": "暫時連不上服務",
+ "hint": "手機暫時連不上服務,正在自動重新連線。"
+ },
"connectStep1": "在電腦上安裝並開啟 {{appName}}",
"connectStep2": "用與手機相同的帳號登入",
"connectStep3": "在「設定 → 遠端連線」中開啟「允許同帳號裝置控制本機」",
@@ -63,7 +71,7 @@
"remoteDisabled": "遠端電腦已關閉允許遠端控制。",
"channelNotAllowed": "目前電腦端版本不支援這個遠端能力。",
"accessRevoked": "這臺電腦已撤銷手機存取權限。",
- "deviceUnresponsive": "電腦端未回應,正在自動重試,請稍後再試。",
+ "deviceUnresponsive": "請求尚未收到回應,正在自動重試。",
"versionMismatch": "與服務端協定版本不一致,請升級 App 後重試。",
"payloadTooLarge": "這次傳輸的內容過大,請拆分後重試。",
"mediaFetchFailed": "取得電腦端檔案失敗,可以稍後重試。",
diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsx
index 3e44c7a43e..fc8888e95a 100644
--- a/apps/mobile/src/session/HomeSurface.tsx
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@ -153,11 +153,11 @@ import {
patchDeviceViewsWithPresence,
} from '@/device-link/presenceDevices';
import {
- connectionIssueHint,
- connectionIssueTitle,
+ connectionHealthCopy,
describeRemoteError,
formatRemoteError,
} from '@/device-link/remoteStatus';
+import { useLocalNetworkStatus } from '@/device-link/localNetworkStatus';
import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
import { ConnectionRecoveryProgress } from '@/components/ConnectionBanner';
import { ConnectionNoticeOverlay, useDelayedConnectionNotice } from '@/components/ConnectionNoticeOverlay';
@@ -525,6 +525,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
const {
connectionEpoch,
connectionIssue,
+ getPresenceAvailability,
invoke,
lastPresenceSnapshot,
recoveringDeviceIds,
@@ -2179,8 +2180,22 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
}, [home.deviceFilters, home.selectedDeviceId, initialHomeSettled, selectedDeviceId]);
// 连接层失败原因比请求级 error 更根因:unstable 在 online 时也需保持可见。
const activeConnectionIssue = status !== 'online' || connectionIssue?.kind === 'unstable' ? connectionIssue : null;
- const selectedDeviceDisconnected = resolveHomeDeviceDisconnected(home.deviceFilters, selectedDeviceId, status === 'connecting');
- const showConnectionRow = selectedDeviceDisconnected || resolveConnectionBannerVisibility({
+ const network = useLocalNetworkStatus();
+ const networkUnavailable = network === 'unavailable';
+ // Cached rows and failed hydration are not proof that a computer is offline.
+ // Use this relay generation's authoritative presence; unknown stays neutral.
+ const selectedDeviceDisconnected = status === 'online'
+ && resolveHomeDeviceDisconnected(home.deviceFilters.map((device) => ({
+ deviceId: device.deviceId,
+ sessionCount: device.sessionCount,
+ available: device.deviceId === null || getPresenceAvailability(device.deviceId) !== false,
+ })), selectedDeviceId, false);
+ const healthCopy = connectionHealthCopy({
+ network, status, issue: activeConnectionIssue,
+ deviceDisconnected: selectedDeviceDisconnected,
+ deviceUnresponsive: homeDeviceRecovery && homeDeviceUnresponsive,
+ });
+ const showConnectionRow = networkUnavailable || selectedDeviceDisconnected || resolveConnectionBannerVisibility({
offline: status !== 'online',
connecting: status === 'connecting',
offlineLongEnough: true,
@@ -2191,7 +2206,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
});
const showConnectionNotice = useDelayedConnectionNotice(showConnectionRow);
const quietSyncing = !showConnectionRow && (refreshing || homeRecoveringDeviceIds.size > 0 || status === 'connecting');
- const showHomeSyncAction = resolveConnectionBannerSyncActionVisibility({
+ const showHomeSyncAction = !networkUnavailable && resolveConnectionBannerSyncActionVisibility({
online: status === 'online',
hasActiveIssue: activeConnectionIssue !== null,
deviceUnresponsive: homeDeviceRecovery,
@@ -2199,19 +2214,15 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
// loadHome has no outer retry after its bounded REST retries are exhausted.
requestErrorAutoRecovering: false,
});
- const showHomeRecoveryProgress = (!activeConnectionIssue
+ const showHomeRecoveryProgress = !networkUnavailable && (!activeConnectionIssue
|| activeConnectionIssue.kind === 'unstable' || activeConnectionIssue.kind === 'replaced')
&& (status === 'connecting' || homeDeviceRecovery);
- const connectionTone = activeConnectionIssue
+ const connectionTone = networkUnavailable || activeConnectionIssue
? 'off'
: homeDeviceRecovery ? 'busy' : selectedDeviceDisconnected ? 'off' : connectionError ? 'muted' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';
- const connectionTitle = activeConnectionIssue
- ? connectionIssueTitle(activeConnectionIssue.kind)
- : 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)
- : homeDeviceRecovery ? t(homeDeviceUnresponsive ? 'deviceLink.deviceUnresponsiveHint' : 'deviceLink.recovery.syncingHint') : selectedDeviceDisconnected ? t('deviceLink.cachedHistory.hint') : connectionError;
+ const connectionTitle = healthCopy?.title ?? (homeDeviceRecovery ? t('deviceLink.recovery.syncing')
+ : connectionError ? t('devices.list.syncFailed') : homeConnectionTitle(status, t));
+ const connectionCopy = healthCopy?.hint ?? (homeDeviceRecovery ? t('deviceLink.recovery.syncingHint') : connectionError);
const emptyStateTitle = initialHomeError ? t('devices.list.syncFailed') : home.emptyTitle;
const emptyStateCopy = initialHomeError ? (connectionError ?? t('devices.list.requestFailed')) : home.emptyCopy;
// 无可控制电脑的引导态(landing)可见性,与 ListEmptyComponent 的分支同口径。
@@ -3244,7 +3255,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
style={[styles.connectionRow, (connectionError || activeConnectionIssue) && styles.connectionRowError]}
testID="connection.banner"
>
- <StatusDot tone={connectionTone} pulsing={!activeConnectionIssue && status === 'connecting'} />
+ <StatusDot tone={connectionTone} pulsing={!networkUnavailable && !activeConnectionIssue && status === 'connecting'} />
<Text ellipsizeMode="tail" numberOfLines={1} style={styles.connectionText} testID="connection.title">
{connectionCopy ? `${connectionTitle} · ${connectionCopy}` : connectionTitle}
</Text>