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。

251 KB
Raw Blame
import { useCloudCompanionHome } from '@/chat/useCloudCompanion';
import { cloudCompanionRows } from '@/chat/cloudCompanion';
import { normalizeTaskTeammateSelection, taskTeammateKey, taskTeammateOptions } from './teammateTaskSource';
import { readTeammateTasks } from './readTeammateTasks';
import { deviceDisplayName } from '@/device-link/deviceName';
import { MountOnFirstOpen } from './MountOnFirstOpen';
import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
import { TaskTagDots } from '@/session/TaskTags';
import { ResidentHomeList, useResidentHomeList } from './ResidentHomeList';
import { HomeNewTaskButton } from './HomeNewTaskButton';
import { SwipeableProjectHeader } from './SwipeableProjectHeader';
import { useRetainedHomeState, getHomeViewSession } from './homeViewSession';
import { rememberRecentTask } from './recentTasks';
import { homeListStyles, SESSION_ROW_LONG_PRESS_MS, SessionStatusMark, SessionStatusPulse } from '@/session/HomeListVisuals';
import { useOptionalHeaderHeight } from '@/session/useOptionalHeaderHeight';
import { rememberComposerEntry } from './composerMorph';
import type { ComposerMorphOrigin } from './composerGeometry';
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';
import { useFocusEffect, useIsFocused, useRouter } from 'expo-router';
import { createContext, useContext, Fragment, memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject, type ReactNode } from 'react';
import {
  ActivityIndicator,
  Alert,
  Animated,
  AppState,
  Platform,
  Modal,
  type NativeScrollEvent,
  type NativeSyntheticEvent,
  Pressable,
  RefreshControl,
  ScrollView,
  SectionList,
  StyleSheet,
  View,
  useWindowDimensions,
  type StyleProp,
  type TextStyle,
  type ViewStyle,
} from 'react-native';
import { Text } from '@/components/AppText';
import { DeviceLinkError, isSharedTaskPeer, type DeviceView, type PresenceSnapshot } from '@cindy/device-link';
import { useSharedTasks } from '@/device-link/useSharedTasks';
import { splitSharedHomeGroup, type SharedHomeRole } from '@/session/sharedHomeGroup';
import {
  Archive,
  Check,
  ChevronDown,
  ChevronRight,
  Crown,
  Ellipsis,
  Folder,
  FolderOpen,
  FileText,
  Hammer,
  Menu,
  Monitor,
  MessagesSquare,
  Lock,
  Pin,
  RefreshCw,
  SquarePen,
  UsersRound,
  X,
} from 'lucide-react-native';
import { Gesture, GestureDetector } from '@/platform/gestureHandler';
import Reanimated, { measure, runOnJS, useAnimatedReaction, useAnimatedRef, useAnimatedStyle, useSharedValue, type AnimatedRef, type SharedValue } from 'react-native-reanimated';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
import { useAuth } from '@/auth/AuthContext';
import { HomeTeammatesSection, useHomeTeammatesSectionContext } from './HomeTeammatesSection';
import { HomeRosterProvider } from './HomeRosterContext';
import { createDisclosureListCell, DisclosureGroupView, DisclosureItem, ListDisclosureScope, useDisclosurePrepare, useListDisclosureTransition } from './listDisclosureTransition';
import { useGuardedPush } from '@/utils/useGuardedPush';
import { useHomeMenuFadeTiming } from '@/session/homeMenuFadeTiming';
import {
  MainWindowActionButton,
  MainWindowActionGroup,
  MainWindowEmptyState,
  StatusDot,
} from '@/components/MobilePrimitives';
import { RemoteAccessGuide } from '@/components/RemoteAccessGuide';
import { HomeChromeDrawer } from '@/session/HomeChromeDrawer';
import { TEAMMATE_COLLECTION_ID } from '@/session/useTeammateRoster';
import { AccountSwitcherSheet } from '@/session/AccountSwitcherSheet';
import { HomeChromeFrost } from '@/session/HomeChromeFrost';
import { HomeGlassMenuPanel, HomeMenuScrim } from '@/session/HomeGlassMenuPanel';
import { FilterReminderDot } from '@/components/FilterReminderDot';
import { HomeHeaderGlassButton } from '@/session/HomeHeaderGlassButton';
import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';
import { useBalancedTitle } from '@/platform/chrome/balancedTitle';
import { HomeSearchBar } from '@/session/HomeSearchBar';
import { HomeProjectMachineLabel } from '@/session/HomeProjectMachineLabel';
import { buildHomeProjectMachineIdentities, type HomeProjectMachineIdentity } from '@/session/homeProjectMachineIdentity';
import {
  HomeNativeStackHeader,
  NativePullDownMenu,
  usesNativePullDownMenu,
  usesNativeStackHeader,
} from '@/platform/chrome';
import {
  buildHomeDisplayPullDownActions,
  homeDisplayActionPatch,
  type HomeDisplayMenuState,
  type HomeDisplayPatch,
  buildHomeScopePullDownActions,
  parseHomeScopePullDownAction,
  homeScopeCollections,
  openHomeRemoteCollection,
} from '@/session/homeChromeMenus';
import { useConversationSearchFilterMenu } from '@/session/useConversationSearchFilterMenu';
import { HomeDisplayMenu } from '@/session/HomeDisplayMenu';
import type { NativePullDownAction } from '@/platform/chrome/NativePullDownMenu';
import {
  activeContentFilterCount,
  DEFAULT_HOME_TASK_INFO_FIELDS,
  type HomeContentFilters,
  type HomeLastActivityFilter,
  type HomeListViewMode,
  type HomeProjectFilter,
  type HomeTeammateFilter,
  type HomeTaskInfoField,
  type HomeVendorFilter,
} from '@/session/homeDisplaySettings';
import { applyHomeContentFilters, filterSharedHomeRows } from '@/session/homeContentFilters';
import {
  HomeRowDisplayContext,
  HomeSessionInfoMeta,
  useHomeRowDisplay,
  type HomeRowDisplay,
} from '@/session/HomeSessionInfoMeta';
import { buildMainWindowLayout } from '@/components/mainWindowLayout';
import { useScreenEdgePadding } from '@/components/screenEdgeInsets';
import { isAccessRevokedError } from '@/device-link/accessRevoked';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
import {
  discoverRemoteHomeCollections,
  remoteResourceDiscoveryTargets,
  type RemoteHomeCollection,
} from '@/device-link/remoteResources';
import {
  createEmptyDeviceIdentityCache,
  loadDeviceIdentityCache,
  reconcileDeviceIdentities,
  saveDeviceIdentityCache,
} from '@/device-link/deviceIdentityStore';
import { toDeviceListItems } from '@/device-link/devices';
import {
  collectFreshPresenceDeviceIds,
  createPresenceFreshnessTracker,
  deviceMirrorCleanupDisposition,
  markPresenceFresh,
  mergeDeviceViewsWithFreshPresence,
  patchDeviceViewsWithPresence,
} from '@/device-link/presenceDevices';
import {
  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';
import { resolveConnectionBannerVisibility, resolveConnectionBannerSyncActionVisibility, resolveHomeConnectionFeedback, resolveHomeDeviceDisconnected, 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';
import {
  remoteScheduleEventStore,
  useRemoteScheduleMirrorInvalidations,
} from '@/scheduler/remoteScheduleEvents';
import { ConversationSearchFilterSheet } from '@/session/ConversationSearchFilterSheet';
import {
  conversationSearchAllowsLocalWrites,
  conversationSearchOriginsFromDeviceModels,
  listConversationSearchProjects,
  shouldReplaceListWithSearchResults,
} from '@/session/conversationSearch';
import { useConversationSearch } from '@/session/useConversationSearch';
import { useRemoteProjectAliases } from '@/session/remoteProjectAliases';
import {
  buildMobileHomePresentation,
  excludeOrcaWorkerSessions,
  type MobileHomeDeviceFilterItem,
  type MobileHomeProjectGroup,
} from '@/session/mobileHome';
import {
  advanceCurrentViewedPriorityHold,
  advanceViewedPriorityHold,
  collectHomePriorityContext,
  holdViewedPriorityRank,
  homeViewedPriorityHold,
  type HomeListSortBy,
  type HomeStatusFilter,
} from '@/session/homeListPriority';
import {
  buildHomeProjectChildOffsets,
  resolveHomeProjectChildAnchor,
  resolveHomeProjectChildWindow,
  shouldWindowHomeProjectChildren,
} from '@/session/homeProjectChildWindow';
import {
  projectDropIndexFromY,
  reorderVisibleProjectByDropIndex,
  resolveVirtualizedDropIndex,
  snapshotManualProjectOrder,
  type HomeProjectOrder,
} from '@/session/homeProjectOrder';
import {
  applyHostProjectOrder,
  controllerKeysFromHost,
  fetchHostProjectOrder,
  rememberRemoteProjectOrderStamp,
  subscribeRemoteProjectOrderChanged,
} from '@/session/remoteProjectOrder';
import {
  createProjectOrderFetchFence,
  isHostProjectOrderReachable,
  projectOrderWriteLedger,
  resolveDisplayedProjectOrder,
  resolveProjectOrderWriteScope,
  UNAVAILABLE_PROJECT_ORDER_SNAPSHOT,
  type SyncedProjectOrderSnapshot,
} from '@cindy/maker-shared/project-order-sync';
import {
  buildHomeSections,
  homeRowsShareRenderData,
  homeRowBefore,
  isFolderHomeRow,
  type HomeRow,
  type HomeSection,
} from '@/session/homeSections';
import {
  readHomeCollapsePreferences,
  readHomeViewPreferences,
  saveHomeCollapsePreferences,
  saveHomeViewPreferences as persistHomeViewPreferences,
  type HomeCollapsePreferences,
  type HomeViewPreferencePatch,
  type HomeViewPreferences,
} from '@/session/homeViewPreferenceStore';
import { homeNavigationOwner, useHomeMode } from '@/session/useHomeMode';
import {
  getCachedHomeListSnapshot,
  scheduleHomeListSnapshotPersist,
} from '@/session/mobileHomeListCache';
import { startBoundedStartupRead } from '@/session/mobileHomeStartup';
import {
  diffHomeDeviceSyncScope,
  HomeDeviceSyncLimiter,
  resolveHomeDeviceSyncIds,
  runHomeDeviceSyncBatch,
} from '@/session/homeDeviceSync';
import { createHomeListFreshness, planHomeListFocusReturn } from '@/session/homeListFreshness';
import { serializeNewSessionDeviceOptions } from '@/session/newSession';
import {
  buildRemoteSessionCardPreview,
  getRemoteSessionPreviewCollapse,
  type RemoteAutomationSessionGroup,
  type RemoteSessionListItem,
  type RemoteSessionLiveActivity,
  type RemoteSessionScheduleInfo,
  type RemoteSessionStatusFilter,
} from '@/session/sessionList';
import {
  RemoteSessionStoreSubscriptionGate,
  remoteSessionStore,
  useRemoteHomeStatusVersion,
  useRemoteMessageVersion,
  useRemoteSessionMessagePreview,
  useRemoteHomeSessions,
  useSessionRunning,
} from '@/session/remoteSessionStore';
import { mapContentEqual } from '@/utils/valueEquality';
import { homeRowPropsEqual } from './homeRowPropsEqual';
import { useStableValue } from '@/utils/useStableValue';
import { useMinuteNow } from '@/utils/useMinuteNow';
import { automationGroupPreview } from '@/session/automationGroupPreview';
import {
  getScheduleIndexInvalidationVersion,
  invalidateOfflineScheduleIndexFailureFor,
  invalidateRunningSessionScheduleEntries,
  invalidateScheduleIndexForDevice,
  loadDeviceSessionScheduleIndex,
  replaceSessionScheduleIndexEntries,
} from '@/session/scheduleIndex';
import { createScheduleIndexDeferRegistry } from '@/session/scheduleIndexDefer';
import {
  latestMobileSessionRow,
  resolveMobileCollapsedGroupStatus,
  resolveMobileSessionRowStatus,
} from '@/session/sessionRightStatus';
import { SessionRightSpinner } from '@/session/SessionRightSpinner';
import { AutomationTimerIcon } from '@/session/AutomationTimerIcon';
import { RenameSessionModal } from '@/session/RenameSessionModal';
import { SessionOptionsPresenter } from '@/session/SessionOptionsExpoSheet';
import { SwipeableSessionRow, type SessionSwipeControls } from '@/session/SwipeableSessionRow';
import { TaskCreatorMark, TaskFollowMark, taskFollowerNames, useTaskFollowers } from '@/session/TaskFollowMark';
import { createSwipeRowRegistry } from '@/session/swipeRowRegistry';
import { useSessionListActions } from '@/session/useSessionListActions';
import { useModalFadeLifecycle } from '@/session/useModalFadeLifecycle';
import type { RemoteSession } from '@/session/types';
import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { fontWeight, iconSize, iconStroke, lineHeight, motionDuration, navigationChrome, radius, spacing, typeScale } from '@/theme/tokens';
import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';
import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';

const LIST_LIMIT = 200;
// Keep the device-link channel responsive while All Sessions hydrates several
// computers. This does not change the 200-row server limit; it only bounds the
// number of device snapshots processed at once.
const HOME_DEVICE_HYDRATE_CONCURRENCY = 2;
// 项目组与自动化组展开后的子列表共用同一个预览限量(设备详情页也 import 复用,避免两处漂移)。
export const PROJECT_PREVIEW_LIMIT = 5;
const PROJECT_CHILD_WINDOW_THRESHOLD = 20;
const PROJECT_CHILD_WINDOW_SIZE = 15;
const PROJECT_CHILD_WINDOW_OVERSCAN = 4;
const PROJECT_CHILD_WINDOW_SHIFT = 4;
const HOME_LIST_INITIAL_RENDER_COUNT = 12;
// 首页列表的 cell:分组展开 / 收起与行的归档、置顶移位共用同一套过渡。
const HomeListCell = createDisclosureListCell();
const HOME_LIST_RENDER_BATCH_SIZE = 12;
const HOME_LIST_WINDOW_SIZE = 5;
const HOME_PROJECT_HEADER_HEIGHT = 56;
const HOME_AUTOMATION_VIEW_ALL_ROW_HEIGHT = 54;
const HOME_SESSION_ROW_HEIGHT = 78;
const HOME_SESSION_SINGLE_LINE_ROW_HEIGHT = 60;
// 自动化组行标题后展开箭头的点击区边长(移动端点击目标 ≥44×44)。
const GROUP_CHEVRON_HIT_SIZE = 44;
// 与 HomeListVisuals sessionTitleRow 的固定高度一致。
const SESSION_TITLE_ROW_HEIGHT = 30;
const CINDY_LIST_GUTTER = 20;
const CINDY_LIST_FAB_BOTTOM = 45;
const HOME_HEADER_MIN_HEIGHT = 48;
/**
 * 新建钮不在系统栏时的列表底部滚动余量:给右下浮动新建钮让出最后一行。
 * 新建钮坐在输入框静止底线上(安全区 + 8,55 圆钮,顶边约安全区 + 63),
 * 沿用历史取值 83,最后一行与圆钮之间留约 20pt。
 */
const LEGACY_HOME_LIST_BOTTOM_RESERVE = 83;
/** 项目块「查看全部」行的左缩进(历史取值,与项目内任务文字列大致对齐,保持布局不变)。 */
const HOME_PROJECT_VIEW_ALL_INSET = 48;
/** 连接提示条同步按钮的视觉尺寸;命中区用 hitSlop 补到 navigationChrome.target(44)。 */
const CONNECTION_ICON_BUTTON_SIZE = 28;
const AnimatedPressable = Animated.createAnimatedComponent(Pressable);

function estimateHomeSessionRowHeight(item: RemoteSessionListItem, textMode = false): number {
  // 文字形态整行单行(预览、定时 / 置顶标记都并到标题行),与 HomeSessionRow 同口径。
  if (textMode) return HOME_SESSION_SINGLE_LINE_ROW_HEIGHT;
  const running = remoteSessionStore.isSessionRunning(item.session.id)
    || item.scheduleInfo?.running === true
    || item.liveActivity?.phase === 'running';
  const hasPreview = item.automationGroup != null
    || !!buildRemoteSessionCardPreview(item, { running })?.trim()
    || !!item.scheduleInfo
    || !!item.session.pinnedAt;
  return hasPreview ? HOME_SESSION_ROW_HEIGHT : HOME_SESSION_SINGLE_LINE_ROW_HEIGHT;
}

function estimateHomeProjectChildHeight(
  item: RemoteSessionListItem,
  expandedAutomationGroups: ReadonlySet<string>,
  textMode: boolean,
): number {
  const rowHeight = estimateHomeSessionRowHeight(item, textMode);
  const group = item.automationGroup;
  if (!group || !expandedAutomationGroups.has(group.key)) return rowHeight;
  const { visibleItems, hiddenCount } = getRemoteSessionPreviewCollapse(group.items, {
    limit: PROJECT_PREVIEW_LIMIT,
    isSessionRunning: (sessionId) => remoteSessionStore.isSessionRunning(sessionId),
  });
  const childrenHeight = visibleItems.reduce(
    (height, child) => height + estimateHomeSessionRowHeight(child, textMode),
    0,
  );
  return rowHeight
    + childrenHeight
    + (hiddenCount > 0 ? HOME_AUTOMATION_VIEW_ALL_ROW_HEIGHT : 0);
}

type RemoteListStatusFilter = Extract<RemoteSessionStatusFilter, 'active' | 'archived' | 'all'>;
type HomeDeviceConnectionState = 'idle' | 'syncing' | 'failed';

type ProjectHeaderLayout = { height: number; key: string; y: number };

type ProjectDragSession = {
  count: number;
  height: number;
  hoverIndex: number;
  key: string;
  layouts: ProjectHeaderLayout[];
  originY: number;
  rootY: number;
  title: string;
  width: number;
  x: number;
};
type HydrateDeviceSessionsResult = {
  failure: HomeDeviceFailure | null;
  needsRerun?: boolean;
  offline: boolean;
  superseded: boolean;
};

type HomeHydrateInFlightEntry = {
  accountGeneration: number;
  device: DeviceView;
  homeSyncGeneration: number;
  promise: Promise<HydrateDeviceSessionsResult>;
  rerunRequested: boolean;
};

type HydrateDeviceSessions = (
  device: DeviceView,
  expectedAccountGeneration?: number,
  options?: { trailingIfInFlight?: boolean },
) => Promise<HydrateDeviceSessionsResult>;

class HomeSyncScopeSupersededError extends Error {
  constructor() {
    super('Home sync scope superseded');
    this.name = 'HomeSyncScopeSupersededError';
  }
}

export interface MobileHomeProps {
  active?: boolean;
  /** The same Home surface, constrained by its host rather than the screen width. */
  width?: number;
  currentSessionId?: string;
  newSessionInSystemBar?: boolean;
  /** Temporary drawers put New task in their own header instead of floating over the short list. */
  newSessionInHeader?: boolean;
  onSelectSession?: (item: RemoteSessionListItem) => void;
  runNavigation?: (action: () => void) => void;
  newSessionActionRef?: MutableRefObject<(() => void) | null>;
}
const ActiveHomeSession = createContext<string | undefined>(undefined);
/** Nested automation rows share their owning list's scroll invalidation. */
export const HomeListViewportContext = createContext<{
  scrollY: SharedValue<number>;
  viewportHeight: number;
} | null>(null);

/**
 * 「最近活跃」筛选用的粗粒度时钟:只在该筛选开启且首页可见时每 5 分钟前进一次
 * (筛选按天截断,分钟级精度没有意义,也避免每分钟重建整张列表);开启或回到首页时立即对时。
 * 关闭时返回 0,调用方在重新计算时取当下时间,且不会因时钟单独触发重算。
 */
const HOME_FILTER_CLOCK_MS = 5 * 60 * 1000;
function useHomeFilterClock(enabled: boolean): number {
  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    if (!enabled) return;
    setNow(Date.now());
    const timer = setInterval(() => setNow(Date.now()), HOME_FILTER_CLOCK_MS);
    return () => clearInterval(timer);
  }, [enabled]);
  return enabled ? now : 0;
}

export function MobileHome(props: MobileHomeProps) {
  const screenFocused = useIsFocused();
  const { accountGeneration } = useAuth();
  return <RemoteSessionStoreSubscriptionGate enabled={screenFocused}>
    <ActiveHomeSession.Provider value={props.currentSessionId}>
      <HomeRosterProvider key={accountGeneration}>
        <HomeScreenContent {...props} />
      </HomeRosterProvider>
    </ActiveHomeSession.Provider>
  </RemoteSessionStoreSubscriptionGate>;
}

function HomeScreenContent({ active = true, width, newSessionInSystemBar = false, newSessionInHeader = false, onSelectSession, runNavigation, newSessionActionRef }: MobileHomeProps) {
  const ownedSharedTasks = useSharedTasks();
  // The retained page and its visible sidebar must never release each other's subscriptions.
  const HOME_LIST_SUBSCRIPTION_OWNER = `device-list:${useId()}`;
  const embedded = width !== undefined;
  const residentList = useResidentHomeList(embedded);
  // Captured here: Android draws the list above the route, outside its roster and navigation context.
  const teammatesSectionContext = useHomeTeammatesSectionContext();
  const { showCollapsedTeammateAvatars, setShowCollapsedTeammateAvatars } = useHomeMode();
  // Bumped by a manual home refresh so the teammate section also re-reads its cloud companions.
  const [teammatesRefreshKey, setTeammatesRefreshKey] = useState(0);
  const activeHomeSession = useContext(ActiveHomeSession);
  const rememberTask = rememberRecentTask;
  const viewSession = getHomeViewSession();
  const [restoredView] = useState(() => viewSession.has('preferencesHydrated'));
  const routeFocused = useIsFocused();
  // The task mirror also feeds navigation while the teammate pane is visible.
  // Only read/sync work stays active; native headers and list presentation remain pane-scoped.
  const screenFocused = routeFocused;
  const screenFocusedRef = useRef(screenFocused);
  screenFocusedRef.current = screenFocused;
  const styles = useThemedStyles(makeStyles);
  const { colors, mode } = useTheme();
  const { t, i18n: i18nInstance } = useTranslation();
  // 项目筛选按账号身份存取(项目 key 跨账号无效);其余视图偏好仍按设备共用。
  const { user: preferenceUser } = useAuth();
  const preferenceOwner = homeNavigationOwner(preferenceUser);
  const preferenceOwnerRef = useRef(preferenceOwner);
  preferenceOwnerRef.current = preferenceOwner;
  const saveHomeViewPreferences = useCallback((
    patch: Omit<HomeViewPreferencePatch, 'projectFilter' | 'teammateFilter'> & { projectFilter?: HomeProjectFilter; teammateFilter?: HomeTeammateFilter },
  ) => {
    const owner = getMobileAuthOwner();
    const { projectFilter, teammateFilter, ...rest } = patch;
    const stored: HomeViewPreferencePatch = { ...rest,
      ...(projectFilter === undefined ? {} : { projectFilter: { owner: preferenceOwnerRef.current, value: projectFilter } }),
      ...(teammateFilter === undefined ? {} : { teammateFilter: { owner: preferenceOwnerRef.current, value: teammateFilter } }),
    };
    return persistHomeViewPreferences(stored).catch(() => {
      if (isMobileAuthOwnerCurrent(owner)) {
        Alert.alert(t('devices.list.alert.actionFailed'), t('models.unified.saveFailed'));
      }
    });
  }, [t]);
  // 分组收起/展开按账号落盘;写失败只意味着下次启动显示旧状态,不打断操作。
  // 「已手动操作」按字段记在视图会话上,常驻首页与侧栏两个实例共用:迟到的恢复只跳过
  // 用户动过的那一类分组,其余分组照常恢复。
  const saveHomeCollapse = useCallback((patch: HomeCollapsePreferences) => {
    viewSession.write('collapseTouchedFields', [
      ...new Set([...viewSession.read<string[]>('collapseTouchedFields', []), ...Object.keys(patch)]),
    ]);
    void saveHomeCollapsePreferences(preferenceOwnerRef.current, patch).catch(() => undefined);
  }, [viewSession]);
  const [sharedCollapsed, setSharedCollapsed] = useRetainedHomeState(viewSession, 'sharedCollapsed', false,
    (next) => saveHomeCollapse({ sharedCollapsed: next }));
  // 所有前进导航(进会话 / 新建 / 设置 / 组页面)统一走守卫 push:列表卡顿时的
  // 连点会各自触发一次裸 push,把同一页压进栈 N 层(返回也要 N 次)。
  const push = useGuardedPush();
  const navigationHost = useRef({ runNavigation, onSelectSession });
  navigationHost.current = { runNavigation, onSelectSession };
  const router = useRouter();
  const guardedPush = useCallback((href: Parameters<typeof push>[0]) => {
    const run = navigationHost.current.runNavigation;
    if (run) run(() => push(href)); else push(href);
  }, [push]);
  const { width: windowWidth, height: screenHeight } = useWindowDimensions();
  const screenWidth = width ?? windowWidth;
  const auth = useAuth();
  const { accountGeneration, deviceId: selfDeviceId, user } = auth;
  // 首页列表持久缓存按账号键控(401 掉线换号不串数据);首页仅登录后可达,user 理应非空。
  const homeCacheUserId = user?.id ?? '';
  const {
    connectionEpoch,
    connectionIssue,
    getPresenceAvailability,
    invoke,
    lastPresenceSnapshot,
    presenceVersion,
    recoveringDeviceIds,
    readDeviceList,
    status,
    subscribe,
    unsubscribe,
  } = useDeviceLink();
  const revokedDevices = useRevokedDevices();
  const sessions = useRemoteHomeSessions();
  const projectAliases = useRemoteProjectAliases();
  const syncInFlightRef = useRef<Promise<void> | null>(null);
  const syncQueuedRef = useRef<{ visible?: boolean } | null>(null);
  const loadHomeRef = useRef<(options?: { visible?: boolean }) => Promise<void>>(async () => undefined);
  const homePendingCacheRef = useRef(new Map<string, { pending: readonly unknown[]; count: number }>());
  const homeLiveActivityIndexRef = useRef(new Map<string, RemoteSessionLiveActivity>());
  const devicesRef = useRef<DeviceView[]>([]);
  // HomeScreen stays mounted while switching saved accounts. Keep an owner generation beside every
  // local projection so requests started by the previous account cannot repopulate the new screen.
  const homeAccountGenerationRef = useRef(accountGeneration);
  homeAccountGenerationRef.current = accountGeneration;
  // schedule-index hydration 延后任务登记表(按设备 id 索引):为同一设备注册新延后任务前取消上一轮
  // pending 的,避免 800ms 窗口内多次 hydrate 时较早回调用旧快照覆盖新状态(并发覆盖竞态);卸载时 cancelAll。
  const scheduleIndexDeferRegistryRef = useRef(createScheduleIndexDeferRegistry());
  const scheduleEventVersionsRef = useRef(new Map<string, number>());
  // Home 只拥有当前显示范围内的 `sessions` topic。target 包含已领取但仍在共享
  // 六路队列中等待的设备;owned 只包含已经真正调用 subscribe 的设备。两者必须
  // 分开,否则切换范围会为尚未订阅的排队设备发出一批无意义 unsubscribe。
  const homeSyncTargetDeviceIdsRef = useRef(new Set<string>());
  const homeListOwnedDeviceIdsRef = useRef(new Set<string>());
  // Per-device generation fences A → B → A scope switches. Membership alone is not
  // sufficient: an old A request may settle after A has been reacquired and must not
  // overwrite the newer snapshot or release the newer owner's subscription.
  const homeSyncGenerationByDeviceRef = useRef(new Map<string, number>());
  // Reconnect rehydrate, presence recovery and Home refresh can all request the same device
  // at once. Share one authoritative list pull per device + scope generation.
  const homeHydrateInFlightByDeviceRef = useRef(new Map<string, HomeHydrateInFlightEntry>());
  // Home 被其它页面盖住时继续持有 `sessions` 订阅、接收增量补丁;回到首页只重拉
  // 「可能漏了推送」的设备(判据见 homeListFreshness),不再每次整份重拉所有电脑。
  const homeListFreshnessRef = useRef(createHomeListFreshness());
  // 最近一次离开首页的时刻;null = 当前在首页(或尚未离开过)。
  const homeBlurredAtRef = useRef<number | null>(null);
  // 待完成的整轮重拉(含设备清单),由 startSilentHomeSync 统一登记。值是请求序号,只有在它
  // 之后开始的 loadHome 整轮成功提交才清除;失败、失焦退出或被跳过时保留,下次回首页仍整轮重拉。
  const homeFullReloadOnFocusRef = useRef<number | null>(null);
  const homeFullReloadSeqRef = useRef(0);
  const requestHomeFullReload = useCallback(() => {
    homeFullReloadOnFocusRef.current = ++homeFullReloadSeqRef.current;
  }, []);
  // 自动化角标待补刷的设备:首页被盖住时收到事件、或刷新被失焦跳过/结果被丢弃。值是登记
  // 序号,只有同一序号的刷新成功应用后才清除;回首页只刷新这些设备。
  const homeScheduleIndexDirtyRef = useRef(new Map<string, number>());
  const homeScheduleIndexDirtySeqRef = useRef(0);
  const markHomeScheduleIndexDirty = useCallback((deviceId: string) => {
    const seq = ++homeScheduleIndexDirtySeqRef.current;
    homeScheduleIndexDirtyRef.current.set(deviceId, seq);
    return seq;
  }, []);
  const homeSyncRowsRef = useRef<ReturnType<typeof toDeviceListItems<DeviceView>>>([]);
  const hydrateDeviceSessionsRef = useRef<HydrateDeviceSessions>(async () => ({
    failure: null,
    offline: false,
    superseded: true,
  }));
  const homeDeviceSyncLimiterRef = useRef(new HomeDeviceSyncLimiter());
  const deviceIdentityCacheRef = useRef(createEmptyDeviceIdentityCache());
  // A timed-out SecureStore read may still complete. Do not persist an empty/rebuilt
  // cache until that read settles and its stored identities have been reapplied.
  const deviceIdentityCachePersistReadyRef = useRef(false);
  const deviceIdentityCachePersistPendingRef = useRef(false);
  // presence 补丁新鲜度:loadHome 用它判断哪些设备在 REST 快照发起后又收到过 presence-changed,
  // 避免用过期快照把它们改回离线(否则出现「会话都同步出来了、新建对话按钮却灰着」的卡死态)。
  const presenceFreshnessRef = useRef(createPresenceFreshnessTracker());
  // 最近一次已登记 freshness 的快照对象:presence effect 因其它依赖变化重跑时,旧快照不能再算「新」。
  const lastPresenceSnapshotProcessedRef = useRef<PresenceSnapshot | null>(null);
  // loadHome 完成时刻的 ref 镜像:首页列表缓存的种入回调用它判断「fresh 是否已先到」,
  // 避免极端竞态下(AsyncStorage 比整轮 loadHome 还慢)用缓存复活已被 removeDevice 清掉的 shard。
  const lastSyncedAtRef = useRef<number | null>(null);
  const [devices, setDevices] = useState<DeviceView[]>([]);
  const [deviceIdentityCacheReady, setDeviceIdentityCacheReady] = useState(false);
  // 首页列表缓存(设备+会话快照)是否已尝试种入:首次 loadHome 等它先落地,保证「先画缓存、
  // fresh 回来再覆盖」的顺序确定性(规则 7),缓存为空时该状态同样置 true、行为与现状一致。
  const [homeListCacheHydrated, setHomeListCacheHydrated] = useState(false);
  // 首次网络同步必须等设备筛选偏好恢复,否则单机用户会先按默认“全部”拉一轮所有电脑。
  const [homeViewPreferencesHydrated, setHomeViewPreferencesHydrated] = useState(restoredView);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<HomeConnectionError>(null);
  const [lastSyncedAt, setLastSyncedAt] = useState<number | null>(null);
  const [selectedDeviceId, setSelectedDeviceId] = useRetainedHomeState<string | null>(viewSession, 'selectedDeviceId', null);
  const [remoteHomeCollections, setRemoteHomeCollections] = useState<RemoteHomeCollection[]>([]);
  const [resourceCacheAccount, setResourceCacheAccount] = useState<number | null>(null);
  const remoteHomeCollectionsRef = useRef<RemoteHomeCollection[]>([]);
  remoteHomeCollectionsRef.current = remoteHomeCollections;
  const selectedDeviceIdRef = useRef<string | null>(selectedDeviceId);
  // Hidden task pane synchronizes every host for its destination badge, independent of UI filters.
  selectedDeviceIdRef.current = active ? selectedDeviceId : null;
  const [searchOpen, setSearchOpen] = useRetainedHomeState(viewSession, 'searchOpen', false);
  const [searchFilterOpen, setSearchFilterOpen] = useState(false);
  // 恢复偏好时暂存的设备名:设备列表尚未同步回来前表头用它兜底,避免显示成占位文案。
  const [restoredDeviceName, setRestoredDeviceName] = useRetainedHomeState<string | null>(viewSession, 'restoredDeviceName', null);
  // 用户已手动切换过筛选/分组后,迟到的偏好恢复不再覆盖用户操作。
  const viewPrefsTouchedRef = useRef(false);
  const leftHomeForSessionRef = useRef(false);
  // 恢复自偏好的设备选择还没做过首次同步后的可用性校验(一次性,校验后或用户手动选择后清掉)。
  const restoredSelectionUnvalidatedRef = useRef(false);
  const [deviceMenuOpen, setDeviceMenuOpen] = useState(false);
  const [chromeMenuOpen, setChromeMenuOpen] = useState(false);
  const [accountSwitcherOpen, setAccountSwitcherOpen] = useState(false);
  const [loggingOut, setLoggingOut] = useState(false);
  // 菜单关闭动画完成(Modal 卸载)后要执行的动作。iOS 上两个兄弟 Modal 重叠时,第二个 Modal
  // 是叠在菜单 Modal 的 VC 上 present 的,菜单淡出后卸载会把它连带 dismiss 掉——所以从菜单里
  // 打开账号切换 / 撤销授权弹窗必须等菜单完全卸载(onClosed)后再挂载,不能同一帧直接 set。
  const pendingMenuActionRef = useRef<(() => void) | null>(null);
  const pendingAccountSwitcherActionRef = useRef<(() => void) | null>(null);
  // 分组展开 / 收起与行的归档、置顶移位统一走 disclosure.run:先挂上布局动画再改状态。
  const disclosure = useListDisclosureTransition();
  const runDisclosure = disclosure.run;
  const prepareListDisclosure = disclosure.prepare;
  const animateListChange = useCallback((apply: () => void) => runDisclosure(apply, { nested: true }), [runDisclosure]);
  const {
    actionSheetSession,
    archiveSession,
    closeRenameSession,
    confirmRenameSession,
    handleSessionSheetAction,
    handleSessionSheetClosed,
    renameSessionDraft,
    renameSessionTarget,
    sessionSwipeControls,
    setActionSheetSession,
    setRenameSessionDraft,
    showSessionOptions,
    swipeRegistry,
    toggleSessionPinned,
  } = useSessionListActions({ animateListChange });
  // 实测 header 高度(onLayout),用于下拉菜单定位;字体放大等导致 header 超过 HOME_HEADER_MIN_HEIGHT 时不再错位。
  const [headerHeight, setHeaderHeight] = useState<number | null>(null);
  const [headerFrosted, setHeaderFrosted] = useState(false);
  const [groupByProject, setGroupByProject] = useRetainedHomeState(viewSession, 'groupByProject', true);
  const [groupDialogue, setGroupDialogue] = useRetainedHomeState(viewSession, 'groupDialogue', false);
  const [sortBy, setSortBy] = useRetainedHomeState<HomeListSortBy>(viewSession, 'sortBy', 'recency');
  const [projectOrder, setProjectOrder] = useRetainedHomeState<HomeProjectOrder>(viewSession, 'projectOrder', 'activity');
  const [manualProjectOrder, setManualProjectOrder] = useRetainedHomeState<string[]>(viewSession, 'manualProjectOrder', []);
  const [teammateFilter, setTeammateFilter] = useRetainedHomeState<HomeTeammateFilter>(viewSession, 'teammateFilter', 'all');
  const [projectFilter, setProjectFilter] = useRetainedHomeState<HomeProjectFilter>(viewSession, 'projectFilter', 'all');
  const [vendorFilter, setVendorFilter] = useRetainedHomeState<HomeVendorFilter>(viewSession, 'vendorFilter', 'all');
  const [lastActivityFilter, setLastActivityFilter] = useRetainedHomeState<HomeLastActivityFilter>(viewSession, 'lastActivityFilter', 'all');
  const [viewMode, setViewMode] = useRetainedHomeState<HomeListViewMode>(viewSession, 'viewMode', 'list');
  const [taskInfoFields, setTaskInfoFields] = useRetainedHomeState<readonly HomeTaskInfoField[]>(viewSession, 'taskInfoFields', DEFAULT_HOME_TASK_INFO_FIELDS);
  const [hostProjectOrders, setHostProjectOrders] = useState<ReadonlyMap<string, SyncedProjectOrderSnapshot>>(() => new Map());
  const projectOrderFetchFenceRef = useRef(createProjectOrderFetchFence());
  const visualProjectKeysRef = useRef<string[]>([]);
  const homeRootRef = useRef<View>(null);
  const projectHeaderRefs = useRef(new Map<string, View>());
  const projectDragRef = useRef<ProjectDragSession | null>(null);
  const projectDragEpochRef = useRef(0);
  const [projectDrag, setProjectDrag] = useState<ProjectDragSession | null>(null);
  const projectDragY = useSharedValue(0);
  const initialScrollOffset = useRef(viewSession.read<number>('scrollOffset', 0));
  const scrollRestored = useRef(initialScrollOffset.current === 0);
  const homeListRef = useRef<SectionList<HomeRow, HomeSection>>(null);
  const attachHomeList = useCallback((list: SectionList<HomeRow, HomeSection> | null) => {
    homeListRef.current = list;
    // A route handoff changes refs, not the native scroll view. Never restore
    // this owner's cached offset over the live resident list's position.
    if (list && residentList.enabled && residentList.mounted?.current) scrollRestored.current = true;
  }, [residentList.enabled, residentList.mounted]);
  const listContentHeight = useRef(0);
  const listViewportHeight = useRef(0);
  const homeScrollY = useSharedValue(initialScrollOffset.current);
  const childViewport = useMemo(() => ({ scrollY: homeScrollY, viewportHeight: screenHeight }), [homeScrollY, screenHeight]);
  const [dialogueShowAll, setDialogueShowAll] = useRetainedHomeState(viewSession, 'dialogueShowAll', false);
  const [priorityHoldEpoch, setPriorityHoldEpoch] = useState(0);
  // deviceId of the revoked-access device whose explanation tip is open (null = closed).
  const [revokedTipDeviceId, setRevokedTipDeviceId] = useState<string | null>(null);
  // 重试申请访问的 in-flight 设备集合(状态供 UI,ref 供并发去重)。用 Set 而非单值:
  // 引导页可对多台被撤销设备并发重试,单值会被后完成的请求提前清掉、还允许重复触发。
  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', [],
    (next) => saveHomeCollapse({ collapsedProjectKeys: next }));
  const [pinnedCollapsed, setPinnedCollapsed] = useRetainedHomeState(viewSession, 'pinnedCollapsed', false,
    (next) => saveHomeCollapse({ pinnedCollapsed: next }));
  // 已展开的自动化组 key(页面级 state:SectionList 虚拟化回收行组件时展开态不丢)。
  const [expandedAutomationGroups, setExpandedAutomationGroups] = useRetainedHomeState<string[]>(viewSession, 'expandedAutomationGroups', [],
    (next) => saveHomeCollapse({ expandedAutomationGroups: next }));
  const [rawDeviceConnectionStates, setDeviceConnectionStates] = useState<Record<string, HomeDeviceConnectionState>>({});
  // 熔断 open(电脑端未响应)的设备复用既有 failed 渲染路径(红圈),不新增视觉:
  // 内部态映射覆盖在 hydrate 状态之上,熔断关闭后自动回落到原状态。
  const unresponsiveDevices = useUnresponsiveDevices();
  const deviceConnectionStates = useMemo<Record<string, HomeDeviceConnectionState>>(() => {
    if (unresponsiveDevices.size === 0) return rawDeviceConnectionStates;
    const merged: Record<string, HomeDeviceConnectionState> = { ...rawDeviceConnectionStates };
    for (const deviceId of unresponsiveDevices) merged[deviceId] = 'failed';
    return merged;
  }, [rawDeviceConnectionStates, unresponsiveDevices]);
  const [scheduleIndex, setScheduleIndex] = useState<Map<string, RemoteSessionScheduleInfo>>(() => new Map());
  const scheduleMirrorInvalidations = useRemoteScheduleMirrorInvalidations();

  // Clear the entire account-owned Home projection before paint. The generation ref is already
  // updated during render, so every older async continuation is fenced even before this reset runs.
  useLayoutEffect(() => {
    syncInFlightRef.current = null;
    syncQueuedRef.current = null;
    devicesRef.current = [];
    homeSyncTargetDeviceIdsRef.current.clear();
    homeListOwnedDeviceIdsRef.current.clear();
    homeSyncGenerationByDeviceRef.current.clear();
    homeHydrateInFlightByDeviceRef.current.clear();
    homeListFreshnessRef.current.clear();
    homeBlurredAtRef.current = null;
    homeFullReloadOnFocusRef.current = null;
    homeScheduleIndexDirtyRef.current.clear();
    scheduleIndexDeferRegistryRef.current.cancelAll();
    scheduleEventVersionsRef.current.clear();
    presenceFreshnessRef.current = createPresenceFreshnessTracker();
    lastPresenceSnapshotProcessedRef.current = null;
    lastSyncedAtRef.current = null;
    restoredSelectionUnvalidatedRef.current = false;
    retryingDeviceIdsRef.current.clear();
    projectOrderFetchFenceRef.current = createProjectOrderFetchFence();
    projectDragEpochRef.current += 1;
    projectDragRef.current = null;

    setDevices([]);
    setHomeListCacheHydrated(false);
    setRefreshing(false);
    setError(null);
    setLastSyncedAt(null);
    setDeviceConnectionStates({});
    setScheduleIndex(new Map());
    setHostProjectOrders(new Map());
    setRevokedTipDeviceId(null);
    setRetryingDeviceIds(new Set());
    setProjectDrag(null);
  }, [accountGeneration]);

  const updateDeviceConnectionState = useCallback((deviceId: string, state: HomeDeviceConnectionState) => {
    setDeviceConnectionStates((current) => updateHomeDeviceConnectionState(current, deviceId, state));
  }, []);

  const isCurrentHomeSyncTarget = useCallback((deviceId: string, generation?: number) => {
    const selected = selectedDeviceIdRef.current;
    return (
      screenFocusedRef.current && (!selected || selected === deviceId)
      && homeSyncTargetDeviceIdsRef.current.has(deviceId)
      && (
        generation === undefined
        || homeSyncGenerationByDeviceRef.current.get(deviceId) === generation
      )
    );
  }, []);

  const advanceHomeSyncGeneration = useCallback((deviceId: string) => {
    const next = (homeSyncGenerationByDeviceRef.current.get(deviceId) ?? 0) + 1;
    homeSyncGenerationByDeviceRef.current.set(deviceId, next);
    return next;
  }, []);

  const releaseHomeListOwner = useCallback((deviceId: string) => {
    if (!homeListOwnedDeviceIdsRef.current.delete(deviceId)) return;
    updateDeviceConnectionState(deviceId, 'idle');
    // unsubscribe 会同步先撤销 registry owner,再等待远端 ACK;即使弱网下 ACK 失败,
    // 下一次重连也不会恢复这台已不可见设备。缓存刻意不删,切回来先画旧快照。
    void unsubscribe(HOME_LIST_SUBSCRIPTION_OWNER, deviceId, ['sessions']).catch(() => undefined);
  }, [HOME_LIST_SUBSCRIPTION_OWNER, unsubscribe, updateDeviceConnectionState]);

  const reconcileHomeDeviceSyncScope = useCallback((desiredDeviceIds: readonly string[]) => {
    const diff = diffHomeDeviceSyncScope(homeSyncTargetDeviceIdsRef.current, desiredDeviceIds);
    homeSyncTargetDeviceIdsRef.current = new Set(desiredDeviceIds);

    for (const deviceId of diff.release) {
      advanceHomeSyncGeneration(deviceId);
      homeListFreshnessRef.current.invalidate(deviceId);
      releaseHomeListOwner(deviceId);
    }
    for (const deviceId of diff.acquire) {
      advanceHomeSyncGeneration(deviceId);
    }
    return diff;
  }, [advanceHomeSyncGeneration, releaseHomeListOwner]);

  useLayoutEffect(() => {
    // Neither the previous computer's error nor the previous filter's error
    // describes the new list scope. Clear it before painting its loading state.
    setError(null);
    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;
    });
  }, [advanceHomeSyncGeneration, requestedListFilter, selectedDeviceId]);

  useEffect(() => () => {
    const owned = [...homeListOwnedDeviceIdsRef.current];
    homeListOwnedDeviceIdsRef.current.clear();
    homeSyncTargetDeviceIdsRef.current.clear();
    for (const deviceId of owned) advanceHomeSyncGeneration(deviceId);
    for (const deviceId of owned) {
      void unsubscribe(HOME_LIST_SUBSCRIPTION_OWNER, deviceId, ['sessions']).catch(() => undefined);
    }
  }, [HOME_LIST_SUBSCRIPTION_OWNER, advanceHomeSyncGeneration, unsubscribe]);

  const reconcileDeviceViews = useCallback((nextRawDevices: readonly DeviceView[]) => {
    const result = reconcileDeviceIdentities(nextRawDevices, deviceIdentityCacheRef.current);
    deviceIdentityCacheRef.current = result.cache;
    if (result.cacheChanged) {
      if (deviceIdentityCachePersistReadyRef.current) void saveDeviceIdentityCache(result.cache);
      else deviceIdentityCachePersistPendingRef.current = true;
    }
    return result;
  }, []);

  // 批量软失效:同一波(REST 快照整批 offline)只让两个 store 各 notify 一次。
  // 逐台通知时设备数超过 React 嵌套更新上限即致命退出(2026-09-10 Android)。
  const softInvalidateDeviceMirrors = useCallback((deviceIds: readonly string[]) => {
    const idSet = new Set(deviceIds);
    if (idSet.size === 0) return;
    const sessionIds = remoteSessionStore.getSessions()
      .filter((session) => !!session.deviceLinkDeviceId && idSet.has(session.deviceLinkDeviceId))
      .map((session) => session.id);
    for (const deviceId of idSet) invalidateScheduleIndexForDevice(deviceId);
    remoteScheduleEventStore.invalidateDeviceMirrors([...idSet]);
    remoteSessionStore.markDevicesOffline([...idSet]);
    setScheduleIndex((current) => invalidateRunningSessionScheduleEntries(current, sessionIds));
  }, []);

  const softInvalidateDeviceMirror = useCallback((deviceId: string) => {
    softInvalidateDeviceMirrors([deviceId]);
  }, [softInvalidateDeviceMirrors]);

  const markDeviceOffline = useCallback((deviceId: string) => {
    // 普通离线是可恢复的传输状态:保留 session/messages,只清 live 投影并失效
    // message marker。恢复后会话立即显示 last-known 内容,后台 reopen 再补最新窗口。
    homeListFreshnessRef.current.invalidate(deviceId);
    softInvalidateDeviceMirror(deviceId);
    setDevices((current) => {
      const next = reconcileDeviceViews(markDeviceViewsOffline(current, new Set([deviceId]))).devices;
      devicesRef.current = next;
      return next;
    });
  }, [reconcileDeviceViews, softInvalidateDeviceMirror]);

  const refreshDeviceScheduleIndex = useCallback((
    deviceId: string,
    sessionIds: readonly string[],
    options?: { accountGeneration?: number; homeSyncGeneration?: number },
  ) => {
    const expectedAccountGeneration = options?.accountGeneration ?? accountGeneration;
    if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
    if (!homeSyncTargetDeviceIdsRef.current.has(deviceId)) return;
    // 先登记待补刷,成功应用后才清除:失焦跳过、在途结果被丢弃都留给回首页补刷。
    const pendingSeq = markHomeScheduleIndexDirty(deviceId);
    if (!screenFocusedRef.current || AppState.currentState !== 'active') return;
    const expectedHomeSyncGeneration = options?.homeSyncGeneration
      ?? homeSyncGenerationByDeviceRef.current.get(deviceId);
    if (
      expectedHomeSyncGeneration === undefined
      || !isCurrentHomeSyncTarget(deviceId, expectedHomeSyncGeneration)
    ) return;
    // 节流(单飞 + 30s TTL):focus / hydrate / schedule 推送三个触发源高频交叠,每次都全量
    // 重放 1+N×listRuns 会拥塞 device-link 管道、拖慢会话打开的关键读(见 scheduleIndex 注释)。
    // Authoritative events invalidate the shared cache before notifying screens.
    const invalidationVersion = getScheduleIndexInvalidationVersion(deviceId);
    void homeDeviceSyncLimiterRef.current.run(async () => {
      if (
        !screenFocusedRef.current || AppState.currentState !== 'active'
        || homeAccountGenerationRef.current !== expectedAccountGeneration
        || !isCurrentHomeSyncTarget(deviceId, expectedHomeSyncGeneration)
      ) return null;
      return loadDeviceSessionScheduleIndex(deviceId, invoke,
        () => screenFocusedRef.current && AppState.currentState === 'active'
          && homeAccountGenerationRef.current === expectedAccountGeneration
          && isCurrentHomeSyncTarget(deviceId, expectedHomeSyncGeneration));
    })
      .then((nextIndex) => {
        if (!nextIndex) return;
        if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
        if (!isCurrentHomeSyncTarget(deviceId, expectedHomeSyncGeneration)) return;
        if (getScheduleIndexInvalidationVersion(deviceId) !== invalidationVersion) return;
        setScheduleIndex((current) => replaceSessionScheduleIndexEntries(
          current,
          sessionIds,
          nextIndex,
        ));
        if (homeScheduleIndexDirtyRef.current.get(deviceId) === pendingSeq) {
          homeScheduleIndexDirtyRef.current.delete(deviceId);
        }
      })
      .catch(() => {
        // 网络失败时保留旧数据,不清零已有徽标——数据清零只应由明确的"已读"事件触发。
      });
  }, [accountGeneration, invoke, isCurrentHomeSyncTarget, markHomeScheduleIndexDirty]);

  const hydrateDeviceSessionsOnce = useCallback((
    device: DeviceView,
    expectedAccountGeneration: number,
    expectedHomeSyncGeneration: number,
  ): Promise<HydrateDeviceSessionsResult> => homeDeviceSyncLimiterRef.current.run(async () => {
    if (
      homeAccountGenerationRef.current !== expectedAccountGeneration
      || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
    ) {
      return { failure: null, offline: false, superseded: true };
    }
    updateDeviceConnectionState(device.deviceId, 'syncing');
    const freshnessToken = homeListFreshnessRef.current.capture(device.deviceId);
    try {
      const assertCurrentScope = () => {
        if (
          homeAccountGenerationRef.current !== expectedAccountGeneration
          || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
        ) throw new HomeSyncScopeSupersededError();
      };
      await withTransientRemoteRetry(async () => {
        assertCurrentScope();
        homeListOwnedDeviceIdsRef.current.add(device.deviceId);
        await subscribe(HOME_LIST_SUBSCRIPTION_OWNER, device.deviceId, ['sessions']);
        assertCurrentScope();
      });
      // A slow activity snapshot must not replay an already successful whole list.
      // Each read captures its own authority fence again on every retry.
      const [[list, sessionListMutationEpoch], [activeSessions, activeSessionSnapshotEpoch]] =
        await runIndependentSnapshotReads([
          async () => {
            assertCurrentScope();
            const epoch = remoteSessionStore.captureDeviceSessionListMutationEpoch(device.deviceId);
            const list = await invoke<RemoteSession[]>(device.deviceId, 'local-db:sessions:list', [
              LIST_LIMIT,
              requestedListFilter,
              { includePinned: true, fresh: true },
            ]);
            const enriched = await readTeammateTasks({ invoke, deviceId: device.deviceId, deviceName: device.name,
              scope: JSON.stringify([expectedAccountGeneration, expectedHomeSyncGeneration, device.deviceId]),
              sessions: Array.isArray(list) ? list : [], previous: remoteSessionStore.getHomeSessions(),
              status: requestedListFilter, limit: LIST_LIMIT,
              publishInitial: rows => {
                assertCurrentScope();
                if (remoteSessionStore.isDeviceSessionListMutationEpochCurrent(device.deviceId, epoch)) {
                  remoteSessionStore.setDeviceSessions(device.deviceId, device.name, rows);
                }
              },
              current: () => homeAccountGenerationRef.current === expectedAccountGeneration
                && isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration),
            });
            assertCurrentScope();
            return [enriched, epoch] as const;
          },
          async () => {
            assertCurrentScope();
            const epoch = remoteSessionStore.captureActiveSessionSnapshotEpoch();
            // Old hosts ignore this optional projection and still return the full snapshot.
            const active = await invoke<unknown>(device.deviceId, 'maker:list-active', [
              { summary: true, snapshotVersion: 2 },
            ]).catch((err) => {
              if (isOptionalActiveSessionSnapshotError(err)) return null;
              throw err;
            });
            return [active, epoch] as const;
          },
        ] as const, withTransientRemoteRetry);
      if (
        homeAccountGenerationRef.current !== expectedAccountGeneration
        || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
      ) {
        return { failure: null, offline: false, superseded: true };
      }
      if (!remoteSessionStore.isDeviceSessionListMutationEpochCurrent(
        device.deviceId,
        sessionListMutationEpoch,
      )) {
        // A list-level push landed after this snapshot started. Keep the live mutation and
        // run one trailing authoritative pull; applying this older whole-list response would
        // roll back sessions:patched or hide a just-created task.
        return {
          failure: null,
          needsRerun: true,
          offline: false,
          superseded: true,
        };
      }
      const nextSessions = Array.isArray(list) ? list : [];
      remoteSessionStore.batch(() => {
        remoteSessionStore.setDeviceSessions(
          device.deviceId,
          device.name,
          nextSessions,
        );
        if (activeSessions !== null) {
          remoteSessionStore.setActiveSessionSnapshots(
            device.deviceId,
            activeSessions,
            activeSessionSnapshotEpoch,
          );
        }
      });
      // schedule-index(1+N 个 listRuns)是次要徽标数据,延后发,避开"开 app→立刻点会话"时和会话关键读
      // 抢同一条 WS 管道(见 scheduleIndexDefer / issue #324)。home 自动化分组与名称已由 fallbackScheduleInfo
      // 兜底,徽标晚半拍出现即可。
      // 按设备 id 登记:同设备上一轮还没执行的延后任务会被先取消,避免较早回调用旧 nextSessions 覆盖新状态。
      // 延后刷新若因首页失焦被跳过,回首页时补刷(列表已标新鲜,不会再触发 hydrate)。
      markHomeScheduleIndexDirty(device.deviceId);
      scheduleIndexDeferRegistryRef.current.schedule(device.deviceId, () => {
        void (async () => {
          while (syncInFlightRef.current) await syncInFlightRef.current;
          if (
            homeAccountGenerationRef.current !== expectedAccountGeneration
            || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
          ) return;
          refreshDeviceScheduleIndex(device.deviceId, nextSessions.map((session) => session.id), {
            accountGeneration: expectedAccountGeneration,
            homeSyncGeneration: expectedHomeSyncGeneration,
          });
        })();
      });
      // 列表被 LIST_LIMIT 截断时,补丁可能改变前 N 条的成员(如归档后第 N+1 条该补进、
      // 窗口外任务因活动排进来),本地无法补全:记下 mutation epoch,回首页时有变就重拉。
      homeListFreshnessRef.current.markFresh(
        device.deviceId,
        freshnessToken,
        nextSessions.length >= LIST_LIMIT
          ? remoteSessionStore.captureDeviceSessionListMutationEpoch(device.deviceId)
          : null,
      );
      updateDeviceConnectionState(device.deviceId, 'idle');
      // hydrate 成功后去抖回写首页列表缓存(collect 在定时器触发时才读 store,拿届时最新快照;
      // 多设备并发 hydrate 只落盘一次)。不在 store 每次变更时写盘。缓存按账号键控。
      scheduleHomeListSnapshotPersist(homeCacheUserId, () => remoteSessionStore.getSessions());
      return { failure: null, offline: false, superseded: false };
    } catch (err) {
      if (
        err instanceof HomeSyncScopeSupersededError
        || homeAccountGenerationRef.current !== expectedAccountGeneration
        || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
      ) {
        return { failure: null, offline: false, superseded: true };
      }
      const offline = isDeviceOfflineError(err);
      homeListFreshnessRef.current.invalidate(device.deviceId);
      if (offline) markDeviceOffline(device.deviceId);
      updateDeviceConnectionState(device.deviceId, 'failed');
      return {
        failure: { deviceId: device.deviceId, deviceName: device.name, error: formatRemoteError(err) },
        offline,
        superseded: false,
      };
    }
  }, 'foreground'), [HOME_LIST_SUBSCRIPTION_OWNER, homeCacheUserId, invoke, isCurrentHomeSyncTarget, markDeviceOffline, markHomeScheduleIndexDirty, refreshDeviceScheduleIndex, requestedListFilter, subscribe, updateDeviceConnectionState]);

  const hydrateDeviceSessions = useCallback((
    device: DeviceView,
    expectedAccountGeneration = accountGeneration,
    options: { trailingIfInFlight?: boolean } = {},
  ): Promise<HydrateDeviceSessionsResult> => {
    const expectedHomeSyncGeneration = homeSyncGenerationByDeviceRef.current.get(device.deviceId);
    if (
      expectedHomeSyncGeneration === undefined
      || homeListFilterRef.current !== requestedListFilter
      || homeAccountGenerationRef.current !== expectedAccountGeneration
      || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
    ) {
      return Promise.resolve({ failure: null, offline: false, superseded: true });
    }

    const existing = homeHydrateInFlightByDeviceRef.current.get(device.deviceId);
    if (
      existing
      && existing.accountGeneration === expectedAccountGeneration
      && existing.homeSyncGeneration === expectedHomeSyncGeneration
    ) {
      existing.device = device;
      if (options.trailingIfInFlight) existing.rerunRequested = true;
      return existing.promise;
    }

    // Mark the hand-off before entering the limiter: reseed can queue behind another peer.
    updateDeviceConnectionState(device.deviceId, 'syncing');
    const promise = hydrateDeviceSessionsOnce(
      device,
      expectedAccountGeneration,
      expectedHomeSyncGeneration,
    );
    const entry: HomeHydrateInFlightEntry = {
      accountGeneration: expectedAccountGeneration,
      device,
      homeSyncGeneration: expectedHomeSyncGeneration,
      promise,
      rerunRequested: false,
    };
    homeHydrateInFlightByDeviceRef.current.set(device.deviceId, entry);
    const settle = (needsRerun: boolean) => {
      if (homeHydrateInFlightByDeviceRef.current.get(device.deviceId) !== entry) return;
      homeHydrateInFlightByDeviceRef.current.delete(device.deviceId);
      if (
        !needsRerun
        && !entry.rerunRequested
      ) return;
      if (
        homeAccountGenerationRef.current !== entry.accountGeneration
        || !isCurrentHomeSyncTarget(device.deviceId, entry.homeSyncGeneration)
      ) return;
      void hydrateDeviceSessionsRef.current(entry.device, entry.accountGeneration);
    };
    void promise.then(
      (result) => settle(result.needsRerun === true),
      () => settle(false),
    );
    return promise;
  }, [accountGeneration, hydrateDeviceSessionsOnce, isCurrentHomeSyncTarget, requestedListFilter, updateDeviceConnectionState]);
  hydrateDeviceSessionsRef.current = hydrateDeviceSessions;

  const probeRevokedDeviceAccess = useCallback(async (
    deviceId: string,
    expectedAccountGeneration = accountGeneration,
  ): Promise<boolean> => {
    if (homeAccountGenerationRef.current !== expectedAccountGeneration) return false;
    try {
      // sessions:list limit=1 是既有的最小被控端响应性探测;不要为了探测给不可见设备
      // 持有 `sessions` topic,也不要把这一行写回完整列表缓存。
      await withTransientRemoteRetry(() => invoke<unknown[]>(deviceId, 'local-db:sessions:list', [
        1,
        'active',
        { includePinned: true, fresh: true },
      ]), { maxAttempts: 3 });
      return homeAccountGenerationRef.current === expectedAccountGeneration;
    } catch {
      return false;
    }
  }, [accountGeneration, invoke]);

  const loadHome = useCallback(async (options: { visible?: boolean } = {}) => {
    const accountGenerationAtStart = accountGeneration;
    if (homeAccountGenerationRef.current !== accountGenerationAtStart) return;
    if (!deviceIdentityCacheReady) return;
    const visible = options.visible === true;
    if (visible) setRefreshing(true);
    if (syncInFlightRef.current) {
      syncQueuedRef.current = options;
      return syncInFlightRef.current.finally(() => {
        if (visible && homeAccountGenerationRef.current === accountGenerationAtStart) {
          setRefreshing(false);
        }
      });
    }

    const fullReloadRequestAtStart = homeFullReloadOnFocusRef.current;
    const rawTask = (async () => {
      setError(null);
      // 记录 REST 请求发起时的 presence 纪元:在请求飞行期间收到过 presence 补丁的设备,
      // 以 devicesRef 里的实时状态为准,不被"请求发起时刻"的过期 REST 快照改回离线。
      // 典型场景:开 App 时桌面端正好重连——REST 快照还是 offline,presence-changed(online)
      // 已把设备补成在线并 hydrate 出会话;若整体覆盖,presence 不会再广播事件来纠正,
      // 首页会卡死在「会话都在、设备全不可用(新建对话按钮灰)」直到手动下拉刷新。
      const presenceEpochAtFetchStart = presenceFreshnessRef.current.epoch;
      const mergeFreshPresence = (list: readonly DeviceView[]) => mergeDeviceViewsWithFreshPresence(
        list,
        devicesRef.current,
        collectFreshPresenceDeviceIds(presenceFreshnessRef.current, presenceEpochAtFetchStart),
      );
      // 设备清单 REST 是整轮同步的闸门:它一次失败整个 loadHome 就失败,而每设备的
      // WS hydrate 已有瞬时重试——闸门自己也必须重试,否则一次弱网抖动就把首页
      // 卡在「同步失败」等手动下拉。maxAttempts 收敛到 3:它前置于全部 hydrate,
      // 不值得为它烧满 6 次退避。
      const res = await withTransientRemoteRetry(
        () => {
          if (homeAccountGenerationRef.current !== accountGenerationAtStart) {
            throw new Error('Home account generation superseded');
          }
          // Provider connection recovery may already own an older roster request. Home's
          // presence fence is captured above, so joining that earlier request could let its
          // stale empty snapshot erase a desktop presence delta that will not be replayed.
          return readDeviceList({ fresh: true });
        },
        { maxAttempts: 3 },
      );
      if (homeAccountGenerationRef.current !== accountGenerationAtStart) return;
      if (!screenFocusedRef.current) return;
      const now = Date.now();
      const serverDevices = mergeFreshPresence(reconcileDeviceViews(res.devices).devices);
      const deviceRows = toDeviceListItems(serverDevices, now, revokedDevices);
      const availableRows = deviceRows.filter((item) => item.canOpen);
      const syncDeviceIds = resolveHomeDeviceSyncIds(
        availableRows.map((item) => ({ canOpen: true, deviceId: item.device.deviceId })),
        selectedDeviceIdRef.current,
      );
      const syncDeviceIdSet = new Set(syncDeviceIds);
      const syncRows = availableRows.filter((item) => syncDeviceIdSet.has(item.device.deviceId));
      const selectedDeviceIdAtSyncStart = selectedDeviceIdRef.current;
      reconcileHomeDeviceSyncScope(syncDeviceIds);
      // 设备清单 / presence 不等列表 fan-out:先发布全量设备状态,再用最多 6 个 worker
      // 补当前显示范围。scope effect 看到的 owner 已在上面领取,不会重复派发。
      devicesRef.current = serverDevices;
      setDevices(serverDevices);
      setDeviceConnectionStates((current) => pruneHomeDeviceConnectionStates(
        current,
        new Set(availableRows.map((item) => item.device.deviceId)),
      ));
      // 单次 REST 快照里的 offline 只是可恢复状态,不能硬删刚同步的会话/消息;
      // 显式关闭远控或撤权才是权限终态,继续清敏感镜像。
      // soft 处先收拢成一批再失效:整批 offline 时逐台通知会击穿 React 嵌套上限。
      const softInvalidateIds: string[] = [];
      for (const item of deviceRows) {
        const disposition = deviceMirrorCleanupDisposition(item.state);
        if (disposition === 'soft') softInvalidateIds.push(item.device.deviceId);
        if (disposition === 'hard') {
          invalidateScheduleIndexForDevice(item.device.deviceId);
          remoteScheduleEventStore.clearDevice(item.device.deviceId);
          remoteScheduleEventStore.clearDeviceMirrorInvalidation(item.device.deviceId);
          remoteSessionStore.removeDevice(item.device.deviceId);
        }
      }
      if (softInvalidateIds.length > 0) softInvalidateDeviceMirrors(softInvalidateIds);
      // 整表对账:REST 全量清单对“设备是否仍绑定”是权威。冷启动从缓存种入、
      // 随后被解绑(完全不在清单里)的设备不会出现在状态分类里,按差集硬清 shard;
      // 这与短暂 offline 不同,否则幽灵项会被快照回写无限续存。
      const knownDeviceIds = new Set(deviceRows.map((item) => item.device.deviceId));
      const ghostDeviceIds = new Set<string>();
      for (const session of remoteSessionStore.getSessions()) {
        const shardId = session.deviceLinkDeviceId;
        if (shardId && !isSharedTaskPeer(shardId) && !knownDeviceIds.has(shardId)) ghostDeviceIds.add(shardId);
      }
      for (const deviceId of ghostDeviceIds) {
        invalidateScheduleIndexForDevice(deviceId);
        remoteScheduleEventStore.clearDevice(deviceId);
        remoteScheduleEventStore.clearDeviceMirrorInvalidation(deviceId);
        remoteSessionStore.removeDevice(deviceId);
      }

      const failures: HomeDeviceFailure[] = [];
      const offlineDeviceIds = new Set<string>();
      const hydrateResults = await runHomeDeviceSyncBatch(syncRows, async (item) => {
        const result = await hydrateDeviceSessions(item.device, accountGenerationAtStart);
        return { deviceId: item.device.deviceId, result };
      }, HOME_DEVICE_HYDRATE_CONCURRENCY);
      for (const { deviceId, result } of hydrateResults) {
        if (result.superseded || homeAccountGenerationRef.current !== accountGenerationAtStart) continue;
        if (result.failure) failures.push(result.failure);
        if (result.offline) {
          offlineDeviceIds.add(deviceId);
        } else if (!result.failure) {
          // REST + hydrate success is authoritative reachability evidence even when relay
          // presence was not replayed on this connection. Retire any prior offline marker
          // so unrelated device invalidations cannot re-clear this device's running badges.
          remoteScheduleEventStore.clearDeviceMirrorInvalidation(deviceId);
          invalidateOfflineScheduleIndexFailureFor(deviceId);
        }
      }
      if (homeAccountGenerationRef.current !== accountGenerationAtStart) return;

      // 收尾再合并一次:hydrate 阶段(可能持续数秒)里新到的 presence 补丁同样不能被覆盖掉。
      const nextDevices = reconcileDeviceViews(
        mergeFreshPresence(markDeviceViewsOffline(serverDevices, offlineDeviceIds)),
      ).devices;
      devicesRef.current = nextDevices;
      setDevices(nextDevices);
      lastSyncedAtRef.current = now;
      setLastSyncedAt(now);
      if (homeFullReloadOnFocusRef.current === fullReloadRequestAtStart) homeFullReloadOnFocusRef.current = null;
      if (selectedDeviceIdRef.current === selectedDeviceIdAtSyncStart) {
        setError(failures.length > 0 ? failures : null);
      }
      // loadHome 整轮成功后也回写一次:覆盖「设备全部下线 / 会话清空」的收敛场景——
      // 此时没有任何 hydrate 成功,只有这里能把缓存里的陈旧设备清掉。
      scheduleHomeListSnapshotPersist(homeCacheUserId, () => remoteSessionStore.getSessions());
    })();

    const task = rawTask
      .catch((err) => {
        if (homeAccountGenerationRef.current !== accountGenerationAtStart) return;
        setError(formatRemoteError(err));
      })
      .finally(() => {
        if (syncInFlightRef.current !== task) return;
        syncInFlightRef.current = null;
        const queued = syncQueuedRef.current;
        if (queued) {
          syncQueuedRef.current = null;
          void loadHomeRef.current(queued);
        }
      });

    syncInFlightRef.current = task;
    return task.finally(() => {
      if (visible && homeAccountGenerationRef.current === accountGenerationAtStart) setRefreshing(false);
    });
  }, [accountGeneration, readDeviceList, deviceIdentityCacheReady, homeCacheUserId, hydrateDeviceSessions, reconcileDeviceViews, reconcileHomeDeviceSyncScope, revokedDevices, softInvalidateDeviceMirror]);
  // A manual refresh also recovers the teammate section: roster, group chats and cloud companions.
  const homeRoster = teammatesSectionContext.shared;
  const refreshHome = useCallback(() => {
    void loadHome({ visible: true });
    if (!homeRoster) return;
    void homeRoster.roster.refresh();
    if (homeRoster.groups.supported) void homeRoster.groups.refresh();
    setTeammatesRefreshKey(key => key + 1);
  }, [homeRoster, loadHome]);
  loadHomeRef.current = loadHome;

  // 冷启动先画缓存:上次 loadHome 成功的设备+会话快照种入 store,先把列表画出来(消除首屏强制
  // spinner);loadHome 返回后由 setDeviceSessions / removeDevice 正常覆盖收敛。缓存为空时列表
  // 保持空、现有 spinner 行为不变。缓存画出的设备只标记「同步中」既有中间态(设备菜单脉冲点),
  // 不进入 devices state——它们不是 live 设备,新建对话的可用性判定仍以 live 数据为准。
  useEffect(() => {
    const expectedAccountGeneration = accountGeneration;
    // 缓存按账号键控:userId 未就绪(理论上首页必已登录,防御性兜底)时不读,直接放行首帧。
    if (!homeCacheUserId) {
      setHomeListCacheHydrated(true);
      return;
    }
    let cancelled = false;
    const read = startBoundedStartupRead(
      getCachedHomeListSnapshot(homeCacheUserId),
      [],
    );
    const applySnapshot = async (snapshot: Awaited<ReturnType<typeof getCachedHomeListSnapshot>>) => {
      await syncInFlightRef.current;
      if (
        cancelled
        || homeAccountGenerationRef.current !== expectedAccountGeneration
        || lastSyncedAtRef.current !== null
      ) return;
      for (const device of snapshot) {
        remoteSessionStore.hydrateDeviceSessionsIfEmpty(device.deviceId, device.deviceName, device.sessions);
      }
    };
    void read.initial
      .then((initial) => {
        void applySnapshot(initial.value);
        if (initial.timedOut) void read.completion.then((late) => {
          if (late.ok) void applySnapshot(late.value);
        });
      })
      .catch(() => undefined)
      .finally(() => {
        if (!cancelled && homeAccountGenerationRef.current === expectedAccountGeneration) {
          setHomeListCacheHydrated(true);
        }
      });
    return () => {
      cancelled = true;
    };
  }, [accountGeneration, homeCacheUserId, updateDeviceConnectionState]);

  useEffect(() => {
    let cancelled = false;
    const read = startBoundedStartupRead(
      loadDeviceIdentityCache(),
      createEmptyDeviceIdentityCache(),
    );
    void read.initial
      .then(async (initial) => {
        if (cancelled) return;
        deviceIdentityCacheRef.current = initial.value;
        deviceIdentityCachePersistReadyRef.current = !initial.timedOut;
        setDeviceIdentityCacheReady(true);
        if (!initial.timedOut) return;

        const late = await read.completion;
        if (cancelled) return;
        if (late.ok) {
          deviceIdentityCacheRef.current = late.value;
          deviceIdentityCachePersistReadyRef.current = true;
          const reconciled = reconcileDeviceViews(devicesRef.current);
          devicesRef.current = reconciled.devices;
          if (reconciled.viewsChanged) setDevices(reconciled.devices);
          return;
        }

        deviceIdentityCachePersistReadyRef.current = true;
        if (deviceIdentityCachePersistPendingRef.current) void saveDeviceIdentityCache(deviceIdentityCacheRef.current);
      });
    return () => {
      cancelled = true;
    };
  }, [reconcileDeviceViews]);

  // 冷启动恢复上次的首页视图偏好(设备范围 + 显示菜单);用户已手动操作过则不覆盖。
  useEffect(() => {
    const expectedAccountGeneration = homeAccountGenerationRef.current;
    let cancelled = false;
    const read = startBoundedStartupRead<HomeViewPreferences | null>(
      readHomeViewPreferences(preferenceOwnerRef.current),
      null,
    );
    // 分组收起记录单独读取:与显示偏好互不牵连,任何一边读失败都不影响另一边恢复。
    const collapseRead = startBoundedStartupRead<HomeCollapsePreferences | null>(
      readHomeCollapsePreferences(preferenceOwnerRef.current),
      null,
    );
    const applyCollapse = (collapse: HomeCollapsePreferences | null) => {
      if (!collapse || restoredView) return;
      if (cancelled || homeAccountGenerationRef.current !== expectedAccountGeneration) return;
      const touched = viewSession.read<string[]>('collapseTouchedFields', []);
      // 直接写入视图会话:恢复出来的值不需要再落盘一次;用户已动过的分组保持其选择。
      for (const key of ['pinnedCollapsed', 'sharedCollapsed', 'collapsedProjectKeys', 'expandedAutomationGroups'] as const) {
        if (collapse[key] !== undefined && !touched.includes(key)) viewSession.write(key, collapse[key]);
      }
    };
    const applyPreferences = (preferences: HomeViewPreferences | null) => {
      if (!preferences || restoredView) return;
      if (
        cancelled
        || homeAccountGenerationRef.current !== expectedAccountGeneration
        || viewPrefsTouchedRef.current
      ) return;
      setGroupByProject(preferences.groupByProject);
      setGroupDialogue(preferences.groupDialogue);
      setSortBy(preferences.sortBy);
      setStatusFilter(preferences.statusFilter);
      setProjectOrder(preferences.projectOrder);
      setManualProjectOrder(preferences.manualProjectOrder);
      setProjectFilter(preferences.projectFilter);
      setTeammateFilter(preferences.teammateFilter);
      setVendorFilter(preferences.vendorFilter);
      setLastActivityFilter(preferences.lastActivityFilter);
      setViewMode(preferences.viewMode);
      setTaskInfoFields(preferences.taskInfoFields);
      if (preferences.selectedDevice) {
        setSelectedDeviceId(preferences.selectedDevice.deviceId);
        setRestoredDeviceName(preferences.selectedDevice.name);
        restoredSelectionUnvalidatedRef.current = true;
      }
    };
    void collapseRead.initial.then((initial) => {
      applyCollapse(initial.value);
      // 超时只是不再等待,迟到的值仍会补上用户没动过的分组。
      if (initial.timedOut) void collapseRead.completion.then((late) => { if (late.ok) applyCollapse(late.value); });
    });
    void read.initial
      .then((initial) => {
        applyPreferences(initial.value);
        if (initial.timedOut) {
          // Native storage can occasionally settle after the startup budget. Let Home start
          // with its safe defaults, then narrow the live scope if the untouched preference
          // eventually arrives; a permanently stuck read can no longer block networking.
          void read.completion.then((late) => {
            if (late.ok) applyPreferences(late.value);
          });
        }
      })
      .finally(() => {
        // The preference values are generation-fenced above, but this startup gate belongs to
        // the mounted Home screen rather than to one account. If the user switches accounts while
        // the bounded read is settling, the old values must stay ignored while the new account is
        // still allowed to start networking with safe defaults.
        if (!cancelled) { viewSession.write('preferencesHydrated', true); setHomeViewPreferencesHydrated(true); }
      });
    return () => {
      cancelled = true;
    };
  }, []);

  // 卸载时取消所有延后中的 schedule-index hydration 定时器,避免回调在卸载后 setScheduleIndex。
  useEffect(() => {
    const registry = scheduleIndexDeferRegistryRef.current;
    return () => {
      registry.cancelAll();
    };
  }, []);

  useEffect(() => {
    if (scheduleMirrorInvalidations.size === 0) return;
    const invalidatedDeviceIds = new Set(scheduleMirrorInvalidations.keys());
    const sessionIds = remoteSessionStore.getSessions()
      .filter((session) => !!session.deviceLinkDeviceId && invalidatedDeviceIds.has(session.deviceLinkDeviceId))
      .map((session) => session.id);
    setScheduleIndex((current) => invalidateRunningSessionScheduleEntries(current, sessionIds));
  }, [scheduleMirrorInvalidations]);

  useEffect(() => remoteScheduleEventStore.subscribe(() => {
    const deviceIds = new Set<string>();
    for (const device of devicesRef.current) deviceIds.add(device.deviceId);
    for (const session of remoteSessionStore.getSessions()) {
      if (session.deviceLinkDeviceId) deviceIds.add(session.deviceLinkDeviceId);
    }

    for (const deviceId of deviceIds) {
      if (!homeSyncTargetDeviceIdsRef.current.has(deviceId)) continue;
      const snapshot = remoteScheduleEventStore.getSnapshot(deviceId);
      const version = snapshot.version;
      if (version === 0) {
        scheduleEventVersionsRef.current.delete(deviceId);
        continue;
      }
      if (version === (scheduleEventVersionsRef.current.get(deviceId) ?? 0)) continue;
      scheduleEventVersionsRef.current.set(deviceId, version);
      const projection = snapshot.lastProjection;
      if (projection?.refresh.sessionIndex !== true && projection?.runPatch.status !== 'running') continue;
      const sessionIds = remoteSessionStore.getSessions()
        .filter((session) => session.deviceLinkDeviceId === deviceId)
        .map((session) => session.id);
      // scheduler 触发的新一次运行不会广播 local-db:sessions:created(桌面 runner 只发
      // schedule 事件),新 run 的会话不会自己进列表。事件带的 sessionId 不在本地列表时,
      // 先触发该设备重拉会话列表 —— hydrate 完成后其内部的 defer 会用新列表刷新 schedule
      // 索引(此处用旧列表刷,新会话的 running/未读条目会被 replaceSessionScheduleIndexEntries
      // 按 sessionIds 白名单丢弃,手机将一直看不到"任务正在运行")。
      const boundSessionId = projection.runPatch.sessionId;
      if (boundSessionId && !sessionIds.includes(boundSessionId)) {
        remoteSessionStore.requestReseed(deviceId);
        continue;
      }
      // 首页被盖住时刷新会被门禁跳过;记下这台,回首页再刷,不在返回时兜底全量刷新。
      if (!screenFocusedRef.current) {
        markHomeScheduleIndexDirty(deviceId);
        continue;
      }
      refreshDeviceScheduleIndex(deviceId, sessionIds);
    }
  }), [refreshDeviceScheduleIndex]);

  // 刷新首页的自动化角标(scheduleIndex)。整轮返回(首次、后台、重连、离开太久)兜底刷新
  // 所有设备:那些情况下自动化事件可能漏收。普通返回只刷新离开期间收到过事件的设备——
  // 事件走首页常驻的 `sessions` 订阅,离开期间照常到达(见 homeScheduleIndexDirtyRef)。
  const refreshHomeScheduleIndexes = useCallback((onlyDeviceIds?: ReadonlySet<string>) => {
    for (const device of devicesRef.current) {
      if (!homeSyncTargetDeviceIdsRef.current.has(device.deviceId)) continue;
      if (onlyDeviceIds && !onlyDeviceIds.has(device.deviceId)) continue;
      const sessionIds = remoteSessionStore.getSessions()
        .filter((session) => session.deviceLinkDeviceId === device.deviceId)
        .map((session) => session.id);
      if (sessionIds.length === 0) continue;
      refreshDeviceScheduleIndex(device.deviceId, sessionIds);
    }
  }, [refreshDeviceScheduleIndex]);

  // 初次加载 + 每次重连(connectionEpoch 变化)都全量刷新。presence 只在状态"变化"时广播、
  // 服务端没有面向新连接的全量重放,后台期间(client.stop)漏掉的上/下线事件只能靠重连时
  // 重拉 REST 快照兜底,否则设备可用性会一直停留在断线前的旧状态。loadHome 内部有
  // syncInFlight 去重,冷启动时与上线瞬间的两次触发只会实际执行一次。
  // 首次触发同时等首页列表缓存种入完成(homeListCacheHydrated,AsyncStorage 读一个小 key,毫秒级):
  // 保证缓存先画、fresh 后覆盖的顺序确定,避免 loadHome 清理下线设备后缓存又把 stale shard 种回去。
  // 所有整轮同步触发(首次、回前台、重连、需整轮的回首页、依赖变化)都经过这里:先登记整轮
  // 重拉请求,再尝试执行。请求只由在它之后开始的 loadHome 整轮成功提交清除;失焦、缓存未就绪、
  // 设备清单失败或中途失焦退出都会保留它,下次回首页仍整轮重拉。
  const startSilentHomeSync = useCallback(() => {
    requestHomeFullReload();
    if (!screenFocusedRef.current) return;
    if (!deviceIdentityCacheReady || !homeListCacheHydrated || !homeViewPreferencesHydrated) return;
    void loadHome({ visible: false });
  }, [deviceIdentityCacheReady, homeListCacheHydrated, homeViewPreferencesHydrated, loadHome, requestHomeFullReload]);

  useEffect(() => {
    if (!screenFocused) homeBlurredAtRef.current = Date.now();
  }, [screenFocused]);

  // 从任务 / 设置等页面返回首页:离开期间订阅一直在、补丁一直在收,只补拉判定为可能漏了
  // 推送的设备。离开太久或尚未完成首轮同步时退回整轮 loadHome。
  const refillStaleHomeDevices = useCallback((deviceIds: readonly string[]) => {
    if (deviceIds.length === 0) return;
    const expectedAccountGeneration = accountGeneration;
    const selectedDeviceIdAtStart = selectedDeviceIdRef.current;
    const stale = new Set(deviceIds);
    const rows = homeSyncRowsRef.current.filter((item) => stale.has(item.device.deviceId));
    void runHomeDeviceSyncBatch(rows, async (item) => (
      hydrateDeviceSessions(item.device, expectedAccountGeneration)
    )).then((results) => {
      if (
        homeAccountGenerationRef.current !== expectedAccountGeneration
        || selectedDeviceIdRef.current !== selectedDeviceIdAtStart
      ) return;
      const failures = results
        .filter((result) => !result.superseded && result.failure)
        .map((result) => result.failure as HomeDeviceFailure);
      if (failures.length > 0) setError(failures);
      else if (results.some((result) => !result.superseded)) setError(null);
    });
  }, [accountGeneration, hydrateDeviceSessions]);

  // Android can recreate the activity or resume the JS runtime without a fresh React
  // mount. Foreground is therefore an authoritative trigger alongside the initial mount
  // and reconnect; loadHome single-flights these overlapping cold-start calls.
  useFocusEffect(
    useCallback(() => {
      // The focus event can fire before useIsFocused re-renders this screen. Navigation has
      // already confirmed focus, so open the scope gate now instead of skipping this return.
      screenFocusedRef.current = true;
      const blurredAt = homeBlurredAtRef.current;
      const forceFull = homeFullReloadOnFocusRef.current !== null;
      homeBlurredAtRef.current = null;
      const plan = planHomeListFocusReturn({
        forceFull,
        blurredAt,
        lastSyncedAt: lastSyncedAtRef.current,
        now: Date.now(),
        deviceIds: homeSyncRowsRef.current.map((item) => item.device.deviceId),
        freshness: homeListFreshnessRef.current,
        listMutationEpoch: (deviceId) => remoteSessionStore.captureDeviceSessionListMutationEpoch(deviceId),
      });
      const scheduleDirty = new Set(homeScheduleIndexDirtyRef.current.keys());
      if (plan.kind === 'refill') {
        refillStaleHomeDevices(plan.deviceIds);
        if (scheduleDirty.size > 0) refreshHomeScheduleIndexes(scheduleDirty);
        return;
      }
      refreshHomeScheduleIndexes();
      startSilentHomeSync();
    }, [refillStaleHomeDevices, refreshHomeScheduleIndexes, startSilentHomeSync]),
  );

  useEffect(() => {
    startSilentHomeSync();
    const subscription = AppState.addEventListener('change', (nextState) => {
      // 退后台后连接会在宽限期后停掉,期间的推送无从补齐:回前台一律按需重拉。
      if (nextState === 'background') homeListFreshnessRef.current.invalidateAll();
      if (nextState === 'active') startSilentHomeSync();
    });
    return () => subscription.remove();
  }, [connectionEpoch, startSilentHomeSync]);

  // 把当前权威设备列表注入 remoteSessionStore,让 store 给所有 useRemoteSessions 消费者(首页项目卡、
  // 设备详情页)统一算展示用 canonicalDeviceId:re-link 后残留的 stale shard 会话按设备名唯一匹配认领回
  // 当前设备,首页归并进哪张卡、详情页就能看到同样这批会话(消除「卡片 N 条、点进去 N-1 条」)。
  useEffect(() => {
    remoteSessionStore.setDeviceIdentity(devices.map((device) => ({ deviceId: device.deviceId, name: device.name })));
  }, [devices]);

  useEffect(() => {
    if (!deviceIdentityCacheReady || !lastPresenceSnapshot) return;
    if (lastPresenceSnapshotProcessedRef.current !== lastPresenceSnapshot) {
      lastPresenceSnapshotProcessedRef.current = lastPresenceSnapshot;
      markPresenceFresh(presenceFreshnessRef.current, lastPresenceSnapshot.deviceId);
    }
    const result = patchDeviceViewsWithPresence(
      devicesRef.current,
      lastPresenceSnapshot,
      selfDeviceId,
    );
    const reconciled = reconcileDeviceViews(result.devices);
    devicesRef.current = reconciled.devices;
    if (result.changed || reconciled.viewsChanged) setDevices(reconciled.devices);
    const hydratedDevice = result.device
      ? reconciled.devices.find((device) => device.deviceId === result.device?.deviceId) ?? result.device
      : null;
    if (!hydratedDevice || !result.becameControllable || !isCurrentHomeSyncTarget(hydratedDevice.deviceId)) return;
    void hydrateDeviceSessions(hydratedDevice).then((hydrateResult) => {
      if (hydrateResult.superseded) return;
      if (hydrateResult.failure) setError(hydrateResult.failure);
      else setError(null);
    });
  }, [deviceIdentityCacheReady, hydrateDeviceSessions, isCurrentHomeSyncTarget, lastPresenceSnapshot, reconcileDeviceViews, selfDeviceId]);

  // Auto-heal revoked access: a host only signals a re-grant by accepting a fresh request, so on
  // every (re)connect silently re-probe each revoked device. The one-row invoke clears the
  // in-memory revoked mark on success (withAccessRevokedHandling) without retaining a hidden
  // list subscription. Scope reconciliation then hydrates it only when it is actually visible.
  useEffect(() => {
    if (status !== 'online') return;
    const revoked = revokedDevicesStore.getSnapshot();
    if (revoked.size === 0) return;
    void runHomeDeviceSyncBatch([...revoked], (deviceId) => (
      homeDeviceSyncLimiterRef.current.run(() => probeRevokedDeviceAccess(deviceId))
    ));
  }, [connectionEpoch, probeRevokedDeviceAccess, status]);

  // Close the revoked tip automatically once access is restored (auto-heal or manual retry).
  useEffect(() => {
    if (revokedTipDeviceId && !revokedDevices.has(revokedTipDeviceId)) setRevokedTipDeviceId(null);
  }, [revokedDevices, revokedTipDeviceId]);

  const retryRevokedDevice = useCallback(async (deviceId: string) => {
    const expectedAccountGeneration = accountGeneration;
    const device = devicesRef.current.find((item) => item.deviceId === deviceId);
    if (!device) return;
    // 同设备重试仍在飞行中时直接忽略,防止连点/引导页重复触发叠加请求。
    if (retryingDeviceIdsRef.current.has(deviceId)) return;
    retryingDeviceIdsRef.current.add(deviceId);
    setRetryingDeviceIds(new Set(retryingDeviceIdsRef.current));
    try {
      await homeDeviceSyncLimiterRef.current.run(
        () => probeRevokedDeviceAccess(device.deviceId, expectedAccountGeneration),
        'foreground',
      );
    } finally {
      if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
      // Retry state is scoped per device; only clear this request to avoid clearing another in-flight retry.
      retryingDeviceIdsRef.current.delete(deviceId);
      setRetryingDeviceIds(new Set(retryingDeviceIdsRef.current));
    }
    // probe invoke clears the revoked mark on success; the tip-close effect handles dismissal.
  }, [accountGeneration, probeRevokedDeviceAccess]);

  // 菜单 Modal 完全关闭(淡出结束 + 卸载)后,执行延后的弹窗动作。
  const handleDeviceMenuClosed = useCallback(() => {
    const action = pendingMenuActionRef.current;
    if (!action) return;
    pendingMenuActionRef.current = null;
    action();
  }, []);

  const handleChromeMenuClosed = useCallback(() => {
    const action = pendingMenuActionRef.current;
    if (!action) return;
    pendingMenuActionRef.current = null;
    action();
  }, []);

  // 菜单展开时清掉上一轮残留的延后动作(例如淡出中途被重新展开,onClosed 未触发的情况)。
  const openDeviceMenu = useCallback(() => {
    pendingMenuActionRef.current = null;
    setChromeMenuOpen(false);
    setDeviceMenuOpen(true);
  }, []);

  const openChromeMenu = useCallback(() => {
    pendingMenuActionRef.current = null;
    setDeviceMenuOpen(false);
    setChromeMenuOpen(true);
  }, []);

  const onListScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
    homeScrollY.value = event.nativeEvent.contentOffset.y;
    if (scrollRestored.current) viewSession.write('scrollOffset', homeScrollY.value);
    const next = event.nativeEvent.contentOffset.y > 8;
    setHeaderFrosted((current) => (current === next ? current : next));
  }, [homeScrollY, viewSession]);

  const deviceRows = useMemo(
    () => toDeviceListItems(devices, Date.now(), revokedDevices),
    [devices, i18nInstance.resolvedLanguage, revokedDevices],
  );
  // 不随首页失焦清空:被任务页等盖住时保留订阅与镜像,增量补丁照常到达;
  // 不可见 / 不可用的设备仍由 resolveHomeDeviceSyncIds 排除并 release。
  const homeSyncDeviceIds = useMemo(() => resolveHomeDeviceSyncIds(
    deviceRows.map((item) => ({
      canOpen: item.canOpen,
      deviceId: item.device.deviceId,
    })),
    active ? selectedDeviceId : null,
  ), [deviceRows, selectedDeviceId, active]);
  const homeSyncDeviceIdSet = useMemo(() => new Set(homeSyncDeviceIds), [homeSyncDeviceIds]);
  const homeSyncRows = useMemo(
    () => deviceRows.filter((item) => homeSyncDeviceIdSet.has(item.device.deviceId)),
    [deviceRows, homeSyncDeviceIdSet],
  );
  homeSyncRowsRef.current = homeSyncRows;

  useEffect(() => {
    const expectedAccountGeneration = accountGeneration;
    const selectedDeviceIdAtStart = selectedDeviceIdRef.current;
    const diff = reconcileHomeDeviceSyncScope(homeSyncDeviceIds);
    if (diff.acquire.length === 0) return;
    const acquireIds = new Set(diff.acquire);
    const rows = homeSyncRows.filter((item) => acquireIds.has(item.device.deviceId));
    void runHomeDeviceSyncBatch(rows, async (item) => (
      hydrateDeviceSessions(item.device, expectedAccountGeneration)
    )).then((results) => {
      if (
        homeAccountGenerationRef.current !== expectedAccountGeneration
        || selectedDeviceIdRef.current !== selectedDeviceIdAtStart
      ) return;
      const failures = results
        .filter((result) => !result.superseded && result.failure)
        .map((result) => result.failure as HomeDeviceFailure);
      if (failures.length > 0) setError(failures);
      else if (results.some((result) => !result.superseded)) setError(null);
    });
  }, [accountGeneration, homeSyncDeviceIds, homeSyncRows, hydrateDeviceSessions, reconcileHomeDeviceSyncScope, selectedDeviceId]);

  useEffect(() => {
    const unregisters = homeSyncRows.map((item) =>
      remoteSessionStore.registerReseedHandler(item.device.deviceId, () => {
        // 首页被盖住时 hydrate 会被 scope 门禁跳过;先记下失效,回到首页再补拉这台。
        homeListFreshnessRef.current.invalidate(item.device.deviceId);
        void hydrateDeviceSessions(item.device, accountGeneration, {
          trailingIfInFlight: true,
        }).then((hydrateResult) => {
          if (hydrateResult.superseded) return;
          if (hydrateResult.failure) setError(hydrateResult.failure);
          else setError(null);
        });
      }),
    );
    return () => {
      for (const unregister of unregisters) unregister();
    };
  }, [accountGeneration, homeSyncRows, hydrateDeviceSessions]);

  const deviceModels = useMemo(() => deviceRows.map((item) => ({
    canOpen: item.canOpen,
    deviceId: item.device.deviceId,
    name: item.device.name,
    state: item.state,
    statusDetail: item.statusDetail,
    statusLabel: item.statusLabel,
  })), [deviceRows]);
  useEffect(() => {
    let cancelled = false;
    remoteHomeCollectionsRef.current = [];
    setRemoteHomeCollections([]);
    setResourceCacheAccount(null);
    void readRemoteResourceSnapshot(homeCacheUserId).then((snapshot) => {
      if (cancelled) return;
      remoteHomeCollectionsRef.current = snapshot.home;
      setRemoteHomeCollections(snapshot.home);
      setResourceCacheAccount(accountGeneration);
    });
    return () => { cancelled = true; };
  }, [accountGeneration, homeCacheUserId]);
  useEffect(() => {
    if (resourceCacheAccount !== accountGeneration || !homeListCacheHydrated || (deviceModels.length === 0 && lastSyncedAt === null)) return;
    let cancelled = false;
    const targets = remoteResourceDiscoveryTargets(deviceModels, remoteHomeCollectionsRef.current);
    if (targets.length === 0) {
      remoteHomeCollectionsRef.current = [];
      setRemoteHomeCollections([]);
      return () => { cancelled = true; };
    }
    void discoverRemoteHomeCollections(
      (deviceId, channel, args) => invoke(deviceId, channel, args, {
        background: true,
        preSend: () => {
          if (cancelled || homeAccountGenerationRef.current !== accountGeneration)
            throw new Error('Remote discovery superseded');
        },
      }),
      targets,
      i18nInstance.language,
      remoteHomeCollectionsRef.current,
    )
      .then((collections) => {
        if (!cancelled && homeAccountGenerationRef.current === accountGeneration) {
          remoteHomeCollectionsRef.current = collections;
          setRemoteHomeCollections(collections);
          void cacheRemoteResourceHome(homeCacheUserId, collections);
        }
      })
      .catch(() => {
        // Optional capability discovery must not turn a healthy Sessions home into an error page.
        // Keep the last same-account manifest during transient link failures.
      });
    return () => { cancelled = true; };
  }, [
    accountGeneration,
    connectionEpoch,
    resourceCacheAccount,
    lastSyncedAt,
    homeListCacheHydrated,
    homeCacheUserId,
    deviceModels,
    i18nInstance.language,
    invoke,
  ]);
  useEffect(() => {
    remoteSessionStore.setConversationSearchDeviceModels(deviceModels.map((item) => ({
      canOpen: item.canOpen,
      deviceId: item.deviceId,
      name: item.name,
      state: item.state,
    })));
  }, [deviceModels]);
  const searchOrigins = useMemo(() => conversationSearchOriginsFromDeviceModels(
    deviceModels,
    {
      selectedDeviceId,
      unresponsiveDeviceIds: unresponsiveDevices,
    },
  ), [deviceModels, selectedDeviceId, unresponsiveDevices]);
  const searchProjects = useMemo(
    () => listConversationSearchProjects(
      excludeOrcaWorkerSessions(sessions),
      new Set(searchOrigins.map((origin) => origin.deviceId)),
      projectAliases,
    ),
    [searchOrigins, sessions, projectAliases],
  );
  const indexedSearch = useConversationSearch({
    enabled: true,
    retainedState: viewSession,
    origins: searchOrigins,
    projects: deviceIdentityCacheReady ? searchProjects : undefined,
    projectAliases,
  });
  const searchQuery = indexedSearch.query;
  const normalizedSearchQuery = searchQuery.trim();
  const messageSearchVersion = useRemoteMessageVersion(normalizedSearchQuery.length > 0);
  const homeStatusVersion = useRemoteHomeStatusVersion();
  const searchFilterA11y = t('devices.list.search.filterAria', {
    agent: t(`devices.list.search.filter.agent.${indexedSearch.agentFilter}`),
    lastActivity: t(`devices.list.search.filter.lastActivity.${indexedSearch.lastActivityFilter}`),
    projects: indexedSearch.projectSelection === 'all'
      ? t('devices.list.search.filter.allProjects')
      : t('devices.list.search.filter.selectedProjects', { count: indexedSearch.projectSelection.length }),
    sort: t(`devices.list.search.filter.sort.${indexedSearch.sortBy}`),
    status: t(`devices.list.search.filter.status.${indexedSearch.statusFilter}`),
  });
  const searchFilterMenu = useConversationSearchFilterMenu({
    activeCount: indexedSearch.activeFilterCount,
    agentKind: indexedSearch.agentFilter,
    lastActivity: indexedSearch.lastActivityFilter,
    lockedProjects: false,
    onAgentKindChange: indexedSearch.setAgentFilter,
    onLastActivityChange: indexedSearch.setLastActivityFilter,
    onProjectsChange: indexedSearch.setProjectSelection,
    onReset: indexedSearch.resetFilters,
    onSortChange: indexedSearch.setSortBy,
    onStatusChange: indexedSearch.setStatusFilter,
    projectSelection: indexedSearch.projectSelection,
    projects: searchProjects,
    sortBy: indexedSearch.sortBy,
    status: indexedSearch.statusFilter,
  });
  useEffect(() => {
    const expectedAccountGeneration = accountGeneration;
    const ids = homeSyncDeviceIds;
    if (ids.length === 0) return undefined;
    let cancelled = false;
    let retryTimer: ReturnType<typeof setTimeout> | undefined;
    const fence = createProjectOrderFetchFence();
    projectOrderFetchFenceRef.current = fence;
    const load = async (attempt: number) => {
      // Project ordering is secondary Home metadata. Let the bounded sessions-list batch
      // finish first so cold start/reconnect does not create a second overlapping six-device
      // fan-out. A queued refresh is included as well; live pushes remain fenced below.
      while (syncInFlightRef.current) {
        await syncInFlightRef.current;
        if (cancelled || homeAccountGenerationRef.current !== expectedAccountGeneration) return;
      }
      const tokens = new Map(ids.map((deviceId) => [deviceId, fence.begin(deviceId)]));
      const entries = await runHomeDeviceSyncBatch(ids, async (deviceId) => {
        const result = await homeDeviceSyncLimiterRef.current.run(async () => {
          if (
            cancelled
            || homeAccountGenerationRef.current !== expectedAccountGeneration
            || !homeSyncTargetDeviceIdsRef.current.has(deviceId)
          ) return { kind: 'transient' } as const;
          return fetchHostProjectOrder(invoke, deviceId);
        });
        return [deviceId, result] as const;
      });
      if (cancelled || homeAccountGenerationRef.current !== expectedAccountGeneration) return;
      for (const [deviceId, result] of entries) {
        if (!fence.shouldApplyFetch(deviceId, tokens.get(deviceId) ?? 0)) continue;
        if (result.kind === 'ok') rememberRemoteProjectOrderStamp(deviceId, result.snapshot.ownerStamp);
      }
      setHostProjectOrders((current) => {
        const next = new Map(current);
        for (const [deviceId, result] of entries) {
          if (!fence.shouldApplyFetch(deviceId, tokens.get(deviceId) ?? 0)) continue;
          if (result.kind === 'ok') next.set(deviceId, result.snapshot);
          else if (result.kind === 'unavailable') next.set(deviceId, UNAVAILABLE_PROJECT_ORDER_SNAPSHOT);
        }
        return next;
      });
      if (attempt < 3 && entries.some(([, result]) => result.kind === 'transient')) {
        retryTimer = setTimeout(() => {
          void load(attempt + 1);
        }, 2000);
      }
    };
    void load(1);
    const unsubscribe = subscribeRemoteProjectOrderChanged((deviceId, snapshot) => {
      if (
        cancelled
        || homeAccountGenerationRef.current !== expectedAccountGeneration
        || !ids.includes(deviceId)
      ) return;
      fence.noteLiveUpdate(deviceId);
      setHostProjectOrders((current) => {
        const next = new Map(current);
        next.set(deviceId, snapshot);
        return next;
      });
    });
    return () => {
      cancelled = true;
      if (retryTimer) clearTimeout(retryTimer);
      unsubscribe();
    };
  }, [accountGeneration, homeSyncDeviceIds, invoke]);
  const revokedTipDeviceName = useMemo(
    () => revokedTipDeviceId
      ? deviceModels.find((item) => item.deviceId === revokedTipDeviceId)?.name ?? t('devices.list.thisComputer')
      : null,
    [deviceModels, revokedTipDeviceId, t],
  );
  // 消息预览仅在搜索时构建全局索引;普通首页由行级 selector 消费。pending/live/running
  // 共用低频 homeStatusVersion,普通文本 token 不再重建这些 Map 或 home → sections 链。
  const messagePreviewIndexRaw = useMemo(() => {
    // 普通首页的预览由可见行按 session 订阅。只有搜索需要跨全部任务建立消息索引。
    if (!normalizedSearchQuery) return new Map<string, string>();
    return remoteSessionStore.getSessionListMessagePreviewIndex(sessions);
  }, [messageSearchVersion, normalizedSearchQuery, sessions]);
  const messagePreviewIndex = useStableValue(messagePreviewIndexRaw, mapContentEqual);
  const pendingInteractionIndexRaw = useMemo(() => {
    const next = new Map<string, number>();
    const activeIds = new Set<string>();
    for (const session of sessions) {
      activeIds.add(session.id);
      const pending = remoteSessionStore.getPendingInteractions(session.id);
      const cached = homePendingCacheRef.current.get(session.id);
      const count = cached?.pending === pending ? cached.count : pending.length;
      if (!cached || cached.pending !== pending) homePendingCacheRef.current.set(session.id, { pending, count });
      if (count > 0) next.set(session.id, count);
    }
    for (const sessionId of homePendingCacheRef.current.keys()) {
      if (!activeIds.has(sessionId)) homePendingCacheRef.current.delete(sessionId);
    }
    return next;
  }, [homeStatusVersion, sessions]);
  const pendingInteractionIndex = useStableValue(pendingInteractionIndexRaw, mapContentEqual);
  const liveActivityIndexRaw = useMemo(() => {
    const next = new Map<string, RemoteSessionLiveActivity>();
    for (const session of sessions) {
      const liveActivity = remoteSessionStore.getSessionLiveActivity(session.id);
      if (liveActivity) next.set(session.id, liveActivity);
    }
    const previous = homeLiveActivityIndexRef.current;
    if (previous.size === next.size) {
      let unchanged = true;
      for (const [sessionId, value] of next) {
        if (previous.get(sessionId) !== value) {
          unchanged = false;
          break;
        }
      }
      if (unchanged) return previous;
    }
    homeLiveActivityIndexRef.current = next;
    return next;
  }, [homeStatusVersion, sessions]);
  const liveActivityIndex = useStableValue(liveActivityIndexRaw, mapContentEqual);
  // 列表隐藏 Orca worker 子会话(本期不支持进 worker 聊天);Lead + 普通会话保留。仅 mobile 侧过滤。
  const homeSessions = useMemo(() => excludeOrcaWorkerSessions(sessions), [sessions]);
  const home = useMemo(
    () => buildMobileHomePresentation({
      projectAliases,
      devices: deviceModels,
      liveActivityIndex,
      messagePreviewIndex,
      pendingInteractionIndex,
      scheduleIndex,
      searchQuery,
      selectedDeviceId,
      sessions: homeSessions,
      statusFilter,
      // 未起名会话的显示文案:共享层不兜中文串,由这里给已解析的 i18n 值。
      unnamedLabel: t('session.menu.unnamedTitle'),
    }),
    [deviceModels, liveActivityIndex, messagePreviewIndex, pendingInteractionIndex, scheduleIndex, searchQuery, selectedDeviceId, homeSessions, statusFilter, t, projectAliases],
  );
  // 「筛选 › 项目」的候选:设备范围内的项目全集,不受搜索与任务状态影响——否则已选中的项目
  // 会因搜索没命中或当前状态下没有任务而从菜单里消失,用户无法单独取消它。
  const projectFilterUniverse = useMemo(
    () => buildMobileHomePresentation({
      projectAliases,
      devices: deviceModels,
      scheduleIndex,
      selectedDeviceId,
      sessions: homeSessions,
      statusFilter: 'all',
      unnamedLabel: t('session.menu.unnamedTitle'),
    }),
    [deviceModels, scheduleIndex, selectedDeviceId, homeSessions, t, projectAliases],
  );
  const projectMachineIdentities = useMemo(
    () => buildHomeProjectMachineIdentities(home, {
      status, getPresenceAvailability, unresponsiveDevices, revokedDevices,
    }),
    // Presence is read through a stable getter; its version/connection epoch must
    // refresh icons even when the page-local device list has not changed.
    [home, status, getPresenceAvailability, presenceVersion, connectionEpoch, unresponsiveDevices, revokedDevices],
  );
  const runningSessionIds = useMemo(() => {
    const ids = new Set<string>();
    for (const session of homeSessions) {
      if (remoteSessionStore.isSessionRunning(session.id)) ids.add(session.id);
      if (liveActivityIndex.get(session.id)?.phase === 'running') ids.add(session.id);
      if (scheduleIndex.get(session.id)?.running) ids.add(session.id);
    }
    return ids;
  }, [homeSessions, homeStatusVersion, liveActivityIndex, scheduleIndex]);
  const homePriorityItems = useMemo(
    () => [...home.pinned, ...home.chats, ...home.projects.flatMap((project) => project.sessions)],
    [home],
  );
  const priorityContext = useMemo(
    () => collectHomePriorityContext(homePriorityItems, runningSessionIds, homeViewedPriorityHold),
    [homePriorityItems, priorityHoldEpoch, runningSessionIds],
  );
  const priorityContextRef = useRef(priorityContext);
  priorityContextRef.current = priorityContext;
  const sortPriorityContext = sortBy === 'priority' ? priorityContext : undefined;
  useEffect(() => {
    if (!leftHomeForSessionRef.current) return;
    // 首页留在导航栈中时仍会收到详情页任务的运行 / 等待状态更新。同步推进 hold,
    // 避免新一轮跑完后旧 unread / waiting 档位重新生效,直到返回首页才跳位。
    if (!advanceCurrentViewedPriorityHold(homeViewedPriorityHold, priorityContext, Date.now())) {
      return;
    }
    setPriorityHoldEpoch((epoch) => epoch + 1);
  }, [priorityContext]);
  const selectedHostOrder = selectedDeviceId ? hostProjectOrders.get(selectedDeviceId) : undefined;
  const hostManualProjectOrder = useMemo(
    () => selectedDeviceId && selectedHostOrder
      ? controllerKeysFromHost(selectedDeviceId, selectedHostOrder)
      : [],
    [selectedDeviceId, selectedHostOrder],
  );
  // The resolver copies the order array. Resolve only when its inputs change:
  // a new array here invalidates every section even on a menu/focus update.
  const displayed = useMemo(
    () => resolveDisplayedProjectOrder(
      resolveProjectOrderWriteScope(selectedDeviceId ? [selectedDeviceId] : 'all', 'local'),
      selectedHostOrder,
      { manualProjectOrder, projectOrder },
      hostManualProjectOrder,
    ),
    [selectedDeviceId, selectedHostOrder, manualProjectOrder, projectOrder, hostManualProjectOrder],
  );
  const displayedProjectOrder = displayed.projectOrder;
  const displayedManualProjectOrder = displayed.manualProjectOrder;
  const sharedGroup = useMemo(() => splitSharedHomeGroup(home, ownedSharedTasks, {
    sessions: homeSessions, searchQuery, statusFilter,
  }), [home, ownedSharedTasks, homeSessions, searchQuery, statusFilter]);
  const cloudTeammates = useCloudCompanionHome(false);
  const cloudTeammateIds = useMemo(() => new Set(cloudTeammates.actors.filter(actor => actor.kind === 'bot').map(actor => actor.externalId)), [cloudTeammates.actors]);
  const cindyTeammateIds = useMemo(() => new Set(cloudTeammates.cindyIds), [cloudTeammates.cindyIds]);
  const effectiveTeammateFilter = useMemo(() => normalizeTaskTeammateSelection(teammateFilter, cloudTeammateIds, cindyTeammateIds), [teammateFilter, cloudTeammateIds, cindyTeammateIds]);
  const teammateOptions = useMemo(() => taskTeammateOptions(
    cloudCompanionRows(teammatesSectionContext.shared?.roster.items ?? [], cloudTeammates.actors, cloudTeammates.deviceNames),
    cloudTeammateIds, i18nInstance.language, cindyTeammateIds,
  ), [teammatesSectionContext.shared?.roster.items, cloudTeammates.actors, cloudTeammates.deviceNames, cloudTeammateIds, i18nInstance.language, cindyTeammateIds]);
  const contentFilters = useMemo<HomeContentFilters>(() => ({
    lastActivity: lastActivityFilter,
    projects: projectFilter,
    teammates: effectiveTeammateFilter,
    teammateKey: item => {
      const session = item.session as RemoteSession;
      const id = session.taskTeammate?.id ?? session.companion?.id;
      return id ? taskTeammateKey(id, session.deviceLinkDeviceId ?? '', cloudTeammateIds, cindyTeammateIds) : undefined;
    },
    vendor: vendorFilter,
  }), [lastActivityFilter, projectFilter, effectiveTeammateFilter, cloudTeammateIds, cindyTeammateIds, vendorFilter]);
  // 「最近活跃」按当前时间截断:列表没有新数据时也要让越过截止线的任务按时移出。
  const filterTick = useHomeFilterClock(lastActivityFilter !== 'all' && screenFocused);
  const filteredSharedRows = useMemo(
    () => filterSharedHomeRows(sharedGroup.rows, contentFilters, filterTick || Date.now()),
    [contentFilters, filterTick, sharedGroup.rows],
  );
  const sharedRows = shouldReplaceListWithSearchResults(searchQuery, indexedSearch.status) ? [] : filteredSharedRows;
  const contentFilterCount = activeContentFilterCount(contentFilters);
  const filteredHome = useMemo(
    () => applyHomeContentFilters(sharedGroup.home, contentFilters, filterTick || Date.now()),
    [contentFilters, filterTick, sharedGroup.home],
  );
  const homeSections = useMemo(
    () => buildHomeSections(filteredHome, groupByProject, pinnedCollapsed, {
      dialogueTitle: t('devices.list.menu.dialogueFolder'),
      groupDialogue,
      manualProjectOrder: displayedManualProjectOrder,
      priorityContext: sortPriorityContext,
      projectOrder: displayedProjectOrder,
      sortBy,
    }),
    [displayedManualProjectOrder, displayedProjectOrder, filteredHome, groupByProject, groupDialogue, pinnedCollapsed, sortPriorityContext, sortBy, t],
  );
  const sections = useMemo(() => {
    if (!shouldReplaceListWithSearchResults(searchQuery, indexedSearch.status)) return homeSections;
    return [{
      data: indexedSearch.results.map((item) => ({
        item,
        key: `search:${(item.session as { deviceLinkDeviceId?: string | null }).deviceLinkDeviceId ?? 'local'}:${item.session.id}`,
        kind: 'session' as const,
        source: 'search' as const,
        sourceLabel: selectedDeviceId
          ? undefined
          : ((item.session as { deviceLinkDeviceName?: string | null }).deviceLinkDeviceName ?? undefined),
      })),
      key: 'search',
      title: null,
    }];
  }, [homeSections, indexedSearch.results, indexedSearch.status, searchQuery, selectedDeviceId]);
  if (displayedProjectOrder !== 'custom') {
    visualProjectKeysRef.current = sections.flatMap((section) => section.data)
      .filter((row): row is Extract<HomeRow, { kind: 'project' }> => row.kind === 'project')
      .map((row) => row.project.key);
  }
  const visibleProjectKeys = useMemo(
    () => sections.flatMap((section) => section.data)
      .filter((row): row is Extract<HomeRow, { kind: 'project' }> => row.kind === 'project')
      .map((row) => row.project.key),
    [sections],
  );

  useFocusEffect(
    useCallback(() => {
      if (!leftHomeForSessionRef.current) return;
      leftHomeForSessionRef.current = false;
      advanceViewedPriorityHold(homeViewedPriorityHold, undefined, priorityContext, Date.now());
      setPriorityHoldEpoch((epoch) => epoch + 1);
    }, [priorityContext]),
  );
  const windowLayout = buildMainWindowLayout({
    actionCount: 1,
    kind: 'list',
    metricCount: 3,
    screenWidth,
  });
  const homeRecoveringDeviceIds = new Set(homeSyncDeviceIds.filter((id) => unresponsiveDevices.has(id)
    || recoveringDeviceIds.has(id) || rawDeviceConnectionStates[id] === 'syncing'));
  const homeDeviceUnresponsive = homeSyncDeviceIds.some((id) => unresponsiveDevices.has(id));
  const { error: connectionError, deviceRecovery: homeDeviceRecovery } = resolveHomeConnectionFeedback(error, homeRecoveringDeviceIds, describeRemoteError);
  const initialHomeSettled = deviceIdentityCacheReady && lastSyncedAt !== null;
  const restoreListPosition = useCallback(() => {
    if (scrollRestored.current || !homeListCacheHydrated || !listViewportHeight.current) return;
    if (listContentHeight.current < initialScrollOffset.current + listViewportHeight.current && !initialHomeSettled) return;
    const responder = homeListRef.current?.getScrollResponder();
    if (!responder) return;
    responder.scrollTo({ y: initialScrollOffset.current, animated: false });
    scrollRestored.current = true;
  }, [homeListCacheHydrated, initialHomeSettled]);
  // Hydration can settle without another content-size event (for example a warm cache).
  useEffect(() => { restoreListPosition(); }, [restoreListPosition, sections]);
  // 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,
  //   若不回退,表头显示旧设备名而列表实际展示全部会话,两者口径不一致。
  // - 恢复自偏好的设备仍在列表但已不可用(canOpen=false,含 access_revoked / 远程控制关闭):
  //   loadHome 已移除其会话、pickPrimaryDevice 也返回 null,继续停留会卡在空列表 +
  //   新建按钮置灰。只对恢复的选择做一次性校验,不改变用户会话内手动选择后设备
  //   转为离线的既有行为(手动选择时设备必然可用)。
  useEffect(() => {
    if (!initialHomeSettled || !selectedDeviceId) return;
    const missing = home.selectedDeviceId === null;
    let restoredUnavailable = false;
    if (!missing && restoredSelectionUnvalidatedRef.current) {
      const filter = home.deviceFilters.find((item) => item.deviceId === selectedDeviceId);
      restoredUnavailable = !!filter && !canBrowseMobileHomeDevice(filter);
      restoredSelectionUnvalidatedRef.current = false;
    }
    if (!missing && !restoredUnavailable) return;
    setSelectedDeviceId(null);
    setRestoredDeviceName(null);
    void saveHomeViewPreferences({ selectedDevice: null });
  }, [home.deviceFilters, home.selectedDeviceId, initialHomeSettled, selectedDeviceId]);
  // 连接层失败原因比请求级 error 更根因:unstable 在 online 时也需保持可见。
  const activeConnectionIssue = status !== 'online' || connectionIssue?.kind === 'unstable' ? connectionIssue : null;
  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,
    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 = !networkUnavailable && resolveConnectionBannerSyncActionVisibility({
    online: status === 'online',
    hasActiveIssue: activeConnectionIssue !== null,
    deviceUnresponsive: homeDeviceRecovery,
    hasRequestError: connectionError !== null,
    // loadHome has no outer retry after its bounded REST retries are exhausted.
    requestErrorAutoRecovering: false,
  });
  const showHomeRecoveryProgress = !networkUnavailable && (!activeConnectionIssue
    || activeConnectionIssue.kind === 'unstable' || activeConnectionIssue.kind === 'replaced')
    && (status === 'connecting' || homeDeviceRecovery);
  const connectionTone = networkUnavailable || activeConnectionIssue
    ? 'off'
    : homeDeviceRecovery ? 'busy' : selectedDeviceDisconnected ? 'off' : connectionError ? 'muted' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';
  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 的分支同口径。
  // 引导态下首页没有可筛选的对话:表头「所有对话 ▾」退化为纯品牌标题、新建 FAB 隐藏,
  // 避免在产品说明页上摆一堆无意义的入口。
  const homeListItemCount = sharedRows.length + sections.reduce((count, section) => count + section.data.length, 0);
  const showRemoteGuide = homeListItemCount === 0
    && !initialHomeLoading
    && !initialHomeError
    && home.pinned.length === 0
    && home.emptyKind === 'noDevice'
    && home.emptyNoDevice !== null;
  const retryRevokedGuideDevices = useCallback(() => {
    const revoked = home.emptyNoDevice?.reason === 'accessRevoked' ? home.emptyNoDevice.devices : [];
    for (const device of revoked) void retryRevokedDevice(device.deviceId);
  }, [home.emptyNoDevice, retryRevokedDevice]);
  const hasOpenableLiveDevice = deviceModels.some((item) => item.canOpen);
  // 首次 loadHome 落地前(含失败态)FAB 只认 live 设备:缓存画出的会话会让 primaryDevice 合成出
  // 「可用」项,但缓存设备不能当 live 设备直接开新会话——列表先画出来,新建入口等 live 数据。
  const newSessionDisabled = !home.primaryDevice || (!initialHomeSettled && !hasOpenableLiveDevice);
  const taskSuggestionsDeviceId = selectedDeviceId ?? home.primaryDevice?.deviceId ?? undefined;
  const taskSuggestionsSyncing = isTaskSuggestionsSyncPending(
    homeSyncDeviceIds, homeListOwnedDeviceIdsRef.current, rawDeviceConnectionStates,
  );
  const taskSuggestionsCandidateMode = remoteTaskSuggestionsMode({
    sessionCount: countHomeSuggestionSessions(home,
      shouldReplaceListWithSearchResults(searchQuery, indexedSearch.status) ? indexedSearch.results : undefined),
    totalSessionCount: home.overview.all,
    hasSearchOrFilter: !!searchQuery.trim() || indexedSearch.activeFilterCount > 0 || statusFilter !== 'active'
      || contentFilterCount > 0,
    // Cached/offline lists and in-flight searches must not look ready to start work.
    ready: status === 'online' && !activeConnectionIssue && !initialHomeLoading && !initialHomeError && !connectionError
      && indexedSearch.status !== 'searching' && !newSessionDisabled
      && deviceModels.some((device) => device.canOpen
        && !recoveringDeviceIds.has(device.deviceId)
        && !unresponsiveDevices.has(device.deviceId)
        && rawDeviceConnectionStates[device.deviceId] !== 'failed'
        && device.deviceId === taskSuggestionsDeviceId),
  });
  const newSessionDeviceOptions = useMemo(
    () => deviceModels
      .filter((item) => item.canOpen)
      .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,
  });
  // 无可控电脑时不提供入口;完整空态已有主按钮,避免重复显示新建 CTA。
  const newSessionEntryVisible = !showRemoteGuide && !taskSuggestionsPending && taskSuggestionsMode !== 'empty';
  // 临时任务列表抽屉的新建放在顶栏,不浮动遮挡短列表。
  const headerNewSession = newSessionInHeader && newSessionEntryVisible;
  const selectedDeviceLabel = useMemo(() => {
    if (!selectedDeviceId) return t('devices.list.allConversations');
    // 设备列表尚未同步回来时,用偏好里存的设备名兜底,避免冷启动表头闪占位文案。
    return home.deviceFilters.find((item) => item.deviceId === selectedDeviceId)?.label
      ?? restoredDeviceName
      ?? t('devices.list.thisComputer');
  }, [home.deviceFilters, restoredDeviceName, selectedDeviceId, t]);
  // 设备名放得下时居中在顶栏中线;放不下时贴住右侧按钮,向左侧富余空间伸展后才截断。
  const homeTitle = useBalancedTitle();
  // Embedded drawers never show the remote-desktop action.
  const showHeaderRemoteDesktop = Boolean(selectedDeviceId) && !embedded;
  const reportHomeTitleSlot = homeTitle.reportSlot;
  const [homeHeaderWidth, setHomeHeaderWidth] = useState(0);
  const [homeTitleSlotFrame, setHomeTitleSlotFrame] = useState<{ x: number; width: number } | null>(null);
  useEffect(() => {
    if (!homeHeaderWidth || !homeTitleSlotFrame) return;
    reportHomeTitleSlot({
      center: homeHeaderWidth / 2,
      end: homeTitleSlotFrame.x + homeTitleSlotFrame.width - spacing.sm,
      start: homeTitleSlotFrame.x + spacing.sm,
    });
  }, [homeHeaderWidth, homeTitleSlotFrame, reportHomeTitleSlot]);

  const openSession = useCallback((item: RemoteSessionListItem) => {
    // 有行处于滑开状态时,点击(本行或他行)只负责收起,不进会话(iOS 列表滑动操作惯例)。
    if (swipeRegistry.closeOpenRow()) return;
    holdViewedPriorityRank(homeViewedPriorityHold, item.session.id, priorityContextRef.current);
    advanceViewedPriorityHold(homeViewedPriorityHold, item.session.id, priorityContextRef.current, Date.now());
    leftHomeForSessionRef.current = true;
    setPriorityHoldEpoch((epoch) => epoch + 1);
    if (navigationHost.current.onSelectSession) {
      navigationHost.current.onSelectSession(item);
      return;
    }
    const session = item.session as RemoteSession;
    // 打开会话走可达优先(与详情页 openSession 口径一致):被认领的 stale 会话优先用 canonicalDeviceId
    // (当前可达设备),否则 re-link 后旧 deviceId 不可达会导致「首页卡片点开打不开」。回退物理 id / store 索引。
    const deviceId = session.canonicalDeviceId ?? session.deviceLinkDeviceId ?? remoteSessionStore.getSessionDeviceId(session.id);
    if (!deviceId) {
      setError(t('devices.list.error.sessionDeviceNotFound'));
      return;
    }
    const focusClientId = 'searchFocusClientId' in item
      ? (item as { searchFocusClientId?: string }).searchFocusClientId
      : undefined;
    const href = {
      pathname: '/sessions/[sessionId]',
      params: {
        deviceId,
        deviceName: deviceDisplayName(deviceId, session.deviceLinkDeviceName),
        sessionId: session.id,
        ...(focusClientId ? { focusClientId } : {}),
      },
    } as const;
    rememberTask(href);
    guardedPush(href);
  }, [guardedPush, rememberTask, swipeRegistry, t]);

  // Every visible row receives this callback, and the list presentation is rebuilt on each
  // task update. Read the latest target on tap so updates do not re-render every row.
  const newSessionTargetRef = useRef({ primaryDevice: home.primaryDevice, newSessionDeviceOptions, selectedDeviceId });
  newSessionTargetRef.current = { primaryDevice: home.primaryDevice, newSessionDeviceOptions, selectedDeviceId };
  const openNewSession = useCallback((project?: MobileHomeProjectGroup, suggestion?: RemoteTaskSuggestionId, explicitDeviceId?: string, origin?: ComposerMorphOrigin) => {
    const { primaryDevice, newSessionDeviceOptions, selectedDeviceId } = newSessionTargetRef.current;
    const deviceId = project?.deviceId ?? explicitDeviceId ?? primaryDevice?.deviceId;
    const deviceName = deviceDisplayName(deviceId ?? '', project?.deviceName ?? newSessionDeviceOptions.find((device) => device.deviceId === deviceId)?.name ?? primaryDevice?.label);
    if (!deviceId) {
      setError(t('devices.list.error.noDevice'));
      return;
    }
    guardedPush({
      pathname: '/sessions/new',
      params: {
        deviceId,
        deviceName,
        deviceOptions: serializeNewSessionDeviceOptions(newSessionDeviceOptions),
        ...(origin ? { composerMorph: rememberComposerEntry(origin) } : {}),
        ...(suggestion ? { suggestion } : {}),
        ...(project?.workingDir ? { workingDir: project.workingDir } : {}),
        // 列表正筛选某台电脑时,新建默认跟随这台电脑(显式指定,盖过"上次选择"的
        // 记忆);推荐入口固定使用已通过就绪检查的电脑,普通新建仍可恢复记忆设备。
        ...(selectedDeviceId || explicitDeviceId ? { deviceExplicit: '1' } : {}),
      },
    });
  }, [guardedPush, t]);

  useEffect(() => {
    if (!newSessionActionRef) return;
    const action = () => openNewSession();
    newSessionActionRef.current = action;
    return () => { if (newSessionActionRef.current === action) newSessionActionRef.current = null; };
  }, [newSessionActionRef, openNewSession]);

  const openSuggestedSession = useCallback((suggestion?: RemoteTaskSuggestionId) => {
    openNewSession(undefined, suggestion, taskSuggestionsDeviceId);
  }, [openNewSession, taskSuggestionsDeviceId]);

  const logout = useCallback(async () => {
    if (loggingOut) return;
    setLoggingOut(true);
    try {
      await auth.logout();
      // Same landing as settings and the partner entries, without relying on the outer auth redirect.
      router.replace('/login');
    } catch (error) {
      Alert.alert(t('devices.list.alert.actionFailed'), formatRemoteError(error));
    } finally {
      setLoggingOut(false);
    }
  }, [auth, loggingOut, router, t]);

  const toggleProject = useCallback((key: string) => {
    if (swipeRegistry.closeOpenRow()) return;
    runDisclosure(() => setCollapsedProjectKeys((current) =>
      current.includes(key) ? current.filter((item) => item !== key) : [...current, key]));
  }, [runDisclosure, swipeRegistry]);

  const showAllDialogueSessions = useCallback(() => {
    runDisclosure(() => setDialogueShowAll(true));
  }, [runDisclosure]);

  const applyDisplayView = useCallback((patch: HomeDisplayPatch & { manualProjectOrder?: string[] }) => {
    const expectedAccountGeneration = accountGeneration;
    viewPrefsTouchedRef.current = true;
    let nextPatch = patch;
    if (
      !selectedDeviceId
      && patch.projectOrder === 'custom'
      && projectOrder !== 'custom'
      && manualProjectOrder.length === 0
    ) {
      nextPatch = {
        ...patch,
        manualProjectOrder: snapshotManualProjectOrder(
          visualProjectKeysRef.current,
          home.projects.filter((project) => project.kind !== 'cindy-make').map((project) => project.key),
        ),
      };
    }
    if (nextPatch.groupByProject !== undefined) setGroupByProject(nextPatch.groupByProject);
    if (nextPatch.groupDialogue !== undefined) setGroupDialogue(nextPatch.groupDialogue);
    if (nextPatch.sortBy !== undefined) setSortBy(nextPatch.sortBy);
    if (nextPatch.statusFilter !== undefined) setStatusFilter(nextPatch.statusFilter);
    if (nextPatch.teammateFilter !== undefined) setTeammateFilter(nextPatch.teammateFilter);
    if (nextPatch.projectFilter !== undefined) setProjectFilter(nextPatch.projectFilter);
    if (nextPatch.vendorFilter !== undefined) setVendorFilter(nextPatch.vendorFilter);
    if (nextPatch.lastActivityFilter !== undefined) setLastActivityFilter(nextPatch.lastActivityFilter);
    if (nextPatch.viewMode !== undefined) setViewMode(nextPatch.viewMode);
    if (nextPatch.taskInfoFields !== undefined) setTaskInfoFields(nextPatch.taskInfoFields);
    if (selectedDeviceId && nextPatch.projectOrder) {
      if (!isHostProjectOrderReachable(hostProjectOrders.get(selectedDeviceId))) {
        if (nextPatch.projectOrder !== undefined) setProjectOrder(nextPatch.projectOrder);
        if (nextPatch.manualProjectOrder !== undefined) setManualProjectOrder(nextPatch.manualProjectOrder);
        void saveHomeViewPreferences(nextPatch);
        return;
      }
      void applyHostProjectOrder(invoke, selectedDeviceId, {
        manualProjectOrder: nextPatch.projectOrder === 'custom'
          ? snapshotManualProjectOrder(
            visualProjectKeysRef.current,
            home.projects.filter((project) => project.kind !== 'cindy-make').map((project) => project.key),
          )
          : hostManualProjectOrder,
        knownHostKeys: hostProjectOrders.get(selectedDeviceId)?.manualProjectOrder,
        ownerStamp: hostProjectOrders.get(selectedDeviceId)?.ownerStamp,
        projectOrder: nextPatch.projectOrder,
      }).then((result) => {
        if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
        if (result.kind === 'unavailable') {
          projectOrderFetchFenceRef.current.noteLiveUpdate(selectedDeviceId);
          setHostProjectOrders((current) => {
            const next = new Map(current);
            next.set(selectedDeviceId, UNAVAILABLE_PROJECT_ORDER_SNAPSHOT);
            return next;
          });
          if (nextPatch.projectOrder !== undefined) setProjectOrder(nextPatch.projectOrder);
          if (nextPatch.manualProjectOrder !== undefined) {
            setManualProjectOrder(nextPatch.manualProjectOrder);
          }
          void saveHomeViewPreferences(nextPatch);
          return;
        }
        if (result.kind !== 'ok') return;
        projectOrderFetchFenceRef.current.noteLiveUpdate(selectedDeviceId);
        setHostProjectOrders((current) => {
          const next = new Map(current);
          next.set(selectedDeviceId, result.snapshot);
          return next;
        });
      });
      const { projectOrder: _hostOrder, manualProjectOrder: _hostKeys, ...viewerPatch } = nextPatch;
      if (Object.keys(viewerPatch).length > 0) void saveHomeViewPreferences(viewerPatch);
      return;
    }
    if (nextPatch.projectOrder !== undefined) setProjectOrder(nextPatch.projectOrder);
    if (nextPatch.manualProjectOrder !== undefined) setManualProjectOrder(nextPatch.manualProjectOrder);
    void saveHomeViewPreferences(nextPatch);
  }, [accountGeneration, home.projects, hostManualProjectOrder, hostProjectOrders, invoke, manualProjectOrder.length, projectOrder, selectedDeviceId]);

  const beginProjectDrag = useCallback((input: {
    absoluteY: number;
    count: number;
    key: string;
    title: string;
  }) => {
    swipeRegistry.closeOpenRow();
    const expectedAccountGeneration = accountGeneration;
    const epoch = projectDragEpochRef.current + 1;
    projectDragEpochRef.current = epoch;
    const keys = visibleProjectKeys;
    const layouts: ProjectHeaderLayout[] = [];
    let pending = keys.length;
    const finish = () => {
      if (
        homeAccountGenerationRef.current !== expectedAccountGeneration
        || projectDragEpochRef.current !== epoch
        || layouts.length === 0
      ) return;
      layouts.sort((a, b) => a.y - b.y);
      const self = layouts.find((item) => item.key === input.key);
      if (!self) return;
      const session: ProjectDragSession = {
        count: input.count,
        height: self.height,
        hoverIndex: projectDropIndexFromY(layouts.filter((item) => item.key !== input.key), input.absoluteY),
        key: input.key,
        layouts,
        originY: self.y,
        rootY: 0,
        title: input.title,
        width: 0,
        x: 0,
      };
      const header = projectHeaderRefs.current.get(input.key);
      header?.measureInWindow((x, _y, width) => {
        homeRootRef.current?.measureInWindow((_rootX, rootY) => {
          if (
            homeAccountGenerationRef.current !== expectedAccountGeneration
            || projectDragEpochRef.current !== epoch
          ) return;
          session.x = x;
          session.width = width;
          session.rootY = rootY;
          projectDragRef.current = session;
          projectDragY.value = self.y - rootY;
          setProjectDrag(session);
        });
      });
    };
    if (pending === 0) return;
    for (const key of keys) {
      const node = projectHeaderRefs.current.get(key);
      if (!node) {
        pending -= 1;
        if (pending === 0) finish();
        continue;
      }
      node.measureInWindow((_x, y, _width, height) => {
        layouts.push({ height, key, y });
        pending -= 1;
        if (pending === 0) finish();
      });
    }
  }, [accountGeneration, projectDragY, visibleProjectKeys, swipeRegistry]);

  const moveProjectDrag = useCallback((absoluteY: number) => {
    const session = projectDragRef.current;
    if (!session) return;
    // 跟手:幽灵行顶边 = 手指 Y - 半行高,避免跳到触点下方。
    projectDragY.value = absoluteY - session.height / 2 - session.rootY;
    const hoverIndex = projectDropIndexFromY(
      session.layouts.filter((item) => item.key !== session.key),
      absoluteY,
    );
    if (hoverIndex === session.hoverIndex) return;
    const next = { ...session, hoverIndex };
    projectDragRef.current = next;
    setProjectDrag(next);
  }, [projectDragY]);

  const endProjectDrag = useCallback(() => {
    const expectedAccountGeneration = accountGeneration;
    projectDragEpochRef.current += 1;
    const session = projectDragRef.current;
    projectDragRef.current = null;
    setProjectDrag(null);
    if (!session) return;
    const scope = resolveProjectOrderWriteScope(selectedDeviceId ? [selectedDeviceId] : 'all', 'local');
    const ledger = projectOrderWriteLedger(
      scope,
      selectedDeviceId ? hostProjectOrders.get(selectedDeviceId) : undefined,
    );
    const persistViewer = (next: string[]) => {
      if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
      viewPrefsTouchedRef.current = true;
      setProjectOrder('custom');
      setManualProjectOrder(next);
      void saveHomeViewPreferences({ projectOrder: 'custom', manualProjectOrder: next });
    };
    const mountedKeysByY = session.layouts.map((item) => item.key);
    if (ledger === 'host' && selectedDeviceId) {
      // 可见集取当前实际渲染的项目(已应用筛选),只保留该电脑可写主机账本的项目;
      // 主机完整账本只作为 currentFullOrder,被筛掉的项目保持原槽位。
      const hostWritable = new Set(home.projects
        .filter((item) => item.kind !== 'cindy-make' && item.deviceId === selectedDeviceId)
        .map((item) => item.key));
      const visibleKeys = visibleProjectKeys.filter((key) => hostWritable.has(key));
      // 虚拟化下 session.hoverIndex 只在已挂载子集从 0 计,先翻译成完整可见列表的插入位;
      // 翻译不出(源行未测到 / 已挂载子集为空)则中止,不写主机账本。
      const dropIndex = resolveVirtualizedDropIndex(
        visibleKeys,
        mountedKeysByY,
        session.key,
        session.hoverIndex,
      );
      if (dropIndex === null) return;
      const currentKeys = controllerKeysFromHost(
        selectedDeviceId,
        hostProjectOrders.get(selectedDeviceId) ?? UNAVAILABLE_PROJECT_ORDER_SNAPSHOT,
      );
      const next = reorderVisibleProjectByDropIndex(
        currentKeys.length > 0 ? currentKeys : visibleKeys,
        visibleKeys,
        session.key,
        dropIndex,
      );
      if (!next) return;
      void applyHostProjectOrder(invoke, selectedDeviceId, {
        knownHostKeys: hostProjectOrders.get(selectedDeviceId)?.manualProjectOrder,
        manualProjectOrder: next,
        ownerStamp: hostProjectOrders.get(selectedDeviceId)?.ownerStamp,
        projectOrder: 'custom',
      }).then((result) => {
        if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
        if (result.kind === 'unavailable') {
          projectOrderFetchFenceRef.current.noteLiveUpdate(selectedDeviceId);
          setHostProjectOrders((current) => {
            const nextOrders = new Map(current);
            nextOrders.set(selectedDeviceId, UNAVAILABLE_PROJECT_ORDER_SNAPSHOT);
            return nextOrders;
          });
          persistViewer(next);
          return;
        }
        if (result.kind !== 'ok') return;
        projectOrderFetchFenceRef.current.noteLiveUpdate(selectedDeviceId);
        setHostProjectOrders((current) => {
          const nextOrders = new Map(current);
          nextOrders.set(selectedDeviceId, result.snapshot);
          return nextOrders;
        });
      });
      return;
    }
    const dropIndex = resolveVirtualizedDropIndex(
      visibleProjectKeys,
      mountedKeysByY,
      session.key,
      session.hoverIndex,
    );
    if (dropIndex === null) return;
    const next = reorderVisibleProjectByDropIndex(
      manualProjectOrder,
      visibleProjectKeys,
      session.key,
      dropIndex,
    );
    if (!next) return;
    persistViewer(next);
  }, [accountGeneration, home.projects, hostProjectOrders, invoke, manualProjectOrder, selectedDeviceId, visibleProjectKeys]);
  useEffect(() => {
    if (!groupDialogue) setDialogueShowAll(false);
  }, [groupDialogue]);

  // 自动化组展开/收起,与项目组共用同一条折叠动画,保持视觉连续性。
  const toggleAutomationGroup = useCallback((key: string) => {
    // 自动化组可能嵌在项目块里:块内其它行也要让位。
    runDisclosure(() => setExpandedAutomationGroups((current) =>
      current.includes(key) ? current.filter((item) => item !== key) : [...current, key]), { nested: true });
  }, [runDisclosure]);

  // 自动化组「查看全部 N 次运行」:与项目组「查看全部」一致,进入该任务的专属列表页
  // (设备详情页的自动化任务作用域模式),不在列表里原地铺开。
  const openAutomationGroup = useCallback((group: RemoteAutomationSessionGroup) => {
    const session = group.items[0]?.session as RemoteSession | undefined;
    if (!session) return;
    // 设备解析与 openSession 同口径:可达优先(canonicalDeviceId),回退物理 id / store 索引。
    const deviceId = session.canonicalDeviceId ?? session.deviceLinkDeviceId ?? remoteSessionStore.getSessionDeviceId(session.id);
    if (!deviceId) {
      setError(t('devices.list.error.taskDeviceNotFound'));
      return;
    }
    // 项目组内的组行(有 workingDir)带上项目维度:baseKey 不含项目 scope,同一任务跨
    // 项目时目标页只该显示本项目的 run(与组行标称的 N 一致)。dialogue 组无目录,不带。
    const workingDir = session.workingDir?.trim();
    guardedPush({
      pathname: '/devices/[deviceId]',
      params: {
        deviceId,
        name: deviceDisplayName(deviceId, session.deviceLinkDeviceName),
        automationGroupKey: group.baseKey,
        automationName: group.title,
        ...(workingDir ? { automationWorkingDir: workingDir } : {}),
        // 快照兜底:目标页 scheduleIndex 尚未加载完成时,先按这批 id 立即显示组内运行,
        // index 就绪后再与组键匹配结果取并集(能捕获新产生的 run)。
        automationSessionIds: JSON.stringify(group.sessionIds),
      },
    });
  }, [guardedPush, t]);

  // 置顶组与项目组一致:点表头收起/展开,共用同一条收起动画。
  const togglePinned = useCallback(() => {
    runDisclosure(() => setPinnedCollapsed((collapsed) => !collapsed));
  }, [runDisclosure]);

  const openProjectSessions = useCallback((project: MobileHomeProjectGroup, search = false) => {
    if (!project.deviceId) return;
    swipeRegistry.closeOpenRow();
    guardedPush({
      pathname: '/devices/[deviceId]',
      // 带上 workingDir + 项目名,让目标页只显示「这个项目」的会话(名副其实地"查看全部 N 条")。
      // 未归类组(workingDir 为空)不传过滤参数,退化为整台设备的会话列表。
      // statusFilter 跟首页当前筛选走,归档/全部入口不能掉回默认 active。
      params: {
        deviceId: project.deviceId,
        name: project.deviceName,
        statusFilter,
        ...(search ? { search: '1' } : {}),
        ...(project.workingDir
          ? { workingDir: project.workingDir, projectName: project.title }
          : {}),
      },
    });
  }, [guardedPush, statusFilter, swipeRegistry]);

  // renderItem 提取为稳定引用:打开「选项」sheet 等与列表数据无关的页面状态变更不再改变
  // renderItem 身份,SectionList 可见行不随之全量重渲染(review P2:每行 Swipeable 动画树
  // 较重)。行内滑动回调全部走「稳定引用 + session 入参」,不为每行现造闭包。
  // 每行输出整体交给 per-item memo 的 HomeListRow(风暴修复第二刀,见其注释):这里只
  // 计算邻接派生位(分割线唯一化 / 置顶尾行 / 折叠位)并以标量 props 传入,保证单行
  // 数据变化只重建该行的包装树。
  const renderHomeRow = useCallback(({ item, index, section }: {
    item: HomeRow;
    index: number;
    section: HomeSection;
  }) => (
    <HomeListRow
      expandedAutomationGroups={expandedAutomationGroups}
      isLastPinnedRow={section.key === 'pinned' && index === section.data.length - 1 && sections.length > 1}
      item={item}
      machineIdentity={isFolderHomeRow(item) ? projectMachineIdentities.get(item.project.key) : undefined}
      nextIsBlock={isBlockHomeRow(section.data[index + 1])}
      onArchive={archiveSession}
      onOpenAutomationGroup={openAutomationGroup}
      onOpenProjectSessions={openProjectSessions}
      onNewProjectTask={openNewSession}
      onOpenSession={openSession}
      onShowOptions={showSessionOptions}
      onToggleAutomationGroup={toggleAutomationGroup}
      onProjectDragEnd={displayedProjectOrder === 'custom' ? endProjectDrag : undefined}
      onProjectDragMove={displayedProjectOrder === 'custom' ? moveProjectDrag : undefined}
      onProjectDragStart={displayedProjectOrder === 'custom' ? beginProjectDrag : undefined}
      onShowAllDialogue={showAllDialogueSessions}
      onToggleProject={toggleProject}
      projectDragging={projectDrag?.key === (item.kind === 'project' ? item.project.key : '')}
      projectHeaderRefs={projectHeaderRefs}
      homeScrollY={homeScrollY}
      viewportHeight={screenHeight}
      onTogglePin={toggleSessionPinned}
      prevIsBlock={isBlockHomeRow(homeRowBefore(sections, section.key, index))}
      projectCollapsed={isFolderHomeRow(item) && collapsedProjectKeys.includes(item.project.key)}
      registry={swipeRegistry}
      showAllDialogue={dialogueShowAll}
      swipe={sessionSwipeControls}
    />
  ), [
    archiveSession,
    collapsedProjectKeys,
    dialogueShowAll,
    beginProjectDrag,
    endProjectDrag,
    moveProjectDrag,
    projectDrag,
    displayedProjectOrder,
    showAllDialogueSessions,
    visibleProjectKeys,
    expandedAutomationGroups,
    openAutomationGroup,
    openProjectSessions,
    openNewSession,
    openSession,
    pinnedCollapsed,
    sections,
    sessionSwipeControls,
    showSessionOptions,
    swipeRegistry,
    toggleAutomationGroup,
    toggleProject,
    toggleSessionPinned,
    homeScrollY,
    screenHeight,
    projectMachineIdentities,
  ]);

  // 底部边到边:列表填满到物理屏底(内容滚到 home indicator 下方),用 inset 兜底而非靠 SafeAreaView 留白带。
  const insets = useSafeAreaInsets();
  // top/left/right 三边不用原生 SafeAreaView 而是手动 padding:原生实现旋转时有概率
  // 漏更新,横屏 insets 残留到竖屏导致整页错位几秒(残留判定与取舍见 screenEdgeInsets.ts)。
  const edgePadding = useScreenEdgePadding({
    insets,
    windowHeight: screenHeight,
    windowWidth: screenWidth,
  });

  // 只服务系统下拉(iOS UIMenu / Android PopupMenu):点选即收起,没有自绘菜单的
  // onClosed 可等,撤权提示直接挂;自绘回退菜单走 DeviceMenuModal 的 onSelect。
  const selectHomeScope = useCallback((item: MobileHomeDeviceFilterItem) => {
    if (item.deviceId && item.state === 'access_revoked') {
      setRevokedTipDeviceId(item.deviceId);
      return;
    }
    viewPrefsTouchedRef.current = true;
    restoredSelectionUnvalidatedRef.current = false;
    setSelectedDeviceId(item.deviceId);
    setRestoredDeviceName(null);
    setDeviceMenuOpen(false);
    void saveHomeViewPreferences({
      selectedDevice: item.deviceId ? { deviceId: item.deviceId, name: item.label } : null,
    });
  }, []);

  const nativeHomeMenus = usesNativePullDownMenu();
  const openRemoteCollection = useCallback((collection: RemoteHomeCollection) => {
    openHomeRemoteCollection(collection, guardedPush);
  }, [guardedPush]);
  const scopeCollections = useMemo(
    () => homeScopeCollections(remoteHomeCollections, TEAMMATE_COLLECTION_ID),
    [remoteHomeCollections],
  );
  const homeScopePullDownActions = useMemo(
    () => buildHomeScopePullDownActions(
      home.deviceFilters,
      t('devices.list.allConversations'),
      scopeCollections.map((collection) => ({
        id: collection.id,
        title: collection.title,
      })),
    ),
    [home.deviceFilters, scopeCollections, t],
  );
  const handleHomeScopeAction = useCallback((id: string) => {
    const parsed = parseHomeScopePullDownAction(id);
    if (parsed.kind === 'collection') {
      const collection = scopeCollections.find((item) => item.id === parsed.collectionId);
      if (!collection) return;
      openRemoteCollection(collection);
      return;
    }
    const item = home.deviceFilters.find((filter) => filter.id === parsed.filterId);
    if (item) selectHomeScope(item);
  }, [home.deviceFilters, openRemoteCollection, scopeCollections, selectHomeScope]);
  const displayMenuState = useMemo<HomeDisplayMenuState>(() => ({
    groupByProject,
    groupDialogue,
    lastActivityFilter,
    projectFilter,
    teammateFilter: effectiveTeammateFilter,
    showCollapsedTeammateAvatars,
    projectOrder: displayedProjectOrder,
    sortBy,
    statusFilter,
    taskInfoFields,
    vendorFilter,
    viewMode,
  }), [showCollapsedTeammateAvatars, displayedProjectOrder, groupByProject, groupDialogue, lastActivityFilter, projectFilter, effectiveTeammateFilter, sortBy, statusFilter, taskInfoFields, vendorFilter, viewMode]);
  // 在看已归档任务时,顶栏「⋯」带提醒点(iOS 系统顶栏 / 自绘按钮两条路径共用这一个判据),
  // 同时把状态写进无障碍名称,读屏用户不用打开菜单也知道列表不是平常的进行中任务。
  const archivedReminder = statusFilter === 'archived';
  const displayA11y = archivedReminder
    ? t('devices.list.a11y.openDisplaySettingsWithStatus', { status: t('devices.list.search.filter.status.archived') })
    : t('devices.list.a11y.openDisplaySettings');
  const homeDisplayPullDownActions = useMemo(
    () => buildHomeDisplayPullDownActions({
      // 与项目候选的 sessionCount 同口径:自动化组行按组内运行数计。
      dialogueCount: projectFilterUniverse.chats.reduce((sum, item) => sum + (item.automationGroup?.sessionCount ?? 1), 0),
      // 候选用设备范围内的完整项目集(不受搜索 / 状态影响);看所有电脑时用设备名区分同名项目。
      projects: projectFilterUniverse.projects.map((project) => ({
        count: project.sessionCount,
        key: project.key,
        subtitle: selectedDeviceId ? undefined : project.deviceName || undefined,
        title: project.title,
      })),
      teammates: teammateOptions,
      state: displayMenuState,
      t,
    }),
    [displayMenuState, teammateOptions, projectFilterUniverse.chats, projectFilterUniverse.projects, selectedDeviceId, t],
  );
  const handleDisplayAction = useCallback((id: string) => {
    const patch = homeDisplayActionPatch(id, displayMenuState);
    if (!patch) return;
    if (patch.showCollapsedTeammateAvatars !== undefined) {
      void setShowCollapsedTeammateAvatars(patch.showCollapsedTeammateAvatars);
    } else applyDisplayView(patch);
  }, [applyDisplayView, displayMenuState, setShowCollapsedTeammateAvatars]);
  // iOS 系统顶栏的菜单项是顶栏选项的一部分,任何变化都会重建顶栏并关掉展开中的菜单。
  // 菜单内容按结构比较、回调走 ref 保持同一引用:后台同步刷新任务列表时,菜单没实质变化
  // 就不重建顶栏;只有用户自己的勾选会更新它。
  const stableDisplayActions = useStableValue(homeDisplayPullDownActions, pullDownActionsEqual);
  const handleDisplayActionRef = useRef(handleDisplayAction);
  handleDisplayActionRef.current = handleDisplayAction;
  const stableDisplayAction = useCallback((id: string) => handleDisplayActionRef.current(id), []);
  const rowDisplay = useMemo<HomeRowDisplay>(
    () => ({ taskInfoFields, viewMode }),
    [taskInfoFields, viewMode],
  );
  const openSelectedRemoteDesktop = useCallback(() => {
    if (!selectedDeviceId) return;
    const device = home.deviceFilters.find((item) => item.deviceId === selectedDeviceId);
    guardedPush({
      pathname: '/devices/desktop/[deviceId]',
      params: { deviceId: selectedDeviceId, deviceName: device?.label ?? selectedDeviceLabel },
    });
  }, [guardedPush, home.deviceFilters, selectedDeviceId, selectedDeviceLabel]);

  const nativeHomeHeader = !embedded && usesNativeStackHeader();
  const homeGeometry = useAdaptiveWindow();
  const keepMenuTopLeft = nativeHomeHeader && homeGeometry.barEdge !== 'none';
  const nativeHeaderHeight = useOptionalHeaderHeight();
  const chromeHeight = nativeHomeHeader
    ? nativeHeaderHeight + (headerHeight ?? 0)
    : (headerHeight ?? edgePadding.paddingTop + HOME_HEADER_MIN_HEIGHT);
  const homeListNode = (
    <HomeRowDisplayContext.Provider value={rowDisplay}>
    <HomeListViewportContext.Provider value={childViewport}>
    <ListDisclosureScope controller={disclosure.controller}>
      <SectionList
        ref={attachHomeList}
        CellRendererComponent={HomeListCell}
        onLayout={(event) => {
          listViewportHeight.current = event.nativeEvent.layout.height;
          restoreListPosition();
        }}
        onContentSizeChange={(_, height) => {
          listContentHeight.current = height;
          restoreListPosition();
        }}
        sections={sections}
        ListHeaderComponent={<>
        <HomeTeammatesSection context={teammatesSectionContext} active={active} refreshKey={teammatesRefreshKey}
          push={guardedPush}
          // Independent of the computer-connection guide: server group chats and cloud companions need no computer.
          visible={indexedSearch.activeFilterCount === 0 && statusFilter !== 'archived'}
          query={searchQuery}
          // Shared group and project blocks draw their own full-width top line.
          showFooter={sharedRows.length === 0 && !isBlockHomeRow(sections[0]?.data[0])}
          runDisclosure={runDisclosure} prepareDisclosure={prepareListDisclosure} />
        {sharedRows.length > 0 ? <DisclosureItem clip style={styles.projectGroup} testID="home.sharedGroup">
          <Pressable
            accessibilityRole="button"
            accessibilityLabel={t('sharedTask.title')}
            accessibilityState={{ expanded: !sharedCollapsed }}
            onPress={() => runDisclosure(() => setSharedCollapsed(value => !value))}
            onPressIn={prepareListDisclosure}
            style={({ pressed }) => [styles.projectRow, pressed && styles.pressed]}
            testID="home.sharedHeader"
          >
            {sharedCollapsed
              ? <ChevronRight color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
              : <ChevronDown color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} />}
            <UsersRound color={colors.textSecondary} size={iconSize.action} strokeWidth={iconStroke.thin} />
            <Text style={styles.projectTitle} numberOfLines={1}>{t('sharedTask.title')}</Text>
          </Pressable>
          {sharedCollapsed ? null : <DisclosureItem exit>{sharedRows.map((row, index) => {
            if (row.item) {
              const content = <HomeSessionRow
                key={row.key}
                indented
                hideDivider={index === sharedRows.length - 1}
                item={row.item}
                sharedRole={row.role}
                expandedAutomationGroups={expandedAutomationGroups}
                onToggleAutomationGroup={toggleAutomationGroup}
                onOpenSession={openSession}
                onOpenAutomationGroup={openAutomationGroup}
                swipe={sessionSwipeControls}
                testID="home.sharedSessionRow"
              />;
              if (row.item.automationGroup || !conversationSearchAllowsLocalWrites(row.item)) return content;
              return <SwipeableSessionRow key={row.key} session={row.item.session as RemoteSession}
                onMarkRead={sessionSwipeControls.onMarkRead} registry={swipeRegistry} onArchive={archiveSession} onShowOptions={showSessionOptions} onTogglePin={toggleSessionPinned}
                testID="home.sharedSessionRow.swipe">{content}</SwipeableSessionRow>;
            }
            return <Pressable
            key={row.key}
            accessibilityRole="button"
            accessibilityLabel={row.task.title + ', ' + t('sharedTask.roleHost')}
            onPress={() => guardedPush({ pathname: '/shared-session', params: { sharedTaskId: row.task.sharedTaskId } })}
            style={({ pressed }) => [styles.sessionListRow, styles.sessionListRowSingleLine, styles.sessionListRowIndented, pressed && styles.pressed]}
            testID="home.sharedOwnerRow"
          >
            <View style={[styles.sessionIconCell, styles.sessionIconCellSingleLine]}>
              <FileText color={colors.textSecondary} size={iconSize.action} strokeWidth={iconStroke.thin} />
            </View>
            <View style={[styles.sharedRoleSlot, styles.sharedRoleSlotSingleLine]} testID={`home.sharedRoleSlot.owned.${row.task.sessionId}`}>
              <Crown
                accessible={false}
                color={colors.warningFg}
                size={iconSize.md}
                strokeWidth={iconStroke.thin}
              />
            </View>
            <View style={[styles.sessionListContent, index === sharedRows.length - 1 && styles.sessionListContentNoDivider]}>
              <View style={styles.sessionTitleRow}>
                <Text style={styles.sessionTitle} numberOfLines={1} ellipsizeMode="tail">{row.task.title}</Text>
              </View>
            </View>
          </Pressable>; })}</DisclosureItem>}
        </DisclosureItem> : null}
        </>}
        style={styles.homeList}
        keyExtractor={(item) => item.key}
        // A grouped row contains its preview children. Twelve such rows can
        // mount dozens of offscreen tasks in one JS turn on Android.
        initialNumToRender={Platform.OS === 'android' && groupByProject ? 4 : HOME_LIST_INITIAL_RENDER_COUNT}
        maxToRenderPerBatch={Platform.OS === 'android' && groupByProject ? 2 : HOME_LIST_RENDER_BATCH_SIZE}
        updateCellsBatchingPeriod={32}
        windowSize={HOME_LIST_WINDOW_SIZE}
        refreshControl={
          <RefreshControl
            progressViewOffset={residentList.enabled ? 0 : chromeHeight}
            refreshing={refreshing}
            onRefresh={refreshHome}
            tintColor={colors.textSecondary}
          />
        }
        scrollEnabled={projectDrag === null}
        stickySectionHeadersEnabled={false}
        contentContainerStyle={[
          styles.listContent,
          {
            paddingBottom: (newSessionInSystemBar || newSessionInHeader ? spacing.sm : LEGACY_HOME_LIST_BOTTOM_RESERVE) + insets.bottom,
            paddingTop: residentList.enabled ? 0 : chromeHeight,
          },
        ]}
        onScroll={onListScroll}
        keyboardShouldPersistTaps="handled"
        keyboardDismissMode="on-drag"
        scrollEventThrottle={16}
        onScrollBeginDrag={() => {
          scrollRestored.current = true;
          // 列表开始滚动即收起已滑开的行(iOS 惯例,避免打开态跟着列表滚)。
          swipeRegistry.closeOpenRow();
          if (!searchQuery.trim()) setSearchOpen(false);
        }}
        testID="devices.list"
        renderSectionHeader={({ section }) => {
          if (section.key !== 'pinned' || !section.title) return null;
          return (
            <Pressable
              accessibilityLabel={t('devices.list.a11y.pinnedConversations', { count: filteredHome.pinned.length })}
              accessibilityRole="button"
              accessibilityState={{ expanded: !pinnedCollapsed }}
              onPress={togglePinned}
              onPressIn={prepareListDisclosure}
              style={({ pressed }) => [styles.projectRow, pressed && styles.pressed]}
              testID="home.pinnedHeader"
            >
              {pinnedCollapsed ? (
                <ChevronRight color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
              ) : (
                <ChevronDown color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
              )}
              <Pin color={colors.textSecondary} size={iconSize.action} strokeWidth={iconStroke.thin} />
              <Text style={styles.projectTitle} numberOfLines={1}>{section.title}</Text>
              <Text style={styles.projectCount} numberOfLines={1}>{filteredHome.pinned.length}</Text>
            </Pressable>
          );
        }}
        renderSectionFooter={({ section }) => section.key === 'pinned' && sections.length > 1
          // 置顶区底部一根全宽线,把置顶对话与下面的其他对话分开(仅当下方还有其他分区时才画;
          // 下方首行是块时不画 —— 块自己的全宽顶线就是这根分割线)。
          && !isBlockHomeRow(sections[1]?.data[0]) ? (
            <View style={styles.pinnedFooter} testID="home.pinnedFooter" />
          ) : null}
        ListEmptyComponent={
          sharedRows.length > 0 ? null : initialHomeLoading || taskSuggestionsPending ? (
            <HomeInitialLoadingState
              style={{
                marginTop: spacing.xxl,
                minHeight: windowLayout.emptyMinHeight,
                padding: windowLayout.emptyPadding,
              }}
            />
          ) : filteredHome.pinned.length > 0 ? (
            // 仅剩置顶且被收起时 item 数为 0,但用户并非"无对话",不显示空状态插画。
            null
          ) : showRemoteGuide && home.emptyNoDevice ? (
            // 无可控制电脑是「首次使用 / 产品模式说明」级空态:按 reason 渲染远程访问引导
            // (首跑三步 / 离线设备卡 / 精确开关 / 重试访问 + 云端 Cindy 预告),而非一句话空态。
            <RemoteAccessGuide
              context={home.emptyNoDevice}
              copy={emptyStateCopy}
              onRecheck={() => void loadHome({ visible: true })}
              onRetryAccess={retryRevokedGuideDevices}
              rechecking={refreshing}
              retrying={retryingDeviceIds.size > 0}
              style={{
                marginTop: spacing.xxl,
                minHeight: windowLayout.emptyMinHeight,
                padding: windowLayout.emptyPadding,
              }}
              testID="home.remoteAccessGuide"
              title={emptyStateTitle}
            />
          ) : contentFilterCount > 0 && !initialHomeError ? (
            // 显示菜单里的筛选把任务全部筛掉了:说清是筛选导致,而不是「还没有任务」。
            <MainWindowEmptyState
              centered
              copy={t('devices.list.menu.filterEmptyCopy')}
              style={{
                marginTop: spacing.xxl,
                minHeight: windowLayout.emptyMinHeight,
                padding: windowLayout.emptyPadding,
              }}
              testID="home.filterEmpty"
              title={t('devices.presentation.sessionList.context.noResults')}
            />
          ) : taskSuggestionsMode === 'empty' ? (
            <RemoteTaskSuggestions mode="empty" onNewSession={() => openSuggestedSession()}
              onSelect={openSuggestedSession} />
          ) : (
            <MainWindowEmptyState
              centered
              copy={emptyStateCopy}
              style={{
                marginTop: spacing.xxl,
                minHeight: windowLayout.emptyMinHeight,
                padding: windowLayout.emptyPadding,
              }}
              testID={initialHomeError ? 'home.syncError' : 'home.empty'}
              title={emptyStateTitle}
            />
          )
        }
        ListFooterComponent={taskSuggestionsMode === 'footer' ? (
          <RemoteTaskSuggestions mode="footer" onNewSession={() => openSuggestedSession()}
            onSelect={openSuggestedSession} />
        ) : null}
        renderItem={renderHomeRow}
      />
    </ListDisclosureScope>
    </HomeListViewportContext.Provider>
    </HomeRowDisplayContext.Provider>
  );
  const homeListOverlays = (<>


      {projectDrag ? (
        <ProjectDragOverlay
          count={projectDrag.count}
          height={projectDrag.height}
          insertY={(() => {
            const line = projectDragInsertY(projectDrag);
            return line === null ? null : line - projectDrag.rootY;
          })()}
          title={projectDrag.title}
          width={projectDrag.width}
          x={projectDrag.x}
          y={projectDragY}
        />
      ) : null}

      {newSessionInSystemBar || newSessionInHeader || !newSessionEntryVisible ? null : (
        // iOS: the circle stretches into the new task's composer pill (origin → morph handoff).
        <HomeNewTaskButton bottomInset={insets.bottom} disabled={newSessionDisabled} morph
          onPress={(origin) => openNewSession(undefined, undefined, undefined, origin)} />
      )}

  </>);
  return (
    <View
      ref={homeRootRef}
      style={[styles.safeArea, { paddingLeft: embedded ? 0 : edgePadding.paddingLeft, paddingRight: embedded ? 0 : edgePadding.paddingRight }]}
      testID="devices.screen"
    >
      {nativeHomeHeader && active ? (
        <HomeNativeStackHeader
          keepMenuTopLeft={keepMenuTopLeft}
          syncing={quietSyncing}
          displayA11y={displayA11y}
          displayActions={stableDisplayActions}
          displayBadge={archivedReminder}
          menuA11y={t('devices.list.a11y.openMenu')}
          onDisplayAction={stableDisplayAction}
          onOpenDeviceMenu={openDeviceMenu}
          onOpenMenu={openChromeMenu}
          onOpenRemoteDesktop={selectedDeviceId ? openSelectedRemoteDesktop : undefined}
          remoteDesktopA11y={t('remoteDesktop.title')}
          onSelectScope={handleHomeScopeAction}
          scopeActions={homeScopePullDownActions}
          showRemoteGuide={showRemoteGuide}
          title={selectedDeviceLabel}
          titleA11y={t('devices.list.a11y.selectScope')}
        />
      ) : null}
      <View
        onLayout={(e) => setHeaderHeight(e.nativeEvent.layout.height)}
        style={[styles.homeChrome, nativeHomeHeader && { top: nativeHeaderHeight }, headerFrosted && !nativeHomeHeader && styles.homeChromeFrosted]}
      >
        <HomeChromeFrost disabled={nativeHomeHeader} visible={headerFrosted}>
        <View style={{ paddingTop: nativeHomeHeader ? 0 : embedded ? spacing.lg : edgePadding.paddingTop }}>
        {nativeHomeHeader ? null : (
        <View onLayout={(e) => setHomeHeaderWidth(e.nativeEvent.layout.width)} style={styles.homeHeader}>
        <View style={styles.headerLeadingActions}>
        {/* 临时任务列表抽屉同样放系统菜单:关闭走遮罩、左滑和系统返回。 */}
        <HomeHeaderGlassButton
          accessibilityLabel={t('devices.list.a11y.openMenu')}
          onPress={openChromeMenu}
          testID="home.chromeMenu"
        >
          <Menu color={colors.textPrimary} size={iconSize.action} strokeWidth={iconStroke.regular} />
        </HomeHeaderGlassButton>
        </View>
        {showRemoteGuide ? (
          // 引导态没有可筛选的范围:正中只留品牌标题。
          <View style={styles.headerTitleWrap} testID="devices.title">
            <Text style={styles.headerTitle} numberOfLines={1}>Cindy</Text>
          </View>
        ) : (
          <View
            onLayout={(e) => {
              const { x, width } = e.nativeEvent.layout;
              setHomeTitleSlotFrame(prev => prev && prev.x === x && prev.width === width ? prev : { x, width });
            }}
            style={styles.headerTitleSlot}
          >
          <NativePullDownMenu
            actions={homeScopePullDownActions}
            onAction={handleHomeScopeAction}
          >
            <Pressable
              accessibilityLabel={t('devices.list.a11y.selectScope')}
              accessibilityRole="button"
              onPress={nativeHomeMenus ? () => undefined : openDeviceMenu}
              onPressIn={nativeHomeMenus ? undefined : openDeviceMenu}
              style={({ pressed }) => [styles.headerTitleWrap, homeTitle.shift != null && styles.headerTitleWrapTrailing, pressed && styles.pressed]}
              testID="devices.title"
            >
              <View
                onLayout={homeTitle.onContentLayout}
                style={[styles.headerTitleCluster, homeTitle.shift != null && { transform: [{ translateX: homeTitle.shift }] }]}
              >
                <Text style={styles.headerTitle} numberOfLines={1}>{selectedDeviceLabel}</Text>
                <ChevronDown color={colors.textSecondary} size={iconSize.xs} strokeWidth={iconStroke.medium} />
                <QuietSyncIndicator active={quietSyncing} />
              </View>
            </Pressable>
          </NativePullDownMenu>
          </View>
        )}
        {showRemoteGuide ? (
          <View style={styles.headerActions} />
        ) : (
          <View style={[styles.headerActions, (showHeaderRemoteDesktop || headerNewSession) && styles.headerActionsWide]}>
            {headerNewSession ? (
              <HomeHeaderGlassButton accessibilityLabel={t('devices.list.a11y.newRemoteConversation')} disabled={newSessionDisabled}
                onPress={() => openNewSession()} testID="home.headerNewSessionButton">
                <SquarePen color={colors.textPrimary} size={iconSize.action} strokeWidth={iconStroke.regular} />
              </HomeHeaderGlassButton>
            ) : null}
            {showHeaderRemoteDesktop ? (
              <HomeHeaderGlassButton accessibilityLabel={t('remoteDesktop.title')} onPress={openSelectedRemoteDesktop} testID="home.remoteDesktopButton">
                <Monitor color={colors.textPrimary} size={iconSize.action} strokeWidth={iconStroke.regular} />
              </HomeHeaderGlassButton>
            ) : null}
            {/* 侧栏本地菜单完整保留分组和多层筛选;系统顶栏继续使用自己的原生菜单。 */}
            <HomeDisplayMenu actions={homeDisplayPullDownActions} onAction={handleDisplayAction} accessibilityLabel={displayA11y}>
              <View>
                <Ellipsis color={colors.textPrimary} size={iconSize.action} strokeWidth={iconStroke.regular} />
                {/* 在看已归档任务时标一个点,提醒列表不是平常的进行中任务。 */}
                {archivedReminder ? <FilterReminderDot offset={styles.displayFilterDotOffset} testID="home.displayFilterDot" /> : null}
              </View>
            </HomeDisplayMenu>
          </View>
        )}
        </View>
        )}

        {searchOpen || !!searchQuery.trim() ? (
          <HomeSearchBar
            autoFocus={searchOpen && !searchQuery}
            filterA11y={searchFilterA11y}
            filterActions={searchFilterMenu.filterActions}
            filterActive={indexedSearch.activeFilterCount > 0}
            onChangeQuery={indexedSearch.setQuery}
            onFilterAction={searchFilterMenu.onFilterAction}
            onOpenFilter={() => setSearchFilterOpen(true)}
            query={searchQuery}
          />
        ) : null}

        </View>
        </HomeChromeFrost>
        {showConnectionNotice ? (
        <ConnectionNoticeOverlay>
        <View
          style={[styles.connectionRow, (connectionError || activeConnectionIssue) && styles.connectionRowError]}
          testID="connection.banner"
        >
          <StatusDot tone={connectionTone} pulsing={!networkUnavailable && !activeConnectionIssue && status === 'connecting'} />
          <Text ellipsizeMode="tail" numberOfLines={1} style={styles.connectionText} testID="connection.title">
            {connectionCopy ? `${connectionTitle} · ${connectionCopy}` : connectionTitle}
          </Text>
          {showHomeSyncAction ? <Pressable
            accessibilityLabel={refreshing ? t('devices.list.a11y.syncing') : t('devices.list.a11y.sync')}
            accessibilityRole="button"
            accessibilityState={{ busy: refreshing || undefined, disabled: refreshing }}
            disabled={refreshing}
            // 视觉 28pt,hitSlop 把命中区补到 44pt(§5 触控目标)。
            hitSlop={(navigationChrome.target - CONNECTION_ICON_BUTTON_SIZE) / 2}
            onPress={refreshHome}
            style={({ pressed }) => [
              styles.connectionIconButton,
              pressed && styles.pressed,
              refreshing && styles.disabled,
            ]}
            testID="connection.syncButton"
          >
            <RefreshCw color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
          </Pressable> : showHomeRecoveryProgress ? (
            <ConnectionRecoveryProgress />
          ) : null}
        </View>
        </ConnectionNoticeOverlay>
        ) : null}
      </View>

      {residentList.enabled ? (
        <ResidentHomeList focused={screenFocused && active} top={chromeHeight}
          left={embedded ? 0 : edgePadding.paddingLeft} right={embedded ? 0 : edgePadding.paddingRight}>
          <ActiveHomeSession.Provider value={activeHomeSession}>
              <View pointerEvents="box-none" style={{ flex: 1, paddingLeft: embedded ? 0 : edgePadding.paddingLeft, paddingRight: embedded ? 0 : edgePadding.paddingRight }}>
                {homeListNode}
              </View>
              <View pointerEvents="box-none" style={[StyleSheet.absoluteFill, { top: -chromeHeight }]}>
                {homeListOverlays}
              </View>
          </ActiveHomeSession.Provider>
        </ResidentHomeList>
      ) : <>{homeListNode}{homeListOverlays}</>}

      <MountOnFirstOpen open={revokedTipDeviceName != null}>{() => <RevokedAccessTip
        deviceName={revokedTipDeviceName}
        retrying={revokedTipDeviceId !== null && retryingDeviceIds.has(revokedTipDeviceId)}
        onClose={() => setRevokedTipDeviceId(null)}
        onRetry={() => {
          if (revokedTipDeviceId) void retryRevokedDevice(revokedTipDeviceId);
        }}
      />}</MountOnFirstOpen>
      <MountOnFirstOpen open={deviceMenuOpen}>{() => <DeviceMenuModal
        collections={scopeCollections}
        filters={home.deviceFilters}
        onClose={() => setDeviceMenuOpen(false)}
        onClosed={handleDeviceMenuClosed}
        onSelectCollection={(collection) => {
          setDeviceMenuOpen(false);
          openRemoteCollection(collection);
        }}
        onSelect={(item) => {
          if (item.deviceId && item.state === 'access_revoked') {
            // 撤销授权提示同样是兄弟 Modal,必须等菜单卸载后再挂(见 pendingMenuActionRef 注释)。
            const deviceId = item.deviceId;
            pendingMenuActionRef.current = () => setRevokedTipDeviceId(deviceId);
            setDeviceMenuOpen(false);
            return;
          }
          viewPrefsTouchedRef.current = true;
          restoredSelectionUnvalidatedRef.current = false;
          setSelectedDeviceId(item.deviceId);
          setRestoredDeviceName(null);
          setDeviceMenuOpen(false);
          void saveHomeViewPreferences({
            selectedDevice: item.deviceId ? { deviceId: item.deviceId, name: item.label } : null,
          });
        }}
        topOffset={chromeHeight}
        visible={deviceMenuOpen}
      />}</MountOnFirstOpen>
      <MountOnFirstOpen open={chromeMenuOpen}>{() => <HomeChromeDrawer
        loggingOut={loggingOut}
        onClose={() => {
          pendingMenuActionRef.current = null;
          setChromeMenuOpen(false);
        }}
        onClosed={handleChromeMenuClosed}
        onOpenSearch={() => {
          // 搜索框 autoFocus 要等菜单窗口完全卸载(onClosed)后再挂载:Android 的
          // Dialog 还在退场时底层 Activity 没有窗口焦点,首次聚焦和软键盘请求会丢。
          pendingMenuActionRef.current = () => setSearchOpen(true);
          setChromeMenuOpen(false);
        }}
        onOpenAccounts={() => {
          pendingMenuActionRef.current = () => setAccountSwitcherOpen(true);
          setChromeMenuOpen(false);
        }}
        onOpenPlugins={() => {
          pendingMenuActionRef.current = null;
          setChromeMenuOpen(false);
          guardedPush('/plugins');
        }}
        onOpenDevices={() => {
          pendingMenuActionRef.current = null;
          setChromeMenuOpen(false);
          guardedPush('/devices/manage');
        }}
        onOpenSettings={() => {
          // 页面转场与抽屉退场同步开始;搜索和账号浮层仍等待 onClosed。
          pendingMenuActionRef.current = null;
          setChromeMenuOpen(false);
          guardedPush('/settings');
        }}
        // 抽屉内部先确认(confirmLogout)再调 onLogout,这里不重复确认。
        hasRunningTasks={runningSessionIds.size > 0}
        onLogout={() => void logout()}
        open={chromeMenuOpen}
        user={user}
      />}</MountOnFirstOpen>
      <MountOnFirstOpen open={accountSwitcherOpen}>{() => <AccountSwitcherSheet
        hasRunningTasks={runningSessionIds.size > 0}
        onAddAccount={() => {
          pendingAccountSwitcherActionRef.current = () => {
            void auth.beginAddAccount();
            guardedPush('/add-account');
          };
          setAccountSwitcherOpen(false);
        }}
        onClose={() => setAccountSwitcherOpen(false)}
        onClosed={() => {
          const action = pendingAccountSwitcherActionRef.current;
          pendingAccountSwitcherActionRef.current = null;
          action?.();
        }}
        visible={accountSwitcherOpen}
      />}</MountOnFirstOpen>
      <MountOnFirstOpen open={searchFilterOpen}>{() => <ConversationSearchFilterSheet
        activeCount={indexedSearch.activeFilterCount}
        agentKind={indexedSearch.agentFilter}
        lastActivity={indexedSearch.lastActivityFilter}
        lockedProjects={false}
        onAgentKindChange={indexedSearch.setAgentFilter}
        onClose={() => setSearchFilterOpen(false)}
        onLastActivityChange={indexedSearch.setLastActivityFilter}
        onProjectsChange={indexedSearch.setProjectSelection}
        onReset={indexedSearch.resetFilters}
        onSortChange={indexedSearch.setSortBy}
        onStatusChange={indexedSearch.setStatusFilter}
        projectSelection={indexedSearch.projectSelection}
        projects={searchProjects}
        sortBy={indexedSearch.sortBy}
        status={indexedSearch.statusFilter}
        topOffset={chromeHeight}
        visible={searchFilterOpen}
      />}</MountOnFirstOpen>
      <MountOnFirstOpen open={actionSheetSession !== null}>{() => <SessionOptionsPresenter
        session={actionSheetSession}
        onAction={handleSessionSheetAction}
        onClose={() => setActionSheetSession(null)}
        onClosed={handleSessionSheetClosed}
        pinnedAt={actionSheetSession?.pinnedAt}
        status={actionSheetSession?.status}
        visible={actionSheetSession !== null}
      />}</MountOnFirstOpen>
      <MountOnFirstOpen open={renameSessionTarget !== null}>{() => <RenameSessionModal
        draft={renameSessionDraft}
        onCancel={closeRenameSession}
        onChangeDraft={setRenameSessionDraft}
        onConfirm={confirmRenameSession}
        // 乐观提交:确认即关弹窗,不存在挂起中的保存态。
        saving={false}
        visible={renameSessionTarget !== null}
      />}</MountOnFirstOpen>
    </View>
  );
}

function HomeInitialLoadingState({ style }: { style?: StyleProp<ViewStyle> }) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  return (
    <View style={[styles.initialLoadingState, style]} testID="home.loading">
      <ActivityIndicator color={colors.textSecondary} size="small" />
      <Text style={styles.initialLoadingText}>{t('devices.list.loading')}</Text>
    </View>
  );
}

function DeviceMenuModal({
  collections,
  filters,
  onClose,
  onClosed,
  onSelect,
  onSelectCollection,
  topOffset,
  visible,
}: {
  collections: readonly RemoteHomeCollection[];
  filters: readonly MobileHomeDeviceFilterItem[];
  onClose(): void;
  /** 淡出动画完成、Modal 真正卸载后触发;父级用它把「打开第二个 Modal」延后到菜单卸载之后。 */
  onClosed?(): void;
  onSelect(item: MobileHomeDeviceFilterItem): void;
  onSelectCollection(item: RemoteHomeCollection): void;
  topOffset: number;
  visible: boolean;
}) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  const { height: screenHeight } = useWindowDimensions();
  const insets = useSafeAreaInsets();
  // 范围菜单只列设备;设置入口已挪到左上角 / 右上角。
  const scopeScrollMaxHeight = Math.max(160, screenHeight - topOffset - insets.bottom - 24);
  // §14.4 轻浮层:fast 入场 / instant 退场纯透明度过渡(减弱动态效果直接显示),关闭淡出后再卸载 Modal。
  const menuFadeTiming = useHomeMenuFadeTiming();
  // mounted/progress/进场时机(onShow)/onClosed 延迟触发(等 Modal 真正卸载的 commit
  // 完成,避免 iOS present-during-dismiss 吞掉第二个弹窗)统一走 useModalFadeLifecycle。
  const { mounted, progress, onShowStartIn } = useModalFadeLifecycle(visible, {
    ...menuFadeTiming,
    onClosed,
  });
  const allFilter = filters.find((item) => item.deviceId === null) ?? null;
  // 离线电脑保留缓存入口;关远控和撤权不由缓存恢复访问权限。
  // 自绘回退与系统下拉(buildHomeScopePullDownActions)同一组条目与勾选:全部 → 集合 → 设备;
  // 不画在线点 / 同步脉冲 / 失败圈,连接状态交给顶栏同步指示与连接条。
  const deviceFilters = filters.filter((item) => item.deviceId !== null && canBrowseMobileHomeDevice(item));
  return (
    <HomeMenuScrim
      backdropTestID="home.deviceMenu.backdrop"
      onClose={onClose}
      onShow={onShowStartIn}
      progress={progress}
      topOffset={topOffset}
      visible={mounted}
    >
        <HomeGlassMenuPanel style={styles.deviceMenuPanelCenter} testID="home.deviceMenu">
          <ScrollView
            style={[styles.deviceMenuScroll, { maxHeight: scopeScrollMaxHeight }]}
            showsVerticalScrollIndicator
          >
            {allFilter ? (
              <DeviceMenuItem
                label={t('devices.list.allConversations')}
                onPress={() => onSelect(allFilter)}
                selected={allFilter.selected}
                testID="home.deviceChip.all"
              />
            ) : null}
            {collections.map((collection) => (
              <DeviceMenuItem
                icon={collection.iconName === 'users'
                  ? <UsersRound color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
                  : undefined}
                key={`collection:${collection.id}`}
                label={collection.title}
                onPress={() => onSelectCollection(collection)}
                selected={false}
                testID={`home.remoteCollection.${collection.id}`}
              />
            ))}
            {deviceFilters.map((item) => (
              <DeviceMenuItem
                dimmed={!canBrowseMobileHomeDevice(item)}
                key={item.id}
                label={item.label}
                onPress={() => onSelect(item)}
                selected={item.selected}
                testID={item.deviceId ? `home.deviceChip.${sanitizeDeviceChipTestId(item.deviceId)}` : undefined}
              />
            ))}
          </ScrollView>
        </HomeGlassMenuPanel>
    </HomeMenuScrim>
  );
}

function DeviceMenuItem({
  checked = false,
  dimmed = false,
  icon,
  label,
  onPress,
  selected,
  testID,
}: {
  checked?: boolean;
  dimmed?: boolean;
  icon?: ReactNode;
  label: string;
  onPress(): void;
  selected: boolean;
  testID?: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const rowDisabled = dimmed;
  return (
    <Pressable
      accessibilityLabel={label}
      accessibilityRole="button"
      accessibilityState={{ checked: checked || undefined, disabled: rowDisabled, selected: selected || undefined }}
      disabled={rowDisabled}
      onPress={() => {
        if (rowDisabled) return;
        onPress();
      }}
      style={({ pressed }) => [
        styles.deviceMenuItem,
        pressed && styles.pressed,
        dimmed && styles.disabled,
      ]}
      testID={testID}
    >
      {/* 左侧固定对位列:选中/勾选打 ✓,设置行放图标,未选中留空槽保证文字列对齐。 */}
      <View style={styles.deviceMenuCheckSlot}>
        {icon ?? (selected || checked ? (
          <Check color={colors.textPrimary} size={iconSize.md} strokeWidth={iconStroke.medium} />
        ) : null)}
      </View>
      <Text numberOfLines={1} style={styles.deviceMenuItemText}>{label}</Text>
    </Pressable>
  );
}

function RevokedAccessTip({
  deviceName,
  onClose,
  onRetry,
  retrying,
}: {
  deviceName: string | null;
  onClose(): void;
  onRetry(): void;
  retrying: boolean;
}) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  return (
    // 说明型提示:只有右上角 × 与「重试访问」;按 DESIGN.md 关闭规则点背景不关闭,
    // 只能用 × 或系统返回。重试在父级持有状态,关闭提示不会中断进行中的重试。
    <Modal animationType="fade" transparent visible={deviceName != null} onRequestClose={onClose}>
      <View style={styles.revokedTipBackdrop} testID="home.revokedTip.backdrop">
        <View style={styles.revokedTipCard}>
          <View style={styles.revokedTipHeader}>
            <View style={styles.revokedTipIcon}>
              <Lock color={colors.textPrimary} size={iconSize.lg} strokeWidth={iconStroke.regular} />
            </View>
            <Pressable
              accessibilityLabel={t('devices.list.a11y.close')}
              accessibilityRole="button"
              hitSlop={8}
              onPress={onClose}
              style={({ pressed }) => [styles.revokedTipClose, pressed && styles.pressed]}
            >
              <X color={colors.textSecondary} size={iconSize.lg} strokeWidth={iconStroke.regular} />
            </Pressable>
          </View>
          <Text style={styles.revokedTipTitle}>{t('devices.list.revoked.title')}</Text>
          <Text style={styles.revokedTipBody}>
            {t('devices.list.revoked.body', { deviceName: deviceName ?? t('devices.list.thisComputer') })}
          </Text>
          <MainWindowActionButton
            action={{
              busy: retrying,
              label: t('devices.list.revoked.retry'),
              onPress: onRetry,
              testID: 'home.revokedTip.retry',
              tone: 'primary',
            }}
            style={styles.revokedTipRetry}
          />
        </View>
      </View>
    </Modal>
  );
}

function sanitizeDeviceChipTestId(value: string): string {
  return value.replace(/[^A-Za-z0-9_-]/g, '_');
}

function projectDragInsertY(drag: ProjectDragSession): number | null {
  const sourceIndex = drag.layouts.findIndex((item) => item.key === drag.key);
  if (sourceIndex < 0 || drag.hoverIndex === sourceIndex) return null;
  const target = drag.layouts[drag.hoverIndex];
  if (!target) return null;
  return drag.hoverIndex > sourceIndex ? target.y + target.height : target.y;
}

function ProjectDragOverlay({
  count,
  height,
  insertY,
  title,
  width,
  x,
  y,
}: {
  count: number;
  height: number;
  insertY: number | null;
  title: string;
  width: number;
  x: number;
  y: SharedValue<number>;
}) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const ghostStyle = useAnimatedStyle(() => ({
    height,
    left: x,
    top: y.value,
    width,
  }));
  return (
    <View pointerEvents="none" style={StyleSheet.absoluteFill} testID="home.projectDragOverlay">
      {insertY === null ? null : <View style={[styles.projectDragInsertLine, { top: insertY }]} />}
      <Reanimated.View style={[styles.projectDragGhost, ghostStyle]}>
        <Folder color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.thin} />
        <Text numberOfLines={1} style={styles.projectTitle}>{title}</Text>
        <Text numberOfLines={1} style={styles.projectCount}>{count}</Text>
      </Reanimated.View>
    </View>
  );
}

function HomeProjectWindowAnchorTracker({
  childOffsets,
  deferOffscreen = false,
  onAnchorChange,
  projectHeaderHeight,
  projectLayoutRevision,
  projectRef,
  scrollY,
  viewportHeight,
}: {
  childOffsets: readonly number[];
  deferOffscreen?: boolean;
  onAnchorChange(anchor: number): void;
  projectHeaderHeight: SharedValue<number>;
  projectLayoutRevision: SharedValue<number>;
  projectRef: AnimatedRef<View>;
  scrollY: SharedValue<number>;
  viewportHeight: number;
}) {
  useAnimatedReaction(
    () => {
      // Both layout and scrolling invalidate the measurement. Read pageY on
      // the UI thread, in screen coordinates; never combine an asynchronous
      // measureInWindow result with a newer scroll offset.
      const revision = projectLayoutRevision.value;
      const offset = scrollY.value;
      if (revision === 0 || !Number.isFinite(offset)) return null;
      const layout = measure(projectRef);
      if (!layout || !Number.isFinite(layout.pageY)) return null;
      return resolveHomeProjectChildAnchor({
        childOffsets,
        preloadDistance: deferOffscreen ? viewportHeight : 0,
        projectHeaderHeight: projectHeaderHeight.value,
        projectTop: layout.pageY,
        shift: PROJECT_CHILD_WINDOW_SHIFT,
        viewportHeight,
        viewportTop: 0,
      });
    },
    (next, previous) => {
      // Project blocks retain their window until the outer list recycles them.
      // Nested groups instead release rows beyond the preload band, avoiding
      // one full native window per expanded group. Failed measurement retains
      // either window; it is not proof that the group has left the screen.
      if (next === null || (next < 0 && !deferOffscreen) || next === previous) return;
      runOnJS(onAnchorChange)(next);
    },
    [childOffsets, deferOffscreen, onAnchorChange, projectHeaderHeight, projectLayoutRevision, projectRef, scrollY, viewportHeight],
  );
  return null;
}

function ProjectRow({
  collapsed,
  dragging = false,
  expandedAutomationGroups,
  headerRefs,
  kind = 'project',
  machineIdentity,
  onDragEnd,
  onDragMove,
  onDragStart,
  onOpenAutomationGroup,
  onOpenProject,
  onNewTask,
  onSearchProject,
  onOpenSession,
  onToggle,
  onToggleAutomationGroup,
  project,
  homeScrollY,
  viewportHeight,
  showAll = false,
  suppressTopBorder = false,
  swipe,
}: {
  collapsed: boolean;
  dragging?: boolean;
  expandedAutomationGroups: readonly string[];
  headerRefs?: MutableRefObject<Map<string, View>>;
  kind?: 'project' | 'dialogue' | 'cindy-make';
  machineIdentity?: HomeProjectMachineIdentity;
  onDragEnd?: () => void;
  onDragMove?: (absoluteY: number) => void;
  onDragStart?: (input: { absoluteY: number; count: number; key: string; title: string }) => void;
  onOpenAutomationGroup(group: RemoteAutomationSessionGroup): void;
  onOpenProject(): void;
  onNewTask(): void;
  onSearchProject(): void;
  onOpenSession(item: RemoteSessionListItem): void;
  onToggle(): void;
  onToggleAutomationGroup(key: string): void;
  project: MobileHomeProjectGroup;
  homeScrollY?: SharedValue<number>;
  viewportHeight: number;
  /** 对话组「查看全部」在原地展开,不跳设备详情。 */
  showAll?: boolean;
  /** 前一行也是块(项目组 / 自动化组)时不画顶线:前块底线已是这根分割线。 */
  suppressTopBorder?: boolean;
  /** 项目标题与子任务共用同一滑动互斥注册表。 */
  swipe?: SessionSwipeControls;
}) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  // 折叠豁免要命令式读会话运行态,而派生链稳定化后本组件不再逐 emit 重渲染(cell 经
  // PureComponent bail)——以低频首页状态版本兜底感知运行态变化,与 AutomationGroup-
  // Children 同款(否则折叠线以下转入 running 的会话不会被豁免展开,review P1)。
  const homeStatusVersion = useRemoteHomeStatusVersion();
  // 与桌面侧栏项目组同一套折叠策略:前 N 条之外豁免最近 24h 活动 / 需关注 / 运行中的条目
  // (豁免语义见共享层 getRemoteSessionPreviewCollapse 注释)。
  // 自动化折叠后 sessions 是"行"(组行代表多条会话):按钮显隐看隐藏行数(hiddenCount),
  // 文案仍用 sessionCount(总会话数),两者语义不同不能混用。
  const { visibleItems: visibleSessions, hiddenCount: hiddenRowCount } = getRemoteSessionPreviewCollapse(
    project.sessions,
    {
      limit: showAll ? project.sessions.length : PROJECT_PREVIEW_LIMIT,
      isSessionRunning: (sessionId) => remoteSessionStore.isSessionRunning(sessionId),
    },
  );
  // 与桌面侧栏收起项目同一规则:仅收起时汇总组内全部任务——任一在跑则组头图标橙色呼吸,
  // 右槽只放一颗点(出错红 > 等你回复蓝 > 完成未读绿);展开后由子行各自显示,组头不重复。
  // 运行态命令式读取,依赖 homeStatusVersion 兜底感知变化(理由同上方折叠豁免)。
  const collapsedStatus = useMemo(
    () => (collapsed
      ? resolveMobileCollapsedGroupStatus(project.sessions, (sessionId) => remoteSessionStore.isSessionRunning(sessionId))
      : null),
    [collapsed, homeStatusVersion, project.sessions],
  );
  const groupIconColor = collapsedStatus?.running ? colors.statusAccent : colors.textSecondary;
  // 组头按钮是单个无障碍元素(子节点标签不会被读出),汇总状态挂在按钮自身的 value 上。
  const collapsedStatusA11y = [
    collapsedStatus?.running ? t('devices.list.a11y.running') : null,
    collapsedStatus?.dot === 'error'
      ? t('devices.list.a11y.taskError')
      : collapsedStatus?.dot === 'awaiting'
        ? t('devices.list.a11y.awaitingYou')
        : collapsedStatus?.dot === 'done'
          ? t('devices.list.a11y.doneUnread')
          : null,
  ].filter(Boolean).join(', ');
  const projectHeaderHeight = useSharedValue(HOME_PROJECT_HEADER_HEIGHT);
  const textMode = useHomeRowDisplay().viewMode === 'text';
  const projectRef = useAnimatedRef<View>();
  const prepareDisclosure = useDisclosurePrepare();
  const [windowAnchor, setWindowAnchor] = useState(0);
  const projectLayoutRevision = useSharedValue(0);
  const estimatedChildHeights = useMemo(() => {
    const expandedKeys = new Set(expandedAutomationGroups);
    return visibleSessions.map((item) => estimateHomeProjectChildHeight(item, expandedKeys, textMode));
  }, [expandedAutomationGroups, homeStatusVersion, textMode, visibleSessions]);
  const estimatedChildOffsets = useMemo(
    () => buildHomeProjectChildOffsets(estimatedChildHeights),
    [estimatedChildHeights],
  );
  // Render a bounded child window immediately, including before native layout
  // is ready. A full-height placeholder here becomes visible when scrolling
  // into a project before its measurement reaches JS. The outer SectionList
  // still bounds mounted groups, and ordinary five-row previews are unchanged.
  const windowingEnabled = shouldWindowHomeProjectChildren({
    collapsed,
    itemCount: visibleSessions.length,
    scrollTrackingAvailable: !!homeScrollY,
    threshold: PROJECT_CHILD_WINDOW_THRESHOLD,
  });
  const scrollY = homeScrollY;
  const childWindow = windowingEnabled
    ? resolveHomeProjectChildWindow({
        anchor: windowAnchor,
        childOffsets: estimatedChildOffsets,
        overscan: PROJECT_CHILD_WINDOW_OVERSCAN,
        windowSize: PROJECT_CHILD_WINDOW_SIZE,
      })
    : {
        end: visibleSessions.length,
        leadingSpacerHeight: 0,
        start: 0,
        trailingSpacerHeight: 0,
      };
  const windowStart = childWindow.start;
  const windowEnd = childWindow.end;
  const renderedSessions = windowingEnabled ? visibleSessions.slice(windowStart, windowEnd) : visibleSessions;
  const leadingSpacerHeight = childWindow.leadingSpacerHeight;
  const trailingSpacerHeight = childWindow.trailingSpacerHeight;
  const groupTestID = kind === 'dialogue' ? 'home.dialogueGroup' : 'home.projectGroup';
  const rowTestID = kind === 'dialogue' ? 'home.dialogueRow' : 'home.projectRow';
  const childTestID = kind === 'dialogue' ? 'home.chatRow' : 'home.projectSessionRow';
  const displayTitle = machineIdentity && !machineIdentity.hideLabel
    ? `${project.title} (${machineIdentity.displayLabel})`
    : project.title;
  const reorderable = kind === 'project' && !!onDragStart && !!onDragMove && !!onDragEnd;
  const actionable = kind === 'project' && !!project.deviceId && !!project.workingDir && !!swipe;
  const dragGesture = useMemo(() => {
    if (!onDragStart || !onDragMove || !onDragEnd || kind !== 'project') return null;
    const start = onDragStart;
    const move = onDragMove;
    const finish = onDragEnd;
    // Worklets serialize captured objects recursively. Capture the two scalar
    // fields here so registering a drag never copies all project task data.
    const { key: projectKey, sessionCount } = project;
    return Gesture.Pan()
      .activateAfterLongPress(600)
      .activeOffsetY([-8, 8])
      .failOffsetX([-12, 12])
      .onStart((event) => {
        runOnJS(start)({
          absoluteY: event.absoluteY,
          count: sessionCount,
          key: projectKey,
          title: displayTitle,
        });
      })
      .onUpdate((event) => {
        runOnJS(move)(event.absoluteY);
      })
      .onFinalize(() => {
        runOnJS(finish)();
      });
  }, [displayTitle, kind, onDragEnd, onDragMove, onDragStart, project.key, project.sessionCount]);
  const header = (
    <Pressable
      accessibilityHint={reorderable ? t('devices.list.menu.projectOrderManualTip') : undefined}
      accessibilityLabel={kind === 'dialogue'
        ? t('devices.list.a11y.dialogue')
        : t('devices.list.a11y.project', { title: displayTitle })}
      accessibilityRole="button"
      accessibilityActions={actionable ? [
        { name: 'newTask', label: t('devices.list.projectActions.newTask') },
        { name: 'allTasks', label: t('devices.list.projectActions.allTasks') },
        { name: 'search', label: t('devices.list.projectActions.search') },
      ] : undefined}
      onAccessibilityAction={actionable ? (event) => {
        swipe?.registry.closeOpenRow();
        switch (event.nativeEvent.actionName) {
          case 'newTask': onNewTask(); break;
          case 'allTasks': onOpenProject(); break;
          case 'search': onSearchProject(); break;
        }
      } : undefined}
      accessibilityState={{ expanded: !collapsed }}
      accessibilityValue={collapsedStatusA11y ? { text: collapsedStatusA11y } : undefined}
      onLayout={(event) => {
        const height = event.nativeEvent.layout.height;
        if (Number.isFinite(height) && height > 0) projectHeaderHeight.value = height;
      }}
      onPress={dragging ? undefined : onToggle}
      onPressIn={dragging ? undefined : () => prepareDisclosure()}
      ref={(node) => {
        if (!headerRefs || kind !== 'project') return;
        if (node) headerRefs.current.set(project.key, node);
        else headerRefs.current.delete(project.key);
      }}
      style={({ pressed }) => [
        styles.projectRow,
        pressed && !dragging && styles.pressed,
        dragging && styles.projectRowDragging,
      ]}
      testID={rowTestID}
    >
      {collapsed ? (
        <ChevronRight color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
      ) : (
        <ChevronDown color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
      )}
      <SessionStatusPulse running={!!collapsedStatus?.running}>
        {kind === 'dialogue' ? (
          <MessagesSquare color={groupIconColor} size={iconSize.xl} strokeWidth={iconStroke.thin} />
        ) : kind === 'cindy-make' ? (
          <Hammer color={groupIconColor} size={iconSize.xl} strokeWidth={iconStroke.thin} />
        ) : collapsed ? (
          <Folder color={groupIconColor} size={iconSize.xl} strokeWidth={iconStroke.thin} />
        ) : (
          <FolderOpen color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.thin} />
        )}
      </SessionStatusPulse>
      <View style={styles.projectLabel}>
        <Text style={[styles.projectTitle, styles.projectFolderTitle]} numberOfLines={1}>{project.title}</Text>
        {machineIdentity ? <HomeProjectMachineLabel identity={machineIdentity} /> : null}
      </View>
      <Text style={styles.projectCount} numberOfLines={1}>{project.sessionCount}</Text>
      {collapsedStatus?.dot ? (
        // 与任务行右槽同一 18×18 槽、同一右边缘,点色与任务行同表。
        <View style={styles.sessionRightStatusCell}>
          <View
            style={[styles.sessionRightDot, {
              backgroundColor: collapsedStatus.dot === 'error'
                ? colors.statusError
                : collapsedStatus.dot === 'awaiting'
                  ? colors.statusAwaiting
                  : colors.statusDone,
            }]}
            testID={`home.projectCollapsedStatus.${collapsedStatus.dot}.${project.key}`}
          />
        </View>
      ) : null}
    </Pressable>
  );
  return (
    <DisclosureGroupView
      collapsable={false}
      onLayout={() => {
        if (!windowingEnabled) return;
        projectLayoutRevision.value += 1;
      }}
      ref={projectRef}
      style={[styles.projectGroup, suppressTopBorder && styles.projectGroupNoTop]}
      testID={groupTestID}
    >
      {windowingEnabled && scrollY ? (
        <HomeProjectWindowAnchorTracker
          childOffsets={estimatedChildOffsets}
          onAnchorChange={setWindowAnchor}
          projectHeaderHeight={projectHeaderHeight}
          projectLayoutRevision={projectLayoutRevision}
          projectRef={projectRef}
          scrollY={scrollY}
          viewportHeight={viewportHeight}
        />
      ) : null}
      {actionable && swipe ? (
        <SwipeableProjectHeader projectKey={project.key} registry={swipe.registry}
          onNewTask={onNewTask} onOpenTasks={onOpenProject} onSearch={onSearchProject}>
          {dragGesture ? <GestureDetector gesture={dragGesture}>{header}</GestureDetector> : header}
        </SwipeableProjectHeader>
      ) : dragGesture ? <GestureDetector gesture={dragGesture}>{header}</GestureDetector> : header}

      {collapsed ? null : (
        <DisclosureItem exit style={styles.projectChildren} testID="home.projectChildren">
          {leadingSpacerHeight > 0 ? <View pointerEvents="none" style={{ height: leadingSpacerHeight }} /> : null}
          {renderedSessions.map((item, renderedIndex) => {
            const index = windowStart + renderedIndex;
            const itemKey = item.automationGroup?.key ?? item.session.id;
            const swipeable = !!swipe
              && !item.automationGroup
              && conversationSearchAllowsLocalWrites(item);
            // Window shifts used to key rows by session id, so crossing one
            // four-row boundary destroyed and recreated four complete native
            // swipe trees in the same frame. Keep a stable pool of render
            // slots while windowing; the row receives new data without paying
            // the native mount/unmount cost. Preserve identity keys outside the
            // windowed path, and remount a slot when its outer shell changes.
            const reactKey = windowingEnabled
              ? `${project.key}:window:${renderedIndex}:${swipeable ? 'swipe' : 'plain'}`
              : itemKey;
            const row = (
              <HomeSessionRow
                expandedAutomationGroups={expandedAutomationGroups}
                // 项目块内最后一个元素不画自己的缩进线:项目块底部的全宽线就是分割线。
                hideDivider={hiddenRowCount === 0 && index === visibleSessions.length - 1}
                indented
                item={item}
                onOpenAutomationGroup={onOpenAutomationGroup}
                onOpenSession={onOpenSession}
                onToggleAutomationGroup={onToggleAutomationGroup}
                swipe={swipe}
                testID={childTestID}
              />
            );
            // 与顶层同一条规则:普通会话子行挂滑动,自动化组行不挂(组行语义含混,
            // 其展开子行由 AutomationGroupChildren 内的透传包裹)。
            // 行外包一层 DisclosureItem:块内的自动化组展开 / 收起、行被归档或置顶移走时,
            // 下面的行平滑让位,被移走的行最后淡掉。
            if (!swipeable) {
              return <DisclosureItem key={reactKey} exit nested>{row}</DisclosureItem>;
            }
            return (
              <DisclosureItem key={reactKey} exit nested>
                <SwipeableSessionRow
                  onArchive={swipe.onArchive}
                  onShowOptions={swipe.onShowOptions}
                  onTogglePin={swipe.onTogglePin}
                  onMarkRead={swipe.onMarkRead}
                  registry={swipe.registry}
                  session={item.session as RemoteSession}
                  testID={`${childTestID}.swipe`}
                >
                  {row}
                </SwipeableSessionRow>
              </DisclosureItem>
            );
          })}
          {trailingSpacerHeight > 0 ? <View pointerEvents="none" style={{ height: trailingSpacerHeight }} /> : null}
          {hiddenRowCount > 0 ? (
            <DisclosureItem nested>
            <Pressable
              accessibilityLabel={t('devices.list.viewAllConversations', { count: project.sessionCount })}
              accessibilityRole="button"
              disabled={kind !== 'dialogue' && !project.deviceId}
              onPress={onOpenProject}
              style={({ pressed }) => [
                styles.projectViewAllRow,
                pressed && styles.pressed,
                kind !== 'dialogue' && !project.deviceId && styles.disabled,
              ]}
              testID={kind === 'dialogue' ? 'home.dialogueViewAll' : 'home.projectViewAll'}
            >
              <Text style={styles.projectViewAllText} numberOfLines={1}>
                {t('devices.list.viewAllConversations', { count: project.sessionCount })}
              </Text>
              <ChevronRight color={colors.textTertiary} size={iconSize.action} strokeWidth={iconStroke.regular} />
            </Pressable>
            </DisclosureItem>
          ) : null}
        </DisclosureItem>
      )}
    </DisclosureGroupView>
  );
}

/**
 * 首页 renderItem 输出的 per-item memo 单元(2026-07-18 风暴修复第二刀)。
 * 内核行(HomeSessionRow)memo 后,每次 sections 真实变化(流式期间预览更新等)仍会
 * 整列表重渲染全部 cell 的 Swipeable / 手势包装树(trace:47 次壳层重渲染 × ~105 cell,
 * 每次 ~500ms)。把整个 renderItem 输出按 item 级 memo,包装树只在自己 item 的数据
 * 变化时更新。数据仍按内容比较,操作回调和宿主状态按引用比较:常驻列表
 * 从首页移到任务侧栏时,必须把点击、滑动和项目操作交给当前宿主。
 * 更新 props 不会重建列表或行实例。
 */
const HomeListRow = memo(HomeListRowInner, homeListRowPropsEqual);

function homeListRowPropsEqual(
  previous: Readonly<Record<string, unknown>>,
  next: Readonly<Record<string, unknown>>,
): boolean {
  const previousItem = previous.item as HomeRow;
  const nextItem = next.item as HomeRow;
  if (!homeRowsShareRenderData(previousItem, nextItem)) {
    return homeRowPropsEqual(previous, next);
  }
  // Preserve action identity checks for every other prop. Point
  // the previous row at the already-proven-equivalent next item so the
  // generic comparator takes its Object.is path instead of JSON.stringify.
  return homeRowPropsEqual({ ...previous, item: nextItem }, next);
}

function HomeListRowInner({
  expandedAutomationGroups,
  isLastPinnedRow,
  item,
  machineIdentity,
  nextIsBlock,
  onArchive,
  onOpenAutomationGroup,
  onOpenProjectSessions,
  onNewProjectTask,
  onOpenSession,
  onProjectDragEnd,
  onProjectDragMove,
  onProjectDragStart,
  onShowAllDialogue,
  onShowOptions,
  onToggleAutomationGroup,
  onToggleProject,
  onTogglePin,
  prevIsBlock,
  projectCollapsed,
  projectDragging,
  projectHeaderRefs,
  homeScrollY,
  viewportHeight,
  registry,
  showAllDialogue,
  swipe,
}: {
  expandedAutomationGroups: readonly string[];
  /** 置顶组展开态:行进入置顶卡片内的缩进/描边形态(CINDY list 视觉)。 */
  isLastPinnedRow: boolean;
  item: HomeRow;
  machineIdentity?: HomeProjectMachineIdentity;
  nextIsBlock: boolean;
  onArchive(session: RemoteSession): void;
  onOpenAutomationGroup(group: RemoteAutomationSessionGroup): void;
  onOpenProjectSessions(project: MobileHomeProjectGroup, search?: boolean): void;
  onNewProjectTask(project: MobileHomeProjectGroup): void;
  onOpenSession(item: RemoteSessionListItem): void;
  onProjectDragEnd?: () => void;
  onProjectDragMove?: (absoluteY: number) => void;
  onProjectDragStart?: (input: { absoluteY: number; count: number; key: string; title: string }) => void;
  onShowAllDialogue(): void;
  onShowOptions(session: RemoteSession): void;
  onToggleAutomationGroup(key: string): void;
  onToggleProject(key: string): void;
  onTogglePin(session: RemoteSession): void;
  prevIsBlock: boolean;
  projectCollapsed: boolean;
  projectDragging: boolean;
  projectHeaderRefs: MutableRefObject<Map<string, View>>;
  homeScrollY?: SharedValue<number>;
  viewportHeight: number;
  registry: ReturnType<typeof createSwipeRowRegistry>;
  showAllDialogue: boolean;
  swipe: SessionSwipeControls;
}) {
  if (isFolderHomeRow(item)) {
    return (
      <ProjectRow
        collapsed={projectCollapsed}
        dragging={projectDragging}
        expandedAutomationGroups={expandedAutomationGroups}
        headerRefs={projectHeaderRefs}
        kind={item.kind}
        machineIdentity={machineIdentity}
        onDragEnd={item.kind === 'project' ? onProjectDragEnd : undefined}
        onDragMove={item.kind === 'project' ? onProjectDragMove : undefined}
        onDragStart={item.kind === 'project' ? onProjectDragStart : undefined}
        onOpenAutomationGroup={onOpenAutomationGroup}
        onOpenProject={item.kind === 'dialogue' ? onShowAllDialogue : () => onOpenProjectSessions(item.project)}
        onNewTask={() => onNewProjectTask(item.project)}
        onSearchProject={() => onOpenProjectSessions(item.project, true)}
        onOpenSession={onOpenSession}
        onToggle={() => onToggleProject(item.project.key)}
        onToggleAutomationGroup={onToggleAutomationGroup}
        project={item.project}
        homeScrollY={homeScrollY}
        viewportHeight={viewportHeight}
        // Cindy Make spans separate workdirs; all tasks stay in this folder.
        showAll={item.kind === 'cindy-make' || (item.kind === 'dialogue' && showAllDialogue)}
        suppressTopBorder={prevIsBlock}
        swipe={swipe}
      />
    );
  }
  const row = (
    <HomeSessionRow
      asBlock
      expandedAutomationGroups={expandedAutomationGroups}
      hideDivider={nextIsBlock || isLastPinnedRow}
      item={item.item}
      onOpenAutomationGroup={onOpenAutomationGroup}
      onOpenSession={onOpenSession}
      onToggleAutomationGroup={onToggleAutomationGroup}
      sourceLabel={item.sourceLabel}
      suppressBlockTopBorder={prevIsBlock}
      swipe={swipe}
      testID={item.source === 'search' ? 'home.searchSessionRow' : homeSessionRowTestId(item.source)}
    />
  );
  // 普通会话行(含置顶区)在这里挂滑动操作;自动化组行不挂 —— 组行代表多次运行,
  // 「置顶/归档这一组」语义含混,但其展开的子行经 swipe 透传同样可滑。
  // 项目组子行 / 自动化子行的滑动在各自渲染路径内包裹;选择态不传 swipe。
  if (item.item.automationGroup || !conversationSearchAllowsLocalWrites(item.item)) return row;
  return (
    <SwipeableSessionRow
      onArchive={onArchive}
      onShowOptions={onShowOptions}
      onTogglePin={onTogglePin}
      onMarkRead={swipe.onMarkRead}
      registry={registry}
      session={item.item.session as RemoteSession}
      testID={`${item.source === 'search' ? 'home.searchSessionRow' : homeSessionRowTestId(item.source)}.swipe`}
    >
      {row}
    </SwipeableSessionRow>
  );
}

// 导出给项目作用域的设备详情页(app/devices/[deviceId].tsx)复用,保证两处会话行视觉一致。
// memo 化(2026-07-18 重渲染风暴):行是列表里最重的单元(Svg 状态标 + Swipeable +
// 手势树,dev 实测单行 ~13ms),父层每次重渲染 105 个挂载行全量重画是风暴的主放大器。
// 数据按内容比较;操作回调也参与比较,避免常驻行沿用已失焦首页的导航闭包。
// 行内运行态仍经 useSessionRunning 订阅。
export const HomeSessionRow = memo(HomeSessionRowInner, homeRowPropsEqual);

function HomeSessionRowInner({
  asBlock = false,
  automationChildTestID,
  automationChildrenTestID,
  deepIndented = false,
  expandedAutomationGroups,
  groupRowTestID,
  hideDivider = false,
  indented = false,
  item,
  onLongPress,
  onOpenAutomationGroup,
  onOpenSession,
  onPressSelection,
  onToggleAutomationGroup,
  selected = false,
  selectionMarkTestID,
  selectionMode = false,
  sharedRole,
  sourceLabel,
  suppressBlockTopBorder = false,
  swipe,
  testID,
  titleTestIDPrefix = 'home.sessionRowTitle',
}: {
  /**
   * 自动化组行以「块」呈现:上下各一根全宽分割线,与项目组同款,把任务块和普通对话区分开。
   * 仅顶层列表传 true;项目组内部的自动化组行保持缩进行样式(已有项目块包裹,不再嵌套块)。
   */
  asBlock?: boolean;
  automationChildTestID?: string;
  automationChildrenTestID?: string;
  /**
   * 自动化组子行的深缩进档(缩进全部收在行内 padding,滑动包装才能全宽):
   * 在 indented 基础上再深一档,保证子行始终比组行(无论组行在 chats 还是项目组内)更深。
   */
  deepIndented?: boolean;
  /** 已展开的自动化组 key 列表(页面级 state,列表虚拟化回收行组件也不丢展开态)。 */
  expandedAutomationGroups?: readonly string[];
  groupRowTestID?: string;
  /**
   * 隐藏本行自己的缩进分割线。用于紧邻「块」(项目组 / 自动化组)上边界的行,以及块内最后
   * 一个元素 —— 块的全宽 border 已经画了线,行内缩进线再画会两根 hairline 叠成一根粗线。
   */
  hideDivider?: boolean;
  indented?: boolean;
  item: RemoteSessionListItem;
  onLongPress?: () => void;
  /** 组展开后子运行超过限量时,点「查看全部 N 次运行」进入该任务的专属列表页(与项目组一致)。 */
  onOpenAutomationGroup?: (group: RemoteAutomationSessionGroup) => void;
  onOpenSession(item: RemoteSessionListItem): void;
  onPressSelection?: () => void;
  /** 提供时,自动化组行点击 = 展开/收起(与设备详情页完整模式的组行约定一致);子行点开各自会话。 */
  onToggleAutomationGroup?: (key: string) => void;
  selected?: boolean;
  selectionMarkTestID?: string;
  selectionMode?: boolean;
  /** Shared-group identity mark. Only owners show a crown; joined tasks match ordinary rows. */
  sharedRole?: SharedHomeRole;
  /** 平铺时标题旁的来源标签(项目名 /「对话」);分组模式下不传。 */
  sourceLabel?: string;
  /** 块模式下,前一行也是块时不画自己的顶线(前块的底线已经是这根线)。 */
  suppressBlockTopBorder?: boolean;
  /** 提供时透传给展开的自动化组子行(子行挂与顶层同款滑动操作);组行自身不消费。 */
  swipe?: SessionSwipeControls;
  testID: string;
  titleTestIDPrefix?: string;
}) {
  const activeSessionId = useContext(ActiveHomeSession);
  const active = item.session.id === activeSessionId || !!(activeSessionId && item.automationGroup?.sessionIds.includes(activeSessionId));
  const prepareDisclosure = useDisclosurePrepare();
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t, i18n } = useTranslation();
  // 运行态走订阅而非命令式读取:行已 memo 化,父层不再逐 emit 重渲染,命令式读取会 stale。
  const latestItem = latestMobileSessionRow(item);
  // 伙伴开的或接手的任务:标题后带第一位伙伴的头像(与桌面侧栏「在跟进」同口径)。
  const followers = useTaskFollowers(latestItem.session);
  const taskTeammate = (latestItem.session as RemoteSession).taskTeammate;
  const sessionIsRunning = useSessionRunning(latestItem.session.id);
  // 已加载消息的预览按 session 订阅。普通流式 token 只让对应的可见行更新,首页根层、
  // sections 和其它任务行都保持原引用。
  const loadedMessagePreview = useRemoteSessionMessagePreview(item.session.id);
  const running = sessionIsRunning || !!latestItem.scheduleInfo?.running;
  // attention 合并 main 的 #368:liveActivity.attention 也点亮关注态(组行直开 primary 的判定沿用)。
  const attention = item.pendingInteractionCount > 0
    || (item.scheduleInfo?.unreadCount ?? 0) > 0
    || item.liveActivity?.attention === true;
  // 右侧状态槽(替代时间位):与桌面侧栏同一套五档优先级与色表
  // (error 红 > awaiting TapTap 蓝 > running spinner > 完成未读绿 > 时间)。
  const group = onToggleAutomationGroup ? item.automationGroup : undefined;
  const groupExpanded = !!group && !!expandedAutomationGroups?.includes(group.key);
  const groupChevronVisible = !!group && !selectionMode;
  const { status: rightStatus, target: statusTarget } = resolveMobileSessionRowStatus(item, sessionIsRunning, groupExpanded);
  const showDraftIndicator = readBooleanField(item.session, 'hasDraft')
    || readBooleanField(item.session, 'hasPausedQueue')
    || readBooleanField(item.session, 'composerDraft');
  const showSchedule = !!item.scheduleInfo || item.session.source === 'scheduler';
  // 对齐桌面多绑定语义:只有同一会话的所有 schedule 都 paused / expired,
  // 才在 Timer 固定槽位叠 Pause 角标;任一 active 绑定仍保留普通 Timer。
  const scheduleStopped = item.scheduleInfo?.allSchedulesStopped === true;
  const showPinned = !!item.session.pinnedAt;
  // 显示形态(显示菜单「文字 / 列表」):文字形态不画预览行,定时 / 置顶标记并到标题行尾。
  const textMode = useHomeRowDisplay().viewMode === 'text';
  // 自动化组行:同一任务的多次运行折叠而成(共享层 groupAutomationListItems 产出)。
  // 没接展开回调的调用点退化为普通行为(点击打开 primary 会话)。
  // 块模式:组行 + 展开的子行整体包在一个上下全宽线的块里;组行自身不再画缩进分割线
  // (收起时块底线紧贴行底,展开时组头与子行之间保持连续无线,均与项目组语义一致)。
  const blockMode = asBlock && !!group;
  // 预览走共享 buildRemoteSessionCardPreview(已并入 #368 的 liveActivity),运行中会显示实时活动;
  // 组行的预览位改为任务态摘要(需关注数 / 执行中 / 已停止 / 下次运行倒计时 / 共 N 次运行),
  // 由 AutomationGroupPreviewText 叶子组件渲染。
  const preview = group
    ? null
    : buildRemoteSessionCardPreview(
        loadedMessagePreview === undefined || loadedMessagePreview === item.messagePreview
          ? item
          : { ...item, messagePreview: loadedMessagePreview },
        { running },
      );
  // 零消息会话没有摘要。此时不要保留双行列表的空白第二行;定时任务与置顶
  // 标记仍占用右下状态槽,因此继续使用双行布局。共享身份位于标题左侧。
  const showPreviewLine = !textMode && (!!group || !!preview?.trim() || showSchedule || showPinned);
  // 组行点击语义对齐桌面版侧边栏:收起且有需关注内容(未读运行 / 待处理)时,点行直接打开
  // 该看的那条会话(共享层 primary:运行中 > 有未读 > 最新);想展开点行首箭头(独立热区)。
  // 无需关注内容或已展开时,点行仍是展开 / 收起。
  const openGroupPrimary = () => {
    if (!group) return;
    const primary = statusTarget;
    if (primary) onOpenSession(primary);
  };
  const groupRowOpensPrimary = !!group && (attention || rightStatus === 'error') && !groupExpanded;
  const accessibilityTitle = sharedRole === 'owned' ? item.title + ', ' + t('sharedTask.roleHost') : item.title;
  const attributedTo = !group && taskTeammate
    ? ', ' + t((latestItem.session as RemoteSession).companion ? 'devices.list.a11y.ownedBy' : 'devices.list.a11y.createdBy', { name: taskTeammate.name }) : '';
  const followedBy = !attributedTo && !group && followers.length
    ? t('devices.list.a11y.followedBy', { names: taskFollowerNames(followers, i18n.language) })
    : '';
  const accessibilityLabel = group
    ? groupRowOpensPrimary
      ? t('devices.list.a11y.openAutomationLatest', { title: accessibilityTitle })
      : t('devices.list.a11y.automationTask', { title: accessibilityTitle })
    : t('devices.list.a11y.openConversation', { title: accessibilityTitle }) + attributedTo + followedBy;
  const handlePress = selectionMode && onPressSelection
    ? onPressSelection
    : group
      ? groupRowOpensPrimary ? openGroupPrimary : () => onToggleAutomationGroup?.(group.key)
      : () => onOpenSession(item);
  return (
    <HomeSessionRowShell
      group={!!group}
      style={blockMode
        ? [
          styles.automationGroupBlock,
          suppressBlockTopBorder && styles.automationGroupBlockNoTop,
        ]
        : undefined}
    >
      <Pressable
        accessibilityRole="button"
        accessibilityLabel={accessibilityLabel}
        accessibilityState={group ? { expanded: groupExpanded, selected: selected || active } : { selected: selected || active }}
        delayLongPress={SESSION_ROW_LONG_PRESS_MS}
        onLongPress={
          !selectionMode && !group && swipe && conversationSearchAllowsLocalWrites(item)
            ? () => {
                swipe.registry.closeOpenRow();
                swipe.onShowOptions(latestMobileSessionRow(item).session as RemoteSession);
              }
            : onLongPress}
        onPress={handlePress}
        onPressIn={group && !groupRowOpensPrimary && !selectionMode ? () => prepareDisclosure(true) : undefined}
        style={({ pressed }) => [
          styles.sessionListRow,
          active && { backgroundColor: colors.surfaceChip },
          !showPreviewLine && styles.sessionListRowSingleLine,
          indented && styles.sessionListRowIndented,
          deepIndented && styles.sessionListRowDeepIndented,
          pressed && styles.pressed,
        ]}
        testID={group ? (groupRowTestID ?? `${testID}.automationGroup`) : testID}
      >
        {selectionMode ? (
          <View style={[styles.selectionMark, selected && styles.selectionMarkSelected]} testID={selectionMarkTestID}>
            {selected ? <Text style={styles.selectionMarkText}>✓</Text> : null}
          </View>
        ) : null}
        <View style={[
          styles.sessionIconCell,
          !showPreviewLine && styles.sessionIconCellSingleLine,
        ]}>
          <SessionStatusMark
            item={item}
            running={running}
            showDraftIndicator={showDraftIndicator}
          />
        </View>
        {sharedRole === 'owned' ? (
          <View
            style={[styles.sharedRoleSlot, !showPreviewLine && styles.sharedRoleSlotSingleLine]}
            testID={`home.sharedRoleSlot.owned.${item.session.id}`}
          >
            <Crown
              accessible={false}
              color={colors.warningFg}
              size={iconSize.md}
              strokeWidth={iconStroke.thin}
            />
          </View>
        ) : null}
        <View style={[
          styles.sessionListContent,
          (hideDivider || blockMode || (!!group && groupExpanded)) && styles.sessionListContentNoDivider,
        ]}>
          <View style={[styles.sessionTitleRow, groupChevronVisible && styles.sessionTitleRowGroupHit]}>
            <View style={[styles.sessionTitleCluster, groupChevronVisible && styles.sessionTitleClusterGroupHit]}>
              <Text
                style={styles.sessionTitle}
                ellipsizeMode="tail"
                numberOfLines={1}
                testID={titleTestIDPrefix === 'deviceDetail.sessionRowTitle'
                  ? `deviceDetail.sessionRowTitle.${item.session.id}`
                  : `home.sessionRowTitle.${item.session.id}`}
              >
                {item.title}
              </Text>
              <TaskTagDots tags={item.session.tags} surfaceColor={colors.surface} />
            </View>
            {group && groupChevronVisible ? (
              // 展开箭头紧跟标题(对齐桌面 AutomationSessionGroupItem):不占行首,组行的图标 /
              // 标题与同级普通任务对齐,展开后的子行(deepIndented)才能稳定比组行深一档。
              // 独立热区:即使组行点击直开会话(有需关注内容时),点箭头仍然是展开 / 收起。
              // 热区 44×44 由箭头自身尺寸承担,不靠 hitSlop(会被父容器边界截掉)。箭头不放进
              // 标题组:标题组里的标签色球不收缩(最多 32 个),会把组内箭头挤出边界被截掉;
              // 作为标题行的不收缩子项,标题组先收缩,箭头始终完整。纵向见 sessionTitleRowGroupHit。
              <Pressable
                accessibilityLabel={groupExpanded ? t('devices.list.a11y.collapse', { title: item.title }) : t('devices.list.a11y.expand', { title: item.title })}
                accessibilityRole="button"
                onPress={(event) => {
                  // 防御性阻断:避免 chevron 点击同时触发父行 onPress(有需关注内容时父行
                  // 是"直开 primary 会话",双触发会边展开边跳页)。与设备菜单重命名按钮同款处理。
                  event.stopPropagation();
                  onToggleAutomationGroup?.(group.key);
                }}
                onPressIn={() => prepareDisclosure(true)}
                style={styles.sessionGroupChevronCell}
                testID={`${testID}.automationGroupChevron`}
              >
                {groupExpanded ? (
                  <ChevronDown color={colors.textSecondary} size={iconSize.lg} strokeWidth={iconStroke.regular} />
                ) : (
                  <ChevronRight color={colors.textSecondary} size={iconSize.lg} strokeWidth={iconStroke.regular} />
                )}
              </Pressable>
            ) : null}
            {groupChevronVisible ? <View style={styles.sessionTitleSpacer} /> : null}
            {sourceLabel ? (
              <Text
                ellipsizeMode="tail"
                numberOfLines={1}
                style={styles.sessionSourceLabel}
                testID={`home.sessionSourceLabel.${item.session.id}`}
              >
                {sourceLabel}
              </Text>
            ) : null}
            {textMode && (showSchedule || showPinned) ? (
              <View style={styles.sessionInlineIcons}>
                {showSchedule ? (
                  <AutomationTimerIcon
                    paused={scheduleStopped}
                    size={iconSize.md}
                    testID={`home.sessionAutomationTimer.${item.session.id}`}
                  />
                ) : null}
                {showPinned ? <Pin color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.thin} /> : null}
              </View>
            ) : null}
            {!group && taskTeammate ? (
              <TaskCreatorMark teammate={taskTeammate} deviceId={item.session.deviceLinkDeviceId ?? ''}
                testID={`home.sessionCreatorMark.${item.session.id}`} />
            ) : !group && followers[0] ? (
              <TaskFollowMark follower={followers[0]} testID={`home.sessionFollowMark.${item.session.id}`} />
            ) : null}
            {rightStatus === 'time' ? (
              // 任务信息(显示菜单勾选):时间 / PR / worktree / Token / 费用,按勾选顺序。
              // 状态点 / spinner 优先占这一格,与桌面信息槽让位规则一致。
              <HomeSessionInfoMeta item={item} textStyle={styles.sessionTime} />
            ) : (
              // 统一 18×18 定位槽(对齐桌面 size-4 槽的做法):点(10)与 spinner(15)
              // 尺寸不同,裸放会导致两者横/纵中心不一致,先居中到同一槽再谈对齐。
              <View style={styles.sessionRightStatusCell}>
                {rightStatus === 'running' ? (
                  // 与桌面右槽完全同款:lucide Loader2/LoaderCircle 圆弧 + 1s 匀速旋转
                  // (对齐 Tailwind animate-spin),中性色 —— running 的橙色语义由行首
                  // vendor icon 呼吸表达。
                  <SessionRightSpinner testID={`home.sessionRightStatus.running.${item.session.id}`} />
                ) : (
                  <View
                    accessibilityLabel={rightStatus === 'error' ? t('devices.list.a11y.taskError') : rightStatus === 'awaiting' ? t('devices.list.a11y.awaitingYou') : t('devices.list.a11y.doneUnread')}
                    accessibilityRole="image"
                    style={[styles.sessionRightDot, {
                      backgroundColor: rightStatus === 'error'
                        ? colors.statusError
                        : rightStatus === 'awaiting'
                          ? colors.statusAwaiting
                          : colors.statusDone,
                    }]}
                    testID={`home.sessionRightStatus.${rightStatus}.${item.session.id}`}
                  />
                )}
              </View>
            )}
          </View>
          {showPreviewLine ? (
            // 组行的标题行向下撑进预览行 7pt 给箭头热区;预览行只有文字和图标,不接触摸,
            // 让重叠处的点击落到箭头,其余位置照常落到整行。
            <View pointerEvents={groupChevronVisible ? 'none' : 'auto'} style={styles.sessionPreviewRow}>
              {group ? (
                <AutomationGroupPreviewText
                  item={item}
                  sessionCount={group.sessionCount}
                  style={styles.sessionPreview}
                  testID={`home.sessionRowPreview.${item.session.id}`}
                />
              ) : (
                <Text
                  ellipsizeMode="tail"
                  numberOfLines={1}
                  style={styles.sessionPreview}
                  testID={`home.sessionRowPreview.${item.session.id}`}
                >
                  {preview}
                </Text>
              )}
              {showSchedule || showPinned ? (
                // 组行与单次自动化会话行同款标记:Timer 放右下(时间下方的尾部图标位),
                // 行首保留正常的会话状态图标(primary 运行的 vendor / 运行态)。
                <View style={styles.sessionTrailingIcons}>
                  {showSchedule ? (
                    <AutomationTimerIcon
                      paused={scheduleStopped}
                      size={iconSize.lg}
                      testID={`home.sessionAutomationTimer.${item.session.id}`}
                    />
                  ) : null}
                  {showPinned ? <Pin color={colors.textTertiary} size={iconSize.lg} strokeWidth={iconStroke.thin} /> : null}
                </View>
              ) : null}
            </View>
          ) : null}
        </View>
      </Pressable>
      {group && groupExpanded && !selectionMode ? (
        <DisclosureItem exit>
          <AutomationGroupChildren
            childTestID={automationChildTestID}
            childrenTestID={automationChildrenTestID}
            group={group}
            inBlock={blockMode}
            suppressTrailingDivider={hideDivider}
            onOpenGroup={onOpenAutomationGroup}
            onOpenSession={onOpenSession}
            swipe={swipe}
            testID={testID}
            titleTestIDPrefix={titleTestIDPrefix}
          />
        </DisclosureItem>
      ) : null}
    </HomeSessionRowShell>
  );
}

/** 只有自动化组行会在自身内部展开子行,才需要挂过渡的外层;普通行保持原来的 View。 */
function HomeSessionRowShell({ children, group, style }: { children: ReactNode; group: boolean; style?: StyleProp<ViewStyle> }) {
  return group
    ? <DisclosureItem clip style={style}>{children}</DisclosureItem>
    : <View style={style}>{children}</View>;
}

/**
 * 自动化组展开后的子运行列表:与项目组同一交互模式 —— 默认只显示前 N 条
 * (限量与 PROJECT_PREVIEW_LIMIT 一致,24h 活动 / 需关注 / 运行中的条目豁免不折叠),
 * 有隐藏行时显示「查看全部 N 次运行」,点击进入该任务的专属列表页
 * (设备详情页的自动化任务作用域模式)。
 */
function AutomationGroupChildren({
  childTestID,
  childrenTestID,
  group,
  inBlock = false,
  // 宿主行已被上层声明"尾线由外层块提供"(如项目块内最后一个元素)时,
  // 展开子列表的尾缘线(末条运行 / 查看全部行)一并抑制,避免与块收尾线叠双(PR-266 greptile P2)。
  suppressTrailingDivider = false,
  onOpenGroup,
  onOpenSession,
  swipe,
  testID,
  titleTestIDPrefix,
}: {
  childTestID?: string;
  childrenTestID?: string;
  group: RemoteAutomationSessionGroup;
  suppressTrailingDivider?: boolean;
  /** 组行处于块模式(上下全宽线):块内最后一个元素不画自己的缩进线,避免与块底线叠成粗线。 */
  inBlock?: boolean;
  onOpenGroup?: (group: RemoteAutomationSessionGroup) => void;
  onOpenSession(item: RemoteSessionListItem): void;
  /** 提供时每条子运行挂与顶层普通会话行同款的左右滑操作。 */
  swipe?: SessionSwipeControls;
  testID: string;
  titleTestIDPrefix?: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t } = useTranslation();
  // 折叠豁免要命令式读子会话运行态,而父行(HomeSessionRow)已 memo 化、不再逐 emit
  // 重渲染——只订阅首页状态版本感知运行态变化,普通文本 token 不再惊动整组。
  useRemoteHomeStatusVersion();
  // 与项目组同一套折叠豁免(24h 活动 / 需关注 / 运行中),见共享层注释。
  const { visibleItems, hiddenCount } = getRemoteSessionPreviewCollapse(group.items, {
    limit: PROJECT_PREVIEW_LIMIT,
    isSessionRunning: (sessionId) => remoteSessionStore.isSessionRunning(sessionId),
  });
  const hasViewAllRow = hiddenCount > 0 && !!onOpenGroup;
  const viewport = useContext(HomeListViewportContext);
  const childrenRef = useAnimatedRef<View>();
  const layoutRevision = useSharedValue(0);
  const headerHeight = useSharedValue(0);
  // A project can retain many expanded automation groups. Preload nearby runs
  // after layout instead of multiplying every project slot by a child window.
  const [windowAnchor, setWindowAnchor] = useState(-1);
  const textMode = useHomeRowDisplay().viewMode === 'text';
  const childOffsets = buildHomeProjectChildOffsets(visibleItems.map((child) => estimateHomeSessionRowHeight(child, textMode)));
  const windowingEnabled = shouldWindowHomeProjectChildren({
    collapsed: false, itemCount: visibleItems.length,
    scrollTrackingAvailable: viewport !== null, threshold: PROJECT_CHILD_WINDOW_THRESHOLD,
  });
  const range = windowingEnabled
    ? windowAnchor >= 0
      ? resolveHomeProjectChildWindow({ anchor: windowAnchor, childOffsets,
        overscan: PROJECT_CHILD_WINDOW_OVERSCAN, windowSize: PROJECT_CHILD_WINDOW_SIZE })
      : { start: 0, end: 0, leadingSpacerHeight: 0, trailingSpacerHeight: childOffsets.at(-1) ?? 0 }
    : { start: 0, end: visibleItems.length, leadingSpacerHeight: 0, trailingSpacerHeight: 0 };
  return (
    <Reanimated.View ref={childrenRef} collapsable={false}
      onLayout={() => { if (windowingEnabled) layoutRevision.value += 1; }}
      style={styles.automationGroupChildren} testID={childrenTestID ?? `${testID}.automationGroupChildren`}>
      {windowingEnabled && viewport ? <HomeProjectWindowAnchorTracker
        deferOffscreen
        childOffsets={childOffsets} onAnchorChange={setWindowAnchor}
        projectHeaderHeight={headerHeight} projectLayoutRevision={layoutRevision}
        projectRef={childrenRef} scrollY={viewport.scrollY} viewportHeight={viewport.viewportHeight}
      /> : null}
      {range.leadingSpacerHeight > 0 ? <View pointerEvents="none" style={{ height: range.leadingSpacerHeight }} /> : null}
      {visibleItems.slice(range.start, range.end).map((child, renderedIndex) => {
        const index = range.start + renderedIndex;
        const key = windowingEnabled ? `${group.key}:window:${renderedIndex}` : child.session.id;
        const row = (
          <HomeSessionRow
            deepIndented
            hideDivider={(inBlock || suppressTrailingDivider) && !hasViewAllRow && index === visibleItems.length - 1}
            item={child}
            onOpenSession={onOpenSession}
            testID={childTestID ?? `${testID}.automationChild`}
            titleTestIDPrefix={titleTestIDPrefix}
          />
        );
        if (!swipe) return <Fragment key={key}>{row}</Fragment>;
        return (
          <SwipeableSessionRow
            key={key}
            onArchive={swipe.onArchive}
            onShowOptions={swipe.onShowOptions}
            onTogglePin={swipe.onTogglePin}
            onMarkRead={swipe.onMarkRead}
            registry={swipe.registry}
            session={child.session as RemoteSession}
            testID={`${testID}.automationChild.swipe`}
          >
            {row}
          </SwipeableSessionRow>
        );
      })}
      {range.trailingSpacerHeight > 0 ? <View pointerEvents="none" style={{ height: range.trailingSpacerHeight }} /> : null}
      {hasViewAllRow ? (
        <Pressable
          accessibilityLabel={t('devices.list.viewAllRuns', { count: group.sessionCount })}
          accessibilityRole="button"
          onPress={() => onOpenGroup?.(group)}
          style={({ pressed }) => [
            styles.automationViewAllRow,
            !inBlock && !suppressTrailingDivider && styles.automationViewAllRowDivider,
            pressed && styles.pressed,
          ]}
          testID={`${testID}.automationViewAll`}
        >
          <Text style={styles.projectViewAllText} numberOfLines={1}>
            {t('devices.list.viewAllRuns', { count: group.sessionCount })}
          </Text>
          <ChevronRight color={colors.textTertiary} size={iconSize.action} strokeWidth={iconStroke.regular} />
        </Pressable>
      ) : null}
    </Reanimated.View>
  );
}

/**
 * 自动化组行预览位(文案规则见 automationGroupPreview)。与 SessionRelativeTime 同理下沉为
 * 叶子组件订阅分钟心跳:倒计时每分钟前进,行主体不跟着重渲染。now 取渲染时刻,
 * 心跳只负责触发,避免模块级快照在无订阅期间过期。
 */
function AutomationGroupPreviewText({ item, sessionCount, style, testID }: {
  item: RemoteSessionListItem;
  sessionCount: number;
  style: StyleProp<TextStyle>;
  testID: string;
}) {
  const { t } = useTranslation();
  useMinuteNow();
  return (
    <Text ellipsizeMode="tail" numberOfLines={1} style={style} testID={testID}>
      {automationGroupPreview(item, sessionCount, t, Date.now())}
    </Text>
  );
}

// 状态提醒点已移到行右侧(替代时间位,与桌面一致),行首图标只保留 vendor 标识 +
// running 呼吸 + 草稿铅笔,不再叠角标点。

function pullDownActionsEqual(a: readonly NativePullDownAction[], b: readonly NativePullDownAction[]): boolean {
  return a === b || JSON.stringify(a) === JSON.stringify(b);
}

/** 该首页行是否以「块」呈现(上下全宽线):项目组,或自动化组行(顶层 asBlock)。 */
function isBlockHomeRow(row: HomeRow | undefined): boolean {
  if (!row) return false;
  return isFolderHomeRow(row) || (row.kind === 'session' && !!row.item.automationGroup);
}

function homeSessionRowTestId(source: 'chat' | 'pinned' | 'project'): string {
  if (source === 'pinned') return 'home.pinnedRow';
  if (source === 'project') return 'home.projectSessionRow';
  return 'home.chatRow';
}

function remoteListStatusFilter(filter: RemoteSessionStatusFilter): RemoteListStatusFilter {
  if (filter === 'archived') return 'archived';
  if (filter === 'all' || filter === 'waiting' || filter === 'automation') return 'all';
  return 'active';
}

function isDeviceOfflineError(error: unknown): boolean {
  if (error instanceof DeviceLinkError) return error.code === 'DEVICE_OFFLINE';
  if (typeof error === 'object' && error !== null && 'code' in error) {
    return (error as { code?: unknown }).code === 'DEVICE_OFFLINE';
  }
  return error instanceof Error && error.message.includes('[DEVICE_OFFLINE]');
}

function isOptionalActiveSessionSnapshotError(error: unknown): boolean {
  if (isAccessRevokedError(error) || isDeviceOfflineError(error)) return false;
  const text = formatRemoteError(error);
  if (text.includes('REMOTE_DISABLED')) return false;
  return true;
}

function markDeviceViewsOffline(
  devices: readonly DeviceView[],
  offlineDeviceIds: ReadonlySet<string>,
): DeviceView[] {
  if (offlineDeviceIds.size === 0) return [...devices];
  return devices.map((device) => {
    if (!offlineDeviceIds.has(device.deviceId)) return device;
    return {
      ...device,
      busy: false,
      online: false,
      remoteControlEnabled: false,
    };
  });
}

function readBooleanField(value: unknown, key: string): boolean {
  return !!value && typeof value === 'object' && !Array.isArray(value) && (value as Record<string, unknown>)[key] === true;
}

function homeConnectionTitle(status: 'online' | 'connecting' | 'stopped', t: TFunction): string {
  if (status === 'connecting') return t('devices.list.connection.connecting');
  if (status === 'stopped') return t('devices.list.connection.disconnected');
  return '';
}

function updateHomeDeviceConnectionState(
  current: Record<string, HomeDeviceConnectionState>,
  deviceId: string,
  state: HomeDeviceConnectionState,
): Record<string, HomeDeviceConnectionState> {
  if (state === 'idle') {
    if (!(deviceId in current)) return current;
    const { [deviceId]: _removed, ...next } = current;
    return next;
  }
  if (current[deviceId] === state) return current;
  return { ...current, [deviceId]: state };
}

function pruneHomeDeviceConnectionStates(
  current: Record<string, HomeDeviceConnectionState>,
  availableDeviceIds: ReadonlySet<string>,
): Record<string, HomeDeviceConnectionState> {
  let changed = false;
  const next: Record<string, HomeDeviceConnectionState> = {};
  for (const [deviceId, state] of Object.entries(current)) {
    if (!availableDeviceIds.has(deviceId)) {
      changed = true;
      continue;
    }
    next[deviceId] = state;
  }
  return changed ? next : current;
}

const makeStyles = (colors: ThemeColors) => StyleSheet.create({
  ...homeListStyles(colors),
  safeArea: { flex: 1, backgroundColor: colors.surface },
  pressed: mobileInteractionStyles.pressed,
  disabled: { opacity: 0.45 },
  homeChrome: {
    left: 0,
    overflow: 'hidden',
    position: 'absolute',
    right: 0,
    top: 0,
    zIndex: 10,
  },
  homeChromeFrosted: {
    borderBottomColor: colors.chatHeaderDivider,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  homeHeader: {
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'space-between',
    minHeight: HOME_HEADER_MIN_HEIGHT,
    paddingBottom: spacing.md,
    paddingHorizontal: spacing.lg,
  },
  headerLeadingActions: {
    // Only the menu button lives here. The title centers itself on the header
    // midline and may use the spare room on this side when the name is long.
    alignItems: 'flex-start',
    flexShrink: 0,
    height: navigationChrome.target,
    justifyContent: 'center',
    width: navigationChrome.target,
  },
  // Sized to the buttons actually shown, so the guide's brand title stays
  // centered and a long device name is not cut short by an empty slot.
  headerActions: {
    alignItems: 'center',
    flexDirection: 'row',
    flexShrink: 0,
    gap: spacing.xs,
    justifyContent: 'flex-end',
    width: navigationChrome.target,
  },
  headerActionsWide: {
    width: navigationChrome.target * 2 + spacing.xs,
  },
  displayFilterDotOffset: { top: -1, right: -2 },
  // 菜单外层替标题占住顶栏中间的剩余宽度,长设备名在这里截断而不是挤开右侧按钮。
  headerTitleSlot: {
    flex: 1,
    minWidth: 0,
  },
  headerTitleWrap: {
    alignItems: 'center',
    flex: 1,
    justifyContent: 'center',
    minHeight: 44,
    minWidth: 0,
    paddingHorizontal: spacing.sm,
  },
  headerTitleWrapTrailing: {
    alignItems: 'flex-end',
  },
  headerTitleCluster: {
    alignItems: 'center',
    flexDirection: 'row',
    flexShrink: 1,
    gap: 6,
    maxWidth: '100%',
    minWidth: 0,
  },
  headerTitle: {
    color: colors.textPrimary,
    flexShrink: 1,
    fontSize: typeScale.title,
    fontWeight: fontWeight.semibold,
    lineHeight: lineHeight.title,
  },
  deviceMenuPanelCenter: {
    alignSelf: 'center',
  },
  connectionRow: {
    alignSelf: 'flex-start',
    maxWidth: '100%',
    backgroundColor: colors.surfaceElevated,
    borderColor: colors.border,
    borderWidth: StyleSheet.hairlineWidth,
    borderRadius: radius.container,
    alignItems: 'center',
    borderBottomColor: colors.border,
    borderBottomWidth: StyleSheet.hairlineWidth,
    flexDirection: 'row',
    gap: spacing.sm,
    minHeight: 42,
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.xs,
  },
  connectionRowError: {
    backgroundColor: colors.surface,
  },
  connectionText: {
    color: colors.textSecondary,
    flexShrink: 1,
    fontSize: typeScale.footnote,
    lineHeight: lineHeight.caption,
    fontWeight: fontWeight.regular,
    minWidth: 0,
  },
  connectionIconButton: {
    alignItems: 'center',
    borderRadius: radius.pill,
    height: CONNECTION_ICON_BUTTON_SIZE,
    justifyContent: 'center',
    width: CONNECTION_ICON_BUTTON_SIZE,
  },
  deviceMenuBackdrop: {
    backgroundColor: colors.overlay,
    flex: 1,
    paddingHorizontal: spacing.lg,
  },
  deviceMenuPanel: {
    // 左锚定窄卡(对齐设计稿「选择器菜单」):贴着头部选择器下方展开,不再横向铺满。
    alignSelf: 'flex-start',
    backgroundColor: colors.surfaceElevated,
    borderColor: colors.border,
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
    maxWidth: 360,
    minWidth: 264,
    padding: spacing.sm,
  },
  deviceMenuScroll: {
    // 仅作为 scope 列表的可滚动容器,flexGrow:0 让短列表时收缩到内容高度(maxHeight 在行内设)。
    flexGrow: 0,
  },
  deviceMenuCheckSlot: {
    alignItems: 'center',
    width: iconSize.md,
  },
  deviceMenuItem: {
    alignItems: 'center',
    borderRadius: radius.container,
    flexDirection: 'row',
    gap: spacing.md,
    minHeight: 48,
    paddingHorizontal: spacing.md,
  },
  deviceMenuItemText: {
    color: colors.textPrimary,
    flex: 1,
    fontSize: typeScale.body,
    fontWeight: fontWeight.medium,
    lineHeight: lineHeight.body,
    minWidth: 0,
  },
  revokedTipBackdrop: {
    alignItems: 'center',
    backgroundColor: colors.overlay,
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: spacing.xl,
  },
  revokedTipCard: {
    backgroundColor: colors.surfaceElevated,
    borderColor: colors.border,
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
    gap: spacing.sm,
    maxWidth: 360,
    padding: spacing.lg,
    width: '100%',
  },
  revokedTipHeader: {
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  revokedTipIcon: {
    alignItems: 'center',
    backgroundColor: colors.surfaceChip,
    borderRadius: radius.pill,
    height: 36,
    justifyContent: 'center',
    width: 36,
  },
  revokedTipClose: {
    alignItems: 'center',
    height: 32,
    justifyContent: 'center',
    width: 32,
  },
  revokedTipTitle: {
    color: colors.textPrimary,
    fontSize: typeScale.title,
    fontWeight: fontWeight.semibold,
    lineHeight: lineHeight.title,
  },
  revokedTipBody: {
    color: colors.textSecondary,
    fontSize: typeScale.body,
    lineHeight: lineHeight.body,
  },
  revokedTipRetry: {
    marginTop: spacing.sm,
  },
  homeList: {
    backgroundColor: colors.surface,
    flex: 1,
  },
  listContent: {
    backgroundColor: colors.surface,
    flexGrow: 1,
    paddingBottom: LEGACY_HOME_LIST_BOTTOM_RESERVE,
    paddingTop: 0,
  },
  // 置顶区收尾线:回 XD-Maker 原版 hairline(换肤卡片化曾置 0,通栏回退一并恢复)。
  pinnedFooter: { backgroundColor: colors.border, height: StyleSheet.hairlineWidth },
  initialLoadingState: {
    alignItems: 'center',
    gap: spacing.sm,
    justifyContent: 'center',
  },
  initialLoadingText: {
    color: colors.textSecondary,
    fontSize: typeScale.footnote,
    fontWeight: fontWeight.regular,
    lineHeight: lineHeight.caption,
  },
  projectGroup: {
    backgroundColor: colors.surface,
    // 全宽分割线挂在项目组的顶部与底部:把整个项目块与上方/下方的普通对话分开,
    // 而非分隔项目头与其下属会话(项目头 → 内容之间保持连续无线)。
    borderBottomColor: colors.border,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderRadius: 0, // 显式方角覆盖,非漂移
    borderTopColor: colors.border,
    borderTopWidth: StyleSheet.hairlineWidth,
    borderWidth: 0,
  },
  projectGroupNoTop: {
    // 前一行也是块时不画顶线,避免两根 hairline 叠成一根粗线。
    borderTopWidth: 0,
  },

  projectRowDragging: {
    opacity: 0.28,
  },
  projectDragGhost: {
    alignItems: 'center',
    backgroundColor: colors.surfaceElevated,
    borderColor: colors.border,
    borderRadius: radius.container,
    borderWidth: StyleSheet.hairlineWidth,
    flexDirection: 'row',
    gap: spacing.sm,
    paddingLeft: spacing.md,
    paddingRight: spacing.lg,
    position: 'absolute',
  },
  projectDragInsertLine: {
    backgroundColor: colors.textPrimary,
    height: StyleSheet.hairlineWidth * 2,
    left: spacing.lg,
    position: 'absolute',
    right: spacing.lg,
  },
  projectChildren: {
    backgroundColor: colors.surface,
  },
  projectViewAllRow: {
    // 永远是项目块的最后一个元素:不画自己的下线,块底部的全宽线就是分割线
    // (再画会两根 hairline 叠成一根粗线)。
    alignItems: 'center',
    flexDirection: 'row',
    gap: spacing.sm,
    minHeight: HOME_AUTOMATION_VIEW_ALL_ROW_HEIGHT,
    paddingLeft: HOME_PROJECT_VIEW_ALL_INSET,
    paddingRight: spacing.lg,
  },
  projectViewAllText: {
    color: colors.textSecondary,
    flex: 1,
    fontSize: typeScale.body,
    fontWeight: fontWeight.medium,
    lineHeight: lineHeight.body,
  },

  automationGroupBlock: {
    // 自动化组(组行 + 展开的子行)整体成块:上下各一根全宽分割线,与项目组(projectGroup)
    // 同款,把任务块和普通对话在视觉上区分开。
    backgroundColor: colors.surface,
    borderBottomColor: colors.border,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderTopColor: colors.border,
    borderTopWidth: StyleSheet.hairlineWidth,
  },
  automationGroupBlockNoTop: {
    // 前一行也是块时不画顶线:前块的底线就是这根分割线,再画会叠成一根粗线。
    borderTopWidth: 0,
  },
  automationGroupChildren: {
    // 自动化组展开的子运行容器:不再用容器 padding 做缩进(会把子行的滑动包装挤离屏边),
    // 深一档的缩进由子行自身的 sessionListRowDeepIndented 承担,视觉层级不变。
    backgroundColor: colors.surface,
  },
  automationViewAllRow: {
    // 「查看全部 N 次运行」:与项目组「查看全部 N 条对话」同款行样式,
    // 左缩进对齐组内子行文字(deepIndented 行的缩进 + 行首图标位)。
    alignItems: 'center',
    flexDirection: 'row',
    gap: spacing.sm,
    minHeight: 54,
    paddingLeft: spacing.md + spacing.lg * 2 + 24 + spacing.md,
    paddingRight: spacing.lg,
  },
  automationViewAllRowDivider: {
    // 仅非块模式(项目组内部的自动化组)画自己的下线;块模式下块底线负责,不再叠一根。
    borderBottomColor: colors.border,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },

  sessionGroupChevronCell: {
    // 自动化组行标题后的展开箭头:标题行的不收缩子项,长标题 / 多标签时标题组先收缩;
    // 自身即 44×44 点击区(图标居中),负左外边距吃掉部分行内间距,让图标视觉上贴近标题。
    alignItems: 'center',
    flexShrink: 0,
    height: GROUP_CHEVRON_HIT_SIZE,
    justifyContent: 'center',
    marginLeft: -12,
    width: GROUP_CHEVRON_HIT_SIZE,
  },
  sessionTitleRowGroupHit: {
    // 组行标题行撑到 44 给箭头热区,上下负外边距抵消,行内布局仍按 sessionTitleRow 高度排。
    height: GROUP_CHEVRON_HIT_SIZE,
    marginVertical: -(GROUP_CHEVRON_HIT_SIZE - SESSION_TITLE_ROW_HEIGHT) / 2,
  },
  sessionTitleClusterGroupHit: {
    // 组行标题组按内容宽度、可收缩,让箭头紧跟其后;右侧余量交给 sessionTitleSpacer。
    flex: 0,
    flexShrink: 1,
  },
  sessionTitleSpacer: {
    flex: 1,
  },

  // 右侧状态槽(替代时间位):18×18 定位槽把点与 spinner 居中到同一锚点;
  // 点 10px(桌面 size-2=8px,手机屏幕密度高、观看距离远,放大一档保证可辨识,
  // 2026-07 产品模拟器实测拍板)。
  sessionRightStatusCell: {
    alignItems: 'center',
    flexShrink: 0,
    height: 18,
    justifyContent: 'center',
    width: 18,
  },
  sessionRightDot: {
    borderRadius: radius.pill, // 10x10 圆点:pill 钳制为半径 5,与原字面量视觉一致
    flexShrink: 0,
    height: 10,
    width: 10,
  },

  sessionSourceLabel: {
    color: colors.textTertiary,
    flexShrink: 1,
    fontSize: typeScale.caption,
    fontWeight: fontWeight.regular,
    lineHeight: lineHeight.body,
    maxWidth: '42%',
    minWidth: 0,
  },

  sharedRoleSlot: {
    alignItems: 'center',
    justifyContent: 'flex-start',
    paddingTop: 26,
    width: iconSize.action,
  },
  sharedRoleSlotSingleLine: {
    justifyContent: 'center',
    paddingTop: 0,
  },
  selectionMark: {
    alignItems: 'center',
    alignSelf: 'center',
    borderColor: colors.borderStrong,
    borderRadius: radius.pill,
    borderWidth: StyleSheet.hairlineWidth,
    height: 22,
    justifyContent: 'center',
    width: 22,
  },
  selectionMarkSelected: {
    backgroundColor: colors.surfaceChip,
    borderColor: colors.textPrimary,
  },
  selectionMarkText: {
    color: colors.textPrimary,
    fontSize: typeScale.caption,
    fontWeight: fontWeight.medium,
    lineHeight: lineHeight.caption,
  },
});