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): 修复任务列表切换时提前显示空状态

Dash94fa8a5099d6
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsx
index 95beae7758..5153f59a7f 100644
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@ -1,7 +1,7 @@
import { useIsFocused, useLocalSearchParams, useRouter } from 'expo-router';
import { withNewSessionCreationRemoval } from '@/session/newSessionCreation';
import { useHeaderHeight } from 'expo-router/react-navigation';
-import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useSharedValue } from 'react-native-reanimated';
import {
ActivityIndicator,
@@ -204,6 +204,11 @@ function DeviceDetailScreenContent() {
const [statusFilter, setStatusFilter] = useState<RemoteSessionStatusFilter>(
() => parseRouteStatusFilter(readRouteString(params.statusFilter)),
);
+ const requestedListFilter = automationScopeKey ? 'all' : remoteListStatusFilter(statusFilter);
+ const listQueryScope = useMemo(() => ({ deviceId, filter: requestedListFilter }), [deviceId, requestedListFilter]);
+ const listQueryScopeRef = useRef(listQueryScope);
+ listQueryScopeRef.current = listQueryScope;
+ const [syncedListQueryScope, setSyncedListQueryScope] = useState<typeof listQueryScope | null>(null);
const [filtersOpen, setFiltersOpen] = useState(false);
const [searchOpen, setSearchOpen] = useState(() => readRouteString(params.search) === '1');
const [searchFilterOpen, setSearchFilterOpen] = useState(false);
@@ -211,6 +216,7 @@ function DeviceDetailScreenContent() {
const headerHeight = useHeaderHeight();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
+ useLayoutEffect(() => { setError(null); }, [listQueryScope]);
// 熔断 open(电脑端未响应):relay 可能仍 online,可见性与 banner 文案单独入参。
const unresponsiveDevices = useUnresponsiveDevices();
const deviceUnresponsive = !!deviceId && unresponsiveDevices.has(deviceId);
@@ -298,6 +304,8 @@ function DeviceDetailScreenContent() {
const syncSessions = useCallback(async () => {
if (!deviceId) return;
+ const isCurrentQuery = () => listQueryScopeRef.current === listQueryScope;
+ if (!isCurrentQuery()) return;
setLoading(true);
setError(null);
try {
@@ -308,11 +316,12 @@ function DeviceDetailScreenContent() {
LIST_LIMIT,
// 自动化任务作用域页承诺展示"该任务的全部 N 次运行",归档的 run 也算,
// 必须拉全量;其余模式仍按当前筛选拉取。
- automationScopeKey ? 'all' : remoteListStatusFilter(statusFilter),
+ requestedListFilter,
// 首拉 / reseed / 筛选重拉都是权威快照,不并入被控端写前查询。
{ includePinned: true, fresh: true },
]);
});
+ if (!isCurrentQuery()) return;
if (!remoteSessionStore.isDeviceSessionListMutationEpochCurrent(deviceId, mutationEpoch)) {
// The existing sync runner queues one follow-up after this stale read.
remoteSessionStore.requestReseed(deviceId);
@@ -337,12 +346,13 @@ function DeviceDetailScreenContent() {
setScheduleIndex(new Map());
});
setLastSyncedAt(Date.now());
+ setSyncedListQueryScope(listQueryScope);
} catch (err) {
- setError(formatRemoteError(err));
+ if (isCurrentQuery()) setError(formatRemoteError(err));
} finally {
- setLoading(false);
+ if (isCurrentQuery()) setLoading(false);
}
- }, [automationScopeKey, canLoadScheduleIndex, deviceId, deviceName, invoke, maker, statusFilter, subscribe]);
+ }, [canLoadScheduleIndex, deviceId, deviceName, invoke, listQueryScope, maker, requestedListFilter, subscribe]);
const loadSessions = useRemoteSyncTask(syncSessions);
useEffect(() => {
@@ -355,7 +365,7 @@ function DeviceDetailScreenContent() {
useEffect(() => {
void loadSessions();
- }, [loadSessions, statusFilter]);
+ }, [loadSessions, listQueryScope]);
useEffect(() => {
if (screenFocused && appStateActive && scheduleEventSnapshot.sessionIndexVersion > 0) void loadSessions();
@@ -485,13 +495,17 @@ function DeviceDetailScreenContent() {
() => deviceSessionEmptyState(statusFilter, searchQuery),
[searchQuery, statusFilter, t],
);
- // 首同步完成前(lastSyncedAt === null)抑制"还没有对话"空状态,避免冷进(deep link)先闪空态
- // 再跳成真列表(规则 7:不闪空白/不跳变)。同步失败时 ConnectionBanner 已有错误 + 重试入口。
+ // 当前设备和筛选同步完成前抑制空状态,旧筛选的成功不能证明新筛选为空。
+ // 同步失败时 ConnectionBanner 已有错误提示,不再同时显示 loading 或空结果。
// 抑制期渲染 RemoteListSyncingPlaceholder(800ms 内空白,超时浮现「正在同步」),
// 慢链路 / 连接翻覆下首同步拖长时不再是无限期纯白。
const suppressListEmptyState = shouldSuppressRemoteListEmptyState({
- itemCount: visibleSessionIds.length,
- hasSyncedThisOpen: lastSyncedAt !== null,
+ // Used only by ListEmptyComponent. An automation group may be empty even
+ // when the host's unfiltered sections contain other tasks.
+ itemCount: 0,
+ hasSyncedThisOpen: syncedListQueryScope === listQueryScope,
+ loading: loading || indexedSearch.status === 'searching',
+ failed: !!error,
});
useEffect(() => {
setSelectedSessionIds((prev) => {
@@ -745,7 +759,9 @@ function DeviceDetailScreenContent() {
testID={`deviceDetail.automationRunRow.${item.session.id}`}
/>
)}
- ListEmptyComponent={
+ ListEmptyComponent={suppressListEmptyState ? (
+ error ? null : <RemoteListSyncingPlaceholder testID="deviceDetail.automationSyncing" />
+ ) : (
<MainWindowEmptyState
centered
copy={t('devices.detail.automationScope.emptyCopy')}
@@ -757,7 +773,7 @@ function DeviceDetailScreenContent() {
testID="deviceDetail.automationEmpty"
title={t('devices.detail.automationScope.emptyTitle')}
/>
- }
+ )}
/>
{actionOverlays}
</SafeAreaView>
@@ -882,7 +898,7 @@ function DeviceDetailScreenContent() {
/>
)}
ListEmptyComponent={suppressListEmptyState ? (
- <RemoteListSyncingPlaceholder testID="deviceDetail.projectSyncing" />
+ error ? null : <RemoteListSyncingPlaceholder testID="deviceDetail.projectSyncing" />
) : (
<MainWindowEmptyState
centered
@@ -1215,7 +1231,7 @@ function DeviceDetailScreenContent() {
section.title ? <Text style={styles.sectionTitle}>{section.title}</Text> : null
)}
ListEmptyComponent={suppressListEmptyState ? (
- <RemoteListSyncingPlaceholder testID="deviceDetail.syncing" />
+ error ? null : <RemoteListSyncingPlaceholder testID="deviceDetail.syncing" />
) : (
<MainWindowEmptyState
centered
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index 1e9f7031e9..1456befb52 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -6,6 +6,7 @@ import { i18n } from '@/i18n';
import { startBoundedStartupRead } from '@/session/mobileHomeStartup';
import { resolveConnectionBannerSyncActionVisibility, resolveConnectionBannerVisibility, resolveHomeConnectionFeedback } from '@/components/connectionBannerVisibility';
import { connectionHealthCopy, describeRemoteError } from '@/device-link/remoteStatus';
+import { isTaskSuggestionsSyncPending } from '@/session/useRemoteTaskSuggestionsPresentation';
function readSource(relativePath: string): string {
return readFileSync(resolve(process.cwd(), relativePath), 'utf8').replace(/\r\n/g, '\n');
@@ -15,7 +16,7 @@ function readSource(relativePath: string): string {
// 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']);
+const feedbackNames = new Set(['homeListScopePending', 'initialHomeLoading', 'initialHomeError', '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)};`, {
@@ -30,6 +31,9 @@ function homeFeedback(overrides: Record<string, unknown>) {
network: 'available', networkUnavailable: false, status: 'online',
selectedDeviceDisconnected: false, activeConnectionIssue: null,
homeDeviceRecovery: false, homeDeviceUnresponsive: false, connectionError: null,
+ initialHomeSettled: true, homeListFilterChanged: false, indexedSearch: { status: 'idle' },
+ homeSyncDeviceIds: ['mac'], homeListOwnedDeviceIdsRef: { current: new Set(['mac']) },
+ rawDeviceConnectionStates: { mac: 'idle' }, isTaskSuggestionsSyncPending,
resolveConnectionBannerSyncActionVisibility, resolveConnectionBannerVisibility, connectionHealthCopy,
t: (key: string) => i18n.t(key), homeConnectionTitle: () => 'online', ...overrides,
};
@@ -42,6 +46,25 @@ function homeFeedback(overrides: Record<string, unknown>) {
}
describe('mobile Home connection feedback', () => {
+ // Unit regression for the reported active/archive flash: run Home's actual
+ // presentation expressions after startup has already settled. Existing tests
+ // only exercised connection banners and never a new list scope or search.
+ it.each([
+ { homeListFilterChanged: true },
+ { homeListOwnedDeviceIdsRef: { current: new Set() } },
+ { rawDeviceConnectionStates: { mac: 'syncing' } },
+ { indexedSearch: { status: 'searching' } },
+ ])('keeps an empty list loading during %o after the first sync', (state) => {
+ expect(homeFeedback(state).initialHomeLoading).toBe(true);
+ });
+
+ it('shows a failed reload as an error instead of a successful empty result', () => {
+ expect(homeFeedback({ connectionError: 'failed' })).toMatchObject({
+ initialHomeLoading: false, initialHomeError: true,
+ });
+ expect(homeFeedback({})).toMatchObject({ initialHomeLoading: false, initialHomeError: false });
+ });
+
it('does not offer manual sync for the device-prefixed unresponsive error shown on Home', () => {
expect(resolveConnectionBannerSyncActionVisibility({
online: true,
@@ -791,8 +814,12 @@ describe('mobile home desktop-first surface', () => {
const source = readSource('src/session/HomeSurface.tsx');
expect(source).toContain('const initialHomeSettled = deviceIdentityCacheReady && lastSyncedAt !== null;');
- expect(source).toContain('const initialHomeLoading = !initialHomeSettled && !connectionError;');
- expect(source).toContain('const initialHomeError = !initialHomeSettled && !!connectionError;');
+ expect(homeFeedback({ initialHomeSettled: false })).toMatchObject({
+ initialHomeLoading: true, initialHomeError: false,
+ });
+ expect(homeFeedback({ initialHomeSettled: false, connectionError: 'failed' })).toMatchObject({
+ initialHomeLoading: false, initialHomeError: true,
+ });
expect(source).toContain('const hasOpenableLiveDevice = deviceModels.some((item) => item.canOpen);');
// 首次 loadHome 落地前(含失败态)FAB 只认 live 设备:首页列表缓存画出的会话会合成出
// 「可用」的 primaryDevice,但缓存设备不能当 live 设备开新会话(settle 后回归 primaryDevice 语义)。
diff --git a/apps/mobile/src/__tests__/sessionEmptyState.test.ts b/apps/mobile/src/__tests__/sessionEmptyState.test.ts
index e276a7d6ca..49011d7997 100644
--- a/apps/mobile/src/__tests__/sessionEmptyState.test.ts
+++ b/apps/mobile/src/__tests__/sessionEmptyState.test.ts
@@ -1,9 +1,87 @@
-import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
import {
shouldSuppressEmptyMessageState,
shouldSuppressRemoteListEmptyState,
} from '@/session/sessionEmptyState';
+// Run the real detail-page sync callback without loading native navigation.
+// Existing policy tests cannot detect an old active/archive response publishing
+// a false successful-empty result. Deferred reads cover that timing in unit tier.
+const detailSource = ts.createSourceFile('detail.tsx', readFileSync(
+ resolve(process.cwd(), 'app/devices/[deviceId].tsx'), 'utf8',
+), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+let syncCode = '';
+function findSync(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.name.getText(detailSource) === 'syncSessions'
+ && node.initializer && ts.isCallExpression(node.initializer)) {
+ syncCode = ts.transpileModule(`const sync = ${node.initializer.arguments[0].getText(detailSource)};`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ }
+ ts.forEachChild(node, findSync);
+}
+findSync(detailSource);
+
+it.each(['resolve', 'reject'])('keeps a new filter pending when the old request settles with %s', async (outcome) => {
+ const firstScope = { deviceId: 'mac', filter: 'active' };
+ const listQueryScopeRef = { current: firstScope };
+ let finish!: (rows: unknown[]) => void;
+ let fail!: (error: Error) => void;
+ const invoke = vi.fn(() => new Promise<unknown[]>((yes, no) => { finish = yes; fail = no; }));
+ const published: unknown[][] = [];
+ let syncedScope: unknown = null;
+ let loading = false;
+ let error: unknown = null;
+ const compile = (listQueryScope: typeof firstScope) => {
+ const bindings = {
+ deviceId: 'mac', deviceName: 'Mac', listQueryScope, listQueryScopeRef,
+ requestedListFilter: listQueryScope.filter, automationScopeKey: null, statusFilter: listQueryScope.filter,
+ remoteListStatusFilter: (filter: string) => filter,
+ LIST_LIMIT: 200, invoke, subscribe: async () => undefined,
+ withTransientRemoteRetry: (read: () => Promise<unknown>) => read(),
+ remoteSessionStore: {
+ captureDeviceSessionListMutationEpoch: () => 0,
+ isDeviceSessionListMutationEpochCurrent: () => true,
+ setDeviceSessions: (_id: string, _name: string, rows: unknown[]) => published.push(rows),
+ },
+ remoteScheduleEventStore: { clearDeviceMirrorInvalidation: () => undefined },
+ invalidateOfflineScheduleIndexFailureFor: () => undefined,
+ getScheduleIndexInvalidationVersion: () => 0,
+ loadSharedSessionScheduleIndex: async () => new Map(), maker: {}, canLoadScheduleIndex: () => true,
+ setScheduleIndex: () => undefined, setLastSyncedAt: () => undefined,
+ setSyncedListQueryScope: (value: unknown) => { syncedScope = value; },
+ setLoading: (value: boolean) => { loading = value; },
+ setError: (value: unknown) => { error = value; }, formatRemoteError: String,
+ };
+ return new Function(...Object.keys(bindings), `${syncCode}\nreturn sync;`)(...Object.values(bindings)) as () => Promise<void>;
+ };
+ const oldRun = compile(firstScope)();
+ await Promise.resolve();
+ // A → archived → A is still a new query; equality of filter text is insufficient.
+ listQueryScopeRef.current = { deviceId: 'mac', filter: 'archived' };
+ listQueryScopeRef.current = { ...firstScope };
+ if (outcome === 'resolve') finish([]); else fail(new Error('old failure'));
+ await oldRun;
+ expect(published).toEqual([]);
+ expect(syncedScope).toBeNull();
+ expect(error).toBeNull();
+ expect(loading).toBe(true);
+
+ const currentRun = compile(listQueryScopeRef.current)();
+ await Promise.resolve();
+ finish([]);
+ await currentRun;
+ expect(published).toEqual([[]]);
+ expect(syncedScope).toBe(listQueryScopeRef.current);
+ expect(loading).toBe(false);
+ expect(shouldSuppressRemoteListEmptyState({
+ itemCount: 0, hasSyncedThisOpen: syncedScope === listQueryScopeRef.current, loading,
+ })).toBe(false);
+});
+
const base = {
loading: false,
showSyncingShell: false,
@@ -41,6 +119,18 @@ describe('shouldSuppressEmptyMessageState', () => {
});
describe('shouldSuppressRemoteListEmptyState', () => {
+ // Regression: reopening an already-synced list with a new filter used to show
+ // "no tasks" while its request was pending, and again when that request failed.
+ // Unit tier: the production presentation policy had only cold-open coverage.
+ it.each([{ loading: true }, { failed: true }])('does not report an empty result during %o', (state) => {
+ expect(shouldSuppressRemoteListEmptyState({
+ itemCount: 0, hasSyncedThisOpen: true, ...state,
+ })).toBe(true);
+ expect(shouldSuppressRemoteListEmptyState({
+ itemCount: 3, hasSyncedThisOpen: true, ...state,
+ })).toBe(false);
+ });
+
it('suppresses the empty state on cold open before the first sync completes (0 items, not synced)', () => {
// 冷进首帧:列表初始 []、lastSyncedAt === null → 抑制,渲染干净空白而非闪"暂无自动化/还没有对话"。
expect(shouldSuppressRemoteListEmptyState({ itemCount: 0, hasSyncedThisOpen: false })).toBe(true);
diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsx
index e6f7a62f8e..1a461bfab7 100644
--- a/apps/mobile/src/session/HomeSurface.tsx
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@ -704,6 +704,9 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
const [retryingDeviceIds, setRetryingDeviceIds] = useState<ReadonlySet<string>>(new Set());
const retryingDeviceIdsRef = useRef<Set<string>>(new Set());
const [statusFilter, setStatusFilter] = useRetainedHomeState<HomeStatusFilter>(viewSession, 'statusFilter', 'active');
+ const requestedListFilter = active ? remoteListStatusFilter(statusFilter) : 'active';
+ const homeListFilterRef = useRef(requestedListFilter);
+ const homeListFilterChanged = homeListFilterRef.current !== requestedListFilter;
const [collapsedProjectKeys, setCollapsedProjectKeys] = useRetainedHomeState<string[]>(viewSession, 'collapsedProjectKeys', []);
const [pinnedCollapsed, setPinnedCollapsed] = useRetainedHomeState(viewSession, 'pinnedCollapsed', false);
// 已展开的自动化组 key(页面级 state:SectionList 虚拟化回收行组件时展开态不丢)。
@@ -808,6 +811,23 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
return diff;
}, [advanceHomeSyncGeneration, releaseHomeListOwner]);
+ useLayoutEffect(() => {
+ if (homeListFilterRef.current === requestedListFilter) return;
+ homeListFilterRef.current = requestedListFilter;
+ // A new filter is a new list scope even on the same computer. Reuse the
+ // existing generation fence so an old active/archive response cannot settle it.
+ for (const deviceId of homeSyncTargetDeviceIdsRef.current) {
+ advanceHomeSyncGeneration(deviceId);
+ homeListFreshnessRef.current.invalidate(deviceId);
+ }
+ setDeviceConnectionStates((current) => {
+ const next = { ...current };
+ for (const deviceId of homeSyncTargetDeviceIdsRef.current) next[deviceId] = 'syncing';
+ return next;
+ });
+ setError(null);
+ }, [advanceHomeSyncGeneration, requestedListFilter]);
+
useEffect(() => () => {
const owned = [...homeListOwnedDeviceIdsRef.current];
homeListOwnedDeviceIdsRef.current.clear();
@@ -944,7 +964,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
const epoch = remoteSessionStore.captureDeviceSessionListMutationEpoch(device.deviceId);
const list = await invoke<RemoteSession[]>(device.deviceId, 'local-db:sessions:list', [
LIST_LIMIT,
- active ? remoteListStatusFilter(statusFilter) : 'active',
+ requestedListFilter,
{ includePinned: true, fresh: true },
]);
return [list, epoch] as const;
@@ -1048,7 +1068,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
superseded: false,
};
}
- }, 'foreground'), [HOME_LIST_SUBSCRIPTION_OWNER, homeCacheUserId, invoke, isCurrentHomeSyncTarget, markDeviceOffline, markHomeScheduleIndexDirty, refreshDeviceScheduleIndex, statusFilter, active, subscribe, updateDeviceConnectionState]);
+ }, 'foreground'), [HOME_LIST_SUBSCRIPTION_OWNER, homeCacheUserId, invoke, isCurrentHomeSyncTarget, markDeviceOffline, markHomeScheduleIndexDirty, refreshDeviceScheduleIndex, requestedListFilter, subscribe, updateDeviceConnectionState]);
const hydrateDeviceSessions = useCallback((
device: DeviceView,
@@ -1058,6 +1078,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
const expectedHomeSyncGeneration = homeSyncGenerationByDeviceRef.current.get(device.deviceId);
if (
expectedHomeSyncGeneration === undefined
+ || homeListFilterRef.current !== requestedListFilter
|| homeAccountGenerationRef.current !== expectedAccountGeneration
|| !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
) {
@@ -1108,7 +1129,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
() => settle(false),
);
return promise;
- }, [accountGeneration, hydrateDeviceSessionsOnce, isCurrentHomeSyncTarget, updateDeviceConnectionState]);
+ }, [accountGeneration, hydrateDeviceSessionsOnce, isCurrentHomeSyncTarget, requestedListFilter, updateDeviceConnectionState]);
hydrateDeviceSessionsRef.current = hydrateDeviceSessions;
const probeRevokedDeviceAccess = useCallback(async (
@@ -2161,8 +2182,13 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
}, [homeListCacheHydrated, initialHomeSettled]);
// Hydration can settle without another content-size event (for example a warm cache).
useEffect(() => { restoreListPosition(); }, [restoreListPosition, sections]);
- const initialHomeLoading = !initialHomeSettled && !connectionError;
- const initialHomeError = !initialHomeSettled && !!connectionError;
+ // Empty is a result of the current scope, not a synonym for "no cached rows".
+ // Include the render before effects acquire a newly selected computer/filter.
+ const homeListScopePending = homeListFilterChanged || isTaskSuggestionsSyncPending(
+ homeSyncDeviceIds, homeListOwnedDeviceIdsRef.current, rawDeviceConnectionStates,
+ );
+ const initialHomeLoading = (!initialHomeSettled || homeListScopePending || indexedSearch.status === 'searching') && !connectionError;
+ const initialHomeError = !!connectionError;
// 首次同步完成后校验恢复/当前选中的设备,不成立时回退「所有对话」并同步持久化:
// - 设备已不存在(解绑):home.selectedDeviceId 是归一化后的口径,查不到会变 null,
// 若不回退,表头显示旧设备名而列表实际展示全部会话,两者口径不一致。
diff --git a/apps/mobile/src/session/sessionEmptyState.ts b/apps/mobile/src/session/sessionEmptyState.ts
index 23ec6e001d..5afa273e34 100644
--- a/apps/mobile/src/session/sessionEmptyState.ts
+++ b/apps/mobile/src/session/sessionEmptyState.ts
@@ -42,8 +42,12 @@ export interface RemoteListEmptyStateInput {
itemCount: number;
/** 本次打开是否已完成过至少一次成功同步(lastSyncedAt != null)。 */
hasSyncedThisOpen: boolean;
+ /** 当前筛选或搜索仍在读取;上一次成功不能证明这次为空。 */
+ loading?: boolean;
+ /** 读取失败由连接提示负责展示,不同时声称列表为空。 */
+ failed?: boolean;
}
export function shouldSuppressRemoteListEmptyState(input: RemoteListEmptyStateInput): boolean {
- return input.itemCount === 0 && !input.hasSyncedThisOpen;
+ return input.itemCount === 0 && (!input.hasSyncedThisOpen || input.loading === true || input.failed === true);
}
diff --git a/apps/mobile/src/session/useConversationSearch.ts b/apps/mobile/src/session/useConversationSearch.ts
index 73994a0b75..2580df4e51 100644
--- a/apps/mobile/src/session/useConversationSearch.ts
+++ b/apps/mobile/src/session/useConversationSearch.ts
@@ -1,5 +1,5 @@
import { useRetainedHomeState, type HomeViewSession } from './homeViewSession';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
import { unresponsiveDevicesStore } from '@/device-link/unresponsiveDevicesStore';
@@ -124,7 +124,9 @@ export function useConversationSearch({
setProjectSelection('all');
}, []);
- useEffect(() => {
+ // Publish "searching" before paint, including the debounce interval. Otherwise
+ // an empty local projection can briefly claim there are no matching tasks.
+ useLayoutEffect(() => {
const trimmed = query.trim();
if (!enabled || !trimmed) {
requestSeq.current += 1;