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): 修复推荐任务前闪现空态 (#4616)

Dashaffb63bc0e19
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index 3f6c7f081f..66a92f8561 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -1,4 +1,5 @@
import { RemoteTaskSuggestions } from '@/session/RemoteTaskSuggestions';
+import { isTaskSuggestionsSyncPending, useRemoteTaskSuggestionsPresentation } from '@/session/useRemoteTaskSuggestionsPresentation';
import { countHomeSuggestionSessions, remoteTaskSuggestionsMode, type RemoteTaskSuggestionId } from '@/session/remoteTaskSuggestionsModel';
import { cacheRemoteResourceHome, readRemoteResourceSnapshot } from '@/device-link/remoteResourceCache';
import { canBrowseMobileHomeDevice } from '@/session/mobileHome';
@@ -1897,7 +1898,10 @@ function HomeScreenContent() {
// 「可用」项,但缓存设备不能当 live 设备直接开新会话——列表先画出来,新建入口等 live 数据。
const newSessionDisabled = !home.primaryDevice || (!initialHomeSettled && !hasOpenableLiveDevice);
const taskSuggestionsDeviceId = selectedDeviceId ?? home.primaryDevice?.deviceId ?? undefined;
- const taskSuggestionsMode = remoteTaskSuggestionsMode({
+ const taskSuggestionsSyncing = isTaskSuggestionsSyncPending(
+ homeSyncDeviceIds, homeListOwnedDeviceIdsRef.current, rawDeviceConnectionStates,
+ );
+ const taskSuggestionsCandidateMode = remoteTaskSuggestionsMode({
sessionCount: countHomeSuggestionSessions(home,
shouldReplaceListWithSearchResults(searchQuery, indexedSearch.status) ? indexedSearch.results : undefined),
totalSessionCount: home.overview.all,
@@ -1906,7 +1910,9 @@ function HomeScreenContent() {
ready: status === 'online' && !activeConnectionIssue && !initialHomeLoading && !initialHomeError && !connectionError
&& indexedSearch.status !== 'searching' && !newSessionDisabled
&& deviceModels.some((device) => device.canOpen
- && !homeRecoveringDeviceIds.has(device.deviceId)
+ && !recoveringDeviceIds.has(device.deviceId)
+ && !unresponsiveDevices.has(device.deviceId)
+ && rawDeviceConnectionStates[device.deviceId] !== 'failed'
&& device.deviceId === taskSuggestionsDeviceId),
});
const newSessionDeviceOptions = useMemo(
@@ -1915,6 +1921,11 @@ function HomeScreenContent() {
.map((item) => ({ deviceId: item.deviceId, name: item.name })),
[deviceModels],
);
+ const { mode: taskSuggestionsMode, pending: taskSuggestionsPending } = useRemoteTaskSuggestionsPresentation({
+ scope: JSON.stringify([accountGeneration, selectedDeviceId, taskSuggestionsDeviceId, [...homeSyncDeviceIds].sort()]),
+ candidateMode: taskSuggestionsCandidateMode,
+ syncing: taskSuggestionsSyncing,
+ });
const selectedDeviceLabel = useMemo(() => {
if (!selectedDeviceId) return t('devices.list.allConversations');
// 设备列表尚未同步回来时,用偏好里存的设备名兜底,避免冷启动表头闪占位文案。
@@ -2676,7 +2687,7 @@ function HomeScreenContent() {
<View style={styles.pinnedFooter} testID="home.pinnedFooter" />
) : null}
ListEmptyComponent={
- initialHomeLoading ? (
+ initialHomeLoading || taskSuggestionsPending ? (
<HomeInitialLoadingState
style={{
marginTop: spacing.xxl,
@@ -2744,7 +2755,7 @@ function HomeScreenContent() {
/>
) : null}
- {showRemoteGuide || taskSuggestionsMode === 'empty' ? null : (
+ {showRemoteGuide || taskSuggestionsPending || taskSuggestionsMode === 'empty' ? null : (
// 无可控电脑时不提供入口;完整空态已有主按钮,避免重复显示新建 CTA。
<Pressable
accessibilityLabel={t('devices.list.a11y.newRemoteConversation')}
diff --git a/apps/mobile/src/__tests__/RemoteTaskSuggestions.test.tsx b/apps/mobile/src/__tests__/RemoteTaskSuggestions.test.tsx
index 699130d527..5f4af8ecd7 100644
--- a/apps/mobile/src/__tests__/RemoteTaskSuggestions.test.tsx
+++ b/apps/mobile/src/__tests__/RemoteTaskSuggestions.test.tsx
@@ -3,6 +3,8 @@ import { act, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { RemoteTaskSuggestions } from "@/session/RemoteTaskSuggestions";
+import { isTaskSuggestionsSyncPending, useRemoteTaskSuggestionsPresentation } from "@/session/useRemoteTaskSuggestionsPresentation";
+import type { RemoteTaskSuggestionsMode } from "@/session/remoteTaskSuggestionsModel";
import { i18n } from "@/i18n";
import { REMOTE_TASK_SUGGESTION_BATCHES } from "@/session/remoteTaskSuggestionsModel";
@@ -41,24 +43,26 @@ vi.mock("@/components/MobilePrimitives", async () => {
children,
onPress,
testID,
+ disabled,
}: {
children: ReactNode;
onPress(): void;
testID: string;
+ disabled?: boolean;
}) =>
createElement(
"button",
- { onClick: onPress, "data-testid": testID },
+ { onClick: onPress, disabled, "data-testid": testID },
children,
),
MainWindowActionButton: ({
action,
}: {
- action: { label: string; onPress(): void; testID: string };
+ action: { label: string; onPress(): void; testID: string; disabled?: boolean };
}) =>
createElement(
"button",
- { onClick: action.onPress, "data-testid": action.testID },
+ { onClick: action.onPress, disabled: action.disabled, "data-testid": action.testID },
action.label,
),
};
@@ -92,6 +96,103 @@ const click = (id: string) =>
);
describe("remote task recommendations", () => {
+ const select = vi.fn();
+ const create = vi.fn();
+ function Presentation(props: { scope: string; candidateMode: RemoteTaskSuggestionsMode; syncing: boolean }) {
+ const { mode, pending } = useRemoteTaskSuggestionsPresentation(props);
+ return mode ? <RemoteTaskSuggestions mode={mode} onSelect={select} onNewSession={create} />
+ : <div>{pending ? 'loading' : 'fallback'}</div>;
+ }
+ const renderPresentation = (syncing: boolean, candidateMode: RemoteTaskSuggestionsMode = 'empty', scope = 'account:computer') =>
+ act(() => root.render(<Presentation scope={scope} syncing={syncing} candidateMode={candidateMode} />));
+
+ it.each(['light', 'dark'])('waits for first sync and keeps recommendations through a refresh in %s', (mode) => {
+ theme.mode = mode;
+ select.mockClear();
+ create.mockClear();
+ renderPresentation(true);
+ expect(host.textContent).toBe('loading');
+ renderPresentation(false);
+ expect(host.textContent).toContain('电脑已连接');
+ click('shuffle');
+ renderPresentation(true);
+ expect(host.textContent).toContain('电脑已连接');
+ expect(host.textContent).toContain('看看下载文件夹里有什么');
+ click('downloads');
+ click('newTask');
+ expect(select).toHaveBeenCalledWith('downloads');
+ expect(create).toHaveBeenCalledOnce();
+ renderPresentation(false);
+ click('downloads');
+ expect(select).toHaveBeenCalledWith('downloads');
+ });
+
+ it('waits before a newly selected cached device is acquired and through queued hydration', () => {
+ renderPresentation(false);
+ const owned = new Set<string>();
+ const renderDevice = (state: 'idle' | 'syncing') => renderPresentation(
+ isTaskSuggestionsSyncPending(['other'], owned, { other: state }), 'empty', 'account:other',
+ );
+ renderDevice('idle'); // Selection render, before the passive acquisition effect.
+ expect(host.textContent).toBe('loading');
+ renderDevice('syncing'); // Queued behind another peer, owner not acquired yet.
+ expect(host.textContent).toBe('loading');
+ owned.add('other');
+ renderDevice('syncing');
+ expect(host.textContent).toBe('loading');
+ renderDevice('idle');
+ expect(host.textContent).toContain('电脑已连接');
+ });
+
+ it('waits for every peer in all-tasks scope, including peers queued beyond the batch limit', () => {
+ const owned = new Set(['primary']);
+ const renderPeers = (secondary?: 'syncing' | 'idle') => renderPresentation(
+ isTaskSuggestionsSyncPending(['primary', 'secondary'], owned,
+ { primary: 'idle', ...(secondary ? { secondary } : {}) }),
+ 'empty', 'account:all',
+ );
+ renderPeers(); // Primary done; secondary hydration has not started.
+ expect(host.textContent).toBe('loading');
+ owned.add('secondary');
+ renderPeers('syncing');
+ expect(host.textContent).toBe('loading');
+ renderPeers('idle');
+ expect(host.textContent).toContain('电脑已连接');
+ click('shuffle');
+ renderPeers('syncing');
+ expect(host.textContent).toContain('看看下载文件夹里有什么');
+ expect(isTaskSuggestionsSyncPending(['primary'], owned, { secondary: 'syncing' })).toBe(false);
+ expect(isTaskSuggestionsSyncPending(['secondary'], owned, { secondary: 'failed' })).toBe(false);
+ });
+
+ it('does not carry ready presentation into another account or device', () => {
+ renderPresentation(false);
+ renderPresentation(true, 'empty', 'account:other-computer');
+ expect(host.textContent).toBe('loading');
+ renderPresentation(false, 'empty', 'account:other-computer');
+ renderPresentation(true, 'empty', 'other-account:other-computer');
+ expect(host.textContent).toBe('loading');
+ });
+
+ it('releases retained recommendations on unavailable, error, filtered-empty or nonempty outcomes', () => {
+ renderPresentation(false);
+ renderPresentation(true);
+ expect(host.textContent).toContain('电脑已连接');
+ // These outcomes all produce no candidate; they must keep their own page branch.
+ renderPresentation(true, null);
+ expect(host.textContent).toBe('fallback');
+ renderPresentation(true);
+ expect(host.textContent).toBe('loading');
+ });
+
+ it('retains an existing footer but does not replace a task list with loading', () => {
+ renderPresentation(true, 'footer');
+ expect(host.textContent).toBe('fallback');
+ renderPresentation(false, 'footer');
+ renderPresentation(true, 'footer');
+ expect(host.textContent).toContain('接下来,让电脑帮你');
+ expect(host.querySelector<HTMLButtonElement>('[data-testid="home.taskSuggestions.findFile"]')?.disabled).toBe(false);
+ });
it.each(["light", "dark"])(
"offers editable task selection and another batch with %s tokens",
(mode) => {
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index f5d2a6271d..a15439cedf 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -723,7 +723,7 @@ describe('mobile home desktop-first surface', () => {
expect(source).toContain('testID="home.remoteAccessGuide"');
// 引导态没有可筛选的对话:表头退化为纯品牌标题(无下拉菜单),新建 FAB 不渲染。
expect(source).toContain('{showRemoteGuide ? (');
- expect(source).toContain("{showRemoteGuide || taskSuggestionsMode === 'empty' ? null : (");
+ expect(source).toContain("{showRemoteGuide || taskSuggestionsPending || taskSuggestionsMode === 'empty' ? null : (");
const guideSource = readSource('src/components/RemoteAccessGuide.tsx');
// 文案已 i18n 化,断言改查 zh-CN catalog(单一事实源);源码只保留结构/交互契约。
diff --git a/apps/mobile/src/__tests__/remoteTaskSuggestions.test.ts b/apps/mobile/src/__tests__/remoteTaskSuggestions.test.ts
index de9a42f72b..94df6ea662 100644
--- a/apps/mobile/src/__tests__/remoteTaskSuggestions.test.ts
+++ b/apps/mobile/src/__tests__/remoteTaskSuggestions.test.ts
@@ -109,7 +109,8 @@ describe("home recommendation connection readiness", () => {
const source = readTextLf(resolve(process.cwd(), "app/devices/index.tsx"), "utf8");
const expression = source.match(/ready: ([\s\S]*?),\n \}\);\n const newSessionDeviceOptions/)?.[1];
expect(expression).toBeTruthy();
- const evaluateReady = new Function("status", "activeConnectionIssue", "homeRecoveringDeviceIds", "selectedDeviceId", `
+ const evaluateReady = new Function("status", "activeConnectionIssue", "recoveringDeviceIds", "selectedDeviceId", `
+ const unresponsiveDevices = new Set(), rawDeviceConnectionStates = {};
const initialHomeLoading = false, initialHomeError = null, connectionError = null;
const indexedSearch = { status: 'idle' }, newSessionDisabled = false;
const deviceModels = [{ deviceId: 'computer', canOpen: true }];
diff --git a/apps/mobile/src/session/useRemoteTaskSuggestionsPresentation.ts b/apps/mobile/src/session/useRemoteTaskSuggestionsPresentation.ts
new file mode 100644
index 0000000000..e640107d2a
--- /dev/null
+++ b/apps/mobile/src/session/useRemoteTaskSuggestionsPresentation.ts
@@ -0,0 +1,33 @@
+import { useLayoutEffect, useRef } from 'react';
+import type { RemoteTaskSuggestionsMode } from './remoteTaskSuggestionsModel';
+
+/** An idle cached peer is not settled until this list scope has acquired its owner. */
+export function isTaskSuggestionsSyncPending(
+ deviceIds: readonly string[],
+ ownedDeviceIds: ReadonlySet<string>,
+ connectionStates: Readonly<Record<string, 'idle' | 'syncing' | 'failed'>>,
+): boolean {
+ return deviceIds.some((id) => !ownedDeviceIds.has(id) || connectionStates[id] === 'syncing');
+}
+
+/** Retain only an already displayed recommendation during an ordinary list refresh. */
+export function useRemoteTaskSuggestionsPresentation({
+ scope,
+ candidateMode,
+ syncing,
+}: {
+ scope: string;
+ candidateMode: RemoteTaskSuggestionsMode;
+ syncing: boolean;
+}) {
+ const displayed = useRef<{ scope: string; mode: RemoteTaskSuggestionsMode } | null>(null);
+ const retain = displayed.current?.scope === scope && displayed.current.mode === candidateMode;
+ const mode = syncing && !retain ? null : candidateMode;
+
+ useLayoutEffect(() => {
+ // A different account/device or an ineligible candidate must not inherit visibility.
+ displayed.current = mode ? { scope, mode } : null;
+ }, [scope, mode]);
+
+ return { mode, pending: syncing && candidateMode === 'empty' && !mode };
+}