Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 修正网络切换归因并保留历史重试入口
Dash4d490acc5f01
diff --git a/apps/mobile/src/__tests__/connectionBannerRecovery.test.tsx b/apps/mobile/src/__tests__/connectionBannerRecovery.test.tsxindex f67d7d9dc4..dcd95d50fa 100644--- a/apps/mobile/src/__tests__/connectionBannerRecovery.test.tsx+++ b/apps/mobile/src/__tests__/connectionBannerRecovery.test.tsx@@ -23,7 +23,11 @@ vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => true }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('@/components/MobilePrimitives', () => ({+ MainWindowActionButton: ({ action }: { action: { onPress(): void; testID: string } }) =>+ createElement('button', { onClick: action.onPress, 'data-testid': action.testID }),+ StatusDot: () => null,+}));vi.mock('@/theme', () => ({ fontWeight: {}, useTheme: () => ({ colors: {} }), useThemedStyles: () => ({}) }));let root: Root;@@ -74,6 +78,26 @@ it('distinguishes service loss, confirmed offline computer and unattributed timeexpect(banner('online', false, true)).toBe('连接暂无响应');});+// Unit regression: a retained history error must not override recovered presence+// or remove its real retry action; existing cases only covered null request errors.+it('restores history retry after the computer reconnects despite a retained offline error', () => {+ const onSync = vi.fn();+ const props = {+ status: 'online' as const, loading: false, error: '[DEVICE_OFFLINE] unavailable',+ requestErrorAutoRecovering: false, lastSyncedAt: null, onSync,+ };+ act(() => root.render(createElement(ConnectionBanner, { ...props, cachedOnly: true })));+ advance(3_000);+ expect(container.querySelector('[data-testid="connection.title"]')?.textContent).toBe('电脑未连接');+ expect(container.querySelector('button')).toBeNull();+ act(() => root.render(createElement(ConnectionBanner, { ...props, cachedOnly: false })));+ expect(container.querySelector('[data-testid="connection.title"]')?.textContent).toBe(i18n.t('deviceLink.syncFailed'));+ const button = container.querySelector<HTMLButtonElement>('[data-testid="connection.syncButton"]');+ expect(button).not.toBeNull();+ act(() => button!.click());+ expect(onSync).toHaveBeenCalledOnce();+});+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__/historyViewProvider.test.tsx b/apps/mobile/src/__tests__/historyViewProvider.test.tsxindex 082753b294..0c42fe0501 100644--- a/apps/mobile/src/__tests__/historyViewProvider.test.tsx+++ b/apps/mobile/src/__tests__/historyViewProvider.test.tsx@@ -483,19 +483,27 @@ describe('Provider network recovery priority', () => {// 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 () => {+ it.each(['outage', 'route switch'] as const)('does not blame either computer for timeouts spanning a phone %s', async (change) => {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(change === 'outage'+ ? { type: 'NONE', isConnected: false, isInternetReachable: false }+ : { ...wifi, type: 'CELLULAR' });networkEvents.network(wifi);devices.forEach((device, index) => {pending[index].forEach(slot => settleDeviceSend(device, slot, 'timeout'));});});expect([...unresponsiveDevicesStore.getSnapshot()]).toEqual([]);+ const fresh = Array.from({ length: 3 }, () => acquireDeviceSendSlot('host-a'));+ await act(async () => {+ networkEvents.network(wifi);+ fresh.forEach(slot => settleDeviceSend('host-a', slot, 'timeout'));+ });+ expect(unresponsiveDevicesStore.has('host-a')).toBe(true);});it('ignores requests issued offline, then counts new failures after recovery', async () => {diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.tsindex 7e014eddc6..1e9f7031e9 100644--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts@@ -1,15 +1,46 @@import { existsSync, readFileSync } from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it, vi } from 'vitest';+import ts from 'typescript';import { i18n } from '@/i18n';import { startBoundedStartupRead } from '@/session/mobileHomeStartup';-import { resolveConnectionBannerSyncActionVisibility, resolveHomeConnectionFeedback } from '@/components/connectionBannerVisibility';-import { describeRemoteError } from '@/device-link/remoteStatus';+import { resolveConnectionBannerSyncActionVisibility, resolveConnectionBannerVisibility, resolveHomeConnectionFeedback } from '@/components/connectionBannerVisibility';+import { connectionHealthCopy, describeRemoteError } from '@/device-link/remoteStatus';function readSource(relativePath: string): string {return readFileSync(resolve(process.cwd(), relativePath), 'utf8').replace(/\r\n/g, '\n');}+// Exercise Home's actual feedback expressions: literal-source assertions missed+// phone-wide outages and broke when the same shared policy gained that input.+const homeSource = ts.createSourceFile('HomeSurface.tsx', readSource('src/session/HomeSurface.tsx'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const feedbackExpressions = new Map<string, string>();+const feedbackNames = new Set(['healthCopy', 'showConnectionRow', 'showHomeSyncAction', 'showHomeRecoveryProgress', 'connectionTitle']);+function collectFeedback(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && feedbackNames.has(node.name.getText(homeSource)) && node.initializer) {+ feedbackExpressions.set(node.name.getText(homeSource), ts.transpileModule(`const result = ${node.initializer.getText(homeSource)};`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText);+ }+ ts.forEachChild(node, collectFeedback);+}+collectFeedback(homeSource);+function homeFeedback(overrides: Record<string, unknown>) {+ const bindings: Record<string, unknown> = {+ network: 'available', networkUnavailable: false, status: 'online',+ selectedDeviceDisconnected: false, activeConnectionIssue: null,+ homeDeviceRecovery: false, homeDeviceUnresponsive: false, connectionError: null,+ resolveConnectionBannerSyncActionVisibility, resolveConnectionBannerVisibility, connectionHealthCopy,+ t: (key: string) => i18n.t(key), homeConnectionTitle: () => 'online', ...overrides,+ };+ for (const name of feedbackNames) {+ const expression = feedbackExpressions.get(name);+ if (!expression) throw new Error(`Missing Home feedback: ${name}`);+ bindings[name] = new Function(...Object.keys(bindings), `${expression}\nreturn result;`)(...Object.values(bindings));+ }+ return bindings;+}+describe('mobile Home connection feedback', () => {it('does not offer manual sync for the device-prefixed unresponsive error shown on Home', () => {expect(resolveConnectionBannerSyncActionVisibility({@@ -25,10 +56,20 @@ describe('mobile Home connection feedback', () => {const source = readSource('src/session/HomeSurface.tsx');expect(source).toContain('resolveHomeConnectionFeedback(error, homeRecoveringDeviceIds, describeRemoteError)');expect(source).toContain('deviceUnresponsive: homeDeviceRecovery,');- expect(source).toContain('const showHomeSyncAction = resolveConnectionBannerSyncActionVisibility(');- expect(source).toContain('const showConnectionRow = selectedDeviceDisconnected || resolveConnectionBannerVisibility(');expect(source).toContain('deviceUnresponsive: homeDeviceUnresponsive,');- expect(source).toContain("homeDeviceRecovery ? t(homeDeviceUnresponsive ? 'deviceLink.deviceUnresponsiveTitle' : 'deviceLink.recovery.syncing')");+ expect(homeFeedback({})).toMatchObject({ showConnectionRow: false, showHomeSyncAction: false });+ expect(homeFeedback({ selectedDeviceDisconnected: true })).toMatchObject({+ showConnectionRow: true, connectionTitle: i18n.t('deviceLink.cachedHistory.title'),+ });+ expect(homeFeedback({ homeDeviceRecovery: true, homeDeviceUnresponsive: true })).toMatchObject({+ showConnectionRow: true, showHomeSyncAction: false, showHomeRecoveryProgress: true,+ connectionTitle: i18n.t('deviceLink.deviceUnresponsiveTitle'),+ });+ expect(homeFeedback({ connectionError: 'failed' })).toMatchObject({ showConnectionRow: true, showHomeSyncAction: true });+ expect(homeFeedback({ network: 'unavailable', networkUnavailable: true, connectionError: 'failed' })).toMatchObject({+ showConnectionRow: true, showHomeSyncAction: false, showHomeRecoveryProgress: false,+ connectionTitle: i18n.t('deviceLink.localNetwork.title'),+ });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('));@@ -520,9 +561,7 @@ describe('mobile home desktop-first surface', () => {expect(source).toContain("updateDeviceConnectionState(device.deviceId, 'syncing');");expect(source).toContain("updateDeviceConnectionState(device.deviceId, 'failed');");expect(source).toContain("updateDeviceConnectionState(device.deviceId, 'idle');");- expect(source).toContain(- 'const showConnectionRow = selectedDeviceDisconnected || resolveConnectionBannerVisibility(',- );+ // Row visibility is exercised through Home's actual expressions above.expect(source).toContain('homeSyncDeviceIds.filter((id) => unresponsiveDevices.has(id)');expect(source).toContain('function DeviceMenuItem');expect(source).not.toContain('function DeviceConnectionSpinner');diff --git a/apps/mobile/src/components/ConnectionBanner.tsx b/apps/mobile/src/components/ConnectionBanner.tsxindex aee339e1d2..8f69902b88 100644--- a/apps/mobile/src/components/ConnectionBanner.tsx+++ b/apps/mobile/src/components/ConnectionBanner.tsx@@ -90,7 +90,9 @@ export function ConnectionBanner({// 熔断已关后残留的 DEVICE_UNRESPONSIVE 错误是陈旧快照,按 null 处理(与// useShowConnectionBanner 同一判定,否则会出现可见但无内容的空壳 banner)。const effectiveError = resolveEffectiveConnectionError(error, deviceUnresponsive);- const deviceDisconnected = cachedOnly || Boolean(effectiveError?.includes('DEVICE_OFFLINE'));+ // Request errors can outlive reconnection (e.g. history pagination). Only the+ // current presence verdict can replace that request's error and retry action.+ const deviceDisconnected = cachedOnly;const healthCopy = connectionHealthCopy({network, status, issue: activeIssue,deviceDisconnected,diff --git a/apps/mobile/src/device-link/localNetworkStatus.ts b/apps/mobile/src/device-link/localNetworkStatus.tsindex bdb171cc3b..bade9fc043 100644--- a/apps/mobile/src/device-link/localNetworkStatus.ts+++ b/apps/mobile/src/device-link/localNetworkStatus.ts@@ -3,7 +3,7 @@ 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' };+let snapshot: { status: LocalNetworkStatus; connectedType?: string } = { status: 'unknown' };const listeners = new Set<() => void>();/** Native network evidence only; a failed computer request cannot change this. */@@ -20,8 +20,12 @@ export const localNetworkStore = {: network.type === 'NONE' || network.isConnected === false || network.isInternetReachable === false? 'unavailable': network.isConnected === true ? 'available' : 'unknown';- if (status === snapshot.status) return;- snapshot = { status };+ // A connected WIFI → CELLULAR transition interrupts old requests even when+ // both paths are available. Repeated capability hints keep the same snapshot.+ const connectedType = network?.isConnected === true && network.type !== 'UNKNOWN' && network.type !== 'NONE'+ ? network.type : undefined;+ if (status === snapshot.status && connectedType === snapshot.connectedType) return;+ snapshot = { status, connectedType };for (const listener of listeners) listener();},};