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。

feat(mobile): 适配 Duo 布局并统一原生控件与任务保活 (#4818)

Dashb6f2836a0200
diff --git a/apps/mobile/app/(auth)/login.tsx b/apps/mobile/app/(auth)/login.tsx
index 313b474379..d88827a9c5 100644
--- a/apps/mobile/app/(auth)/login.tsx
+++ b/apps/mobile/app/(auth)/login.tsx
@@ -1,17 +1,13 @@
+import { SystemNavigationBack, useSystemNavigationBack } from '@/platform/chrome/SystemNavigationBack';
+import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';
+import { resolveLoginGroupPlacement } from '@/auth/loginGroupPlacement';
import { Stack } from 'expo-router';
import { X } from 'lucide-react-native';
+import { HomeHeaderGlassButton } from '@/session/HomeHeaderGlassButton';
+import { hasNativeLoginButtons, LoginNativeButton } from '@/components/LoginNativeButton';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import {
- Animated,
- Easing,
- Keyboard,
- Linking,
- Platform,
- Pressable,
- StyleSheet,
- View,
-} from 'react-native';
+import { Animated, Easing, Keyboard, Linking, Platform, Pressable, ScrollView, StyleSheet, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import type { AccountDeletionStatus, SocialProvider, VerificationKind } from '@cindy/auth-client';
@@ -130,6 +126,8 @@ export function LoginScreen({
[remoteSessionStoreVersion],
);
const stage = useLoginSurface();
+ const loginWindow = useAdaptiveWindow();
+ const systemBack = useSystemNavigationBack() && !additionalAccount;
const insets = useSafeAreaInsets();
// 舞台有效主题(首启亮色门可强制 light,与系统主题可能不一致):状态栏样式
// 必须跟舞台而不是系统,经 screen option 走 VC-based 通道(见 _layout 注释)。
@@ -461,7 +459,7 @@ export function LoginScreen({
testID="login.accountSwitcher"
/>
) : null;
- const backNode = backAction ? (
+ const backNode = backAction && !systemBack ? (
<LoginBackButton
disabled={auth.isBusy}
label={loginText('back')}
@@ -1245,26 +1243,25 @@ export function LoginScreen({
// 组内容缩放 = stage.scale × loginGroupScale(§3.6 pad 构图 0.794117 / 0.655357,
// 手机 1)。Safe Area:背景 edge-to-edge(stage 宿主不裁),功能区保持 insets 内——
// 组底边越过 bottom inset 时整组按差值上移(附录 C §3.4 工程定案)。
- const groupScale = stage.scale * stage.loginGroupScale;
- const groupLeftPx = stage.offsetX + stage.loginX * stage.scale;
- const groupTopPxRaw = stage.offsetY + stage.loginY * stage.scale;
- const bottomLimitPx = stage.viewportHeight - insets.bottom;
+ const keyboard = useLoginKeyboardRect();
+ const foldedLogin = loginWindow.regions.some(r => r.kind === 'division');
+ const scrollForKeyboard = foldedLogin || (stage.mode === 'compact-wide' && stage.viewportHeight < 480
+ && (!keyboard.visible || (keyboard.rect != null && keyboard.rect.width >= loginWindow.width * 0.95)));
// consent PR:identifier 主视图下方多出协议行(行底 622 超出组高 560 共 62 设计px)。
// 流程底边全步骤恒取 622(含协议行的最低内容):一防步骤切换时 lift 释放产生
// 整组纵向跳变(规则 7,codex 审查 P1),二让下方外层/内层容器 bounds 恒包住
// 协议行——RN(尤其 Android)对父 bounds 外子节点不派发触摸,协议行必须在界内。
const flowBottomDesignPx = loginSizes.flowHeight + LOGIN_CONSENT_ROW.bottomOverflow;
- const liftPx = Math.max(
- 0,
- groupTopPxRaw + flowBottomDesignPx * groupScale - bottomLimitPx,
+ const { x: groupLeftPx, y: groupTopPx, height: groupVisibleHeight, scale: groupScale } = resolveLoginGroupPlacement(
+ loginWindow, stage, flowBottomDesignPx,
+ scrollForKeyboard && keyboard.visible && keyboard.rect && keyboard.rect.width >= loginWindow.width * 0.95
+ ? Math.max(0, loginWindow.height - keyboard.rect.y) : 0,
);
- const groupTopPx = Math.max(0, groupTopPxRaw - liftPx);
// 键盘契约(Step 5b.1,方案 B):唯一位移源 = 自定义 translate。
// v5 冻结测量拓扑:基线只在下方「外层未变换测量 wrapper」上 measureInWindow
// (天然不含 translate);键盘事件 / viewport 变化(Android resize)后重测,
// 基线随 resize 更新 → 位移只计一次,无系统/自定义双算。
- const keyboard = useLoginKeyboardRect();
const outerGroupRef = useRef<View>(null);
const [groupBaseline, setGroupBaseline] = useState<{
x: number;
@@ -1290,11 +1287,12 @@ export function LoginScreen({
// viewport 不缩窗,需独立跟踪全高以算「全高 - 键盘高 - 系统栏底」键盘顶(见
// loginKeyboardAvoidance computeDockedKeyboardTop)。取 max 抗缩窗/旋转噪声。
const [fullViewportHeight, setFullViewportHeight] = useState(stage.viewportHeight);
+ const fullViewportWidthRef = useRef(stage.viewportWidth);
useEffect(() => {
- setFullViewportHeight((prev) =>
- stage.viewportHeight > prev ? stage.viewportHeight : prev,
- );
- }, [stage.viewportHeight]);
+ const resized = fullViewportWidthRef.current !== stage.viewportWidth;
+ fullViewportWidthRef.current = stage.viewportWidth;
+ setFullViewportHeight(prev => resized || !keyboard.visible ? stage.viewportHeight : Math.max(prev, stage.viewportHeight));
+ }, [stage.viewportHeight, stage.viewportWidth, keyboard.visible]);
const ssoOrgHistoryBottom =
ssoOrgMode && ssoOrgHistoryOpen && ssoOrgHistory.length > 1
? LOGIN_SSO_ORG_HISTORY.y + LOGIN_SSO_ORG_HISTORY.maxHeight
@@ -1339,7 +1337,7 @@ export function LoginScreen({
fullViewportHeight,
insets.bottom,
]);
- const keyboardShift = shiftResult.shift;
+ const keyboardShift = scrollForKeyboard ? 0 : shiftResult.shift;
// handoff 面板入场(demo:300+moveMs 起步,自下而上 20px + 渐显 420ms;
// reduced-motion/已登录直入由 Provider 收敛为 done,此处直落终态)
@@ -1367,6 +1365,8 @@ export function LoginScreen({
>
{/* 渲染为 null,仅把状态栏样式写进本屏 screen options。iOS 专用:
Android 由舞台内组件式 StatusBar 控制,不走 RNS 双轨 */}
+ {!additionalAccount ? <SystemNavigationBack available={!!backAction} disabled={auth.isBusy}
+ label={loginText('back')} onPress={() => backAction?.()} /> : null}
{Platform.OS === 'ios' ? (
<Stack.Screen
options={{
@@ -1374,28 +1374,14 @@ export function LoginScreen({
}}
/>
) : null}
+
{additionalAccount && onClose ? (
- <Pressable
- accessibilityLabel={t('shared.closePanel')}
- accessibilityRole="button"
- accessibilityState={{ disabled: auth.isBusy }}
- disabled={auth.isBusy}
- hitSlop={8}
- onPress={onClose}
- style={({ pressed }) => [
- styles.closeButton,
- { top: insets.top + spacing.sm },
- pressed && styles.closeButtonPressed,
- auth.isBusy && styles.closeButtonDisabled,
- ]}
- testID="login.closeButton"
- >
- <X
- color={colors.textPrimary}
- size={iconSize.lg}
- strokeWidth={iconStroke.regular}
- />
- </Pressable>
+ <View style={{ position: 'absolute', right: spacing.lg, top: insets.top + spacing.sm, zIndex: 20 }}>
+ <HomeHeaderGlassButton accessibilityLabel={t('shared.closePanel')}
+ disabled={auth.isBusy} onPress={onClose} testID="login.closeButton">
+ <X color={colors.textPrimary} size={iconSize.action} strokeWidth={iconStroke.regular} />
+ </HomeHeaderGlassButton>
+ </View>
) : null}
{/* 外层未变换测量 wrapper(v5 冻结拓扑):持布局基线,不参与任何 translate */}
<View
@@ -1411,7 +1397,7 @@ export function LoginScreen({
ref={outerGroupRef}
style={{
// 恒含协议行区间(622 设计px):协议行必须在父 bounds 内才可命中(见 flowBottomDesignPx 注)
- height: flowBottomDesignPx * groupScale,
+ height: groupVisibleHeight,
left: groupLeftPx,
position: 'absolute',
top: groupTopPx,
@@ -1419,7 +1405,13 @@ export function LoginScreen({
}}
>
{/* 内层 translate 容器:键盘位移唯一施加处(方案 B) */}
- <View style={{ flex: 1, transform: [{ translateY: -keyboardShift }] }}>
+ <ScrollView
+ style={{ flex: 1, transform: [{ translateY: -keyboardShift }] }}
+ contentContainerStyle={{ height: flowBottomDesignPx * groupScale }}
+ keyboardShouldPersistTaps="handled"
+ scrollEnabled={groupVisibleHeight < flowBottomDesignPx * groupScale}
+ showsVerticalScrollIndicator={false}
+ >
<Animated.View
style={{
flex: 1,
@@ -1443,7 +1435,7 @@ export function LoginScreen({
{stateContent}
</View>
</Animated.View>
- </View>
+ </ScrollView>
</View>
<AccountSwitcherSheet
hasRunningTasks={hasRunningTasks}
@@ -1662,7 +1654,12 @@ function AccountDeletionStatusPanel({
? loginText('accountDeletionProcessingCopy')
: loginText('accountDeletionCompletedCopy')}
</Text>
- {onDismiss ? (
+ {onDismiss ? (hasNativeLoginButtons ? (
+ <LoginNativeButton label={loginText('accountDeletionDismiss')} onPress={onDismiss}
+ testID="login.accountDeletionDismissButton" variant="text"
+ width={frame.width - scaled(B.padding) * 2} height={Math.max(44, scaled(B.lineHeight))} fontSize={scaled(B.font)}
+ style={{ marginTop: scaled(B.bodyLinkGap) }} />
+ ) : (
<Pressable
accessibilityRole="button"
hitSlop={resolveDeletionBubbleLinkHitSlop(frame.scale)}
@@ -1679,7 +1676,7 @@ function AccountDeletionStatusPanel({
{loginText('accountDeletionDismiss')}
</Text>
</Pressable>
- ) : null}
+ )) : null}
</View>
);
}
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index e705f4ed32..4da8f9ede0 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -1,3 +1,6 @@
+import { recentTaskKey } from '@/session/recentTasks';
+import { RecentMessageHistoriesProvider } from '@/session/RecentMessageHistories';
+import { ResidentHomeListProvider } from '@/session/ResidentHomeList';
import { AndroidUpdateSheet } from '@/update/AndroidUpdateSheet';
import { PeerFileTransport } from '@/device-link/peerFileTransport';
import { startLocalDiagnostics } from '@/debug/localDiagnostics';
@@ -24,6 +27,9 @@ import {
type ThemeColors,
} from '@/theme';
import { SafeAreaProvider } from 'react-native-safe-area-context';
+import { AdaptiveWindowProvider } from '@/platform/AdaptiveWindow';
+import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';
+import { sessionPaneLayout } from '@/session/sessionPaneLayout';
import { AuthProvider, useAuth } from '@/auth/AuthContext';
import { useLoginFirstLaunchLight } from '@/auth/loginFirstLaunchGate';
import { loginText } from '@/auth/loginMessages';
@@ -80,6 +86,10 @@ import { HomeEntryProvider, useHomeEntrySplashRelease } from '@/session/HomeEntr
import { RemoteDesktopHost } from '@/remote-desktop/RemoteDesktopHost';
function NavigationGate() {
+ const windowGeometry = useAdaptiveWindow();
+ // Establish chrome before push starts, rather than revealing a hidden bar after mount.
+ const sessionHeaderShown = Platform.OS === 'ios'
+ && (windowGeometry.barEdge !== 'none' || !sessionPaneLayout(windowGeometry).persistent);
const auth = useAuth();
const router = useRouter();
const segments = useSegments();
@@ -150,9 +160,14 @@ function NavigationGate() {
/>
) : null}
<RemoteDesktopHost>
+ <ResidentHomeListProvider key={auth.accountGeneration}>
+ <RecentMessageHistoriesProvider>
<Stack
+ key={auth.accountGeneration}
screenOptions={{
headerShown: false,
+ // Custom titles register after mount and clear on unmount. Never expose route names in between.
+ title: '',
contentStyle: { backgroundColor: colors.surface },
...(Platform.OS === 'ios'
? { statusBarStyle: statusBarTheme === 'dark' ? 'light' : 'dark' }
@@ -164,6 +179,13 @@ function NavigationGate() {
gestureResponseDistance: { end: 44 },
}}
>
+ <Stack.Screen name="sessions/[sessionId]" getId={({ params }) => recentTaskKey(params ?? {})} options={{
+ headerShown: sessionHeaderShown,
+ headerTransparent: true,
+ headerShadowVisible: false,
+ headerBackVisible: false,
+ headerStyle: { backgroundColor: 'transparent' },
+ }} />
{/* 设置从左侧抽屉进入:接着抽屉方向从左边推出,不要默认从右边盖上来。 */}
<Stack.Screen name="settings" options={{ animation: 'slide_from_left' }} />
<Stack.Screen
@@ -171,6 +193,8 @@ function NavigationGate() {
options={{ animation: 'fade', gestureEnabled: false }}
/>
</Stack>
+ </RecentMessageHistoriesProvider>
+ </ResidentHomeListProvider>
</RemoteDesktopHost>
</NavigationThemeProvider>
);
@@ -425,6 +449,7 @@ function RootLayout() {
return (
<GestureHandlerRootView style={styles.gestureRoot}>
<SafeAreaProvider>
+ <AdaptiveWindowProvider>
<ThemeProvider>
{/* 语言 Provider 常驻 root:恢复持久化 override,覆盖含 (auth) 在内的全部屏幕 */}
<LocaleProvider>
@@ -442,6 +467,7 @@ function RootLayout() {
</MobileLoginHandoffProvider>
</LocaleProvider>
</ThemeProvider>
+ </AdaptiveWindowProvider>
</SafeAreaProvider>
</GestureHandlerRootView>
);
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsx
index b9f0175b75..81ce6e2691 100644
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@ -73,7 +73,7 @@ import {
} from '@/session/conversationSearch';
import { useConversationSearch } from '@/session/useConversationSearch';
import { sessionMatchesProjectDir } from '@/session/mobileHome';
-import { HomeSessionRow } from './index';
+import { HomeSessionRow } from '@/session/HomeSurface';
import { RenameSessionModal } from '@/session/RenameSessionModal';
import { SessionOptionsPresenter } from '@/session/SessionOptionsExpoSheet';
import { SwipeableSessionRow, type SessionSwipeControls } from '@/session/SwipeableSessionRow';
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index 86f0fe9d59..a375ea2642 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -1,5032 +1,5 @@
-import { TaskTagDots } from '@/session/TaskTags';
-import { GlassView } from "expo-glass-effect";
-import { useLiquidGlassAvailable } from "@/session/useLiquidGlassAvailable";
-import { useHeaderHeight } from "expo-router/react-navigation";
-import { SessionHeaderNativeBlur } from "@/session/SessionHeaderNativeControls";
-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 } from 'expo-router';
-import { Fragment, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject, type ReactNode } from 'react';
-import {
- ActivityIndicator,
- Alert,
- Animated,
- AppState,
- Easing,
- 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, type DeviceView, type PresenceSnapshot } from '@cindy/device-link';
-import {
- Archive,
- Check,
- ChevronDown,
- ChevronRight,
- Ellipsis,
- Folder,
- FolderOpen,
- Hammer,
- LoaderCircle,
- Menu,
- Monitor,
- MessagesSquare,
- Lock,
- Pencil,
- Pin,
- RefreshCw,
- RadioTower,
- 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 { configureCollapseAnimation } from '@/utils/collapseAnimation';
-import { useGuardedPush } from '@/utils/useGuardedPush';
-import { MobileVendorIcon } from '@/components/MobileVendorIcon';
-import {
- MainWindowActionGroup,
- MainWindowEmptyState,
- StatusDot,
-} from '@/components/MobilePrimitives';
-import { RemoteAccessGuide } from '@/components/RemoteAccessGuide';
-import { HomeChromeDrawer } from '@/session/HomeChromeDrawer';
-import { AccountSwitcherSheet } from '@/session/AccountSwitcherSheet';
-import { HomeChromeFrost } from '@/session/HomeChromeFrost';
-import { HomeGlassMenuPanel, HomeMenuScrim } from '@/session/HomeGlassMenuPanel';
-import { HomeHeaderGlassButton } from '@/session/HomeHeaderGlassButton';
-import { HomeSearchBar } from '@/session/HomeSearchBar';
-import { HomeProjectMachineLabel } from '@/session/HomeProjectMachineLabel';
-import { buildHomeProjectMachineIdentities, type HomeProjectMachineIdentity } from '@/session/homeProjectMachineIdentity';
-import {
- HomeNativeStackHeader,
- NativePullDownMenu,
- usesNativePullDownMenu,
- usesNativeStackHeader,
- usesSystemActionMenu,
-} from '@/platform/chrome';
-import {
- buildHomeDisplayPullDownActions,
- buildHomeScopePullDownActions,
- parseHomeScopePullDownAction,
- homeDisplayMenuPatch,
- type HomeDisplayMenuKey,
-} from '@/session/homeChromeMenus';
-import { useConversationSearchFilterMenu } from '@/session/useConversationSearchFilterMenu';
-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,
- serializeRemoteResourceTargets,
- 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 {
- connectionIssueHint,
- connectionIssueTitle,
- describeRemoteError,
- formatRemoteError,
-} from '@/device-link/remoteStatus';
-import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
-import { ConnectionRecoveryProgress } from '@/components/ConnectionBanner';
-import { ConnectionNoticeOverlay, useDelayedConnectionNotice } from '@/components/ConnectionNoticeOverlay';
-import { resolveConnectionBannerVisibility, resolveConnectionBannerSyncActionVisibility, resolveHomeConnectionFeedback, 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 {
- 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 {
- readHomeViewPreferences,
- saveHomeViewPreferences,
- type HomeViewPreferences,
-} from '@/session/homeViewPreferenceStore';
-import {
- getCachedHomeListSnapshot,
- scheduleHomeListSnapshotPersist,
-} from '@/session/mobileHomeListCache';
-import { startBoundedStartupRead } from '@/session/mobileHomeStartup';
-import {
- diffHomeDeviceSyncScope,
- HomeDeviceSyncLimiter,
- resolveHomeDeviceSyncIds,
- runHomeDeviceSyncBatch,
-} from '@/session/homeDeviceSync';
-import { serializeNewSessionDeviceOptions } from '@/session/newSession';
-import {
- buildRemoteSessionCardPreview,
- formatRemoteSessionSidebarTime,
- getRemoteSessionPreviewCollapse,
- type RemoteAutomationSessionGroup,
- type RemoteSessionListItem,
- type RemoteSessionLiveActivity,
- type RemoteSessionScheduleInfo,
- type RemoteSessionStatusFilter,
-} from '@/session/sessionList';
-import {
- RemoteSessionStoreSubscriptionGate,
- remoteSessionStore,
- useRemoteHomeStatusVersion,
- useRemoteMessageVersion,
- useRemoteSessionMessagePreview,
- useRemoteSessions,
- useSessionRunning,
-} from '@/session/remoteSessionStore';
-import { dataPropsEqual, mapContentEqual } from '@/utils/valueEquality';
-import { useStableValue } from '@/utils/useStableValue';
-import { useMinuteNow } from '@/utils/useMinuteNow';
-import {
- getScheduleIndexInvalidationVersion,
- invalidateOfflineScheduleIndexFailureFor,
- invalidateRunningSessionScheduleEntries,
- invalidateScheduleIndexForDevice,
- loadDeviceSessionScheduleIndex,
- replaceSessionScheduleIndexEntries,
-} from '@/session/scheduleIndex';
-import { createScheduleIndexDeferRegistry } from '@/session/scheduleIndexDefer';
-import { latestMobileSessionRow, resolveMobileSessionRowStatus } from '@/session/sessionRightStatus';
-import { AutomationTimerIcon } from '@/session/AutomationTimerIcon';
-import { RenameSessionModal } from '@/session/RenameSessionModal';
-import { SessionOptionsPresenter } from '@/session/SessionOptionsExpoSheet';
-import { SwipeableSessionRow, type SessionSwipeControls } from '@/session/SwipeableSessionRow';
-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, radius, spacing, typeScale } from '@/theme/tokens';
-
-const LIST_LIMIT = 200;
-const HOME_LIST_SUBSCRIPTION_OWNER = 'device-list';
-// 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;
-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;
-const CINDY_LIST_GUTTER = 20;
-const CINDY_LIST_FAB_SIZE = 55;
-const CINDY_LIST_FAB_BOTTOM = 45;
-const HOME_HEADER_MIN_HEIGHT = 48;
-const AnimatedPressable = Animated.createAnimatedComponent(Pressable);
-
-function estimateHomeSessionRowHeight(item: RemoteSessionListItem): number {
- 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>,
-): number {
- const rowHeight = estimateHomeSessionRowHeight(item);
- 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),
- 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';
- }
-}
+import { MobileHome } from '@/session/HomeSurface';
export default function HomeScreen() {
- const screenFocused = useIsFocused();
- return (
- <RemoteSessionStoreSubscriptionGate enabled={screenFocused}>
- <HomeScreenContent />
- </RemoteSessionStoreSubscriptionGate>
- );
-}
-
-function HomeScreenContent() {
- const screenFocused = useIsFocused();
- const screenFocusedRef = useRef(screenFocused);
- screenFocusedRef.current = screenFocused;
- const styles = useThemedStyles(makeStyles);
- const { colors, mode } = useTheme();
- const liquidGlass = useLiquidGlassAvailable();
- const { t, i18n: i18nInstance } = useTranslation();
- // 所有前进导航(进会话 / 新建 / 设置 / 组页面)统一走守卫 push:列表卡顿时的
- // 连点会各自触发一次裸 push,把同一页压进栈 N 层(返回也要 N 次)。
- const guardedPush = useGuardedPush();
- const { width: screenWidth, height: screenHeight } = useWindowDimensions();
- const auth = useAuth();
- const { accountGeneration, deviceId: selfDeviceId, user } = auth;
- // 首页列表持久缓存按账号键控(401 掉线换号不串数据);首页仅登录后可达,user 理应非空。
- const homeCacheUserId = user?.id ?? '';
- const {
- connectionEpoch,
- connectionIssue,
- invoke,
- lastPresenceSnapshot,
- recoveringDeviceIds,
- readDeviceList,
- status,
- subscribe,
- unsubscribe,
- } = useDeviceLink();
- const revokedDevices = useRevokedDevices();
- const sessions = useRemoteSessions();
- 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>());
- 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(false);
- const [refreshing, setRefreshing] = useState(false);
- const [error, setError] = useState<HomeConnectionError>(null);
- const [lastSyncedAt, setLastSyncedAt] = useState<number | null>(null);
- const [selectedDeviceId, setSelectedDeviceId] = useState<string | null>(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);
- selectedDeviceIdRef.current = selectedDeviceId;
- const [searchOpen, setSearchOpen] = useState(false);
- const [searchFilterOpen, setSearchFilterOpen] = useState(false);
- // 恢复偏好时暂存的设备名:设备列表尚未同步回来前表头用它兜底,避免显示成占位文案。
- const [restoredDeviceName, setRestoredDeviceName] = useState<string | null>(null);
- // 用户已手动切换过筛选/分组后,迟到的偏好恢复不再覆盖用户操作。
- const viewPrefsTouchedRef = useRef(false);
- const leftHomeForSessionRef = useRef(false);
- // 恢复自偏好的设备选择还没做过首次同步后的可用性校验(一次性,校验后或用户手动选择后清掉)。
- const restoredSelectionUnvalidatedRef = useRef(false);
- const [deviceMenuOpen, setDeviceMenuOpen] = useState(false);
- const [displaySettingsOpen, setDisplaySettingsOpen] = useState(false);
- const [chromeMenuOpen, setChromeMenuOpen] = useState(false);
- const [accountSwitcherOpen, setAccountSwitcherOpen] = useState(false);
- const [chromeMenuCloseInstant, setChromeMenuCloseInstant] = 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);
- const {
- actionSheetSession,
- archiveSession,
- closeRenameSession,
- confirmRenameSession,
- handleSessionSheetAction,
- handleSessionSheetClosed,
- renameSessionDraft,
- renameSessionTarget,
- sessionSwipeControls,
- setActionSheetSession,
- setRenameSessionDraft,
- showSessionOptions,
- swipeRegistry,
- toggleSessionPinned,
- } = useSessionListActions();
- // 实测 header 高度(onLayout),用于下拉菜单定位;字体放大等导致 header 超过 HOME_HEADER_MIN_HEIGHT 时不再错位。
- const [headerHeight, setHeaderHeight] = useState<number | null>(null);
- const [headerFrosted, setHeaderFrosted] = useState(false);
- const [groupByProject, setGroupByProject] = useState(true);
- const [groupDialogue, setGroupDialogue] = useState(false);
- const [sortBy, setSortBy] = useState<HomeListSortBy>('recency');
- const [projectOrder, setProjectOrder] = useState<HomeProjectOrder>('activity');
- const [manualProjectOrder, setManualProjectOrder] = useState<string[]>([]);
- 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 homeScrollY = useSharedValue(0);
- const [dialogueShowAll, setDialogueShowAll] = useState(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] = useState<HomeStatusFilter>('active');
- const [collapsedProjectKeys, setCollapsedProjectKeys] = useState<string[]>([]);
- const [pinnedCollapsed, setPinnedCollapsed] = useState(false);
- // 已展开的自动化组 key(页面级 state:SectionList 虚拟化回收行组件时展开态不丢)。
- const [expandedAutomationGroups, setExpandedAutomationGroups] = useState<string[]>([]);
- 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();
- 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);
- setSelectedDeviceId(null);
- setRestoredDeviceName(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 (
- (!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);
- }, [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);
- releaseHomeListOwner(deviceId);
- }
- for (const deviceId of diff.acquire) {
- advanceHomeSyncGeneration(deviceId);
- }
- return diff;
- }, [advanceHomeSyncGeneration, releaseHomeListOwner]);
-
- 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);
- }
- }, [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 再补最新窗口。
- 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 },
- ) => {
- if (!screenFocusedRef.current || AppState.currentState !== 'active') return;
- const expectedAccountGeneration = options?.accountGeneration ?? accountGeneration;
- const expectedHomeSyncGeneration = options?.homeSyncGeneration
- ?? homeSyncGenerationByDeviceRef.current.get(deviceId);
- if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
- 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,
- ));
- })
- .catch(() => {
- // 网络失败时保留旧数据,不清零已有徽标——数据清零只应由明确的"已读"事件触发。
- });
- }, [accountGeneration, invoke, isCurrentHomeSyncTarget]);
-
- 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');
- 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,
- remoteListStatusFilter(statusFilter),
- { includePinned: true, fresh: true },
- ]);
- return [list, 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 },
- ]).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 (Array.isArray(activeSessions)) {
- remoteSessionStore.setActiveSessionSnapshots(
- device.deviceId,
- activeSessions,
- activeSessionSnapshotEpoch,
- );
- }
- });
- // schedule-index(1+N 个 listRuns)是次要徽标数据,延后发,避开"开 app→立刻点会话"时和会话关键读
- // 抢同一条 WS 管道(见 scheduleIndexDefer / issue #324)。home 自动化分组与名称已由 fallbackScheduleInfo
- // 兜底,徽标晚半拍出现即可。
- // 按设备 id 登记:同设备上一轮还没执行的延后任务会被先取消,避免较早回调用旧 nextSessions 覆盖新状态。
- 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,
- });
- })();
- });
- 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);
- if (offline) markDeviceOffline(device.deviceId);
- updateDeviceConnectionState(device.deviceId, 'failed');
- return {
- failure: { deviceId: device.deviceId, deviceName: device.name, error: formatRemoteError(err) },
- offline,
- superseded: false,
- };
- }
- }, 'foreground'), [homeCacheUserId, invoke, isCurrentHomeSyncTarget, markDeviceOffline, refreshDeviceScheduleIndex, statusFilter, subscribe, updateDeviceConnectionState]);
-
- const hydrateDeviceSessions = useCallback((
- device: DeviceView,
- expectedAccountGeneration = accountGeneration,
- options: { trailingIfInFlight?: boolean } = {},
- ): Promise<HydrateDeviceSessionsResult> => {
- const expectedHomeSyncGeneration = homeSyncGenerationByDeviceRef.current.get(device.deviceId);
- if (
- expectedHomeSyncGeneration === undefined
- || 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, 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 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');
- }
- return readDeviceList();
- },
- { maxAttempts: 3 },
- );
- if (homeAccountGenerationRef.current !== accountGenerationAtStart) 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 && !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 (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]);
- 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(),
- null,
- );
- const applyPreferences = (preferences: HomeViewPreferences | null) => {
- if (!preferences) 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);
- if (preferences.selectedDevice) {
- setSelectedDeviceId(preferences.selectedDevice.deviceId);
- setRestoredDeviceName(preferences.selectedDevice.name);
- restoredSelectionUnvalidatedRef.current = true;
- }
- };
- 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) 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;
- }
- refreshDeviceScheduleIndex(deviceId, sessionIds);
- }
- }), [refreshDeviceScheduleIndex]);
-
- // 从自动化 / 会话页返回首页时,兜底刷新一次 scheduleIndex:
- // markScheduleRunsRead 的桌面广播若在导航切换途中丢失(silent swallow / 弱网 / tap listener
- // 未挂),之前依赖 remoteScheduleEventStore.subscribe 的路径就永远不会补跑,首页那颗
- // "已完成未读"绿点会一直挂着。useFocusEffect 每次 focus 都按当前设备清一遍未读徽标,
- // 命中真实变化才会 setScheduleIndex(entries 等值比较),不触发无谓 re-render。
- useFocusEffect(
- useCallback(() => {
- for (const device of devicesRef.current) {
- if (!homeSyncTargetDeviceIdsRef.current.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 种回去。
- const startSilentHomeSync = useCallback(() => {
- if (!deviceIdentityCacheReady || !homeListCacheHydrated || !homeViewPreferencesHydrated) return;
- void loadHome({ visible: false });
- }, [deviceIdentityCacheReady, homeListCacheHydrated, homeViewPreferencesHydrated, loadHome]);
-
- // 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(() => {
- startSilentHomeSync();
- }, [startSilentHomeSync]),
- );
-
- useEffect(() => {
- startSilentHomeSync();
- const subscription = AppState.addEventListener('change', (nextState) => {
- 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;
- setDisplaySettingsOpen(false);
- setChromeMenuOpen(false);
- setDeviceMenuOpen(true);
- }, []);
-
- const openChromeMenu = useCallback(() => {
- pendingMenuActionRef.current = null;
- setDeviceMenuOpen(false);
- setDisplaySettingsOpen(false);
- setChromeMenuCloseInstant(false);
- setChromeMenuOpen(true);
- }, []);
-
- const openDisplaySettings = useCallback(() => {
- pendingMenuActionRef.current = null;
- setDeviceMenuOpen(false);
- setChromeMenuOpen(false);
- setDisplaySettingsOpen(true);
- }, []);
-
- const onListScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
- homeScrollY.value = event.nativeEvent.contentOffset.y;
- const next = event.nativeEvent.contentOffset.y > 8;
- setHeaderFrosted((current) => (current === next ? current : next));
- }, [homeScrollY]);
-
- const deviceRows = useMemo(
- () => toDeviceListItems(devices, Date.now(), revokedDevices),
- [devices, i18nInstance.resolvedLanguage, revokedDevices],
- );
- const homeSyncDeviceIds = useMemo(() => resolveHomeDeviceSyncIds(
- deviceRows.map((item) => ({
- canOpen: item.canOpen,
- deviceId: item.device.deviceId,
- })),
- selectedDeviceId,
- ), [deviceRows, selectedDeviceId]);
- const homeSyncDeviceIdSet = useMemo(() => new Set(homeSyncDeviceIds), [homeSyncDeviceIds]);
- const homeSyncRows = useMemo(
- () => deviceRows.filter((item) => homeSyncDeviceIdSet.has(item.device.deviceId)),
- [deviceRows, homeSyncDeviceIdSet],
- );
-
- useEffect(() => {
- const expectedAccountGeneration = accountGeneration;
- const selectedDeviceIdAtStart = selectedDeviceId;
- 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, () => {
- 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(
- invoke,
- 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)),
- ),
- [searchOrigins, sessions],
- );
- const indexedSearch = useConversationSearch({
- enabled: true,
- origins: searchOrigins,
- projects: searchProjects,
- });
- 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({
- 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],
- );
- const projectMachineIdentities = useMemo(
- () => buildHomeProjectMachineIdentities(home, deviceConnectionStates),
- [home, deviceConnectionStates],
- );
- 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],
- );
- 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 = selectedDeviceId && selectedHostOrder
- ? controllerKeysFromHost(selectedDeviceId, selectedHostOrder)
- : [];
- const displayed = resolveDisplayedProjectOrder(
- resolveProjectOrderWriteScope(selectedDeviceId ? [selectedDeviceId] : 'all', 'local'),
- selectedHostOrder,
- { manualProjectOrder, projectOrder },
- hostManualProjectOrder,
- );
- const displayedProjectOrder = displayed.projectOrder;
- const displayedManualProjectOrder = displayed.manualProjectOrder;
- const homeSections = useMemo(
- () => buildHomeSections(home, groupByProject, pinnedCollapsed, {
- dialogueTitle: t('devices.list.menu.dialogueFolder'),
- groupDialogue,
- manualProjectOrder: displayedManualProjectOrder,
- priorityContext,
- projectOrder: displayedProjectOrder,
- sortBy,
- }),
- [displayedManualProjectOrder, displayedProjectOrder, groupByProject, groupDialogue, home, pinnedCollapsed, priorityContext, 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 initialHomeLoading = !initialHomeSettled && !connectionError;
- const initialHomeError = !initialHomeSettled && !!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 selectedDeviceDisconnected = status !== 'connecting' && home.deviceFilters.some((item) => item.deviceId !== null
- && (!selectedDeviceId || item.deviceId === selectedDeviceId) && item.sessionCount > 0)
- && !home.deviceFilters.some((item) => item.deviceId !== null
- && (!selectedDeviceId || item.deviceId === selectedDeviceId) && item.available);
- const showConnectionRow = 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 = 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 = (!activeConnectionIssue
- || activeConnectionIssue.kind === 'unstable' || activeConnectionIssue.kind === 'replaced')
- && (status === 'connecting' || homeDeviceRecovery);
- const connectionTone = activeConnectionIssue
- ? 'off'
- : homeDeviceRecovery ? 'busy' : selectedDeviceDisconnected ? 'off' : connectionError ? 'muted' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';
- const connectionTitle = activeConnectionIssue
- ? connectionIssueTitle(activeConnectionIssue.kind)
- : homeDeviceRecovery ? t(homeDeviceUnresponsive ? 'deviceLink.deviceUnresponsiveTitle' : 'deviceLink.recovery.syncing')
- : selectedDeviceDisconnected ? t('deviceLink.cachedHistory.title') : connectionError ? t('devices.list.syncFailed') : homeConnectionTitle(status, t);
- const connectionCopy = activeConnectionIssue
- ? connectionIssueHint(activeConnectionIssue.kind)
- : homeDeviceRecovery ? t(homeDeviceUnresponsive ? 'deviceLink.deviceUnresponsiveHint' : 'deviceLink.recovery.syncingHint') : selectedDeviceDisconnected ? t('deviceLink.cachedHistory.hint') : connectionError;
- const emptyStateTitle = initialHomeError ? t('devices.list.syncFailed') : home.emptyTitle;
- const emptyStateCopy = initialHomeError ? (connectionError ?? t('devices.list.requestFailed')) : home.emptyCopy;
- // 无可控制电脑的引导态(landing)可见性,与 ListEmptyComponent 的分支同口径。
- // 引导态下首页没有可筛选的对话:表头「所有对话 ▾」退化为纯品牌标题、新建 FAB 隐藏,
- // 避免在产品说明页上摆一堆无意义的入口。
- const homeListItemCount = 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',
- // 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,
- });
- 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 openSession = useCallback((item: RemoteSessionListItem) => {
- // 有行处于滑开状态时,点击(本行或他行)只负责收起,不进会话(iOS 列表滑动操作惯例)。
- if (swipeRegistry.closeOpenRow()) return;
- holdViewedPriorityRank(homeViewedPriorityHold, item.session.id, priorityContext);
- advanceViewedPriorityHold(homeViewedPriorityHold, item.session.id, priorityContext, Date.now());
- leftHomeForSessionRef.current = true;
- setPriorityHoldEpoch((epoch) => epoch + 1);
- 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;
- guardedPush({
- pathname: '/sessions/[sessionId]',
- params: {
- deviceId,
- deviceName: session.deviceLinkDeviceName ?? deviceId,
- sessionId: session.id,
- ...(focusClientId ? { focusClientId } : {}),
- },
- });
- }, [guardedPush, priorityContext, swipeRegistry, t]);
-
- const openNewSession = useCallback((project?: MobileHomeProjectGroup, suggestion?: RemoteTaskSuggestionId, explicitDeviceId?: string) => {
- const deviceId = project?.deviceId ?? explicitDeviceId ?? home.primaryDevice?.deviceId;
- const deviceName = project?.deviceName ?? newSessionDeviceOptions.find((device) => device.deviceId === deviceId)?.name ?? home.primaryDevice?.label ?? deviceId ?? '';
- if (!deviceId) {
- setError(t('devices.list.error.noDevice'));
- return;
- }
- guardedPush({
- pathname: '/sessions/new',
- params: {
- deviceId,
- deviceName,
- deviceOptions: serializeNewSessionDeviceOptions(newSessionDeviceOptions),
- ...(suggestion ? { suggestion } : {}),
- ...(project?.workingDir ? { workingDir: project.workingDir } : {}),
- // 列表正筛选某台电脑时,新建默认跟随这台电脑(显式指定,盖过"上次选择"的
- // 记忆);推荐入口固定使用已通过就绪检查的电脑,普通新建仍可恢复记忆设备。
- ...(selectedDeviceId || explicitDeviceId ? { deviceExplicit: '1' } : {}),
- },
- });
- }, [guardedPush, home.primaryDevice, newSessionDeviceOptions, selectedDeviceId, t]);
-
- const openSuggestedSession = useCallback((suggestion?: RemoteTaskSuggestionId) => {
- openNewSession(undefined, suggestion, taskSuggestionsDeviceId);
- }, [openNewSession, taskSuggestionsDeviceId]);
-
- const logout = useCallback(async () => {
- if (loggingOut) return;
- setLoggingOut(true);
- try {
- await auth.logout();
- } catch (error) {
- Alert.alert(t('devices.list.alert.actionFailed'), formatRemoteError(error));
- } finally {
- setLoggingOut(false);
- }
- }, [auth, loggingOut, t]);
-
- const toggleProject = useCallback((key: string) => {
- configureCollapseAnimation();
- setCollapsedProjectKeys((current) =>
- current.includes(key) ? current.filter((item) => item !== key) : [...current, key]);
- }, []);
-
- const showAllDialogueSessions = useCallback(() => {
- setDialogueShowAll(true);
- }, []);
-
- const applyDisplayView = useCallback((patch: {
- groupByProject?: boolean;
- groupDialogue?: boolean;
- sortBy?: HomeListSortBy;
- statusFilter?: HomeStatusFilter;
- projectOrder?: HomeProjectOrder;
- 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 (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;
- }) => {
- 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]);
-
- 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) {
- const visibleKeys = home.projects
- .filter((item) => item.kind !== 'cindy-make' && item.deviceId === selectedDeviceId)
- .map((item) => item.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) => {
- configureCollapseAnimation();
- setExpandedAutomationGroups((current) =>
- current.includes(key) ? current.filter((item) => item !== key) : [...current, key]);
- }, []);
-
- // 自动化组「查看全部 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: session.deviceLinkDeviceName ?? deviceId,
- automationGroupKey: group.baseKey,
- automationName: group.title,
- ...(workingDir ? { automationWorkingDir: workingDir } : {}),
- // 快照兜底:目标页 scheduleIndex 尚未加载完成时,先按这批 id 立即显示组内运行,
- // index 就绪后再与组键匹配结果取并集(能捕获新产生的 run)。
- automationSessionIds: JSON.stringify(group.sessionIds),
- },
- });
- }, [guardedPush, t]);
-
- // 置顶组与项目组一致:点表头收起/展开,共用同一条收起动画。
- const togglePinned = useCallback(() => {
- configureCollapseAnimation();
- setPinnedCollapsed((collapsed) => !collapsed);
- }, []);
-
- const openProjectSessions = useCallback((project: MobileHomeProjectGroup) => {
- if (!project.deviceId) return;
- guardedPush({
- pathname: '/devices/[deviceId]',
- // 带上 workingDir + 项目名,让目标页只显示「这个项目」的会话(名副其实地"查看全部 N 条")。
- // 未归类组(workingDir 为空)不传过滤参数,退化为整台设备的会话列表。
- // statusFilter 跟首页当前筛选走,归档/全部入口不能掉回默认 active。
- params: {
- deviceId: project.deviceId,
- name: project.deviceName,
- statusFilter,
- ...(project.workingDir
- ? { workingDir: project.workingDir, projectName: project.title }
- : {}),
- },
- });
- }, [guardedPush, statusFilter]);
-
- // 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}
- 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,
- 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,
- });
-
- const selectHomeScope = useCallback((item: MobileHomeDeviceFilterItem) => {
- if (item.deviceId && item.state === 'access_revoked') {
- const deviceId = item.deviceId;
- if (usesSystemActionMenu()) {
- setRevokedTipDeviceId(deviceId);
- return;
- }
- 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,
- });
- }, []);
-
- const nativeHomeMenus = usesNativePullDownMenu();
- const homeScopePullDownActions = useMemo(
- () => buildHomeScopePullDownActions(
- home.deviceFilters,
- t('devices.list.allConversations'),
- remoteHomeCollections.map((collection) => ({
- id: collection.id,
- title: collection.title,
- })),
- ),
- [home.deviceFilters, remoteHomeCollections, t],
- );
- const handleHomeScopeAction = useCallback((id: string) => {
- const parsed = parseHomeScopePullDownAction(id);
- if (parsed.kind === 'collection') {
- const collection = remoteHomeCollections.find((item) => item.id === parsed.collectionId);
- if (!collection) return;
- guardedPush({
- pathname: '/resources/[collectionId]',
- params: {
- collectionId: collection.id,
- title: collection.title,
- targets: serializeRemoteResourceTargets(collection.targets),
- },
- });
- return;
- }
- const item = home.deviceFilters.find((filter) => filter.id === parsed.filterId);
- if (item) selectHomeScope(item);
- }, [guardedPush, home.deviceFilters, remoteHomeCollections, selectHomeScope]);
- const homeDisplayPullDownActions = useMemo(
- () => buildHomeDisplayPullDownActions({
- groupByProject,
- groupByProjectLabel: t('devices.list.menu.groupByProject'),
- groupDialogue,
- groupDialogueLabel: t('devices.list.menu.groupDialogue'),
- groupHeading: t('devices.list.menu.groupHeading'),
- projectOrder: displayedProjectOrder,
- projectOrderActivityLabel: t('devices.list.menu.projectOrderActivity'),
- projectOrderCustomLabel: t('devices.list.menu.projectOrderManual'),
- projectOrderHeading: t('devices.list.menu.projectOrderHeading'),
- showProjectOrder: true,
- sortBy,
- sortByPriorityLabel: t('devices.list.menu.sortByPriority'),
- sortByTimeLabel: t('devices.list.menu.sortByTime'),
- sortHeading: t('devices.list.menu.sortHeading'),
- statusActiveLabel: t('devices.list.menu.statusActive'),
- statusAllLabel: t('devices.list.menu.statusAll'),
- statusArchivedLabel: t('devices.list.menu.statusArchived'),
- statusFilter,
- statusHeading: t('devices.list.menu.statusHeading'),
- }),
- [displayedProjectOrder, groupByProject, groupDialogue, sortBy, statusFilter, t],
- );
- 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 = usesNativeStackHeader();
- const nativeHeaderHeight = useHeaderHeight();
- const chromeHeight = nativeHomeHeader
- ? nativeHeaderHeight + (headerHeight ?? 0)
- : (headerHeight ?? edgePadding.paddingTop + HOME_HEADER_MIN_HEIGHT);
- return (
- <View
- ref={homeRootRef}
- style={[styles.safeArea, { paddingLeft: edgePadding.paddingLeft, paddingRight: edgePadding.paddingRight }]}
- testID="devices.screen"
- >
- {nativeHomeHeader ? <SessionHeaderNativeBlur height={nativeHeaderHeight + spacing.xxl} /> : null}
- {nativeHomeHeader ? (
- <HomeNativeStackHeader
- syncing={quietSyncing}
- displayA11y={t('devices.list.a11y.openDisplaySettings')}
- displayActions={homeDisplayPullDownActions}
- menuA11y={t('devices.list.a11y.openMenu')}
- onDisplayAction={(id) => {
- applyDisplayView(homeDisplayMenuPatch(id as HomeDisplayMenuKey, {
- groupByProject,
- groupDialogue,
- }));
- }}
- onOpenDeviceMenu={openDeviceMenu}
- onOpenDisplaySettings={openDisplaySettings}
- 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 : edgePadding.paddingTop }}>
- {nativeHomeHeader ? null : (
- <View style={styles.homeHeader}>
- <HomeHeaderGlassButton
- accessibilityLabel={t('devices.list.a11y.openMenu')}
- onPress={openChromeMenu}
- testID="home.chromeMenu"
- >
- <Menu color={colors.textPrimary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
- </HomeHeaderGlassButton>
- {showRemoteGuide ? (
- // 引导态没有可筛选的范围:正中只留品牌标题。
- <View style={styles.headerTitleWrap} testID="devices.title">
- <Text style={styles.headerTitle} numberOfLines={1}>Cindy</Text>
- </View>
- ) : (
- <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, pressed && styles.pressed]}
- testID="devices.title"
- >
- <View style={styles.headerTitleCluster}>
- <Text style={styles.headerTitle} numberOfLines={1}>{selectedDeviceLabel}</Text>
- <ChevronDown color={colors.textSecondary} size={iconSize.xs} strokeWidth={iconStroke.medium} />
- <QuietSyncIndicator active={quietSyncing} />
- </View>
- </Pressable>
- </NativePullDownMenu>
- )}
- {showRemoteGuide ? (
- <View style={styles.headerIconButton} />
- ) : (
- <View style={styles.headerActions}>
- {selectedDeviceId ? (
- <HomeHeaderGlassButton accessibilityLabel={t('remoteDesktop.title')} onPress={openSelectedRemoteDesktop} testID="home.remoteDesktopButton">
- <Monitor color={colors.textPrimary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
- </HomeHeaderGlassButton>
- ) : null}
- <NativePullDownMenu
- actions={homeDisplayPullDownActions}
- onAction={(id) => applyDisplayView(homeDisplayMenuPatch(id as HomeDisplayMenuKey, { groupByProject, groupDialogue }))}
- >
- <HomeHeaderGlassButton accessibilityLabel={t('devices.list.a11y.openDisplaySettings')} onPress={nativeHomeMenus ? () => undefined : openDisplaySettings} testID="home.displaySettingsButton">
- <Ellipsis color={colors.textPrimary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
- </HomeHeaderGlassButton>
- </NativePullDownMenu>
- </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={!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}
- onPress={() => void loadHome({ visible: true })}
- 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>
-
- <SectionList
- sections={sections}
- style={styles.homeList}
- keyExtractor={(item) => item.key}
- initialNumToRender={HOME_LIST_INITIAL_RENDER_COUNT}
- maxToRenderPerBatch={HOME_LIST_RENDER_BATCH_SIZE}
- updateCellsBatchingPeriod={32}
- windowSize={HOME_LIST_WINDOW_SIZE}
- refreshControl={
- <RefreshControl
- progressViewOffset={chromeHeight}
- refreshing={refreshing}
- onRefresh={() => void loadHome({ visible: true })}
- />
- }
- scrollEnabled={projectDrag === null}
- stickySectionHeadersEnabled={false}
- contentContainerStyle={[
- styles.listContent,
- {
- paddingBottom: 83 + insets.bottom,
- paddingTop: chromeHeight,
- },
- ]}
- onScroll={onListScroll}
- scrollEventThrottle={16}
- onScrollBeginDrag={() => {
- // 列表开始滚动即收起已滑开的行(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: home.pinned.length })}
- accessibilityRole="button"
- accessibilityState={{ expanded: !pinnedCollapsed }}
- onPress={togglePinned}
- 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}>{home.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={
- initialHomeLoading || taskSuggestionsPending ? (
- <HomeInitialLoadingState
- style={{
- marginTop: spacing.xxl,
- minHeight: windowLayout.emptyMinHeight,
- padding: windowLayout.emptyPadding,
- }}
- />
- ) : home.pinned.length > 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}
- />
- ) : 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}
- />
-
- {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}
-
- {showRemoteGuide || taskSuggestionsPending || taskSuggestionsMode === 'empty' ? null : (
- // 无可控电脑时不提供入口;完整空态已有主按钮,避免重复显示新建 CTA。
- <Pressable
- accessibilityLabel={t('devices.list.a11y.newRemoteConversation')}
- accessibilityRole="button"
- accessibilityState={{ busy: initialHomeLoading || undefined, disabled: newSessionDisabled }}
- disabled={newSessionDisabled}
- onPress={() => openNewSession()}
- style={({ pressed }) => [
- styles.newChatButton,
- liquidGlass && styles.newChatButtonTransparent,
- { bottom: CINDY_LIST_FAB_BOTTOM + insets.bottom },
- pressed && styles.pressed,
- newSessionDisabled && styles.disabled,
- ]}
- testID="home.newChatButton"
- >
- {liquidGlass ? (
- <GlassView colorScheme={mode} glassEffectStyle="regular" tintColor={`${colors.homeListFab}B3`} isInteractive style={styles.newChatGlass}>
- <View pointerEvents="none" style={styles.newChatGlassIcon}>
- <SquarePen color={colors.ctaText} size={iconSize.xxl} strokeWidth={iconStroke.regular} />
- </View>
- </GlassView>
- ) : (
- <SquarePen color={colors.ctaText} size={iconSize.xxl} strokeWidth={iconStroke.regular} />
- )}
- </Pressable>
- )}
-
- <RevokedAccessTip
- deviceName={revokedTipDeviceName}
- retrying={revokedTipDeviceId !== null && retryingDeviceIds.has(revokedTipDeviceId)}
- onClose={() => setRevokedTipDeviceId(null)}
- onRetry={() => {
- if (revokedTipDeviceId) void retryRevokedDevice(revokedTipDeviceId);
- }}
- />
- <DeviceMenuModal
- collections={remoteHomeCollections}
- connectionStates={deviceConnectionStates}
- filters={home.deviceFilters}
- onClose={() => setDeviceMenuOpen(false)}
- onClosed={handleDeviceMenuClosed}
- onSelectCollection={(collection) => {
- setDeviceMenuOpen(false);
- guardedPush({
- pathname: '/resources/[collectionId]',
- params: {
- collectionId: collection.id,
- title: collection.title,
- targets: serializeRemoteResourceTargets(collection.targets),
- },
- });
- }}
- 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}
- />
- <HomeChromeDrawer
- closeInstant={chromeMenuCloseInstant}
- loggingOut={loggingOut}
- onClose={() => {
- setChromeMenuCloseInstant(false);
- setChromeMenuOpen(false);
- }}
- onClosed={() => {
- setChromeMenuCloseInstant(false);
- handleChromeMenuClosed();
- }}
- onOpenSearch={() => {
- setSearchOpen(true);
- setChromeMenuCloseInstant(false);
- setChromeMenuOpen(false);
- }}
- onOpenAccounts={() => {
- pendingMenuActionRef.current = () => setAccountSwitcherOpen(true);
- setChromeMenuCloseInstant(false);
- setChromeMenuOpen(false);
- }}
- onOpenDevices={() => {
- pendingMenuActionRef.current = null;
- guardedPush('/devices/manage');
- setChromeMenuCloseInstant(true);
- setChromeMenuOpen(false);
- }}
- onOpenSettings={() => {
- pendingMenuActionRef.current = null;
- guardedPush('/settings');
- setChromeMenuCloseInstant(true);
- setChromeMenuOpen(false);
- }}
- onLogout={() => void logout()}
- open={chromeMenuOpen}
- user={user}
- />
- <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}
- />
- <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}
- />
- <HomeDisplaySettingsModal
- groupByProject={groupByProject}
- groupDialogue={groupDialogue}
- onChangeView={applyDisplayView}
- onClose={() => setDisplaySettingsOpen(false)}
- projectOrder={displayedProjectOrder}
- sortBy={sortBy}
- statusFilter={statusFilter}
- topOffset={chromeHeight}
- visible={displaySettingsOpen}
- />
- <SessionOptionsPresenter
- session={actionSheetSession}
- onAction={handleSessionSheetAction}
- onClose={() => setActionSheetSession(null)}
- onClosed={handleSessionSheetClosed}
- pinnedAt={actionSheetSession?.pinnedAt}
- status={actionSheetSession?.status}
- visible={actionSheetSession !== null}
- />
- <RenameSessionModal
- draft={renameSessionDraft}
- onCancel={closeRenameSession}
- onChangeDraft={setRenameSessionDraft}
- onConfirm={confirmRenameSession}
- // 乐观提交:确认即关弹窗,不存在挂起中的保存态。
- saving={false}
- visible={renameSessionTarget !== null}
- />
- </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,
- connectionStates,
- filters,
- onClose,
- onClosed,
- onSelect,
- onSelectCollection,
- topOffset,
- visible,
-}: {
- collections: readonly RemoteHomeCollection[];
- connectionStates: Record<string, HomeDeviceConnectionState>;
- 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:展开用 ≤150ms 纯透明度过渡(不做位移/缩放),关闭淡出后再卸载 Modal。
- // mounted/progress/进场时机(onShow)/onClosed 延迟触发(等 Modal 真正卸载的 commit
- // 完成,避免 iOS present-during-dismiss 吞掉第二个弹窗)统一走 useModalFadeLifecycle。
- const { mounted, progress, onShowStartIn } = useModalFadeLifecycle(visible, {
- inMs: 140,
- outMs: 110,
- onClosed,
- });
- const allFilter = filters.find((item) => item.deviceId === null) ?? null;
- // 离线电脑保留缓存入口;关远控和撤权不由缓存恢复访问权限。
- 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
- connectionState={item.deviceId ? connectionStates[item.deviceId] ?? 'idle' : 'idle'}
- dimmed={!canBrowseMobileHomeDevice(item)}
- key={item.id}
- label={item.label}
- onPress={() => onSelect(item)}
- selected={item.selected}
- status={deviceMenuStatus(item)}
- testID={item.deviceId ? `home.deviceChip.${sanitizeDeviceChipTestId(item.deviceId)}` : undefined}
- />
- ))}
- </ScrollView>
- </HomeGlassMenuPanel>
- </HomeMenuScrim>
- );
-}
-
-function HomeDisplaySettingsModal({
- groupByProject,
- groupDialogue,
- onChangeView,
- onClose,
- projectOrder,
- showProjectOrder = true,
- sortBy,
- statusFilter,
- topOffset,
- visible,
-}: {
- groupByProject: boolean;
- groupDialogue: boolean;
- onChangeView(patch: {
- groupByProject?: boolean;
- groupDialogue?: boolean;
- sortBy?: HomeListSortBy;
- statusFilter?: HomeStatusFilter;
- projectOrder?: HomeProjectOrder;
- manualProjectOrder?: string[];
- }): void;
- onClose(): void;
- projectOrder: HomeProjectOrder;
- showProjectOrder?: boolean;
- sortBy: HomeListSortBy;
- statusFilter: HomeStatusFilter;
- topOffset: number;
- visible: boolean;
-}) {
- const styles = useThemedStyles(makeStyles);
- const { t } = useTranslation();
- const { height: screenHeight } = useWindowDimensions();
- const insets = useSafeAreaInsets();
- const scrollMaxHeight = Math.max(200, screenHeight - topOffset - insets.bottom - 24);
- const { mounted, progress, onShowStartIn } = useModalFadeLifecycle(visible, {
- inMs: 140,
- outMs: 110,
- });
- return (
- <HomeMenuScrim
- backdropTestID="home.displaySettings.backdrop"
- onClose={onClose}
- onShow={onShowStartIn}
- progress={progress}
- topOffset={topOffset}
- visible={mounted}
- >
- <HomeGlassMenuPanel style={styles.deviceMenuPanelEnd} testID="home.displaySettings">
- <ScrollView style={[styles.deviceMenuScroll, { maxHeight: scrollMaxHeight }]} showsVerticalScrollIndicator>
- <Text style={styles.deviceMenuSectionLabel}>{t('devices.list.menu.groupHeading')}</Text>
- <DeviceMenuItem
- checked={groupByProject}
- label={t('devices.list.menu.groupByProject')}
- onPress={() => onChangeView({ groupByProject: !groupByProject })}
- selected={false}
- testID="home.deviceMenu.groupByProject"
- />
- <DeviceMenuItem
- checked={groupDialogue}
- label={t('devices.list.menu.groupDialogue')}
- onPress={() => onChangeView({ groupDialogue: !groupDialogue })}
- selected={false}
- testID="home.deviceMenu.groupDialogue"
- />
- <View style={styles.deviceMenuDivider} />
- <Text style={styles.deviceMenuSectionLabel}>{t('devices.list.menu.sortHeading')}</Text>
- <DeviceMenuItem
- label={t('devices.list.menu.sortByTime')}
- onPress={() => onChangeView({ sortBy: 'recency' })}
- selected={sortBy === 'recency'}
- testID="home.deviceMenu.sort.recency"
- />
- <DeviceMenuItem
- label={t('devices.list.menu.sortByPriority')}
- onPress={() => onChangeView({ sortBy: 'priority' })}
- selected={sortBy === 'priority'}
- testID="home.deviceMenu.sort.priority"
- />
- {groupByProject && showProjectOrder ? (
- <>
- <View style={styles.deviceMenuDivider} />
- <Text style={styles.deviceMenuSectionLabel}>{t('devices.list.menu.projectOrderHeading')}</Text>
- <DeviceMenuItem
- label={t('devices.list.menu.projectOrderActivity')}
- onPress={() => onChangeView({ projectOrder: 'activity' })}
- selected={projectOrder === 'activity'}
- testID="home.deviceMenu.projectOrder.activity"
- />
- <DeviceMenuItem
- label={t('devices.list.menu.projectOrderManual')}
- onPress={() => onChangeView({ projectOrder: 'custom' })}
- selected={projectOrder === 'custom'}
- testID="home.deviceMenu.projectOrder.custom"
- />
- {projectOrder === 'custom' ? (
- <Text style={styles.deviceMenuHint}>{t('devices.list.menu.projectOrderManualTip')}</Text>
- ) : null}
- </>
- ) : null}
- <View style={styles.deviceMenuDivider} />
- <Text style={styles.deviceMenuSectionLabel}>{t('devices.list.menu.statusHeading')}</Text>
- <DeviceMenuItem
- label={t('devices.list.menu.statusActive')}
- onPress={() => onChangeView({ statusFilter: 'active' })}
- selected={statusFilter === 'active'}
- testID="home.deviceMenu.status.active"
- />
- <DeviceMenuItem
- label={t('devices.list.menu.statusArchived')}
- onPress={() => onChangeView({ statusFilter: 'archived' })}
- selected={statusFilter === 'archived'}
- testID="home.deviceMenu.status.archived"
- />
- <DeviceMenuItem
- label={t('devices.list.menu.statusAll')}
- onPress={() => onChangeView({ statusFilter: 'all' })}
- selected={statusFilter === 'all'}
- testID="home.deviceMenu.status.all"
- />
- </ScrollView>
- </HomeGlassMenuPanel>
- </HomeMenuScrim>
- );
-}
-
-function DeviceMenuItem({
- checked = false,
- connectionState,
- dimmed = false,
- icon,
- label,
- onPress,
- selected,
- status,
- testID,
-}: {
- checked?: boolean;
- connectionState?: HomeDeviceConnectionState;
- dimmed?: boolean;
- icon?: ReactNode;
- label: string;
- onPress(): void;
- selected: boolean;
- status?: 'online' | 'offline';
- 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>
- {status ? (
- <View style={styles.deviceMenuStatusSlot}>
- <StatusDot tone={status === 'online' ? 'ready' : 'off'} pulsing={connectionState === 'syncing'} />
- {connectionState === 'failed' ? <View style={styles.deviceConnectionFailedRing} /> : null}
- </View>
- ) : null}
- </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 (
- <Modal animationType="fade" transparent visible={deviceName != null} onRequestClose={onClose}>
- <Pressable style={styles.revokedTipBackdrop} onPress={onClose} testID="home.revokedTip.backdrop">
- {/* Inner press swallow keeps taps on the card from dismissing via the backdrop. */}
- <Pressable style={styles.revokedTipCard} onPress={() => undefined}>
- <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>
- <Pressable
- accessibilityLabel={t('devices.list.revoked.retry')}
- accessibilityRole="button"
- accessibilityState={{ busy: retrying, disabled: retrying }}
- disabled={retrying}
- onPress={onRetry}
- style={({ pressed }) => [styles.revokedTipRetry, pressed && styles.pressed, retrying && styles.disabled]}
- testID="home.revokedTip.retry"
- >
- {retrying ? (
- <ActivityIndicator color={colors.ctaText} size="small" />
- ) : (
- <Text style={styles.revokedTipRetryText}>{t('devices.list.revoked.retry')}</Text>
- )}
- </Pressable>
- </Pressable>
- </Pressable>
- </Modal>
- );
-}
-
-function sanitizeDeviceChipTestId(value: string): string {
- return value.replace(/[^A-Za-z0-9_-]/g, '_');
-}
-
-function deviceMenuStatus(item: MobileHomeDeviceFilterItem): 'online' | 'offline' {
- return item.available && (item.state === 'ready' || item.state === 'busy') ? 'online' : 'offline';
-}
-
-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,
- onAnchorChange,
- projectHeaderHeight,
- projectLayoutRevision,
- projectRef,
- scrollY,
- viewportHeight,
-}: {
- childOffsets: readonly number[];
- 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,
- projectHeaderHeight: projectHeaderHeight.value,
- projectTop: layout.pageY,
- shift: PROJECT_CHILD_WINDOW_SHIFT,
- viewportHeight,
- viewportTop: 0,
- });
- },
- (next, previous) => {
- // A temporarily unavailable native view is not evidence that its rows
- // left the viewport. Keep the last bounded window until measured again.
- if (next === null || next === previous) return;
- runOnJS(onAnchorChange)(next);
- },
- [childOffsets, onAnchorChange, projectHeaderHeight, projectLayoutRevision, projectRef, scrollY, viewportHeight],
- );
- return null;
-}
-
-function ProjectRow({
- collapsed,
- dragging = false,
- expandedAutomationGroups,
- headerRefs,
- kind = 'project',
- machineIdentity,
- onDragEnd,
- onDragMove,
- onDragStart,
- onOpenAutomationGroup,
- onOpenProject,
- 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;
- 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),
- },
- );
- const projectHeaderHeight = useSharedValue(HOME_PROJECT_HEADER_HEIGHT);
- const projectRef = useAnimatedRef<View>();
- const [windowAnchor, setWindowAnchor] = useState(-1);
- const projectLayoutRevision = useSharedValue(0);
- const estimatedChildHeights = useMemo(() => {
- const expandedKeys = new Set(expandedAutomationGroups);
- return visibleSessions.map((item) => estimateHomeProjectChildHeight(item, expandedKeys));
- }, [expandedAutomationGroups, homeStatusVersion, visibleSessions]);
- const estimatedChildOffsets = useMemo(
- () => buildHomeProjectChildOffsets(estimatedChildHeights),
- [estimatedChildHeights],
- );
- // Keep the common five-row preview unchanged. A large expanded group keeps
- // its complete estimated height as a spacer until native layout establishes
- // that its child area intersects the viewport. This avoids mounting an
- // off-screen child window just because the folder header entered the outer
- // SectionList render window.
- const windowingEnabled = shouldWindowHomeProjectChildren({
- collapsed,
- itemCount: visibleSessions.length,
- scrollTrackingAvailable: !!homeScrollY,
- threshold: PROJECT_CHILD_WINDOW_THRESHOLD,
- });
- const scrollY = homeScrollY;
- const childContentHeight = estimatedChildOffsets[estimatedChildOffsets.length - 1] ?? 0;
- const childWindow = windowingEnabled
- ? windowAnchor >= 0
- ? resolveHomeProjectChildWindow({
- anchor: windowAnchor,
- childOffsets: estimatedChildOffsets,
- overscan: PROJECT_CHILD_WINDOW_OVERSCAN,
- windowSize: PROJECT_CHILD_WINDOW_SIZE,
- })
- : {
- end: 0,
- leadingSpacerHeight: 0,
- start: 0,
- trailingSpacerHeight: childContentHeight,
- }
- : {
- 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 dragGesture = useMemo(() => {
- if (!onDragStart || !onDragMove || !onDragEnd || kind !== 'project') return null;
- const start = onDragStart;
- const move = onDragMove;
- const finish = onDragEnd;
- return Gesture.Pan()
- .activateAfterLongPress(380)
- .onStart((event) => {
- runOnJS(start)({
- absoluteY: event.absoluteY,
- count: project.sessionCount,
- key: project.key,
- 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"
- accessibilityState={{ expanded: !collapsed }}
- onLayout={(event) => {
- const height = event.nativeEvent.layout.height;
- if (Number.isFinite(height) && height > 0) projectHeaderHeight.value = height;
- }}
- onPress={dragging ? undefined : onToggle}
- 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} />
- )}
- {kind === 'dialogue' ? (
- <MessagesSquare color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.thin} />
- ) : kind === 'cindy-make' ? (
- <Hammer color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.thin} />
- ) : collapsed ? (
- <Folder color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.thin} />
- ) : (
- <FolderOpen color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.thin} />
- )}
- <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>
- </Pressable>
- );
- return (
- <Reanimated.View
- 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}
- {dragGesture ? <GestureDetector gesture={dragGesture}>{header}</GestureDetector> : header}
-
- {collapsed ? null : (
- <View 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 内的透传包裹)。
- if (!swipeable) {
- return <Fragment key={reactKey}>{row}</Fragment>;
- }
- return (
- <SwipeableSessionRow
- key={reactKey}
- onArchive={swipe.onArchive}
- onShowOptions={swipe.onShowOptions}
- onTogglePin={swipe.onTogglePin}
- registry={swipe.registry}
- session={item.session as RemoteSession}
- testID={`${childTestID}.swipe`}
- >
- {row}
- </SwipeableSessionRow>
- );
- })}
- {trailingSpacerHeight > 0 ? <View pointerEvents="none" style={{ height: trailingSpacerHeight }} /> : null}
- {hiddenRowCount > 0 ? (
- <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>
- ) : null}
- </View>
- )}
- </Reanimated.View>
- );
-}
-
-/**
- * 首页 renderItem 输出的 per-item memo 单元(2026-07-18 风暴修复第二刀)。
- * 内核行(HomeSessionRow)memo 后,每次 sections 真实变化(流式期间预览更新等)仍会
- * 整列表重渲染全部 cell 的 Swipeable / 手势包装树(trace:47 次壳层重渲染 × ~105 cell,
- * 每次 ~500ms)。把整个 renderItem 输出按 item 级 memo,包装树只在自己 item 的数据
- * 变化时重建。比较器与 HomeSessionRow 同款 dataPropsEqual:函数 props 跳过——闭包
- * 审计:onArchive / onShowOptions / onTogglePin / onOpen* / onToggle* 均为 useCallback
- * 且只闭合 router / store / 稳定 setState;registry(swipeRegistry)与 swipe 为
- * useMemo 单例。给本组件新增函数 prop 时必须复审闭包稳定性。projectCollapsed /
- * prevIsBlock 等邻接派生位由 renderItem 计算成标量传入,天然参与比较。
- */
-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 dataPropsEqual(previous, next);
- }
- // dataPropsEqual retains the existing semantics 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 dataPropsEqual({ ...previous, item: nextItem }, next);
-}
-
-function HomeListRowInner({
- expandedAutomationGroups,
- isLastPinnedRow,
- item,
- machineIdentity,
- nextIsBlock,
- onArchive,
- onOpenAutomationGroup,
- onOpenProjectSessions,
- 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): 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)}
- 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}
- 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 个挂载行全量重画是风暴的主放大器。
-// 比较器 dataPropsEqual:数据 props(item / 布尔位 / expandedAutomationGroups)深比较,
-// **函数 props 跳过**——闭包审计:onOpenSession / onToggleAutomationGroup /
-// onOpenAutomationGroup 只闭合 router / 稳定 setState / 稳定 store 引用,新旧闭包可互换;
-// swipe(SessionSwipeControls)为父层 useMemo 单例,内部函数同理。给行新增函数 prop 时
-// 必须重新审计闭包稳定性,否则会拿着 stale 闭包运行。行内运行态经 useSessionRunning
-// 订阅(不再依赖父层重渲染带入),展开组子行的运行态订阅见 AutomationGroupChildren。
-export const HomeSessionRow = memo(HomeSessionRowInner, dataPropsEqual);
-
-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,
- 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;
- /** 平铺时标题旁的来源标签(项目名 /「对话」);分组模式下不传。 */
- sourceLabel?: string;
- /** 块模式下,前一行也是块时不画自己的顶线(前块的底线已经是这根线)。 */
- suppressBlockTopBorder?: boolean;
- /** 提供时透传给展开的自动化组子行(子行挂与顶层同款滑动操作);组行自身不消费。 */
- swipe?: SessionSwipeControls;
- testID: string;
- titleTestIDPrefix?: string;
-}) {
- const styles = useThemedStyles(makeStyles);
- const { colors } = useTheme();
- const { t } = useTranslation();
- // 运行态走订阅而非命令式读取:行已 memo 化,父层不再逐 emit 重渲染,命令式读取会 stale。
- const latestItem = latestMobileSessionRow(item);
- 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 { 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;
- // 自动化组行:同一任务的多次运行折叠而成(共享层 groupAutomationListItems 产出)。
- // 没接展开回调的调用点退化为普通行为(点击打开 primary 会话)。
- // 块模式:组行 + 展开的子行整体包在一个上下全宽线的块里;组行自身不再画缩进分割线
- // (收起时块底线紧贴行底,展开时组头与子行之间保持连续无线,均与项目组语义一致)。
- const blockMode = asBlock && !!group;
- // 预览走共享 buildRemoteSessionCardPreview(已并入 #368 的 liveActivity),运行中会显示实时活动;
- // 组行的预览位改为任务态摘要(需关注数 / 执行中 / 共 N 次运行),对齐桌面版组头 meta。
- const preview = group
- ? automationGroupPreview(item, group.sessionCount, t)
- : buildRemoteSessionCardPreview(
- loadedMessagePreview === undefined || loadedMessagePreview === item.messagePreview
- ? item
- : { ...item, messagePreview: loadedMessagePreview },
- { running },
- );
- // 零消息会话没有摘要。此时不要保留双行列表的空白第二行;但定时任务与置顶
- // 标记仍占用右下状态槽,因此继续使用双行布局。
- const showPreviewLine = !!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 handlePress = selectionMode && onPressSelection
- ? onPressSelection
- : group
- ? groupRowOpensPrimary ? openGroupPrimary : () => onToggleAutomationGroup?.(group.key)
- : () => onOpenSession(item);
- return (
- <View
- style={blockMode
- ? [
- styles.automationGroupBlock,
- suppressBlockTopBorder && styles.automationGroupBlockNoTop,
- ]
- : undefined}
- >
- <Pressable
- accessibilityRole="button"
- accessibilityLabel={group
- ? groupRowOpensPrimary ? t('devices.list.a11y.openAutomationLatest', { title: item.title }) : t('devices.list.a11y.automationTask', { title: item.title })
- : t('devices.list.a11y.openConversation', { title: item.title })}
- accessibilityState={group ? { expanded: groupExpanded, selected } : { selected }}
- delayLongPress={400}
- onLongPress={
- !selectionMode && !group && swipe && conversationSearchAllowsLocalWrites(item)
- ? () => {
- swipe.registry.closeOpenRow();
- swipe.onShowOptions(latestMobileSessionRow(item).session as RemoteSession);
- }
- : onLongPress}
- onPress={handlePress}
- style={({ pressed }) => [
- styles.sessionListRow,
- !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}
- {group && !selectionMode ? (
- // 展开箭头放行首,与项目组的折叠交互一致(chevron → 图标 → 标题);
- // 独立热区:即使组行点击直开会话(有需关注内容时),点箭头仍然是展开 / 收起。
- <Pressable
- accessibilityLabel={groupExpanded ? t('devices.list.a11y.collapse', { title: item.title }) : t('devices.list.a11y.expand', { title: item.title })}
- accessibilityRole="button"
- hitSlop={{ bottom: 12, left: 12, right: 4, top: 12 }}
- onPress={(event) => {
- // 防御性阻断:避免 chevron 点击同时触发父行 onPress(有需关注内容时父行
- // 是"直开 primary 会话",双触发会边展开边跳页)。与设备菜单重命名按钮同款处理。
- event.stopPropagation();
- onToggleAutomationGroup?.(group.key);
- }}
- style={styles.sessionGroupChevronCell}
- testID={`${testID}.automationGroupChevron`}
- >
- {groupExpanded ? (
- <ChevronDown color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
- ) : (
- <ChevronRight color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
- )}
- </Pressable>
- ) : null}
- <View style={[
- styles.sessionIconCell,
- !showPreviewLine && styles.sessionIconCellSingleLine,
- ]}>
- <SessionStatusMark
- item={item}
- running={running}
- showDraftIndicator={showDraftIndicator}
- />
- </View>
- <View style={[
- styles.sessionListContent,
- (hideDivider || blockMode || (!!group && groupExpanded)) && styles.sessionListContentNoDivider,
- ]}>
- <View style={styles.sessionTitleRow}>
- <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} />
- {sourceLabel ? (
- <Text
- ellipsizeMode="tail"
- numberOfLines={1}
- style={styles.sessionSourceLabel}
- testID={`home.sessionSourceLabel.${item.session.id}`}
- >
- {sourceLabel}
- </Text>
- ) : null}
- {rightStatus === 'time' ? (
- <SessionRelativeTime lastActivityAt={item.lastActivityAt} style={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 ? (
- <View style={styles.sessionPreviewRow}>
- <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 ? (
- <AutomationGroupChildren
- childTestID={automationChildTestID}
- childrenTestID={automationChildrenTestID}
- group={group}
- inBlock={blockMode}
- suppressTrailingDivider={hideDivider}
- onOpenGroup={onOpenAutomationGroup}
- onOpenSession={onOpenSession}
- swipe={swipe}
- testID={testID}
- titleTestIDPrefix={titleTestIDPrefix}
- />
- ) : null}
- </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;
- return (
- <View style={styles.automationGroupChildren} testID={childrenTestID ?? `${testID}.automationGroupChildren`}>
- {visibleItems.map((child, index) => {
- 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={child.session.id}>{row}</Fragment>;
- return (
- <SwipeableSessionRow
- key={child.session.id}
- onArchive={swipe.onArchive}
- onShowOptions={swipe.onShowOptions}
- onTogglePin={swipe.onTogglePin}
- registry={swipe.registry}
- session={child.session as RemoteSession}
- testID={`${testID}.automationChild.swipe`}
- >
- {row}
- </SwipeableSessionRow>
- );
- })}
- {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}
- </View>
- );
-}
-
-/** 自动化组行的预览位文案:需关注数 > 执行中 > 共 N 次运行(对齐桌面版组头 meta 的优先级)。 */
-function automationGroupPreview(item: RemoteSessionListItem, sessionCount: number, t: TFunction): string {
- const unread = item.scheduleInfo?.unreadCount ?? 0;
- const waiting = item.pendingInteractionCount;
- if (unread > 0 || waiting > 0) {
- return [
- unread > 0 ? t('devices.list.preview.needAttention', { count: unread }) : null,
- waiting > 0 ? t('devices.list.preview.waiting', { count: waiting }) : null,
- ].filter(Boolean).join(' · ');
- }
- if (item.scheduleInfo?.running) return t('devices.list.preview.automationRunning');
- return t('devices.list.preview.totalRuns', { count: sessionCount });
-}
-
-// 状态提醒点已移到行右侧(替代时间位,与桌面一致),行首图标只保留 vendor 标识 +
-// running 呼吸 + 草稿铅笔,不再叠角标点。
-function SessionStatusMark({
- item,
- running,
- showDraftIndicator,
-}: {
- item: RemoteSessionListItem;
- running: boolean;
- showDraftIndicator: boolean;
-}) {
- const styles = useThemedStyles(makeStyles);
- const { colors } = useTheme();
- const archived = item.session.status === 'archived';
- const orcaLead = item.session.orcaRole === 'lead';
- const attached = readBooleanField(item.session, 'attached') || readBooleanField(item.session, 'deviceLinkAttached');
- // 用户拍板 2026-07-20(对齐桌面):running 一律 Thinking Orange(statusAccent)。
- const glyphColor = running ? colors.statusAccent : colors.textTertiary;
- return (
- <View style={styles.sessionStatusMark}>
- {archived ? (
- <Archive color={colors.textTertiary} size={iconSize.lg} strokeWidth={iconStroke.thin} />
- ) : orcaLead ? (
- // 与桌面 SessionStatusIcon /「+」菜单协同项同款 UsersRound,不再用旧 Puzzle。
- <SessionStatusPulse running={running}>
- <UsersRound color={glyphColor} size={iconSize.action} strokeWidth={iconStroke.thin} />
- </SessionStatusPulse>
- ) : attached ? (
- <SessionStatusPulse running={running}>
- <RadioTower color={glyphColor} size={iconSize.lg} strokeWidth={iconStroke.thin} />
- </SessionStatusPulse>
- ) : (
- <MobileVendorIcon
- color={glyphColor}
- running={running}
- // Claude 星标 logo 视觉重量偏小,+1px 光学补偿对齐 Codex 标(刻意非阶梯值)。
- size={isClaudeCodeAgentKind(item.session.agentKind) ? 19 : iconSize.lg}
- vendor={item.session.agentKind}
- />
- )}
- {!archived && showDraftIndicator ? (
- <View style={styles.sessionDraftIndicator}>
- {/* 9px:Pencil 微徽标,徽标容器几何依赖(designTokenDiscipline ALLOWLIST 登记豁免)。 */}
- <Pencil color={colors.textSecondary} size={9} strokeWidth={iconStroke.medium} />
- </View>
- ) : null}
- </View>
- );
-}
-
-/** 行右侧 running spinner —— 与桌面 SessionItem 右槽同款:LoaderCircle(即桌面的
- * lucide Loader2)圆弧图标,1s linear 无限旋转(Tailwind animate-spin 同参数)。 */
-/**
- * 行右侧相对时间标签(「刚刚 / N 分钟前」)的独家保鲜叶子:行主体 memo 化后不再逐
- * emit 重渲染,时间标签失去偶然保鲜会无限期冻结(review P1);而把分钟订阅挂在行
- * 本体又等于每分钟重画全列表重型子树(review 复核 P1)。下沉到只渲染一个 Text 的
- * 叶子组件独家订阅 useMinuteNow:每分钟只重渲染 ~百个纯 Text,行主体纹丝不动。
- */
-function SessionRelativeTime({ lastActivityAt, style }: { lastActivityAt: string; style: StyleProp<TextStyle> }) {
- useMinuteNow();
- return (
- <Text style={style} numberOfLines={1}>
- {formatRemoteSessionSidebarTime(lastActivityAt)}
- </Text>
- );
-}
-
-function SessionRightSpinner({ testID }: { testID?: string }) {
- const { colors } = useTheme();
- const { t } = useTranslation();
- const spin = useRef(new Animated.Value(0)).current;
- useEffect(() => {
- const loop = Animated.loop(
- Animated.timing(spin, {
- duration: 1000,
- easing: Easing.linear,
- toValue: 1,
- useNativeDriver: true,
- }),
- );
- loop.start();
- return () => {
- loop.stop();
- };
- }, [spin]);
- const rotate = spin.interpolate({ inputRange: [0, 1], outputRange: ['0deg', '360deg'] });
- return (
- <Animated.View
- accessibilityLabel={t('devices.list.a11y.running')}
- style={{ transform: [{ rotate }] }}
- testID={testID}
- >
- <LoaderCircle color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />
- </Animated.View>
- );
-}
-
-function SessionStatusPulse({ children, running }: { children: ReactNode; running: boolean }) {
- const opacity = useRef(new Animated.Value(running ? 0.3 : 1)).current;
- useEffect(() => {
- opacity.stopAnimation();
- if (!running) {
- opacity.setValue(1);
- return;
- }
- opacity.setValue(0.3);
- const loop = Animated.loop(
- Animated.sequence([
- Animated.timing(opacity, {
- duration: 750,
- easing: Easing.inOut(Easing.ease),
- toValue: 1,
- useNativeDriver: true,
- }),
- Animated.timing(opacity, {
- duration: 750,
- easing: Easing.inOut(Easing.ease),
- toValue: 0.3,
- useNativeDriver: true,
- }),
- ]),
- );
- loop.start();
- return () => {
- loop.stop();
- };
- }, [opacity, running]);
-
- return <Animated.View style={{ opacity }}>{children}</Animated.View>;
-}
-
-/** 该首页行是否以「块」呈现(上下全宽线):项目组,或自动化组行(顶层 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 isClaudeCodeAgentKind(agentKind: string): boolean {
- return agentKind === 'cc' || agentKind === 'claude-code';
-}
-
-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 '';
+ return <MobileHome />;
}
-
-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({
- safeArea: { flex: 1, backgroundColor: colors.surface },
- pressed: { opacity: 0.72 },
- 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,
- },
- headerIconButton: {
- alignItems: 'center',
- flexShrink: 0,
- height: 44,
- justifyContent: 'center',
- width: 44,
- },
- headerActions: {
- alignItems: 'center',
- flexDirection: 'row',
- gap: spacing.xs,
- },
- headerTitleWrap: {
- alignItems: 'center',
- flex: 1,
- justifyContent: 'center',
- minHeight: 44,
- minWidth: 0,
- paddingHorizontal: spacing.sm,
- },
- headerTitleCluster: {
- alignItems: 'center',
- flexDirection: 'row',
- flexShrink: 1,
- gap: 6,
- maxWidth: '100%',
- minWidth: 0,
- },
- headerTitle: {
- color: colors.textPrimary,
- flexShrink: 1,
- fontSize: typeScale.listTitle,
- fontWeight: fontWeight.semibold,
- lineHeight: lineHeight.listTitleCompact,
- },
- deviceMenuPanelCenter: {
- alignSelf: 'center',
- },
- deviceMenuPanelEnd: {
- alignSelf: 'flex-end',
- },
- connectionRow: {
- 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,
- flex: 1,
- fontSize: typeScale.caption,
- fontWeight: fontWeight.medium,
- minWidth: 0,
- },
- connectionIconButton: {
- alignItems: 'center',
- borderRadius: radius.pill,
- height: 28,
- justifyContent: 'center',
- width: 28,
- },
- deviceConnectionFailedRing: {
- borderColor: colors.errorBorder,
- // 16×16 圆环:语义是正圆,用 pill(RN 钳制到半高)而非碰巧同值的 control 档。
- borderRadius: radius.pill,
- borderWidth: 1.5,
- height: 16,
- position: 'absolute',
- width: 16,
- },
- 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,
- },
- deviceMenuSectionLabel: {
- color: colors.textTertiary,
- fontSize: typeScale.caption,
- fontWeight: fontWeight.medium,
- lineHeight: lineHeight.caption,
- paddingHorizontal: spacing.md,
- paddingTop: spacing.sm,
- },
- deviceMenuHint: {
- color: colors.textTertiary,
- fontSize: typeScale.caption,
- fontWeight: fontWeight.regular,
- lineHeight: lineHeight.caption,
- paddingHorizontal: spacing.md,
- paddingVertical: spacing.sm,
- },
- deviceMenuStatusSlot: {
- alignItems: 'center',
- height: 20,
- justifyContent: 'center',
- position: 'relative',
- width: 20,
- },
- deviceMenuDivider: {
- backgroundColor: colors.border,
- height: StyleSheet.hairlineWidth,
- marginHorizontal: spacing.sm,
- marginVertical: spacing.sm,
- },
- 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.medium,
- lineHeight: lineHeight.subtitle,
- },
- revokedTipBody: {
- color: colors.textSecondary,
- fontSize: typeScale.body,
- lineHeight: lineHeight.body,
- },
- revokedTipRetry: {
- alignItems: 'center',
- backgroundColor: colors.cta,
- borderRadius: radius.pill,
- height: 44,
- justifyContent: 'center',
- marginTop: spacing.sm,
- },
- revokedTipRetryText: {
- color: colors.ctaText,
- fontSize: typeScale.body,
- fontWeight: fontWeight.semibold,
- },
- homeList: {
- backgroundColor: colors.surface,
- flex: 1,
- },
- listContent: {
- backgroundColor: colors.surface,
- flexGrow: 1,
- paddingBottom: 83,
- 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.caption,
- fontWeight: fontWeight.medium,
- lineHeight: lineHeight.code,
- },
- projectGroup: {
- backgroundColor: colors.surface,
- // 全宽分割线挂在项目组的顶部与底部:把整个项目块与上方/下方的普通对话分开,
- // 而非分隔项目头与其下属会话(项目头 → 内容之间保持连续无线)。
- borderBottomColor: colors.border,
- borderBottomWidth: StyleSheet.hairlineWidth,
- borderRadius: 0, // 显式方角覆盖,非漂移
- borderTopColor: colors.border,
- borderTopWidth: StyleSheet.hairlineWidth,
- borderWidth: 0,
- },
- projectGroupNoTop: {
- // 前一行也是块时不画顶线,避免两根 hairline 叠成一根粗线。
- borderTopWidth: 0,
- },
- projectRow: {
- alignItems: 'center',
- backgroundColor: colors.surface,
- flexDirection: 'row',
- gap: 8,
- minHeight: 56,
- paddingLeft: spacing.md,
- paddingRight: spacing.lg,
- paddingVertical: spacing.sm,
- },
- projectLabel: {
- alignItems: 'center',
- flex: 1,
- flexDirection: 'row',
- gap: 6, // Desktop ProjectNode name / remote icon / machine label gap-1.5.
- minWidth: 0,
- },
- projectTitle: {
- color: colors.textPrimary,
- flex: 1,
- fontSize: typeScale.body,
- fontWeight: fontWeight.medium,
- lineHeight: lineHeight.listTitle,
- minWidth: 0,
- },
- projectFolderTitle: {
- flex: 0,
- flexShrink: 1,
- },
- projectCount: {
- color: colors.textTertiary,
- fontSize: typeScale.footnote,
- fontWeight: fontWeight.regular,
- lineHeight: lineHeight.subtitle,
- },
- projectRowDragging: {
- opacity: 0.28,
- },
- projectDragGhost: {
- alignItems: 'center',
- backgroundColor: colors.surfaceElevated,
- borderColor: colors.border,
- borderRadius: radius.container,
- borderWidth: StyleSheet.hairlineWidth,
- flexDirection: 'row',
- gap: 8,
- 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: 54,
- paddingLeft: 48,
- paddingRight: spacing.lg,
- },
- projectViewAllText: {
- color: colors.textSecondary,
- flex: 1,
- fontSize: typeScale.body,
- fontWeight: fontWeight.medium,
- lineHeight: lineHeight.body,
- },
- sessionListRow: {
- alignItems: 'stretch',
- backgroundColor: colors.surface,
- flexDirection: 'row',
- gap: spacing.md,
- height: HOME_SESSION_ROW_HEIGHT,
- paddingLeft: spacing.md,
- },
- sessionListRowSingleLine: {
- height: HOME_SESSION_SINGLE_LINE_ROW_HEIGHT,
- },
- sessionListRowIndented: {
- // 项目下属会话向右多缩进一档,让"隶属于该项目"在视觉上更明显
- // (连同行内分割线一起右移,形成嵌套层级感)。
- paddingLeft: spacing.md + spacing.lg,
- },
- sessionListRowDeepIndented: {
- // 自动化组子行:比 indented 再深一档(缩进全部收在行内,滑动包装全宽才能贴屏边),
- // 保证子行始终比组行(无论组行在 chats 还是项目组内)更深一层。
- paddingLeft: spacing.md + spacing.lg * 2,
- },
- 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,
- },
- sessionIconCell: {
- alignItems: 'center',
- justifyContent: 'flex-start',
- paddingTop: 22,
- width: 24,
- },
- sessionIconCellSingleLine: {
- justifyContent: 'center',
- paddingTop: 0,
- },
- sessionGroupChevronCell: {
- // 自动化组行行首的展开箭头列:与项目组行首 chevron 对齐(尺寸 22、次级色),
- // 垂直对齐标题行(与 sessionIconCell 同一基线)。
- alignItems: 'center',
- justifyContent: 'flex-start',
- marginRight: -spacing.xs,
- paddingTop: 23,
- width: 22,
- },
- sessionListContent: {
- borderBottomColor: colors.border,
- borderBottomWidth: StyleSheet.hairlineWidth,
- flex: 1,
- justifyContent: 'center',
- minWidth: 0,
- paddingBottom: spacing.sm,
- paddingRight: spacing.lg,
- paddingTop: spacing.sm,
- },
- sessionListContentNoDivider: {
- // 紧邻块(项目组 / 自动化组)边界的行不画自己的缩进线:块的全宽 border 已经是这根线,
- // 两根 hairline 相邻会叠成一根明显更粗的线(即「项目组上边线偏粗」的根因)。
- borderBottomWidth: 0,
- },
- sessionTitleRow: {
- alignItems: 'center',
- flexDirection: 'row',
- gap: spacing.sm,
- height: 30,
- },
- sessionStatusMark: {
- alignItems: 'center',
- height: 24,
- justifyContent: 'center',
- overflow: 'visible',
- position: 'relative',
- width: 24,
- },
- // 右侧状态槽(替代时间位):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,
- },
- sessionDraftIndicator: {
- alignItems: 'center',
- bottom: -3,
- height: 12,
- justifyContent: 'center',
- position: 'absolute',
- right: -3,
- width: 12,
- },
- sessionTitle: {
- color: colors.textPrimary,
- flex: 1,
- fontSize: typeScale.subtitle,
- fontWeight: fontWeight.semibold,
- lineHeight: lineHeight.listTitle,
- minWidth: 0,
- },
- sessionSourceLabel: {
- color: colors.textTertiary,
- flexShrink: 1,
- fontSize: typeScale.caption,
- fontWeight: fontWeight.regular,
- lineHeight: lineHeight.body,
- maxWidth: '42%',
- minWidth: 0,
- },
- sessionPreviewRow: {
- alignItems: 'flex-start',
- flexDirection: 'row',
- gap: spacing.sm,
- height: lineHeight.subtitle,
- },
- sessionPreview: {
- color: colors.textSecondary,
- flex: 1,
- fontSize: typeScale.code,
- fontWeight: fontWeight.regular,
- lineHeight: lineHeight.subtitle,
- minWidth: 0,
- },
- sessionTrailingIcons: {
- alignItems: 'center',
- flexDirection: 'row',
- gap: spacing.sm,
- justifyContent: 'flex-end',
- minHeight: lineHeight.subtitle,
- paddingTop: 3,
- },
- sessionTime: {
- color: colors.textTertiary,
- flexShrink: 0,
- fontSize: typeScale.footnote,
- fontWeight: fontWeight.regular,
- lineHeight: lineHeight.body,
- },
- 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,
- },
- newChatButtonTransparent: {
- backgroundColor: 'transparent',
- borderWidth: 0,
- },
- newChatGlass: {
- width: '100%',
- height: '100%',
- borderRadius: radius.pill,
- },
- newChatGlassIcon: {
- flex: 1,
- alignItems: 'center',
- justifyContent: 'center',
- },
- newChatButton: {
- alignItems: 'center',
- backgroundColor: colors.homeListFab,
- borderColor: colors.homeListFabBorder,
- borderRadius: radius.pill,
- borderWidth: colors.homeListFabBorder === 'transparent' ? 0 : StyleSheet.hairlineWidth,
- bottom: CINDY_LIST_FAB_BOTTOM,
- height: CINDY_LIST_FAB_SIZE,
- justifyContent: 'center',
- position: 'absolute',
- right: CINDY_LIST_GUTTER,
- width: CINDY_LIST_FAB_SIZE,
- },
-});
diff --git a/apps/mobile/app/files/[sessionId].tsx b/apps/mobile/app/files/[sessionId].tsx
index b031812939..cea1868e7a 100644
--- a/apps/mobile/app/files/[sessionId].tsx
+++ b/apps/mobile/app/files/[sessionId].tsx
@@ -1,3 +1,4 @@
+import { SystemNavigationBack, useSystemNavigationBack } from '@/platform/chrome/SystemNavigationBack';
/**
* 远程文件浏览(网格为主视图,对标 iOS Files)。
*
@@ -7,6 +8,8 @@
* Quick Look 预览路由。缩略图经 thumbnail op 懒加载(fileThumbnails 内存缓存)。
*/
import * as Clipboard from 'expo-clipboard';
+import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';
+import { ModalContentArea } from '@/platform/ModalContentArea';
import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
import { fsWatchTopic } from '@cindy/device-link';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -132,7 +135,9 @@ export default function RemoteFileBrowserScreen() {
const deviceName = readRouteString(params.deviceName) ?? deviceId;
const relPath = readRouteString(params.relPath) ?? '';
const router = useRouter();
- const { width: screenWidth } = useWindowDimensions();
+ const systemBack = useSystemNavigationBack();
+ const fileWindow = useAdaptiveWindow();
+ const screenWidth = fileWindow.width - fileWindow.insets.left - fileWindow.insets.right;
const auth = useAuth();
const { connectionIssue, openLink, status, subscribe, unsubscribe } = useDeviceLink();
const maker = useMobileMakerTransport(deviceId);
@@ -727,6 +732,7 @@ export default function RemoteFileBrowserScreen() {
return (
<SafeAreaView style={styles.safeArea} testID="files.screen">
+ <SystemNavigationBack label={t('shared.back')} onPress={() => goBackGuarded(router)} />
{searchOpen ? (
<SearchHeader
loading={searchLoading}
@@ -745,11 +751,11 @@ export default function RemoteFileBrowserScreen() {
/>
) : (
<View style={styles.navRow} testID="files.navRow">
- <ScreenBackButton
+ {!systemBack ? <ScreenBackButton
hitSlop={8}
onPress={() => goBackGuarded(router)}
testID="files.backButton"
- />
+ /> : null}
<Pressable
accessibilityLabel={t('files.browser.a11yTitleMenu')}
onPress={() => setTitleMenuOpen(true)}
@@ -1331,8 +1337,9 @@ function TitleMenu({
);
return (
- <Modal animationType="fade" onRequestClose={onClose} transparent visible={open}>
+ <Modal supportedOrientations={['portrait', 'portrait-upside-down', 'landscape-left', 'landscape-right']} animationType="fade" onRequestClose={onClose} transparent visible={open}>
<Pressable onPress={onClose} style={styles.overlay} testID="files.titleMenuOverlay">
+ <ModalContentArea>
<Pressable onPress={() => undefined} style={styles.titleMenuCard}>
{levels.map((level, index) => (
<View key={`level:${level.relPath}`}>
@@ -1371,6 +1378,7 @@ function TitleMenu({
{row('folder.copy', t('files.browser.copyPath'), false, onCopyCurrentPath,
<Copy color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />)}
</Pressable>
+ </ModalContentArea>
</Pressable>
</Modal>
);
@@ -1405,8 +1413,9 @@ function ContextMenu({
];
return (
- <Modal animationType="fade" onRequestClose={onClose} transparent visible>
+ <Modal supportedOrientations={['portrait', 'portrait-upside-down', 'landscape-left', 'landscape-right']} animationType="fade" onRequestClose={onClose} transparent visible>
<Pressable onPress={onClose} style={styles.overlayCenter} testID="files.contextMenuOverlay">
+ <ModalContentArea>
<View style={styles.liftedCard}>
<View style={styles.liftedThumbZone}>
{item.kind === 'dir' ? (
@@ -1434,6 +1443,7 @@ function ContextMenu({
</View>
))}
</View>
+ </ModalContentArea>
</Pressable>
</Modal>
);
@@ -1706,8 +1716,8 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
borderColor: colors.border,
borderRadius: radius.container,
borderWidth: StyleSheet.hairlineWidth,
- marginHorizontal: spacing.xxl * 2 + spacing.sm,
- marginTop: 96,
+ width: '100%',
+ maxWidth: 360,
overflow: 'hidden',
},
menuRow: {
diff --git a/apps/mobile/app/files/preview/[sessionId].tsx b/apps/mobile/app/files/preview/[sessionId].tsx
index 7487828120..9de31ab580 100644
--- a/apps/mobile/app/files/preview/[sessionId].tsx
+++ b/apps/mobile/app/files/preview/[sessionId].tsx
@@ -1,3 +1,4 @@
+import { SystemNavigationBack, useSystemNavigationBack } from '@/platform/chrome/SystemNavigationBack';
/**
* 远程文件 Quick Look 预览。
*
@@ -20,6 +21,7 @@
* (fetchRemoteAbsFileToUrl);无同目录翻页、无缩略图(直接取原图)。
*/
import * as Clipboard from 'expo-clipboard';
+import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';
import { Image } from 'expo-image';
import { useIsFocused, useLocalSearchParams, useRouter } from 'expo-router';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -163,7 +165,10 @@ export default function RemoteFilePreviewScreen() {
const targetLineRaw = Number(readRouteString(params.line) ?? '');
const targetLine = Number.isInteger(targetLineRaw) && targetLineRaw > 0 ? targetLineRaw : null;
const router = useRouter();
- const { width: pageWidth } = useWindowDimensions();
+ const systemBack = useSystemNavigationBack();
+ const previewWindow = useAdaptiveWindow();
+ const [measuredPageWidth, setMeasuredPageWidth] = useState<number | null>(null);
+ const pageWidth = measuredPageWidth ?? Math.max(1, previewWindow.width - previewWindow.insets.left - previewWindow.insets.right);
const { openLink } = useDeviceLink();
const auth = useAuth();
const maker = useMobileMakerTransport(deviceId);
@@ -492,7 +497,9 @@ export default function RemoteFilePreviewScreen() {
if (!current || !siblings) {
return (
<SafeAreaView style={styles.safeArea} testID="filePreview.screen">
+ <SystemNavigationBack close label={t('files.preview.done')} onPress={() => goBackGuarded(router)} />
<PreviewNav
+ hideDone={systemBack}
meta={error ?? ''}
onDone={() => goBackGuarded(router)}
onShare={null}
@@ -509,7 +516,9 @@ export default function RemoteFilePreviewScreen() {
return (
<SafeAreaView edges={htmlBrowser ? [] : undefined} style={styles.safeArea} testID="filePreview.screen">
{!htmlBrowser ? <>
+ <SystemNavigationBack close label={t('files.preview.done')} onPress={() => goBackGuarded(router)} />
<PreviewNav
+ hideDone={systemBack}
meta={[
`${pageIndex + 1} / ${siblings.length}`,
// absPath 单文件模式没有目录列举,size 未知(0)不显示,避免「0 B」。
@@ -523,6 +532,7 @@ export default function RemoteFilePreviewScreen() {
</> : null}
<FlatList
+ onLayout={event => setMeasuredPageWidth(Math.max(1, event.nativeEvent.layout.width))}
data={siblings}
getItemLayout={(_, index) => ({ index, length: pageWidth, offset: pageWidth * index })}
ref={pagerRef}
@@ -637,11 +647,13 @@ export default function RemoteFilePreviewScreen() {
/* ------------------------------ 页面组件 ------------------------------ */
function PreviewNav({
+ hideDone = false,
meta,
onDone,
onShare,
title,
}: {
+ hideDone?: boolean;
meta: string;
onDone(): void;
onShare: (() => void) | null;
@@ -652,9 +664,9 @@ function PreviewNav({
const { t } = useTranslation();
return (
<View style={styles.navRow}>
- <Pressable accessibilityLabel={t('files.preview.done')} hitSlop={10} onPress={onDone} testID="filePreview.done">
+ {!hideDone ? <Pressable accessibilityLabel={t('files.preview.done')} hitSlop={10} onPress={onDone} testID="filePreview.done">
<Text style={styles.doneText}>{t('files.preview.done')}</Text>
- </Pressable>
+ </Pressable> : null}
<View style={styles.navTitleCol}>
<Text numberOfLines={1} style={styles.navTitle} testID="filePreview.title">{title}</Text>
{meta ? <Text numberOfLines={1} style={styles.navMeta}>{meta}</Text> : null}
@@ -1357,6 +1369,7 @@ function ToolbarButton({
return (
<Pressable
accessibilityLabel={label}
+ accessibilityRole="button"
disabled={disabled}
onPress={onPress}
style={({ pressed }) => [styles.toolItem, (pressed || disabled) && styles.pressed]}
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 8ec4c65525..f9eb79c9bb 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1,3 +1,12 @@
+import { HomeHeaderGlassButton } from '@/session/HomeHeaderGlassButton';
+import { HomeNewTaskButton } from '@/session/HomeNewTaskButton';
+import { RecentMessageHistories, MessageHistoryOverlay } from '@/session/RecentMessageHistories';
+import { rememberRecentTask } from '@/session/recentTasks';
+import { SystemNavigationBack, useSystemNavigationBack } from '@/platform/chrome/SystemNavigationBack';
+import { keyboardControlRegion } from '@/platform/windowGeometry';
+import { useAdaptiveWindow, PaneViewportProvider } from '@/platform/AdaptiveWindowContext';
+import { useSessionHeaderHeight } from '@/session/useSessionHeaderHeight';
+import { sessionPaneLayout } from '@/session/sessionPaneLayout';
import { ComposerExpandButton } from '@/session/ComposerExpandButton';
import { nativeComposerAvailable } from '@/session/ComposerNativeInput';
import { getActiveMobileSessionRealm } from '@/config/env';
@@ -22,8 +31,8 @@ import {
Image,
List,
ListTodo,
- Menu,
Monitor,
+ Menu,
Mic,
Pencil,
Pin,
@@ -45,11 +54,10 @@ import {
addScreenshotListener,
renderConversationShareHtmlToPng,
} from 'xdt-screenshot-monitor';
-import { useFocusEffect, useLocalSearchParams, useNavigation, useRouter } from 'expo-router';
+import { Stack, useFocusEffect, useLocalSearchParams, useNavigation, useRouter } from 'expo-router';
import { forwardRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode, type RefObject, type SetStateAction } from 'react';
import {
ActivityIndicator,
- AccessibilityInfo,
Alert,
AppState,
BackHandler,
@@ -60,7 +68,6 @@ import {
ScrollView,
StyleSheet,
View,
- findNodeHandle,
useWindowDimensions,
type GestureResponderEvent,
type LayoutChangeEvent,
@@ -966,6 +973,9 @@ export default function SessionScreen() {
// 新发起的请求作废旧请求。
const rewindRequestSeqRef = useRef(0);
const deviceName = readRouteParam(params.deviceName) ?? deviceId;
+ useFocusEffect(useCallback(() => {
+ rememberRecentTask({ pathname: '/sessions/[sessionId]', params: { deviceId, deviceName, sessionId } });
+ }, [deviceId, deviceName, sessionId]));
const routeDraft = readRouteParam(params.draft);
const routeFocusClientId = readRouteParam(params.focusClientId);
const routeFocusComposerRequestKey = readRouteParam(params.focusComposerRequestKey);
@@ -2657,6 +2667,17 @@ export default function SessionScreen() {
})
: composerRuntimeSummary.modelSummary
: '';
+ const adaptiveWindow = useAdaptiveWindow();
+ const nativeHeaderHeight = useSessionHeaderHeight(JSON.stringify([
+ windowDimensions.width, windowDimensions.height, windowDimensions.fontScale,
+ insets.top, insets.bottom, insets.left, insets.right, adaptiveWindow.barEdge,
+ ]));
+ const paneLayout = sessionPaneLayout(adaptiveWindow);
+ const horizontalSystemHeader = Platform.OS === 'ios' && adaptiveWindow.barEdge === 'none'
+ && !paneLayout.persistent && !shareSelectionActive;
+ const composerRegion = keyboardControlRegion(adaptiveWindow, keyboardState.height);
+ const detailViewport = useMemo(() => ({ width: paneLayout.detail.width, height: windowDimensions.height }),
+ [paneLayout.detail.width, windowDimensions.height]);
const nativeShellLayout = useMemo(() => buildSessionNativeShellLayout({
attachmentPickerOpen: false,
keyboardHeight: keyboardState.height,
@@ -2665,20 +2686,18 @@ export default function SessionScreen() {
platform: Platform.OS === 'ios' ? 'ios' : Platform.OS === 'android' ? 'android' : 'web',
safeAreaBottomInset: insets.bottom,
screenHeight: windowDimensions.height,
- screenWidth: windowDimensions.width,
+ screenWidth: detailViewport.width,
}), [
insets.bottom,
keyboardState.height,
keyboardState.visible,
windowDimensions.height,
- windowDimensions.width,
+ detailViewport.width,
]);
const composerTouchLayout = useMemo(() => buildComposerTouchLayout({
- screenWidth: windowDimensions.width,
- }), [windowDimensions.width]);
- // 宽屏导航形态(iPad / 安卓折叠屏与横屏大屏机):左上角三条杠 + 任务列表抽屉,
- // 原地替换当前路由参数切任务;窄屏保持传统返回键。断点与按平台分闸(iOS 仅 iPad,
- // iPhone 不发)见 wideSessionNav.ts。
+ screenWidth: detailViewport.width,
+ }), [detailViewport.width]);
+ // Wide nonpersistent windows offer quick switching separately from back navigation.
const wideSessionNav = useMemo(() => buildWideSessionNavLayout({
iosPad: Platform.OS === 'ios' && Platform.isPad,
platform: Platform.OS,
@@ -2699,15 +2718,17 @@ export default function SessionScreen() {
// pending 只能拦住「首击本身就是导航」的连点;遮罩/back/左滑/当前任务先关闭时 pending
// 仍为空。closing 从任一关闭入口同步置 true,完整覆盖退场 commit 前的快速二次点击。
const sessionListDrawerClosingRef = useRef(false);
- // 非导航关闭的焦点归还必须晚于父级 overlayMounted=false commit:否则按钮仍在
- // no-hide-descendants 子树里,VoiceOver/TalkBack 会忽略聚焦并丢失焦点。
- const returnDrawerFocusAfterCloseRef = useRef(false);
- const sessionListButtonRef = useRef<View>(null);
+ const openSessionListDrawer = useCallback(() => {
+ if (!wideSessionNav.enabled || paneLayout.persistent || sessionListDrawerClosingRef.current) return;
+ setSessionListDrawerOverlayMounted(true);
+ setSessionListDrawerOpen(true);
+ }, [paneLayout.persistent, wideSessionNav.enabled]);
const closeSessionListDrawer = useCallback(() => {
+ if (!sessionListDrawerOverlayMounted) return;
if (sessionListDrawerClosingRef.current) return;
sessionListDrawerClosingRef.current = true;
setSessionListDrawerOpen(false);
- }, []);
+ }, [sessionListDrawerOverlayMounted]);
// 旋转 / 分屏收窄回到窄屏形态时,抽屉没有入口也没有意义,直接关掉。
useEffect(() => {
if (!wideSessionNav.enabled && sessionListDrawerOverlayMounted) closeSessionListDrawer();
@@ -2721,38 +2742,27 @@ export default function SessionScreen() {
const subscription = BackHandler.addEventListener('hardwareBackPress', () => true);
return () => subscription.remove();
}, [sessionListDrawerOpen, sessionListDrawerOverlayMounted]);
- const openSessionListDrawer = useCallback(() => {
- pendingDrawerNavigationRef.current = null;
- sessionListDrawerClosingRef.current = false;
- returnDrawerFocusAfterCloseRef.current = false;
- Keyboard.dismiss();
- setSessionListDrawerOverlayMounted(true);
- setSessionListDrawerOpen(true);
- }, []);
const queueDrawerNavigation = useCallback((action: () => void) => {
// closing 覆盖所有关闭来源,包括 pending 为空的纯关闭;首个意图获胜。
if (sessionListDrawerClosingRef.current || pendingDrawerNavigationRef.current) return;
+ if (paneLayout.persistent && !sessionListDrawerOverlayMounted) { action(); return; }
sessionListDrawerClosingRef.current = true;
pendingDrawerNavigationRef.current = action;
setSessionListDrawerOpen(false);
- }, []);
+ }, [paneLayout.persistent, sessionListDrawerOverlayMounted]);
const handleSessionListDrawerClosed = useCallback(() => {
const action = pendingDrawerNavigationRef.current;
sessionListDrawerClosingRef.current = false;
- if (!action) returnDrawerFocusAfterCloseRef.current = true;
setSessionListDrawerOverlayMounted(false);
if (!action) return;
pendingDrawerNavigationRef.current = null;
action();
}, []);
useEffect(() => {
- if (sessionListDrawerOverlayMounted || !returnDrawerFocusAfterCloseRef.current) return;
- returnDrawerFocusAfterCloseRef.current = false;
- // 导航型关闭不会登记归还请求;外部导航已让本页失焦时也不抢新屏焦点。
- if (!navigation.isFocused()) return;
- const returnNode = sessionListButtonRef.current ? findNodeHandle(sessionListButtonRef.current) : null;
- if (returnNode != null) AccessibilityInfo.setAccessibilityFocus(returnNode);
- }, [navigation, sessionListDrawerOverlayMounted]);
+ if (!paneLayout.persistent || !sessionListDrawerOverlayMounted) return;
+ setSessionListDrawerOpen(false);
+ closeSessionListDrawer();
+ }, [paneLayout.persistent, sessionListDrawerOverlayMounted, closeSessionListDrawer]);
const handleDrawerSelectSession = useCallback((item: RemoteSessionListItem) => {
const targetSession = item.session as RemoteSession;
const focusClientId = 'searchFocusClientId' in item
@@ -2793,16 +2803,13 @@ export default function SessionScreen() {
// 前进导航防连点:快速双击「新建」会把 /sessions/new 压栈两层(返回要退两次),
// 与首页各入口同一把 guardedPush 锁。
const guardedPush = useGuardedPush();
+ const homeNewSessionActionRef = useRef<(() => void) | null>(null);
const handleDrawerNewSession = useCallback(() => {
+ if (homeNewSessionActionRef.current) { homeNewSessionActionRef.current(); return; }
queueDrawerNavigation(() => {
guardedPush({ pathname: '/sessions/new', params: { deviceId, deviceName } });
});
}, [deviceId, deviceName, guardedPush, queueDrawerNavigation]);
- // 抽屉「主页」是显式的去处承诺,不是「返回」:从设备详情/自动化页进来时 back 只退一层,
- // 会落在中间页。dismissTo 沿当前栈一路退到根页,栈里没有根页(深链冷启动)则推入。
- const handleDrawerGoHome = useCallback(() => {
- queueDrawerNavigation(() => router.dismissTo('/'));
- }, [queueDrawerNavigation, router]);
const handleComposerInputPressIn = useCallback(() => {
if (voiceRecordingActiveRef.current || voiceState === 'listening') {
finishVoiceRecordingRef.current?.();
@@ -8931,30 +8938,16 @@ export default function SessionScreen() {
}
}, [applyComposerDocument, deviceId, maker, messageActionBusy, requestSync, rewindState, sessionId]);
- return (
- <View style={styles.safeArea} testID="session.screen">
- <ComposerKeyboardAvoidingView
- keyboard={keyboardState}
- // 抽屉开着时把背后内容从读屏树里摘掉:iOS 用 accessibilityElementsHidden
- // (与抽屉侧 accessibilityViewIsModal 配对),Android 用 importantForAccessibility
- // ——后者才对 TalkBack 生效(与 ComposerRichInput 的双平台配对惯例一致)。
- accessibilityElementsHidden={sessionListDrawerOverlayMounted}
- behavior={nativeShellLayout.keyboardAvoidingBehavior}
- importantForAccessibility={sessionListDrawerOverlayMounted ? 'no-hide-descendants' : 'auto'}
- keyboardVerticalOffset={nativeShellLayout.keyboardVerticalOffset}
- style={styles.keyboard}
- >
- {Platform.OS === 'ios' ? (
- <SessionHeaderNativeBlur height={Math.max(topOverlayHeight, insets.top + 44) + spacing.xxl} />
- ) : null}
- <View ref={topOverlayRef} onLayout={handleTopOverlayLayout} pointerEvents="box-none" style={styles.sessionChrome} testID="session.chrome">
- <View style={[styles.sessionChromeContent, { paddingTop: insets.top }]}>
- <SessionHeaderBar
+ const headerNode = (
+ <>
+ <Stack.Screen options={{ gestureEnabled: !sessionListDrawerOverlayMounted }} />
+ <SessionHeaderBar
+ horizontalSystemHeader={horizontalSystemHeader}
currentSession={currentSession}
diffCount={diffCount}
isDeviceAccessRevoked={isDeviceAccessRevoked}
shareSelectionLeadingInset={nativeShellLayout.wideViewport
- ? Math.max(0, (windowDimensions.width - nativeShellLayout.contentMaxWidth) / 2)
+ ? Math.max(0, (detailViewport.width - nativeShellLayout.contentMaxWidth) / 2)
: 0}
shareSelectAllNode={shareSelectionActive ? (
<ShareSelectAllButton busy={conversationShareBusy} shareableIds={allShareableIds} />
@@ -8963,9 +8956,9 @@ export default function SessionScreen() {
syncingImmediately={showSyncingImmediately}
messageCount={Math.max(messages.length, currentSession?._count?.messages ?? 0)}
messageOnly={sessionManagedByHost}
- onBack={goBackToHome}
- onOpenSessionList={wideSessionNav.enabled ? openSessionListDrawer : undefined}
- sessionListButtonRef={sessionListButtonRef}
+ onBack={sessionListDrawerOverlayMounted ? closeSessionListDrawer : goBackToHome}
+ onOpenSessionList={!paneLayout.persistent && wideSessionNav.enabled ? openSessionListDrawer : undefined}
+ onNewSession={paneLayout.persistent ? handleDrawerNewSession : undefined}
onOpenFiles={() => {
if (!currentSession?.workingDir) return;
router.push({
@@ -9000,6 +8993,28 @@ export default function SessionScreen() {
|| currentSession?.workingDir
|| (connectionError ? t('session.screen.sessionNotSynced') : (deviceName || t('session.screen.conversationFallback')))}
/>
+ </>
+ );
+ return (
+ <View style={styles.safeArea} testID="session.screen">
+ <PaneViewportProvider value={detailViewport}>
+ <ComposerKeyboardAvoidingView
+ keyboard={keyboardState}
+ // 抽屉开着时把背后内容从读屏树里摘掉:iOS 用 accessibilityElementsHidden
+ // (与抽屉侧 accessibilityViewIsModal 配对),Android 用 importantForAccessibility
+ // ——后者才对 TalkBack 生效(与 ComposerRichInput 的双平台配对惯例一致)。
+ accessibilityElementsHidden={sessionListDrawerOverlayMounted}
+ behavior={nativeShellLayout.keyboardAvoidingBehavior}
+ importantForAccessibility={sessionListDrawerOverlayMounted ? 'no-hide-descendants' : 'auto'}
+ keyboardVerticalOffset={nativeShellLayout.keyboardVerticalOffset}
+ style={[styles.keyboard, { marginLeft: paneLayout.detail.x, marginRight: Math.max(0, windowDimensions.width - paneLayout.detail.x - paneLayout.detail.width) }]}
+ >
+ {Platform.OS === 'ios' ? (
+ <SessionHeaderNativeBlur height={Math.max(topOverlayHeight, insets.top + 44) + spacing.xxl} />
+ ) : null}
+ <View ref={topOverlayRef} onLayout={handleTopOverlayLayout} pointerEvents="box-none" style={styles.sessionChrome} testID="session.chrome">
+ <View style={[styles.sessionChromeContent, { paddingTop: horizontalSystemHeader ? nativeHeaderHeight : insets.top + (paneLayout.persistent ? spacing.lg : 0) }]}>
+ {headerNode}
{showConnectionBanner || showCachedHistoryNotice ? (
<ConnectionBanner
@@ -9331,6 +9346,14 @@ export default function SessionScreen() {
{/* showSyncingShell:session 还没回来但在同步,消息区先出骨架(走 MessageRenderer 的 loading 态)。 */}
{showMessageHistory || showSyncingShell ? (
+ <RecentMessageHistories
+ key={auth.accountGeneration}
+ activeKey={JSON.stringify([deviceId, sessionId])}
+ ready={topOverlayHeight > 0 && (historyView.snapshot.ready || messageListItems.length > 0 || (!loading && !syncingWhileEmpty))}
+ topInset={topOverlayHeight}
+ bottomInset={bottomOverlayHeight}
+ interactive={!sessionListDrawerOverlayMounted}>
+
<ChatFilePathContext.Provider value={chatFilePathContextValue}>
<MessageRenderer
remoteDeviceId={deviceId}
@@ -9426,10 +9449,12 @@ export default function SessionScreen() {
</>
)}
scrollResetKey={sessionId}
+ isReadingPositionActive={() => messageScreenFocusedRef.current && messageAppActiveRef.current}
syncingWhileEmpty={syncingWhileEmpty}
testID="session.messageList"
/>
</ChatFilePathContext.Provider>
+ </RecentMessageHistories>
) : null}
</>
@@ -9449,10 +9474,16 @@ export default function SessionScreen() {
pointerEvents="box-none"
style={[
styles.sessionBottomLayer,
+ adaptiveWindow.regions.length > 0 && {
+ left: Math.max(0, composerRegion.x - paneLayout.detail.x),
+ right: Math.max(0, paneLayout.detail.x + paneLayout.detail.width - composerRegion.x - composerRegion.width),
+ maxHeight: composerRegion.height,
+ },
nativeComposerFrameAvailable && sessionOperationLayout.composerSlot === 'editable' && !shareSelectionActive
&& styles.sessionBottomFloating,
shareSelectionActive && { overflow: 'visible' },
- { bottom: nativeShellLayout.keyboardBottomInset },
+ { bottom: Math.max(nativeShellLayout.keyboardBottomInset, adaptiveWindow.regions.length > 0
+ ? windowDimensions.height - composerRegion.y - composerRegion.height - insets.bottom : 0) },
]}
testID="session.bottomLayer"
>
@@ -9709,6 +9740,13 @@ export default function SessionScreen() {
</View>
</View>
</ComposerKeyboardAvoidingView>
+ </PaneViewportProvider>
+
+ {Platform.OS === 'ios' && adaptiveWindow.barEdge !== 'none' && paneLayout.persistent
+ && !shareSelectionActive && !sessionListDrawerOverlayMounted ? (
+ <HomeNewTaskButton bottomInset={insets.bottom} onPress={handleDrawerNewSession} />
+ ) : null}
+
{shareSelectionActive && selectedShareMessages.length > 0 ? (
<ConversationShareSvg
key={`${shareImages.revision}-${mode}`}
@@ -9719,21 +9757,21 @@ export default function SessionScreen() {
width={windowDimensions.width}
/>
) : null}
- {wideSessionNav.enabled || sessionListDrawerOverlayMounted ? (
- // 树内 overlay(zIndex 40)盖住顶部 chrome 与底部 composer;树内层叠而非 Modal 的
- // 取舍见 SessionListDrawer 头注释。退出宽屏时也保留到 onClosed,否则退场期旋转/
- // 收窄会直接卸载组件并吞掉已登记的导航动作。
+ <MessageHistoryOverlay>
+ {/* Keep the drawer above resident histories, including its closing animation. */}
<SessionListDrawer
+ newSessionActionRef={homeNewSessionActionRef}
+ newSessionInSystemBar={paneLayout.persistent && Platform.OS === 'ios' && adaptiveWindow.barEdge !== 'none'}
currentSessionId={sessionId}
onClose={closeSessionListDrawer}
onClosed={handleSessionListDrawerClosed}
- onGoHome={handleDrawerGoHome}
- onNewSession={handleDrawerNewSession}
+ runNavigation={queueDrawerNavigation}
onSelectSession={handleDrawerSelectSession}
- open={sessionListDrawerOpen}
- width={sessionListDrawerWidthRef.current}
+ persistent={paneLayout.persistent && !sessionListDrawerOverlayMounted}
+ open={(paneLayout.persistent && !sessionListDrawerOverlayMounted) || sessionListDrawerOpen}
+ width={paneLayout.persistent && !sessionListDrawerOverlayMounted ? paneLayout.sidebarWidth : sessionListDrawerWidthRef.current}
/>
- ) : null}
+ </MessageHistoryOverlay>
</View>
);
}
@@ -9741,6 +9779,7 @@ export default function SessionScreen() {
type SessionHeaderIcon = typeof Folder;
function SessionHeaderBar({
+ horizontalSystemHeader,
currentSession,
diffCount,
isDeviceAccessRevoked,
@@ -9751,8 +9790,9 @@ function SessionHeaderBar({
messageCount,
messageOnly,
onBack,
- onOpenFiles,
+ onNewSession,
onOpenSessionList,
+ onOpenFiles,
onOpenSettings,
onOpenUsage,
onOpenRemoteDesktop,
@@ -9763,9 +9803,9 @@ function SessionHeaderBar({
readOnlyReason,
remoteUnavailableReason,
searchOpen,
- sessionListButtonRef,
title,
}: {
+ horizontalSystemHeader: boolean;
currentSession: RemoteSession | null;
diffCount: number;
isDeviceAccessRevoked: boolean;
@@ -9779,10 +9819,8 @@ function SessionHeaderBar({
/** Host-managed canonical Sessions expose conversation controls only. */
messageOnly: boolean;
onBack(): void;
- /** 宽屏导航形态下提供:左上角改为三条杠,点击拉出任务列表抽屉(替代返回)。 */
+ onNewSession?: () => void;
onOpenSessionList?: () => void;
- /** 三条杠按钮 ref:抽屉关闭后读屏焦点归还的锚点。 */
- sessionListButtonRef?: RefObject<View | null>;
onOpenFiles(): void;
onOpenSettings(): void;
onOpenUsage(): void;
@@ -9833,6 +9871,47 @@ function SessionHeaderBar({
session: currentSession,
});
const nativeHeader = Platform.OS === 'ios';
+ const systemBack = useSystemNavigationBack();
+ const sessionListButton = onOpenSessionList ? (
+ <HomeHeaderGlassButton accessibilityLabel={t('home.drawer.openA11y')}
+ onPress={onOpenSessionList} testID="session.sessionListButton">
+ <Menu color={colors.textPrimary} size={iconSize.action} strokeWidth={iconStroke.regular} />
+ </HomeHeaderGlassButton>
+ ) : null;
+
+ // Let UINavigationBar align controls with the system status area, including Duo portrait.
+ if (horizontalSystemHeader) {
+ const files = overview?.actions.find(action => action.id === 'files');
+ return <>
+ <Stack.Screen options={{ headerShown: true, headerTransparent: true,
+ headerShadowVisible: false, headerBackVisible: false, headerTitleAlign: 'center',
+ headerStyle: { backgroundColor: 'transparent' }, headerTintColor: colors.textPrimary,
+ // Route-owned options survive the title component's unmount during a pop transition.
+ headerTitle: () => (
+ <View style={{ maxWidth: 240, height: 44, flexShrink: 1, justifyContent: 'center' }}>
+ <SessionHeaderNativeTitle title={title} pinned={!messageOnly && !!currentSession?.pinnedAt}
+ syncing={syncing} syncingImmediately={syncingImmediately} notice={notice} />
+ </View>
+ ),
+ }} />
+ <Stack.Toolbar placement="left">
+ {sessionListButton ? <Stack.Toolbar.View hidesSharedBackground>{sessionListButton}</Stack.Toolbar.View> : null}
+ <Stack.Toolbar.View hidesSharedBackground>
+ <SessionHeaderNativeBack label={t('shared.back')} onPress={onBack} />
+ </Stack.Toolbar.View>
+ </Stack.Toolbar>
+ <Stack.Toolbar placement="right">
+ <Stack.Toolbar.View hidesSharedBackground>
+ <SessionHeaderNativeActions available={!!currentSession}
+ desktopLabel={t('remoteDesktop.title')}
+ filesLabel={t('session.presentation.overview.actions.files.a11y')}
+ moreLabel={t('session.menu.details')} files={files}
+ onDetails={onOpenSettings} onDesktop={onOpenRemoteDesktop}
+ onAction={id => actionHandlers[id]()} />
+ </Stack.Toolbar.View>
+ </Stack.Toolbar>
+ </>;
+ }
// 分享选择模式只保留全选;底部关闭按钮负责退出。
if (shareSelectAllNode) {
@@ -9845,25 +9924,26 @@ function SessionHeaderBar({
]}
testID="session.summary"
>
+ <Stack.Screen options={{ headerShown: false }} />
{shareSelectAllNode}
</View>
);
}
return (
<View style={[styles.sessionHeaderBar, nativeHeader && styles.sessionHeaderBarNative]} testID="session.summary">
- {onOpenSessionList ? (
- // 宽屏(iPad / 折叠屏展开 / 横屏手机):三条杠拉任务列表抽屉,返回语义由抽屉里的
- // 「主页」项与系统返回手势承担。
- <SessionHeaderIconButton
- accessibilityLabel={t('home.drawer.openA11y')}
- active={false}
- buttonRef={sessionListButtonRef}
- hitSlop={4}
- icon={Menu}
- onPress={onOpenSessionList}
- testID="session.sessionListButton"
- />
- ) : nativeHeader ? (
+ <SystemNavigationBack label={t('shared.back')} onPress={onBack} />
+ {sessionListButton}
+ {systemBack ? <Stack.Toolbar placement="right">
+ <Stack.Toolbar.Button icon={require('../../assets/navigation/monitor.png')} iconRenderingMode="template"
+ accessibilityLabel={t('remoteDesktop.title')} disabled={!currentSession} onPress={onOpenRemoteDesktop} />
+ <Stack.Toolbar.Button icon={require('../../assets/navigation/folder.png')} iconRenderingMode="template"
+ accessibilityLabel={t('session.presentation.overview.actions.files.a11y')}
+ disabled={!currentSession || !overview?.actions.some(action => action.id === 'files' && !action.disabled)}
+ onPress={onOpenFiles} />
+ <Stack.Toolbar.Button icon="ellipsis" accessibilityLabel={t('session.menu.details')}
+ disabled={!currentSession} onPress={onOpenSettings} />
+ </Stack.Toolbar> : null}
+ {systemBack ? null : nativeHeader ? (
<SessionHeaderNativeBack label={t('shared.back')} onPress={onBack} />
) : (
<ScreenBackButton
@@ -9910,7 +9990,7 @@ function SessionHeaderBar({
</View>
)}
- {nativeHeader ? (
+ {systemBack ? null : nativeHeader ? (
<SessionHeaderNativeActions
available={!!currentSession}
desktopLabel={t('remoteDesktop.title')}
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 139fb7875f..cfe912bc42 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -5355,7 +5355,8 @@ export default function NewRemoteSessionScreen() {
{creating ? <ActivityIndicator color={colors.textSecondary} /> : null}
</View> : null}
- <View style={styles.bottomCluster}>
+ <ScrollView style={{ flex: 1 }} contentContainerStyle={styles.bottomCluster}
+ keyboardShouldPersistTaps="handled" showsVerticalScrollIndicator={false}>
<View style={styles.selectorStack}>
<View style={styles.deviceSelectorWrap}>
<Pressable
@@ -5914,7 +5915,7 @@ export default function NewRemoteSessionScreen() {
/>
</View>
</View>
- </View>
+ </ScrollView>
</View>
</ComposerKeyboardAvoidingView>
<ContextSheet
@@ -6329,7 +6330,7 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
flexShrink: 0,
},
bottomCluster: {
- flex: 1,
+ flexGrow: 1,
gap: spacing.lg,
justifyContent: 'flex-end',
paddingBottom: spacing.md,
diff --git a/apps/mobile/assets/navigation/LICENSE b/apps/mobile/assets/navigation/LICENSE
new file mode 100644
index 0000000000..325e8ff0aa
--- /dev/null
+++ b/apps/mobile/assets/navigation/LICENSE
@@ -0,0 +1,15 @@
+ISC License
+
+Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2022.
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/apps/mobile/assets/navigation/README.md b/apps/mobile/assets/navigation/README.md
new file mode 100644
index 0000000000..d729cb9f04
--- /dev/null
+++ b/apps/mobile/assets/navigation/README.md
@@ -0,0 +1,9 @@
+# Native toolbar artwork
+
+`monitor.svg` and `folder.svg` preserve the existing lucide-react-native 0.468.0
+Monitor and Folder geometry,
+22pt (`iconSize.xl`), viewBox stroke width 2 (`iconStroke.regular`). PNGs at 1x,
+2x and 3x let the native toolbar use this same outline icon as a template image,
+without substituting an SF Symbol or losing Duo's native vertical placement.
+Metro bundles these JS-referenced assets; no native asset catalog change.
+Lucide's ISC license is included in LICENSE.
diff --git a/apps/mobile/assets/navigation/folder.png b/apps/mobile/assets/navigation/folder.png
new file mode 100644
index 0000000000..2da4397e1e
Binary files /dev/null and b/apps/mobile/assets/navigation/folder.png differ
diff --git a/apps/mobile/assets/navigation/folder.svg b/apps/mobile/assets/navigation/folder.svg
new file mode 100644
index 0000000000..0ae8ad1111
--- /dev/null
+++ b/apps/mobile/assets/navigation/folder.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/></svg>
diff --git a/apps/mobile/assets/navigation/[email protected] b/apps/mobile/assets/navigation/[email protected]
new file mode 100644
index 0000000000..f4fe3e3b9d
Binary files /dev/null and b/apps/mobile/assets/navigation/[email protected] differ
diff --git a/apps/mobile/assets/navigation/[email protected] b/apps/mobile/assets/navigation/[email protected]
new file mode 100644
index 0000000000..af67833f1d
Binary files /dev/null and b/apps/mobile/assets/navigation/[email protected] differ
diff --git a/apps/mobile/assets/navigation/monitor.png b/apps/mobile/assets/navigation/monitor.png
new file mode 100644
index 0000000000..d80c181716
Binary files /dev/null and b/apps/mobile/assets/navigation/monitor.png differ
diff --git a/apps/mobile/assets/navigation/monitor.svg b/apps/mobile/assets/navigation/monitor.svg
new file mode 100644
index 0000000000..5c7cef40ca
--- /dev/null
+++ b/apps/mobile/assets/navigation/monitor.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="14" x="2" y="3" rx="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/></svg>
diff --git a/apps/mobile/assets/navigation/[email protected] b/apps/mobile/assets/navigation/[email protected]
new file mode 100644
index 0000000000..5491dc6ef5
Binary files /dev/null and b/apps/mobile/assets/navigation/[email protected] differ
diff --git a/apps/mobile/assets/navigation/[email protected] b/apps/mobile/assets/navigation/[email protected]
new file mode 100644
index 0000000000..ca99232d24
Binary files /dev/null and b/apps/mobile/assets/navigation/[email protected] differ
diff --git a/apps/mobile/modules/xdt-ios-action-sheet/ios/CindyResidentHistoryView.swift b/apps/mobile/modules/xdt-ios-action-sheet/ios/CindyResidentHistoryView.swift
new file mode 100644
index 0000000000..0b689dee23
--- /dev/null
+++ b/apps/mobile/modules/xdt-ios-action-sheet/ios/CindyResidentHistoryView.swift
@@ -0,0 +1,77 @@
+import ExpoModulesCore
+import UIKit
+
+/// Weak discovery only. React owns the hosts and the five-entry eviction policy.
+private enum ResidentHistories {
+ static let hosts = NSMapTable<NSString, CindyResidentHistoryHost>(keyOptions: .strongMemory, valueOptions: .weakMemory)
+ static let slots = NSHashTable<CindyResidentHistorySlot>.weakObjects()
+
+ static func attach(_ key: String) {
+ guard !key.isEmpty, let host = hosts.object(forKey: key as NSString),
+ let slot = slots.allObjects.last(where: { $0.surfaceId == key && $0.selected && $0.window != nil }) else { return }
+ if host.content.superview !== slot {
+ host.content.removeFromSuperview()
+ slot.addSubview(host.content)
+ }
+ host.content.frame = slot.bounds
+ }
+}
+
+/// Fabric continues to own this host at the app root. Only its plain UIKit
+/// content container moves, so Fabric's parent/child mounting contract stays intact.
+final class CindyResidentHistoryHost: ExpoView {
+ let content = UIView()
+ var surfaceId = "" {
+ didSet {
+ if ResidentHistories.hosts.object(forKey: oldValue as NSString) === self {
+ ResidentHistories.hosts.removeObject(forKey: oldValue as NSString)
+ }
+ ResidentHistories.hosts.setObject(self, forKey: surfaceId as NSString)
+ ResidentHistories.attach(surfaceId)
+ }
+ }
+ override func mountChildComponentView(_ childComponentView: UIView, index: Int) {
+ content.insertSubview(childComponentView, at: index)
+ }
+ override func unmountChildComponentView(_ childComponentView: UIView, index: Int) {
+ childComponentView.removeFromSuperview()
+ }
+ override func layoutSubviews() {
+ super.layoutSubviews()
+ if let slot = content.superview { content.frame = slot.bounds }
+ }
+ deinit {
+ content.removeFromSuperview()
+ if ResidentHistories.hosts.object(forKey: surfaceId as NSString) === self {
+ ResidentHistories.hosts.removeObject(forKey: surfaceId as NSString)
+ }
+ }
+}
+
+/// Lives inside the actual native navigation screen, preserving system back
+/// gestures, transitions, native glass underlap and route-owned overlays.
+final class CindyResidentHistorySlot: ExpoView {
+ var surfaceId = "" { didSet { reconnect() } }
+ var selected = false { didSet { reconnect() } }
+ required init(appContext: AppContext? = nil) {
+ super.init(appContext: appContext)
+ clipsToBounds = true
+ ResidentHistories.slots.add(self)
+ }
+ private func reconnect() {
+ for child in subviews where child !== ResidentHistories.hosts.object(forKey: surfaceId as NSString)?.content {
+ child.removeFromSuperview()
+ }
+ ResidentHistories.attach(surfaceId)
+ }
+ override func didMoveToWindow() {
+ super.didMoveToWindow()
+ if window == nil {
+ for child in subviews { child.removeFromSuperview() }
+ } else { reconnect() }
+ }
+ override func layoutSubviews() {
+ super.layoutSubviews()
+ for child in subviews { child.frame = bounds }
+ }
+}
diff --git a/apps/mobile/modules/xdt-ios-action-sheet/ios/CindyWindowGeometry.h b/apps/mobile/modules/xdt-ios-action-sheet/ios/CindyWindowGeometry.h
new file mode 100644
index 0000000000..f9b4974748
--- /dev/null
+++ b/apps/mobile/modules/xdt-ios-action-sheet/ios/CindyWindowGeometry.h
@@ -0,0 +1,8 @@
+#import <UIKit/UIKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+/// View-local layout observation; never chooses a window from connectedScenes.
+@interface CindyWindowGeometry : UIView
+@property(nonatomic, copy, nullable) void (^onChange)(NSDictionary *geometry);
+@end
+NS_ASSUME_NONNULL_END
diff --git a/apps/mobile/modules/xdt-ios-action-sheet/ios/CindyWindowGeometry.m b/apps/mobile/modules/xdt-ios-action-sheet/ios/CindyWindowGeometry.m
new file mode 100644
index 0000000000..ff62165f13
--- /dev/null
+++ b/apps/mobile/modules/xdt-ios-action-sheet/ios/CindyWindowGeometry.m
@@ -0,0 +1,117 @@
+#import "CindyWindowGeometry.h"
+
+#if __has_include(<UIKit/UIViewReservedRegion.h>) && __has_include(<UIKit/UIVerticalBarEdge.h>)
+#define CINDY_RESERVED_REGIONS 1
+#else
+#define CINDY_RESERVED_REGIONS 0
+#endif
+
+@interface CindyWindowGeometry (Observation)
+- (void)publishGeometry;
+@end
+/// CADisplayLink retains its target; the target must not retain the observed view.
+@interface CindyGeometryTick : NSObject
+@property(nonatomic, weak) CindyWindowGeometry *view;
+- (void)tick;
+@end
+@implementation CindyGeometryTick
+- (void)tick { [self.view publishGeometry]; }
+@end
+
+@implementation CindyWindowGeometry {
+ CADisplayLink *_displayLink;
+ NSDictionary *_lastGeometry;
+}
+- (instancetype)initWithFrame:(CGRect)frame {
+ if ((self = [super initWithFrame:frame])) {
+ self.userInteractionEnabled = NO;
+ self.accessibilityElementsHidden = YES;
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(stopObserving)
+ name:UIApplicationDidEnterBackgroundNotification object:nil];
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(startObserving)
+ name:UIApplicationDidBecomeActiveNotification object:nil];
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(sceneChanged:)
+ name:UISceneDidActivateNotification object:nil];
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(sceneChanged:)
+ name:UISceneWillDeactivateNotification object:nil];
+ }
+ return self;
+}
+- (void)dealloc {
+ [_displayLink invalidate];
+ [NSNotificationCenter.defaultCenter removeObserver:self];
+}
+- (void)didMoveToWindow {
+ [super didMoveToWindow];
+ [self stopObserving];
+ _lastGeometry = nil;
+ [self startObserving];
+}
+- (void)sceneChanged:(NSNotification *)notification {
+ if (notification.object != self.window.windowScene) return;
+ if ([notification.name isEqualToString:UISceneWillDeactivateNotification]) [self stopObserving];
+ else [self startObserving];
+}
+- (void)stopObserving { [_displayLink invalidate]; _displayLink = nil; }
+- (void)startObserving {
+ if (!self.window || self.window.windowScene.activationState != UISceneActivationStateForegroundActive) return;
+ [self publishGeometry];
+#if CINDY_RESERVED_REGIONS
+ if (@available(iOS 27.1, *)) {
+ // A region can move without bounds or size-class changes (hinge/camera).
+ // Sample only attached, active views; unchanged snapshots never cross JS.
+ if (!_displayLink) {
+ CindyGeometryTick *target = [CindyGeometryTick new];
+ target.view = self;
+ _displayLink = [CADisplayLink displayLinkWithTarget:target selector:@selector(tick)];
+ _displayLink.preferredFrameRateRange = CAFrameRateRangeMake(5, 10, 10);
+ [_displayLink addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes];
+ }
+ }
+#endif
+}
+- (void)layoutSubviews { [super layoutSubviews]; [self publishGeometry]; }
+- (void)safeAreaInsetsDidChange { [super safeAreaInsetsDidChange]; [self publishGeometry]; }
+- (void)traitCollectionDidChange:(UITraitCollection *)previous {
+ [super traitCollectionDidChange:previous];
+ [self publishGeometry];
+}
+- (void)publishGeometry {
+ if (!self.window || CGRectIsEmpty(self.bounds)) return;
+ UIEdgeInsets safe = self.safeAreaInsets;
+ NSMutableArray *regions = [NSMutableArray array];
+ NSString *edge = @"none";
+ BOOL supported = NO;
+#if CINDY_RESERVED_REGIONS
+ if (@available(iOS 27.1, *)) {
+ supported = YES;
+ // These edges are hardware-relative, not mirrored for RTL content.
+ switch (self.traitCollection.verticalBarEdge) {
+ case UIVerticalBarEdgeLeading: edge = @"left"; break;
+ case UIVerticalBarEdgeTrailing: edge = @"right"; break;
+ default: break;
+ }
+ NSArray *kinds = @[UIViewReservedRegionKind.divisionRegionKind, UIViewReservedRegionKind.occlusionRegionKind];
+ for (NSUInteger i = 0; i < kinds.count; i++) {
+ for (UIViewReservedRegion *region in [self reservedRegionsOfKind:kinds[i]]) {
+ CGRect rect = CGRectIntersection(self.bounds, region.frame);
+ if (CGRectIsNull(rect) || CGRectIsEmpty(rect)) continue;
+ [regions addObject:@{@"kind": i == 0 ? @"division" : @"occlusion",
+ @"x": @(rect.origin.x), @"y": @(rect.origin.y),
+ @"width": @(rect.size.width), @"height": @(rect.size.height)}];
+ }
+ }
+ }
+#endif
+ NSDictionary *geometry = @{
+ @"width": @(self.bounds.size.width), @"height": @(self.bounds.size.height),
+ @"insets": @{@"top": @(safe.top), @"right": @(safe.right), @"bottom": @(safe.bottom), @"left": @(safe.left)},
+ @"regularWidth": @(self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassRegular),
+ @"regularHeight": @(self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassRegular),
+ @"barEdge": edge, @"regions": regions, @"reservedRegionsSupported": @(supported)
+ };
+ if ([_lastGeometry isEqualToDictionary:geometry]) return;
+ _lastGeometry = geometry;
+ if (self.onChange) self.onChange(geometry);
+}
+@end
diff --git a/apps/mobile/modules/xdt-ios-action-sheet/ios/CindyWindowLayoutView.swift b/apps/mobile/modules/xdt-ios-action-sheet/ios/CindyWindowLayoutView.swift
new file mode 100644
index 0000000000..71566ca016
--- /dev/null
+++ b/apps/mobile/modules/xdt-ios-action-sheet/ios/CindyWindowLayoutView.swift
@@ -0,0 +1,22 @@
+import ExpoModulesCore
+import UIKit
+
+/// Transparent probe sharing the React container's bounds and window.
+final class CindyWindowLayoutView: ExpoView {
+ let onGeometryChange = EventDispatcher()
+ private let geometry = CindyWindowGeometry()
+ required init(appContext: AppContext? = nil) {
+ super.init(appContext: appContext)
+ isUserInteractionEnabled = false
+ accessibilityElementsHidden = true
+ geometry.onChange = { [weak self] value in
+ guard let payload = value as? [String: Any] else { return }
+ self?.onGeometryChange(payload)
+ }
+ addSubview(geometry)
+ }
+ override func layoutSubviews() {
+ super.layoutSubviews()
+ geometry.frame = bounds
+ }
+}
diff --git a/apps/mobile/modules/xdt-ios-action-sheet/ios/XdtIosActionSheetModule.swift b/apps/mobile/modules/xdt-ios-action-sheet/ios/XdtIosActionSheetModule.swift
index 1af3234b2e..59250283a0 100644
--- a/apps/mobile/modules/xdt-ios-action-sheet/ios/XdtIosActionSheetModule.swift
+++ b/apps/mobile/modules/xdt-ios-action-sheet/ios/XdtIosActionSheetModule.swift
@@ -9,6 +9,20 @@ public class XdtIosActionSheetModule: Module {
public func definition() -> ModuleDefinition {
Name("XdtIosActionSheet")
+ Constant("windowLayoutAvailable") { true }
+ View(CindyWindowLayoutView.self) {
+ Events("onGeometryChange")
+ }
+ Constant("residentHistoryAvailable") { true }
+ View(CindyResidentHistoryHost.self) {
+ ViewName("ResidentHistoryHost")
+ Prop("surfaceId") { (view, id: String) in view.surfaceId = id }
+ }
+ View(CindyResidentHistorySlot.self) {
+ ViewName("ResidentHistorySlot")
+ Prop("surfaceId") { (view, id: String) in view.surfaceId = id }
+ Prop("selected") { (view, selected: Bool) in view.selected = selected }
+ }
AsyncFunction("show") { (options: [String: Any], promise: Promise) in
DispatchQueue.main.async {
diff --git a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
index e4b89b0e29..12ff720ba0 100644
--- a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
+++ b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx
@@ -10,6 +10,7 @@ const { resolveInteraction } = vi.hoisted(() => ({ resolveInteraction: vi.fn() }
vi.mock('@/device-link/useMobileMakerTransport', () => ({
useMobileMakerTransport: () => ({ resolveInteraction }),
}));
+vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }) }));
vi.mock('react-native', async () => {
const { createElement } = await import('react');
const view = (tag: string) => ({ children, onPress, disabled, testID }: {
diff --git a/apps/mobile/src/__tests__/automationGroupPress.test.ts b/apps/mobile/src/__tests__/automationGroupPress.test.ts
index 49f4284bd1..b0ac801ff6 100644
--- a/apps/mobile/src/__tests__/automationGroupPress.test.ts
+++ b/apps/mobile/src/__tests__/automationGroupPress.test.ts
@@ -4,7 +4,7 @@ import { describe, expect, it, vi } from 'vitest';
import type { RemoteSessionListItem } from '@cindy/maker-shared/session-list';
import { resolveMobileSessionRowStatus } from '../session/sessionRightStatus';
-const source = readFileSync(resolve(process.cwd(), 'app/devices/index.tsx'), 'utf8').replace(/\r\n/g, '\n');
+const source = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8').replace(/\r\n/g, '\n');
const start = source.indexOf(' const openGroupPrimary = () => {');
const body = source.slice(start, source.indexOf(' return (', start));
// Execute the actual row handler while keeping native rendering out of this unit test.
diff --git a/apps/mobile/src/__tests__/composerSheetOrientation.test.tsx b/apps/mobile/src/__tests__/composerSheetOrientation.test.tsx
new file mode 100644
index 0000000000..91cb2b7310
--- /dev/null
+++ b/apps/mobile/src/__tests__/composerSheetOrientation.test.tsx
@@ -0,0 +1,47 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { expect, it, vi } from 'vitest';
+import { ComposerSheet } from '../session/ComposerSheet.ios';
+import { presentationDetents } from '@expo/ui/swift-ui/modifiers';
+const state = vi.hoisted(() => ({ width: 402, height: 874, sheet: null as any }));
+vi.mock('react-native', () => ({
+ View: ({ children }: any) => <div>{children}</div>, ScrollView: ({ children }: any) => <div>{children}</div>,
+ useWindowDimensions: () => ({ width: state.width, height: state.height }),
+}));
+vi.mock('@expo/ui', () => ({ Host: ({ children }: any) => <div>{children}</div> }));
+vi.mock('@expo/ui/swift-ui', () => {
+ const Container = ({ children }: any) => <div>{children}</div>;
+ return { Form: Container, Button: Container, Group: Container, HStack: Container, Image: Container,
+ RNHostView: Container, Spacer: Container, Text: Container, VStack: Container,
+ BottomSheet: (props: any) => { state.sheet = props; return <div>{props.children}</div>; },
+ };
+});
+vi.mock('@expo/ui/swift-ui/modifiers', () => ({
+ ...Object.fromEntries(['accessibilityLabel', 'contentShape', 'buttonStyle', 'font', 'foregroundStyle', 'frame', 'padding', 'presentationDetents', 'presentationDragIndicator', 'scrollContentBackground'].map(name => [name, vi.fn(() => ({}))])),
+ shapes: { rectangle: () => ({}) },
+}));
+vi.mock('@/theme', () => ({ iconSize: { lg: 20 }, useTheme: () => ({ mode: 'light', colors: {} }) }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+
+it('selects a supported native detent when opening and rotating a menu', () => {
+ const root = createRoot(document.createElement('div'));
+ const onClose = vi.fn(); const onClosed = vi.fn();
+ const render = () => act(() => root.render(<ComposerSheet visible title="" nativeContent onClose={onClose} onClosed={onClosed}><span>Menu</span></ComposerSheet>));
+ try {
+ render();
+ expect(presentationDetents).toHaveBeenLastCalledWith(['medium', 'large'], { selection: 'medium' });
+ state.width = 874; state.height = 402; render();
+ expect(presentationDetents).toHaveBeenLastCalledWith(['large'], { selection: 'large' });
+ expect(state.sheet.isPresented).toBe(true);
+ state.width = 402; state.height = 874; render();
+ expect(presentationDetents).toHaveBeenLastCalledWith(['medium', 'large'], { selection: 'medium' });
+ expect(onClose).not.toHaveBeenCalled();
+ act(() => state.sheet.onIsPresentedChange(false));
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(onClosed).not.toHaveBeenCalled();
+ act(() => state.sheet.onDismiss());
+ expect(onClosed).toHaveBeenCalledOnce();
+ } finally { act(() => root.unmount()); }
+});
diff --git a/apps/mobile/src/__tests__/conversationSearchLifecycle.test.tsx b/apps/mobile/src/__tests__/conversationSearchLifecycle.test.tsx
index 84c8972dca..988699c59a 100644
--- a/apps/mobile/src/__tests__/conversationSearchLifecycle.test.tsx
+++ b/apps/mobile/src/__tests__/conversationSearchLifecycle.test.tsx
@@ -2,6 +2,7 @@
import { act, createElement } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { HomeViewSession } from '@/session/homeViewSession';
import { useConversationSearch } from '@/session/useConversationSearch';
import {
searchConversationsAcrossDevices,
@@ -27,9 +28,10 @@ const invoke = vi.fn();
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root;
let search: ReturnType<typeof useConversationSearch>;
-function Probe({ count = 1, reachable = true }: { count?: number; reachable?: boolean }) {
+function Probe({ count = 1, reachable = true, retainedState }: { count?: number; reachable?: boolean; retainedState?: HomeViewSession }) {
search = useConversationSearch({
enabled: true,
+ retainedState,
origins: [{ deviceId: 'mac', deviceName: 'Mac', reachable }],
projects: [
{
@@ -98,6 +100,24 @@ async function start() {
});
}
describe('mobile search scope refresh', () => {
+ it('keeps the real search query and filters when Home moves between hosts', async () => {
+ const retainedState = new HomeViewSession();
+ vi.mocked(searchConversationsAcrossDevices).mockResolvedValue(page);
+ await act(async () => root.render(<Probe key="page" retainedState={retainedState} />));
+ act(() => {
+ search.setQuery('needle');
+ search.setSortBy('activityDesc');
+ search.setStatusFilter('active');
+ search.setProjectSelection(['mac:/repo']);
+ });
+ await act(async () => root.render(<Probe key="sidebar" retainedState={retainedState} />));
+ expect(search.query).toBe('needle');
+ expect(search.sortBy).toBe('activityDesc');
+ expect(search.statusFilter).toBe('active');
+ expect(search.projectSelection).toEqual(['mac:/repo']);
+ await act(async () => vi.advanceTimersByTimeAsync(250));
+ expect(search.results.map((result) => result.session.id)).toEqual(['body-match']);
+ });
it('keeps the indexed page visible when project counts and object references refresh', async () => {
await start();
expect(search.status).toBe('ready');
diff --git a/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts b/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts
index 307813ecca..fba78f7bbb 100644
--- a/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts
+++ b/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts
@@ -353,7 +353,10 @@ describe('buildConversationShareHtml 富内容导出', () => {
expect(html).toMatch(
/#xdt-content\.share-stage\s*\{[\s\S]*?display: flex;[\s\S]*?flex-direction: column;[\s\S]*?gap: 16px;/,
);
- expect(shareBarSource).toContain('height: 44,');
+ expect(shareBarSource).toContain('<HomeHeaderGlassButton');
+ const chromeStyle = readFileSync(resolve(process.cwd(), 'src/platform/chrome/nativeGlassButtonStyle.ios.ts'), 'utf8');
+ expect(chromeStyle).toContain('size = navigationChrome.target');
+ expect(chromeStyle).toContain(': { width: size, height: size })');
expect(shareBarSource).toContain('minHeight: 44,');
expect(shareBarSource).toContain('minWidth: 112,');
expect(shareBarSource).toContain('fontSize: typeScale.body,');
diff --git a/apps/mobile/src/__tests__/designTokenDiscipline.test.ts b/apps/mobile/src/__tests__/designTokenDiscipline.test.ts
index 19feff7252..48db1481fd 100644
--- a/apps/mobile/src/__tests__/designTokenDiscipline.test.ts
+++ b/apps/mobile/src/__tests__/designTokenDiscipline.test.ts
@@ -43,12 +43,12 @@ const ALLOWLIST: Array<{ file: string; snippet: string; reason: string }> = [
reason: 'composer 多行形态组件几何(desktop-first 测试钉死)',
},
{
- file: 'app/devices/index.tsx',
+ file: 'src/session/HomeListVisuals.tsx',
snippet: 'size={9}',
reason: 'Pencil 微徽标,徽标容器几何依赖 9px',
},
{
- file: 'app/devices/index.tsx',
+ file: 'src/session/HomeListVisuals.tsx',
snippet: '? 19 : iconSize.lg',
reason: 'Claude logo 视觉重量偏小的 +1px 光学补偿',
},
@@ -73,7 +73,7 @@ const ALLOWLIST: Array<{ file: string; snippet: string; reason: string }> = [
reason: '标注角标微徽标几何(红底 12px 徽标内画笔,阶梯档过大)',
},
{
- file: 'app/devices/index.tsx',
+ file: 'src/session/HomeSurface.tsx',
snippet: 'borderRadius: 0',
reason: '显式方角覆盖,非漂移(通栏布局回退恢复,用户改稿 2026-07-21)',
},
diff --git a/apps/mobile/src/__tests__/goalNativeForm.test.tsx b/apps/mobile/src/__tests__/goalNativeForm.test.tsx
index 53a02a3bf7..7e72e7b6ce 100644
--- a/apps/mobile/src/__tests__/goalNativeForm.test.tsx
+++ b/apps/mobile/src/__tests__/goalNativeForm.test.tsx
@@ -19,9 +19,10 @@ vi.mock('@expo/ui/swift-ui', async () => {
};
});
vi.mock('@expo/ui/swift-ui/modifiers', () => Object.fromEntries(
- ['accessibilityHint', 'accessibilityLabel', 'buttonStyle', 'contentShape', 'disabled', 'font', 'foregroundStyle', 'frame', 'lineLimit', 'pickerStyle', 'tag'].map(key => [key, (value: any) => ({ [key]: value })]).concat([['shapes', { rectangle: () => ({}) }] as any]),
+ ['buttonBorderShape', 'controlSize', 'accessibilityHint', 'accessibilityLabel', 'buttonStyle', 'contentShape', 'disabled', 'font', 'foregroundStyle', 'frame', 'lineLimit', 'pickerStyle', 'tag'].map(key => [key, (value: any) => ({ [key]: value })]).concat([['shapes', { rectangle: () => ({}) }] as any]),
));
-vi.mock('@/theme', () => ({ useTheme: () => ({ colors: {} }) }));
+vi.mock('@/theme', () => ({ navigationChrome: { target: 44 }, useTheme: () => ({ colors: {} }) }));
+vi.mock('@/session/useLiquidGlassAvailable', () => ({ useLiquidGlassAvailable: () => true }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('@/session/ComposerNativeSection', () => ({ ComposerNativeSection: (p: any) => createElement('section', null, p.children) }));
vi.mock('@/session/goalStatusLabel', () => ({ goalReasonText: () => '', goalStatusLabel: (status: string) => status, GOAL_STATUS_LABEL: {} }));
diff --git a/apps/mobile/src/__tests__/historyDiskStoreExpo.test.ts b/apps/mobile/src/__tests__/historyDiskStoreExpo.test.ts
new file mode 100644
index 0000000000..dce0c1a9fa
--- /dev/null
+++ b/apps/mobile/src/__tests__/historyDiskStoreExpo.test.ts
@@ -0,0 +1,56 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const state = vi.hoisted(() => ({ files: new Map<string, string>(), failMove: false, failWrite: false }));
+vi.mock('expo-file-system', () => {
+ class Directory {
+ uri: string;
+ constructor(parent: string, name: string) { this.uri = `${parent}/${name}`; }
+ create() {}
+ }
+ class File {
+ uri: string;
+ constructor(parent: Directory | string, name?: string) {
+ this.uri = name ? `${typeof parent === 'string' ? parent : parent.uri}/${name}` : String(parent);
+ }
+ get exists() { return state.files.has(this.uri); }
+ text() { return Promise.resolve(state.files.get(this.uri)); }
+ delete() { state.files.delete(this.uri); }
+ moveSync(destination: File) {
+ if (state.failMove) throw new Error('move failed');
+ state.files.set(destination.uri, state.files.get(this.uri)!);
+ state.files.delete(this.uri);
+ // Expo mutates the source object after a move.
+ this.uri = destination.uri;
+ }
+ }
+ return { Directory, File, Paths: { cache: 'file:///cache' } };
+});
+vi.mock('expo-file-system/legacy', () => ({
+ writeAsStringAsync: async (uri: string, text: string) => {
+ state.files.set(uri, text);
+ if (state.failWrite) throw new Error('write failed');
+ },
+}));
+import { createHistoryDiskIO } from '../session/historyDiskStoreExpo';
+
+beforeEach(() => { state.files.clear(); state.failMove = false; state.failWrite = false; });
+describe('Expo history disk IO', () => {
+ it('keeps committed snapshots and the index after moving the staging file', async () => {
+ const io = createHistoryDiskIO();
+ await io.write('view-a.json', 'first');
+ await io.write('view-a.json', 'updated');
+ await io.write('index.json', '{}');
+ expect(await io.read('view-a.json')).toBe('updated');
+ expect(await io.read('index.json')).toBe('{}');
+ expect(state.files.size).toBe(2);
+ expect([...state.files.keys()].some(key => key.endsWith('.tmp'))).toBe(false);
+ });
+ it.each(['failMove', 'failWrite'] as const)('cleans staging files after %s without deleting the previous snapshot', async failure => {
+ const io = createHistoryDiskIO();
+ await io.write('view-a.json', 'original');
+ state[failure] = true;
+ await expect(io.write('view-a.json', 'replacement')).rejects.toThrow();
+ expect(await io.read('view-a.json')).toBe('original');
+ expect(state.files.size).toBe(1);
+ });
+});
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index a15439cedf..7d238f9c3e 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -1,4 +1,4 @@
-import { readFileSync } from 'node:fs';
+import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it, vi } from 'vitest';
import { i18n } from '@/i18n';
@@ -22,7 +22,7 @@ describe('mobile Home connection feedback', () => {
});
it('wires Home itself to the shared recovery indicator instead of an unconditional retry button', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
expect(source).toContain('resolveHomeConnectionFeedback(error, homeRecoveringDeviceIds, describeRemoteError)');
expect(source).toContain('deviceUnresponsive: homeDeviceRecovery,');
expect(source).toContain('const showHomeSyncAction = resolveConnectionBannerSyncActionVisibility(');
@@ -33,7 +33,7 @@ describe('mobile Home connection feedback', () => {
const hydrate = source.slice(source.indexOf('const hydrateDeviceSessions = useCallback('), source.indexOf('const probeRevokedDeviceAccess'));
expect(hydrate.indexOf("updateDeviceConnectionState(device.deviceId, 'syncing')")).toBeLessThan(hydrate.indexOf('const promise = hydrateDeviceSessionsOnce('));
expect(source).toContain('useDelayedConnectionNotice(showConnectionRow)');
- const row = source.slice(source.indexOf('{showConnectionNotice ? ('), source.indexOf('<SectionList'));
+ const row = source.slice(source.indexOf('{showConnectionNotice ? ('), source.indexOf('</ConnectionNoticeOverlay>'));
expect(row).toMatch(/showHomeSyncAction\s*\?\s*<Pressable/);
const progress = row.slice(row.indexOf(': showHomeRecoveryProgress ?'));
expect(progress).toContain('<ConnectionRecoveryProgress');
@@ -155,7 +155,7 @@ describe('mobile Home startup reads', () => {
describe('mobile home desktop-first surface', () => {
it('surfaces durable logout failures from the home drawer', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
const logoutStart = source.indexOf('const logout = useCallback');
const logoutBody = source.slice(
logoutStart,
@@ -179,10 +179,10 @@ describe('mobile home desktop-first surface', () => {
});
it('keeps the home list leaner than device detail surfaces', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
const removedListTokenPrefix = 'home' + 'List';
- expect(source).toContain('export default function HomeScreen()');
+ expect(source).toContain('export function MobileHome(props: MobileHomeProps)');
expect(source).not.toContain('export default function DevicesScreen()');
expect(source).not.toContain('styles.deviceChipBadge');
expect(source).not.toContain('styles.worktreeBadge');
@@ -217,9 +217,15 @@ describe('mobile home desktop-first surface', () => {
expect(source).toContain('testID="home.displaySettingsButton"');
expect(source).toContain('<HomeChromeDrawer');
expect(source).toContain('<HomeHeaderGlassButton');
- const headerGlass = readSource('src/session/HomeHeaderGlassButton.tsx');
- expect(headerGlass).toMatch(/from ['"]expo-glass-effect['"]/);
- expect(headerGlass).toContain('glassEffectStyle="regular"');
+ const headerGlass = readSource('src/session/HomeHeaderGlassButton.ios.tsx');
+ expect(headerGlass).toContain('<NativeChromeButton');
+ const nativeBack = readSource('src/platform/chrome/NativeChromeBackButton.ios.tsx');
+ expect(nativeBack).toContain('<NativeChromeButton');
+ const systemBack = readSource('src/platform/chrome/SystemNavigationBack.tsx');
+ expect(systemBack).toContain('<Stack.Toolbar.Button');
+ expect(systemBack).not.toContain('<Stack.Toolbar.View');
+ expect(systemBack).not.toContain('<NativeChromeButton');
+ expect(headerGlass).not.toContain('expo-glass-effect');
expect(source).toContain('<HomeChromeFrost disabled={nativeHomeHeader} visible={headerFrosted}>');
expect(source).toContain('</HomeChromeFrost>');
expect(source).toContain('<HomeNativeStackHeader');
@@ -284,10 +290,14 @@ describe('mobile home desktop-first surface', () => {
expect(source).not.toContain('styles.sessionBadge');
expect(source).toContain('backgroundColor: colors.surface');
expect(source).toContain('borderBottomColor: colors.border');
- expect(source).toContain('colors.homeListFab');
- // 2026-07-21 通栏回退:FAB 图标退回 XD-Maker 原版 SquarePen(用户定稿),尺寸/描边同回原档。
- expect(source).toContain('SquarePen,');
- expect(source).toContain('<SquarePen color={colors.ctaText} size={iconSize.xxl} strokeWidth={iconStroke.regular} />');
+ expect(source).not.toContain('<GlassView');
+ expect(source).toContain('<HomeHeaderGlassButton');
+ const floatingAction = readSource('src/session/HomeNewTaskButton.tsx');
+ expect(source).toContain('<HomeNewTaskButton');
+ expect(floatingAction).toContain('prominent size={HOME_NEW_TASK_SIZE} artworkSize={iconSize.xxl}');
+ // Preserve SquarePen artwork while adopting the shared native action size.
+ expect(floatingAction).toContain('SquarePen');
+ expect(floatingAction).toContain('<SquarePen color={colors.ctaText} size={iconSize.xxl} strokeWidth={iconStroke.regular} />');
expect(source).not.toContain('<Send');
expect(source).not.toContain('function HomeNewChatGlyph');
expect(source).not.toContain("import Svg, { Path } from 'react-native-svg';");
@@ -295,14 +305,14 @@ describe('mobile home desktop-first surface', () => {
expect(source).not.toContain(`colors.${removedListTokenPrefix}Divider`);
expect(source).not.toContain(`colors.${removedListTokenPrefix}Shadow`);
expect(source).toContain('fontWeight: fontWeight.medium');
- expect(source).toContain('testID="home.newChatButton"');
- expect(source).toContain("position: 'absolute'");
- expect(source).toContain('bottom: CINDY_LIST_FAB_BOTTOM');
- expect(source).toContain('right: CINDY_LIST_GUTTER');
+ expect(floatingAction).toContain('testID="home.newChatButton"');
+ expect(floatingAction).toContain("position: 'absolute'");
+ expect(floatingAction).toContain('bottom: 45 + bottomInset');
+ expect(floatingAction).toContain('right: 20');
});
it('opens desktop-parity search filters from the search sliders, not display settings', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
const searchBar = readSource('src/session/HomeSearchBar.tsx');
const filterSheet = readSource('src/session/ConversationSearchFilterSheet.tsx');
@@ -326,7 +336,7 @@ describe('mobile home desktop-first surface', () => {
});
it('uses TapTap blue for the online dot treatment', () => {
- const homeSource = readSource('app/devices/index.tsx');
+ const homeSource = readSource('src/session/HomeSurface.tsx');
const primitivesSource = readSource('src/components/MobilePrimitives.tsx');
const tokenSource = readSource('src/theme/tokens.ts');
const removedListTokenPrefix = 'home' + 'List';
@@ -346,7 +356,7 @@ describe('mobile home desktop-first surface', () => {
});
it('mirrors the desktop sidebar Agent identity slot and running treatment', () => {
- const homeSource = readSource('app/devices/index.tsx');
+ const homeSource = readSource('src/session/HomeSurface.tsx') + readSource('src/session/HomeListVisuals.tsx');
const vendorIconSource = readSource('src/components/MobileVendorIcon.tsx');
const agentMarkSource = readSource('src/components/MobileAgentMark.tsx');
const providerMarkSource = readSource('src/session/MobileProviderMark.tsx');
@@ -411,7 +421,7 @@ describe('mobile home desktop-first surface', () => {
});
it('uses desktop-style attention dots for unread automation on the home list without extra row text', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
const scheduleIndexSource = readSource('src/session/scheduleIndex.ts');
expect(source).toContain('const [scheduleIndex, setScheduleIndex]');
@@ -458,7 +468,7 @@ describe('mobile home desktop-first surface', () => {
});
it('gives device chips stable per-device e2e anchors for multi-device local smoke', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
const maestroSource = readSource('scripts/maestro-e2e.mjs');
const localSmokeSource = readSource('scripts/local-device-link-smoke.mjs');
const deviceDetailFlow = readSource('e2e/maestro/session_list_controls.yaml');
@@ -474,7 +484,7 @@ describe('mobile home desktop-first surface', () => {
});
it('keeps device management in the drawer and scope selection direct', () => {
- const home = readSource('app/devices/index.tsx');
+ const home = readSource('src/session/HomeSurface.tsx');
const drawer = readSource('src/session/HomeChromeDrawer.tsx');
const management = readSource('app/devices/manage.tsx');
@@ -488,7 +498,7 @@ describe('mobile home desktop-first surface', () => {
});
it('scopes multi-device connection feedback to the affected device chip', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
expect(source).toContain("type HomeDeviceConnectionState = 'idle' | 'syncing' | 'failed';");
expect(source).toContain('const [rawDeviceConnectionStates, setDeviceConnectionStates]');
@@ -512,7 +522,7 @@ describe('mobile home desktop-first surface', () => {
});
it('keeps project and session rows at desktop sidebar information density', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
const automationTimerSource = readSource('src/session/AutomationTimerIcon.tsx');
const desktopProjectNode = readSource(
'../../apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsx',
@@ -524,7 +534,7 @@ describe('mobile home desktop-first surface', () => {
const sessionRowEnd = source.indexOf('function SessionStatusMark', sessionRowStart);
const sessionRowSource = source.slice(sessionRowStart, sessionRowEnd);
const stylesStart = source.indexOf('const makeStyles');
- const stylesSource = source.slice(stylesStart);
+ const stylesSource = source.slice(stylesStart) + readSource('src/session/HomeListVisuals.tsx');
expect(desktopProjectNode).toContain('const Chevron = isCollapsed ? ChevronRight : ChevronDown;');
expect(projectRowSource).toContain('project.title');
@@ -589,7 +599,7 @@ describe('mobile home desktop-first surface', () => {
});
it('keeps presence global while reconnecting only the visible Home sync scope', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
expect(source).toContain('void loadHome({ visible: false });');
expect(source).toMatch(/startBoundedStartupRead\(\s*getCachedHomeListSnapshot\(homeCacheUserId\)/);
@@ -601,7 +611,7 @@ describe('mobile home desktop-first surface', () => {
source.indexOf('// 卸载时取消所有延后中的 schedule-index hydration'),
);
expect(preferenceHydration).toContain('homeAccountGenerationRef.current !== expectedAccountGeneration');
- expect(preferenceHydration).toContain('if (!cancelled) setHomeViewPreferencesHydrated(true);');
+ expect(preferenceHydration).toContain("if (!cancelled) { viewSession.write('preferencesHydrated', true); setHomeViewPreferencesHydrated(true); }");
expect(source).toContain('const deviceIdentityCachePersistPendingRef = useRef(false);');
// 重连(connectionEpoch 变化)必须无条件重拉全量设备 REST:presence 只在变化时广播、无全量重放,
// 后台漏掉的上/下线事件只能靠重连快照兜底;每设备列表 fan-out 再按可见 scope 收窄。
@@ -637,7 +647,7 @@ describe('mobile home desktop-first surface', () => {
expect(source).toContain('mergeDeviceViewsWithFreshPresence(');
expect(source).toContain('markPresenceFresh(presenceFreshnessRef.current, lastPresenceSnapshot.deviceId);');
expect(source).toContain('collectFreshPresenceDeviceIds(presenceFreshnessRef.current, presenceEpochAtFetchStart)');
- expect(source).toContain('progressViewOffset={chromeHeight}');
+ expect(source).toContain('progressViewOffset={residentList.enabled ? 0 : chromeHeight}');
expect(source).toContain('onRefresh={() => void loadHome({ visible: true })}');
expect(source).toContain('onPress={() => void loadHome({ visible: true })}');
expect(source).toContain('patchDeviceViewsWithPresence(');
@@ -649,7 +659,7 @@ describe('mobile home desktop-first surface', () => {
});
it('starts the silent list sync on Home focus and Android foreground activation', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
const silentSync = source.slice(
source.indexOf('const startSilentHomeSync = useCallback'),
source.indexOf('// 把当前权威设备列表注入 remoteSessionStore'),
@@ -667,7 +677,7 @@ describe('mobile home desktop-first surface', () => {
});
it('binds every Home device projection and async continuation to the active account generation', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
// Home remains mounted across saved-account activation, so clearing the shared DeviceLink
// stores is insufficient: page-local refs/state must disappear before the next paint too.
@@ -696,7 +706,7 @@ describe('mobile home desktop-first surface', () => {
});
it('does not show the no-device empty state before startup sync settles', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
expect(source).toContain('const initialHomeSettled = deviceIdentityCacheReady && lastSyncedAt !== null;');
expect(source).toContain('const initialHomeLoading = !initialHomeSettled && !connectionError;');
@@ -712,7 +722,7 @@ describe('mobile home desktop-first surface', () => {
});
it('renders the remote-access onboarding guide for the no-device empty state', () => {
- const source = readSource('app/devices/index.tsx');
+ const source = readSource('src/session/HomeSurface.tsx');
// 无可控制电脑时不再是一句话空态,而是产品模式引导(按 reason 分场景 + 云端 Cindy 预告);
// 启动同步失败(initialHomeError)仍走同步失败空态,不冒充引导。
@@ -723,7 +733,7 @@ describe('mobile home desktop-first surface', () => {
expect(source).toContain('testID="home.remoteAccessGuide"');
// 引导态没有可筛选的对话:表头退化为纯品牌标题(无下拉菜单),新建 FAB 不渲染。
expect(source).toContain('{showRemoteGuide ? (');
- expect(source).toContain("{showRemoteGuide || taskSuggestionsPending || taskSuggestionsMode === 'empty' ? null : (");
+ expect(source).toContain("{newSessionInSystemBar || showRemoteGuide || taskSuggestionsPending || taskSuggestionsMode === 'empty' ? null : (");
const guideSource = readSource('src/components/RemoteAccessGuide.tsx');
// 文案已 i18n 化,断言改查 zh-CN catalog(单一事实源);源码只保留结构/交互契约。
@@ -743,3 +753,31 @@ describe('mobile home desktop-first surface', () => {
expect(t('deviceLink.cloudTeaserCopy')).toBe('上线后无需电脑,手机版即可直接使用。');
});
});
+
+describe('home menu native header ownership', () => {
+ it('hosts the Duo top-left menu inside the native bar instead of under its touch surface', () => {
+ const home = readSource('src/session/HomeSurface.tsx');
+ const header = readSource('src/platform/chrome/HomeNativeStackHeader.tsx');
+ expect(home).toContain("nativeHomeHeader && homeGeometry.barEdge !== 'none'");
+ expect(home).toContain('keepMenuTopLeft={keepMenuTopLeft}');
+ expect(home).not.toContain('{keepMenuTopLeft ? (');
+ const leftToolbar = header.split('<Stack.Toolbar placement="left">')[1].split('</Stack.Toolbar>')[0];
+ expect(leftToolbar).toContain('<Stack.Toolbar.View hidesSharedBackground>');
+ expect(leftToolbar).toContain('onPress={onOpenMenu}');
+ expect(leftToolbar).toContain('testID="home.chromeMenu"');
+ // Ordinary system toolbar actions keep their native adaptation.
+ expect(leftToolbar).toContain('<Stack.Toolbar.Button');
+ });
+});
+
+describe('home menu presentation', () => {
+ it('keeps iOS on the left drawer instead of shadowing it with a bottom sheet', () => {
+ expect(existsSync(resolve(process.cwd(), 'src/session/HomeChromeDrawer.ios.tsx'))).toBe(false);
+ const drawer = readSource('src/session/HomeChromeDrawer.tsx');
+ expect(drawer).toContain('translateX:');
+ expect(drawer).toContain('FullWindowOverlay');
+ expect(drawer).toContain('onPress={onClose}');
+ expect(drawer).toContain('Gesture.Pan()');
+ expect(drawer).not.toContain('ComposerSheet');
+ });
+});
diff --git a/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts b/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts
index e35de67b74..999f0bd0b3 100644
--- a/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts
+++ b/apps/mobile/src/__tests__/homeProjectChildWindow.test.ts
@@ -13,7 +13,7 @@ import {
describe('home project child window', () => {
it('uses the current native position despite delayed scroll events and transient failed measurements', () => {
const source = ts.createSourceFile('index.tsx', readFileSync(
- resolve(process.cwd(), 'app/devices/index.tsx'), 'utf8',
+ resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8',
), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const tracker = source.statements.find((node): node is ts.FunctionDeclaration => (
ts.isFunctionDeclaration(node) && node.name?.text === 'HomeProjectWindowAnchorTracker'
@@ -117,7 +117,7 @@ describe('home project child window', () => {
});
it('keeps layout readiness out of the first-render window gate', () => {
- const source = readFileSync(resolve(process.cwd(), 'app/devices/index.tsx'), 'utf8');
+ const source = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');
const setupStart = source.indexOf('const windowingEnabled = shouldWindowHomeProjectChildren({');
const setupEnd = source.indexOf('const scrollY = homeScrollY;', setupStart);
const setup = source.slice(setupStart, setupEnd);
@@ -139,7 +139,7 @@ describe('home project child window', () => {
});
it('bounds the outer home list window instead of retaining every flat row', () => {
- const source = readFileSync(resolve(process.cwd(), 'app/devices/index.tsx'), 'utf8');
+ const source = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');
expect(source).toContain('initialNumToRender={HOME_LIST_INITIAL_RENDER_COUNT}');
expect(source).toContain('maxToRenderPerBatch={HOME_LIST_RENDER_BATCH_SIZE}');
diff --git a/apps/mobile/src/__tests__/homeViewSession.test.tsx b/apps/mobile/src/__tests__/homeViewSession.test.tsx
new file mode 100644
index 0000000000..c57f1df597
--- /dev/null
+++ b/apps/mobile/src/__tests__/homeViewSession.test.tsx
@@ -0,0 +1,71 @@
+// @vitest-environment jsdom
+import { act, type Dispatch, type SetStateAction } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { getHomeViewSession, useRetainedHomeState } from '@/session/homeViewSession';
+import { setMobileAuthOwner, invalidateMobileAuthOwnerForSwitch } from '@/auth/authOwnerGeneration';
+
+describe('Home state handoff between page and sidebar', () => {
+ let root: Root;
+ let container: HTMLDivElement;
+ let values: { query: string; device: string | null; expanded: string[]; offset: number };
+ let setQuery: Dispatch<SetStateAction<string>>;
+ let setDevice: Dispatch<SetStateAction<string | null>>;
+ let setExpanded: Dispatch<SetStateAction<string[]>>;
+ function HomeProbe() {
+ const session = getHomeViewSession();
+ const [query, updateQuery] = useRetainedHomeState(session, 'search.query', '');
+ const [device, updateDevice] = useRetainedHomeState<string | null>(session, 'selectedDeviceId', null);
+ const [expanded, updateExpanded] = useRetainedHomeState<string[]>(session, 'expandedAutomationGroups', []);
+ values = { query, device, expanded, offset: session.read('scrollOffset', 0) };
+ setQuery = updateQuery; setDevice = updateDevice; setExpanded = updateExpanded;
+ return null;
+ }
+ beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ setMobileAuthOwner(null); setMobileAuthOwner('first');
+ container = document.createElement('div'); root = createRoot(container);
+ });
+ afterEach(async () => { await act(async () => root.unmount()); setMobileAuthOwner(null); });
+ it('retains interactions synchronously through full-width → sidebar → full-width remounts', async () => {
+ await act(async () => root.render(<HomeProbe key="page" />));
+ await act(async () => {
+ setQuery('needle'); setDevice('mac');
+ setExpanded((previous) => [...previous, 'group-1']);
+ setExpanded((previous) => [...previous, 'group-2']);
+ getHomeViewSession().write('scrollOffset', 480);
+ root.render(<HomeProbe key="sidebar" />);
+ });
+ expect(values!).toEqual({ query: 'needle', device: 'mac', expanded: ['group-1', 'group-2'], offset: 480 });
+ await act(async () => { setQuery('sidebar edit'); root.render(<HomeProbe key="page-again" />); });
+ expect(values!.query).toBe('sidebar edit');
+ expect(values!.device).toBe('mac');
+ });
+ it('does not carry view state across account/realm changes or a switch back to the same account', async () => {
+ await act(async () => root.render(<HomeProbe key="first" />));
+ await act(async () => { setQuery('private'); setDevice('private-mac'); });
+ const oldUpdate = setQuery!;
+ const oldSession = getHomeViewSession();
+ setMobileAuthOwner('first', 'cn');
+ await act(async () => root.render(<HomeProbe key="other-realm" />));
+ await act(async () => oldUpdate('late callback'));
+ oldSession.write('scrollOffset', 900);
+ expect(values!).toEqual({ query: '', device: null, expanded: [], offset: 0 });
+ expect(getHomeViewSession().read('search.query', '')).toBe('');
+ invalidateMobileAuthOwnerForSwitch();
+ setMobileAuthOwner('first');
+ await act(async () => root.render(<HomeProbe key="returned" />));
+ expect(values!.query).toBe('');
+ });
+ it('updates the mounted Home when a sidebar changes shared filters', async () => {
+ await act(async () => root.render(<HomeProbe />));
+ await act(async () => {
+ getHomeViewSession().write('search.query', 'from sidebar');
+ getHomeViewSession().write('selectedDeviceId', 'other-mac');
+ });
+ expect(values!.query).toBe('from sidebar');
+ expect(values!.device).toBe('other-mac');
+ await act(async () => setQuery((previous) => `${previous}!`));
+ expect(getHomeViewSession().read('search.query', '')).toBe('from sidebar!');
+ });
+});
diff --git a/apps/mobile/src/__tests__/inactiveSessionListSubscriptions.test.ts b/apps/mobile/src/__tests__/inactiveSessionListSubscriptions.test.ts
index c84528f03c..a9a63bfc5e 100644
--- a/apps/mobile/src/__tests__/inactiveSessionListSubscriptions.test.ts
+++ b/apps/mobile/src/__tests__/inactiveSessionListSubscriptions.test.ts
@@ -8,7 +8,7 @@ function source(path: string): string {
describe('inactive session list subscriptions', () => {
it('gates both mounted list routes by navigation focus', () => {
- for (const path of ['app/devices/index.tsx', 'app/devices/[deviceId].tsx']) {
+ for (const path of ['src/session/HomeSurface.tsx', 'app/devices/[deviceId].tsx']) {
const screen = source(path);
expect(screen).toContain('const screenFocused = useIsFocused();');
expect(screen).toContain(
diff --git a/apps/mobile/src/__tests__/iosChromeActionMenu.test.ts b/apps/mobile/src/__tests__/iosChromeActionMenu.test.ts
index 0f21e00778..93ccf694ef 100644
--- a/apps/mobile/src/__tests__/iosChromeActionMenu.test.ts
+++ b/apps/mobile/src/__tests__/iosChromeActionMenu.test.ts
@@ -70,7 +70,7 @@ describe("iOS chrome presenters stay on the system menu path", () => {
"utf8",
);
const home = readTextLf(
- resolve(process.cwd(), "app/devices/index.tsx"),
+ resolve(process.cwd(), "src/session/HomeSurface.tsx"),
"utf8",
);
const pullDown = readTextLf(
diff --git a/apps/mobile/src/__tests__/messageFollowGesture.test.ts b/apps/mobile/src/__tests__/messageFollowGesture.test.ts
index 53837901f1..5032668616 100644
--- a/apps/mobile/src/__tests__/messageFollowGesture.test.ts
+++ b/apps/mobile/src/__tests__/messageFollowGesture.test.ts
@@ -21,7 +21,7 @@ const callbackNames = [
'scrollToBottom', 'handleScroll', 'handleHistoryTouchStart', 'maybeTriggerHistoryTouch',
'handleHistoryTouchMove', 'handleHistoryTouchEnd', 'handleHistoryTouchCancel',
'handleScrollBeginDrag', 'handleScrollEndDrag', 'handleMomentumScrollBegin',
- 'handleMomentumScrollEnd', 'handleContentSize',
+ 'handleMomentumScrollEnd', 'handleContentSize', 'reconcileReopeningAnchor',
] as const;
type CallbackName = typeof callbackNames[number];
const declarations = renderer!.body!.statements.filter((node) => (
@@ -49,6 +49,8 @@ const renderOpacity = new Function('listRevealed', 'initialRevealProgress',
function harness() {
const ref = <T>(current: T) => ({ current });
const state = {
+ historyActiveRef: ref(true),
+ historyPositioningRef: ref(true),
nearBottomRef: ref(true), readingOlderRef: ref(false),
isDraggingRef: ref(false), isMomentumScrollingRef: ref(false),
historyTouchStartYRef: ref<number | null>(null), historyTouchTriggeredRef: ref(false),
@@ -59,6 +61,9 @@ function harness() {
programmaticScrollSettleAtRef: ref(0), mvcpSettleAtRef: ref(0),
tailFollowerRef: ref(null),
initialAnchorDoneRef: ref(true),
+ reopeningAnchorRef: ref<{ anchor: { key: string; viewportOffset: number }; expires: number; corrections: number } | null>(null),
+ reopeningFrameRef: ref<number | null>(null),
+ readingPositionActiveRef: ref(() => true),
initialRevealAnimationRef: ref<{ stop: () => void } | null>({ stop: vi.fn() }),
historyPrependTransactionRef: ref(null), nativeScrollEventSequenceRef: ref(0),
shareSelectionActiveRef: ref(false),
@@ -69,9 +74,15 @@ function harness() {
metrics.offsetY = metrics.contentHeight - metrics.viewportHeight;
});
const environment = {
+ readingPosition: { write: vi.fn() }, reopeningPosition: undefined,
+ captureCurrentHistoryAnchor: vi.fn((): { key: string; viewportOffset: number } | null => null),
+ getCurrentHistoryTopOffsetAdjustment: vi.fn(() => 0),
+ resolveMobileMessageHistoryAnchorOffset: vi.fn(() => 600),
...scrollModel, ...state, createMobileTailFollower, mobileDebugEnabled, mobileDebugLog,
initialRevealProgress: { setValue: vi.fn() }, setListRevealed: vi.fn(),
listRef: ref({
+ getState: () => ({ scrollLength: 800, scroll: state.scrollMetricsRef.current.offsetY,
+ data: [{ key: 'saved' }], sizeAtIndex: () => 1000 }),
scrollToEnd: tailScroll,
scrollToIndex: vi.fn(),
scrollToOffset: ({ offset, animated }: { offset: number; animated: boolean }) => {
@@ -96,6 +107,8 @@ function harness() {
} });
return {
...callbacks, state, tailScroll, scrollEvent,
+ readingPosition: environment.readingPosition,
+ captureCurrentHistoryAnchor: environment.captureCurrentHistoryAnchor,
initialRevealProgress: environment.initialRevealProgress,
setListRevealed: environment.setListRevealed,
handleScrollEndDrag: (event = scrollEvent(state.scrollMetricsRef.current.offsetY)) => (
@@ -114,6 +127,68 @@ beforeEach(() => {
afterEach(() => { setMobileDebugSink(undefined); vi.useRealTimers(); vi.unstubAllGlobals(); vi.restoreAllMocks(); });
describe('streaming follow yields to the reader', () => {
+ it('ignores scroll and content growth while its retained task is hidden', () => {
+ const h = harness();
+ h.state.historyActiveRef.current = false;
+ h.state.historyPositioningRef.current = false;
+ h.handleScroll(h.scrollEvent(50));
+ h.handleContentSize(400, 2600);
+ settle();
+ expect(h.state.scrollMetricsRef.current.offsetY).toBe(1200);
+ expect(h.tailScroll).not.toHaveBeenCalled();
+ });
+ it('finishes preload geometry before focus without publishing the offscreen position', () => {
+ const h = harness();
+ h.state.historyActiveRef.current = false;
+ h.handleScroll(h.scrollEvent(700));
+ expect(h.state.scrollMetricsRef.current.offsetY).toBe(700);
+ h.handleContentSize(400, 2600);
+ settle();
+ expect(h.state.scrollMetricsRef.current.offsetY).toBe(1800);
+ expect(h.setListRevealed).toHaveBeenCalledWith(true);
+ const calls = h.tailScroll.mock.calls.length;
+ h.state.historyActiveRef.current = true;
+ h.runStickToLatestVerify();
+ settle();
+ expect(h.tailScroll).toHaveBeenCalledTimes(calls);
+ });
+ it('saves user movement during an older-page request and its final momentum sample', () => {
+ const h = harness();
+ h.state.readingOlderRef.current = true;
+ h.state.isMomentumScrollingRef.current = true;
+ h.captureCurrentHistoryAnchor.mockImplementation(() => ({
+ key: 'long', viewportOffset: -h.state.scrollMetricsRef.current.offsetY,
+ }));
+ h.handleScroll(h.scrollEvent(600));
+ expect(h.readingPosition.write).toHaveBeenLastCalledWith({
+ anchor: { key: 'long', viewportOffset: -600 }, atEnd: false,
+ });
+ h.handleMomentumScrollEnd(h.scrollEvent(650));
+ expect(h.readingPosition.write).toHaveBeenLastCalledWith({
+ anchor: { key: 'long', viewportOffset: -650 }, atEnd: false,
+ });
+ h.readingPosition.write.mockClear();
+ h.handleScroll(h.scrollEvent(900)); // Layout-only event during prepend.
+ expect(h.readingPosition.write).not.toHaveBeenCalled();
+ });
+ it.each([true, false])('ends bookmark correction after native acknowledgment (focused=%s)', (focused) => {
+ const h = harness();
+ h.state.historyActiveRef.current = focused;
+ h.state.nearBottomRef.current = false;
+ h.state.reopeningAnchorRef.current = {
+ anchor: { key: 'saved', viewportOffset: -20 }, expires: Date.now() + 1500, corrections: 0,
+ };
+ // Reveal timeout is not proof of positioning, and must not block later acknowledgment.
+ h.state.initialRevealAnimationRef.current = null;
+ h.handleScroll(h.scrollEvent(500));
+ expect(h.state.reopeningAnchorRef.current).not.toBeNull();
+ h.reconcileReopeningAnchor(); // A correction is already queued before native acknowledgment.
+ h.handleScroll(h.scrollEvent(600));
+ expect(h.state.reopeningAnchorRef.current).toBeNull();
+ h.handleContentSize(400, 2600);
+ settle();
+ expect(h.tailScroll).not.toHaveBeenCalled();
+ });
it('keeps revealed history opaque after a delayed native stop value and keyboard rerenders', () => {
const h = harness();
const progress = { value: 0 };
diff --git a/apps/mobile/src/__tests__/messageHistoryAnchor.test.ts b/apps/mobile/src/__tests__/messageHistoryAnchor.test.ts
index 754524828f..0ee4b186f1 100644
--- a/apps/mobile/src/__tests__/messageHistoryAnchor.test.ts
+++ b/apps/mobile/src/__tests__/messageHistoryAnchor.test.ts
@@ -63,19 +63,29 @@ describe('messageHistoryAnchor', () => {
});
});
- it('captures the closest measured row when LegendList has not resolved its visible range', () => {
+ it('captures the containing row when LegendList has not resolved its visible range', () => {
expect(captureMobileHistoryAnchor({
data: [{ key: 'm1' }, { key: 'm2' }],
positionAtIndex: (index) => [40, 190][index],
scroll: 170,
start: -1,
}, (item) => item.key)).toEqual({
- key: 'm2',
- viewportOffset: 20,
- fallbacks: [{ key: 'm1', viewportOffset: -130 }],
+ key: 'm1',
+ viewportOffset: -130,
+ fallbacks: [{ key: 'm2', viewportOffset: 20 }],
});
});
+ it('restores inside a long message even when the following row measurement changes', () => {
+ const data = [{ key: 'long' }, { key: 'next' }];
+ const anchor = captureMobileHistoryAnchor({ data, start: -1, scroll: 1800,
+ positionAtIndex: index => [0, 2400][index] }, item => item.key)!;
+ expect(anchor.key).toBe('long');
+ expect(resolveMobileHistoryAnchorOffset(anchor, {
+ positionByKey: key => key === 'long' ? 0 : 3200,
+ })).toBe(1800);
+ });
+
it('uses logarithmic position lookup and only captures nearby fallback rows', () => {
const positionReads: number[] = [];
const data = Array.from({ length: 800 }, (_, index) => ({ key: `m${index}` }));
diff --git a/apps/mobile/src/__tests__/messageHistoryAutofillCallbacks.test.ts b/apps/mobile/src/__tests__/messageHistoryAutofillCallbacks.test.ts
index 5b0c44ec18..d02369911a 100644
--- a/apps/mobile/src/__tests__/messageHistoryAutofillCallbacks.test.ts
+++ b/apps/mobile/src/__tests__/messageHistoryAutofillCallbacks.test.ts
@@ -31,6 +31,7 @@ visit(source);
function fixture() {
const requestLoadEarlier = vi.fn();
const bindings = {
+ historyActiveRef: { current: true },
onLoadEarlier: () => {},
readingOlderRef: { current: false },
queuedLoadEarlierRef: { current: false },
@@ -58,6 +59,16 @@ const callback = ${callbackSource};`, {
}
describe('history autofill production callback', () => {
+ it('pauses hidden retained lists without consuming the paging budget', () => {
+ const { bindings, attempt, requestLoadEarlier } = fixture();
+ bindings.historyActiveRef.current = false;
+ attempt();
+ expect(requestLoadEarlier).not.toHaveBeenCalled();
+ expect(bindings.initialHistoryAutofillRemainingRef.current).toBe(3);
+ bindings.historyActiveRef.current = true;
+ attempt();
+ expect(requestLoadEarlier).toHaveBeenCalledTimes(1);
+ });
it('continues through host pages behind an unchanged first rendered row, within the cold-open budget', () => {
const { bindings, attempt, requestLoadEarlier } = fixture();
attempt();
diff --git a/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts b/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts
index 8666721301..dd763b2ae4 100644
--- a/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts
+++ b/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts
@@ -134,7 +134,8 @@ describe('mobile message media thumbnail wiring', () => {
expect(rendererSource).toContain("payload?.kind === 'media' && payload.media.kind === 'image'");
expect(rendererSource).toContain('<ImageLightbox');
expect(rendererSource).toContain('lightboxImagesForPayload(galleryImages, payload)');
- expect(rendererSource).toContain("const imageLightboxOpen = payload?.kind === 'media' && payload.media.kind === 'image';");
+ expect(rendererSource).toContain("const imageLightboxOpen = historyActive && payload?.kind === 'media' && payload.media.kind === 'image';");
+ expect(rendererSource).toContain('payload={historyActive ? payload : null}');
expect(rendererSource).toContain('() => (imageLightboxOpen');
expect(rendererSource).toContain(': null),');
// 旧的内嵌缩放查看器与图库箭头已退役
diff --git a/apps/mobile/src/__tests__/messageReadingPosition.test.ts b/apps/mobile/src/__tests__/messageReadingPosition.test.ts
new file mode 100644
index 0000000000..4c4827d24d
--- /dev/null
+++ b/apps/mobile/src/__tests__/messageReadingPosition.test.ts
@@ -0,0 +1,32 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
+import { clearMessageReadingPositions, messageReadingPosition } from '../session/messageReadingPosition';
+
+const position = { anchor: { key: 'message-4', viewportOffset: -32 }, atEnd: false };
+describe('recent message reading positions', () => {
+ beforeEach(() => { setMobileAuthOwner('reader'); clearMessageReadingPositions(); });
+ it('restores synchronously without sharing between devices or tasks', () => {
+ messageReadingPosition('a', 'task').write(position);
+ expect(messageReadingPosition('a', 'task').read()).toEqual(position);
+ expect(messageReadingPosition('b', 'task').read()).toBeUndefined();
+ expect(messageReadingPosition('a', 'other').read()).toBeUndefined();
+ });
+ it('drops bookmarks on account changes and rejects writes from the old page', () => {
+ const old = messageReadingPosition('a', 'task'); old.write(position);
+ setMobileAuthOwner('other'); old.write(position);
+ expect(old.read()).toBeUndefined();
+ expect(messageReadingPosition('a', 'task').read()).toBeUndefined();
+ });
+ it('does not resurrect a bookmark after task invalidation', () => {
+ const old = messageReadingPosition('a', 'task'); old.write(position);
+ clearMessageReadingPositions('a', 'task'); old.write(position);
+ expect(messageReadingPosition('a', 'task').read()).toBeUndefined();
+ });
+ it('bounds retention to eight recent tasks and preserves explicit follow-latest', () => {
+ const old = messageReadingPosition('a', 'old'); old.write(position);
+ for (let i = 0; i < 8; i++) messageReadingPosition('a', String(i)).write(position);
+ expect(old.read()).toBeUndefined();
+ messageReadingPosition('a', '7').write({ anchor: null, atEnd: true });
+ expect(messageReadingPosition('a', '7').read()).toEqual({ anchor: null, atEnd: true });
+ });
+});
diff --git a/apps/mobile/src/__tests__/messageReadingRestore.test.ts b/apps/mobile/src/__tests__/messageReadingRestore.test.ts
new file mode 100644
index 0000000000..b09e51e9fa
--- /dev/null
+++ b/apps/mobile/src/__tests__/messageReadingRestore.test.ts
@@ -0,0 +1,156 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+
+// Execute the production initial-position effect with a deterministic native list boundary.
+const source = ts.createSourceFile('renderer.tsx', readFileSync(resolve(process.cwd(),
+ 'src/session/MessageRenderer.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+let effect = '';
+let correction = '';
+let paddingEffect = '';
+function visit(node: ts.Node) {
+ if (ts.isCallExpression(node) && node.expression.getText(source) === 'useEffect'
+ && node.arguments[0]?.getText(source).includes('const prev = prevTopPaddingRef.current;')) {
+ paddingEffect = node.arguments[0].getText(source);
+ }
+ if (ts.isCallExpression(node) && node.expression.getText(source) === 'useLayoutEffect'
+ && node.arguments[0]?.getText(source).includes('const savedKey =')) {
+ effect = node.arguments[0].getText(source);
+ }
+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'reconcileReopeningAnchor'
+ && node.initializer && ts.isCallExpression(node.initializer)) {
+ correction = node.initializer.arguments[0].getText(source);
+ }
+ ts.forEachChild(node, visit);
+}
+visit(source);
+
+function restore(focused: string | null = null, key = 'message') {
+ const scrollToIndex = vi.fn();
+ const scrollToEndProgrammatically = vi.fn();
+ const bindings = {
+ initialAnchorDoneRef: { current: false },
+ listData: [{ key: 'message' }],
+ initialRevealProgress: { setValue: vi.fn() },
+ setListRevealed: vi.fn(),
+ initialRevealGenerationRef: { current: 0 },
+ initialRevealAnimationRef: { current: null },
+ Animated: { timing: () => ({ start: vi.fn() }) },
+ MOBILE_INITIAL_REVEAL_MAX_MS: 300,
+ Easing: { step1: vi.fn() },
+ focusedItemKeyRef: { current: focused },
+ reopeningPosition: { atEnd: false, anchor: { key, viewportOffset: -37 } },
+ mobileMessageHistoryRowKeyByIdentity: vi.fn(),
+ nearBottomRef: { current: true },
+ setIsAwayFromBottom: vi.fn(),
+ markProgrammaticScroll: vi.fn(),
+ reopeningAnchorRef: { current: null },
+ reconcileReopeningAnchor: vi.fn(),
+ listRef: { current: { scrollToIndex } },
+ scrollToEndProgrammatically,
+ };
+ expect(effect).not.toBe('');
+ const compiled = ts.transpileModule(`const run = ${effect};`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
+ }).outputText;
+ new Function(...Object.keys(bindings), `${compiled}\nrun();`)(...Object.values(bindings));
+ return { ...bindings, scrollToIndex };
+}
+
+describe('initial reading position', () => {
+ it('restores the saved message offset without first jumping to the end', () => {
+ const result = restore();
+ expect(result.scrollToIndex).toHaveBeenCalledWith({ animated: false, index: 0,
+ viewPosition: 0, viewOffset: -37 });
+ expect(result.scrollToEndProgrammatically).not.toHaveBeenCalled();
+ expect(result.nearBottomRef.current).toBe(false);
+ });
+ it('leaves explicit message-link navigation in control', () => {
+ expect(restore('link-target').scrollToIndex).not.toHaveBeenCalled();
+ });
+ it('falls back to latest when the saved row is no longer in cached history', () => {
+ const result = restore(null, 'removed');
+ expect(result.scrollToIndex).not.toHaveBeenCalled();
+ expect(result.scrollToEndProgrammatically).toHaveBeenCalledWith(false);
+ expect(result.nearBottomRef.current).toBe(true);
+ });
+});
+
+describe('reading position after real row measurements', () => {
+ function setup() {
+ let frame: (() => void) | undefined;
+ const scrollToOffset = vi.fn();
+ const list = { scrollLength: 600, scroll: 200, data: [{ key: 'saved' }], sizeAtIndex: vi.fn((): number | undefined => undefined) };
+ const bindings = {
+ historyPositioningRef: { current: true },
+ reopeningAnchorRef: { current: { anchor: { key: 'saved', viewportOffset: -30 }, expires: Date.now() + 1500, corrections: 0 } as null | { anchor: object; expires: number; corrections: number } },
+ reopeningFrameRef: { current: null as number | null },
+ requestAnimationFrame: vi.fn((callback: () => void) => { frame = callback; return 1; }),
+ listRef: { current: { getState: () => list, scrollToOffset } },
+ mobileMessageHistoryRowKeyByIdentity: vi.fn(),
+ resolveMobileMessageHistoryAnchorOffset: vi.fn(() => 830),
+ getCurrentHistoryTopOffsetAdjustment: vi.fn(() => 32),
+ MOBILE_ANCHOR_VERIFY_TOLERANCE: 2,
+ markProgrammaticScroll: vi.fn(),
+ };
+ const compiled = ts.transpileModule(`const run = ${correction};`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
+ }).outputText;
+ const run = new Function(...Object.keys(bindings), `${compiled}\nreturn run;`)(...Object.values(bindings));
+ return { ...bindings, list, run, scrollToOffset, flush: () => { const callback = frame; frame = undefined; callback?.(); } };
+ }
+ it('waits for measurements, coalesces layout events, and stops commanding once aligned', () => {
+ const r = setup();
+ r.run(); r.flush(); expect(r.scrollToOffset).not.toHaveBeenCalled();
+ r.list.sizeAtIndex.mockReturnValue(1000);
+ r.run(); r.run(); r.flush();
+ expect(r.scrollToOffset).toHaveBeenCalledExactlyOnceWith({ offset: 830, animated: false });
+ r.list.scroll = 830;
+ r.run(); r.flush(); expect(r.scrollToOffset).toHaveBeenCalledTimes(1);
+ });
+ it('does not fight a user gesture or keep correcting later dynamic content', () => {
+ const r = setup(); r.list.sizeAtIndex.mockReturnValue(1000);
+ r.run(); r.reopeningAnchorRef.current = null; r.flush();
+ expect(r.scrollToOffset).not.toHaveBeenCalled();
+ r.reopeningAnchorRef.current = { anchor: { key: 'saved' }, expires: Date.now() - 1, corrections: 0 };
+ r.run(); r.flush(); expect(r.scrollToOffset).not.toHaveBeenCalled();
+ expect(r.reopeningAnchorRef.current).toBeNull();
+ });
+});
+
+
+describe('top padding during bookmark restoration', () => {
+ function run(restoring: boolean, sequence = 1, nearBottom = false) {
+ const bindings = {
+ prevTopPaddingRef: { current: 0 }, topPadding: 90,
+ nearBottomRef: { current: nearBottom }, readingOlderRef: { current: false },
+ reopeningAnchorRef: { current: restoring ? { anchor: {} } : null },
+ reconcileReopeningAnchor: vi.fn(), initialAnchorDoneRef: { current: true },
+ nativeScrollEventSequenceRef: { current: sequence },
+ scrollMetricsRef: { current: { offsetY: sequence ? 600 : 0 } },
+ scrollToOffsetProgrammatically: vi.fn(),
+ };
+ expect(paddingEffect).not.toBe('');
+ const compiled = ts.transpileModule(`const run = ${paddingEffect};`, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
+ }).outputText;
+ new Function(...Object.keys(bindings), `${compiled}\nrun();`)(...Object.values(bindings));
+ expect(bindings.prevTopPaddingRef.current).toBe(90);
+ return bindings;
+ }
+ it('lets the bookmark resolver own positioning instead of cancelling its index seek', () => {
+ const r = run(true, 0);
+ expect(r.reconcileReopeningAnchor).toHaveBeenCalledOnce();
+ expect(r.scrollToOffsetProgrammatically).not.toHaveBeenCalled();
+ });
+ it('does not compensate using an unobserved native offset', () => {
+ expect(run(false, 0).scrollToOffsetProgrammatically).not.toHaveBeenCalled();
+ });
+ it('still compensates a measured reading position after restoration', () => {
+ expect(run(false).scrollToOffsetProgrammatically).toHaveBeenCalledWith(690, false);
+ });
+ it('leaves latest-message positioning to the tail follower', () => {
+ expect(run(false, 1, true).scrollToOffsetProgrammatically).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/__tests__/modalLayout.test.ts b/apps/mobile/src/__tests__/modalLayout.test.ts
new file mode 100644
index 0000000000..d563684794
--- /dev/null
+++ b/apps/mobile/src/__tests__/modalLayout.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+import { modalLayout } from '@/platform/modalLayout';
+import type { WindowGeometry } from '@/platform/windowGeometry';
+
+const window: WindowGeometry = { width: 956, height: 670, regularWidth: true, regularHeight: true,
+ insets: { top: 24, right: 84, bottom: 34, left: 0 }, barEdge: 'right',
+ regions: [], reservedRegionsSupported: true };
+describe('custom modal bounds', () => {
+ it('floats with margins and a bounded width instead of a partial-width bottom sheet', () => {
+ const { floating, region } = modalLayout(window);
+ expect(floating).toBe(true);
+ expect(region.width).toBe(560);
+ expect(region.x - window.insets.left).toBe(window.width - window.insets.right - region.x - region.width);
+ expect(region.y).toBeGreaterThan(window.insets.top);
+ expect(region.y + region.height).toBeLessThan(window.height - window.insets.bottom);
+ });
+ it('keeps the whole panel above the keyboard in a short landscape window', () => {
+ const { region } = modalLayout({ ...window, height: 466 }, 260);
+ expect(region.y + region.height).toBeLessThanOrEqual(206);
+ expect(region.height).toBeGreaterThan(0);
+ });
+ it('stays within one fold region', () => {
+ const { region } = modalLayout({ ...window, regions: [{kind: 'division', x: 460, y: 0, width: 20, height: 670}] });
+ expect(region.x).toBeGreaterThanOrEqual(480);
+ expect(region.x + region.width).toBeLessThanOrEqual(872);
+ });
+ it('retains bottom sheet presentation on compact portrait phones', () => {
+ expect(modalLayout({ ...window, width: 390, height: 844, barEdge: 'none' }).floating).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/__tests__/nativeGlassControls.test.tsx b/apps/mobile/src/__tests__/nativeGlassControls.test.tsx
new file mode 100644
index 0000000000..b218787937
--- /dev/null
+++ b/apps/mobile/src/__tests__/nativeGlassControls.test.tsx
@@ -0,0 +1,92 @@
+// @vitest-environment jsdom
+import { act, type ReactNode } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, expect, it, vi } from 'vitest';
+import { NativeChromeButton } from '../platform/chrome/NativeChromeButton.ios';
+import { LoginNativeButton } from '../components/LoginNativeButton.ios';
+import { useNativeGlassButtonStyle } from '../platform/chrome/nativeGlassButtonStyle.ios';
+
+const state = vi.hoisted(() => ({ glass: true, mode: 'light' }));
+vi.mock('@/theme', () => ({
+ navigationChrome: { target: 44, clear: { light: { foreground: 'black', scrim: 'light-scrim' }, dark: { foreground: 'white', scrim: 'dark-scrim' } } },
+ iconSize: { action: 20 }, iconStroke: { regular: 2 }, radius: { pill: 9999 },
+ useTheme: () => ({ mode: state.mode, colors: { textPrimary: 'primary', textSecondary: 'secondary', cta: 'cta', destructive: 'danger', surfaceElevated: 'surface' } }),
+}));
+vi.mock('@/session/useLiquidGlassAvailable', () => ({ useLiquidGlassAvailable: () => state.glass }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('react-native', () => ({ View: ({ children }: any) => <div>{children}</div>, Image: () => null }));
+vi.mock('lucide-react-native', () => {
+ const Icon = () => null;
+ return { LogOut: Icon, Monitor: Icon, Search: Icon, Settings: Icon, UsersRound: Icon };
+});
+vi.mock('@expo/ui', () => ({ Host: ({ children }: any) => <div>{children}</div> }));
+vi.mock('@expo/ui/swift-ui', () => {
+ const Container = ({ children }: any) => <div>{children}</div>;
+ return {
+ HStack: Container, VStack: Container, RNHostView: Container, Text: Container, Image: () => null,
+ ProgressView: () => <span role="progressbar" />,
+ Button: ({ children, label, onPress, testID, modifiers = [] }: any) => <button data-testid={testID}
+ disabled={modifiers.some((m: any) => m.name === 'disabled' && m.value)} onClick={onPress}>{children ?? label}</button>,
+ };
+});
+vi.mock('@expo/ui/swift-ui/modifiers', () => {
+ const names = ['background', 'buttonBorderShape', 'buttonStyle', 'contentShape', 'controlSize', 'foregroundStyle', 'frame', 'glassEffect', 'accessibilityElement', 'accessibilityLabel', 'accessibilityAddTraits', 'disabled', 'font', 'labelStyle', 'lineLimit'];
+ return { ...Object.fromEntries(names.map(name => [name, (value: any) => ({ name, value })])), shapes: { circle: () => 'circle', capsule: () => 'capsule' } };
+});
+const roots: ReturnType<typeof createRoot>[] = [];
+afterEach(() => { act(() => roots.splice(0).forEach(root => root.unmount())); state.glass = true; state.mode = 'light'; });
+function mount(children: ReactNode) {
+ const host = document.createElement('div');
+ const root = createRoot(host); roots.push(root);
+ act(() => root.render(children));
+ return host;
+}
+it('prevents disabled glass actions', () => {
+ const click = vi.fn();
+ const host = mount(<NativeChromeButton label="disabled" testID="disabled" disabled onPress={click} />);
+ act(() => (host.querySelector('[data-testid="disabled"]') as HTMLButtonElement).click());
+ expect(click).not.toHaveBeenCalled();
+});
+it.each(['light', 'dark'])('keeps clear glass foreground/backing paired in %s', mode => {
+ state.mode = mode;
+ let modifiers: any[] = [];
+ function Probe() { modifiers = useNativeGlassButtonStyle({ shape: 'circle', clear: true }); return null; }
+ mount(<Probe />);
+ expect(modifiers).toContainEqual({ name: 'foregroundStyle', value: mode === 'light' ? 'black' : 'white' });
+ expect(modifiers).toContainEqual({ name: 'background', value: `${mode}-scrim` });
+ expect(modifiers).toContainEqual({ name: 'frame', value: { width: 44, height: 44 } });
+});
+it('keeps unsupported-glass controls native with bordered prominent styling', () => {
+ state.glass = false; let modifiers: any[] = [];
+ function Probe() { modifiers = useNativeGlassButtonStyle({ prominent: true }); return null; }
+ mount(<Probe />);
+ expect(modifiers).toContainEqual({ name: 'buttonStyle', value: 'borderedProminent' });
+ expect(modifiers.some(m => m.name === 'glassEffect')).toBe(false);
+});
+
+it.each(['light', 'dark'])('blocks repeated login submissions while busy, then re-enables in %s', mode => {
+ state.mode = mode;
+ const click = vi.fn();
+ const host = document.createElement('div');
+ const root = createRoot(host); roots.push(root);
+ const render = (busy: boolean) => root.render(<LoginNativeButton label="Verify" onPress={click}
+ busy={busy} width={540} height={80} fontSize={24} variant="primary" />);
+ act(() => render(true));
+ expect(host.querySelector('[role="progressbar"]')).not.toBeNull();
+ act(() => host.querySelector('button')!.click());
+ expect(click).not.toHaveBeenCalled();
+ act(() => render(false));
+ expect(host.querySelector('[role="progressbar"]')).toBeNull();
+ act(() => host.querySelector('button')!.click());
+ expect(click).toHaveBeenCalledTimes(1);
+});
+
+it('keeps provider artwork inside a native button and prevents disabled activation', () => {
+ const click = vi.fn();
+ const host = mount(<LoginNativeButton label="Provider" disabled onPress={click}
+ width={80} height={80} fontSize={24} variant="circle"><span data-brand="original" /></LoginNativeButton>);
+ expect(host.querySelectorAll('button')).toHaveLength(1);
+ expect(host.querySelector('button [data-brand="original"]')).not.toBeNull();
+ act(() => host.querySelector('button')!.click());
+ expect(click).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index 0403defbf6..ac3e13fb0b 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -1033,7 +1033,7 @@ describe('pickNewSessionDefaultDevice', () => {
// 避免锚点(如 deps 数组)变化时 indexOf 失效产生误导性报错。
describe('new session default device follows the home device filter', () => {
it('sends deviceExplicit for a home device filter or a checked recommendation target', () => {
- const homeSource = readTextLf(resolve(process.cwd(), 'app/devices/index.tsx'), 'utf8');
+ const homeSource = readTextLf(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');
// 筛选电脑或推荐指定电脑时带显式标记;普通新建保留记忆回落。
expect(homeSource).toContain("...(selectedDeviceId || explicitDeviceId ? { deviceExplicit: '1' } : {})");
});
diff --git a/apps/mobile/src/__tests__/orcaCardRetention.test.tsx b/apps/mobile/src/__tests__/orcaCardRetention.test.tsx
new file mode 100644
index 0000000000..f071a1bcad
--- /dev/null
+++ b/apps/mobile/src/__tests__/orcaCardRetention.test.tsx
@@ -0,0 +1,55 @@
+// @vitest-environment jsdom
+import React, { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { describe, expect, it } from 'vitest';
+import { useFoldableExpandedState, __test_internals } from '@/session/expandedBlockMemory';
+
+// Run the real card and its shared state hook; substitute only native chrome.
+const source = ts.createSourceFile('renderer.tsx', readFileSync(resolve(process.cwd(),
+ 'src/session/MessageRenderer.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+const card = source.statements.find(node => ts.isFunctionDeclaration(node)
+ && node.name?.text === 'OrcaCollabCard')!;
+const compiled = ts.transpileModule(card.getText(source), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
+}).outputText;
+let generation = 1;
+const bindings = {
+ React, useFoldableExpandedState, useAuth: () => ({ accountGeneration: generation }),
+ useTheme: () => ({ colors: {} }), useThemedStyles: () => ({}), makeStyles: () => ({}),
+ Bot: () => null, iconSize: {}, iconStroke: {}, Text: 'span', View: 'div',
+ CollabCardShell: ({ controlledExpanded, onControlledToggle, children }: {
+ controlledExpanded: boolean; onControlledToggle: () => void; children: () => React.ReactNode;
+ }) => <button aria-expanded={controlledExpanded} onClick={onControlledToggle}>
+ {controlledExpanded ? children() : null}
+ </button>,
+};
+const Card = new Function(...Object.keys(bindings), `${compiled}; return OrcaCollabCard;`)(...Object.values(bindings));
+
+describe('worker card reading state', () => {
+ it.each(['report', 'dispatch'])('remembers %s toggles across remounts, independently per card/account', async (variant) => {
+ const defaultExpanded = variant === 'dispatch';
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ __test_internals.reset(); generation = 1;
+ const container = document.createElement('div');
+ const root = createRoot(container);
+ const show = async (key: string) => act(async () => root.render(<Card blockKey={key}
+ card={{ variant, title: 'Worker', body: 'Long report' }} />));
+ try {
+ await show('pc/task/a');
+ expect(container.querySelector('button')?.getAttribute('aria-expanded')).toBe(String(defaultExpanded));
+ await act(async () => container.querySelector('button')!.click());
+ await act(async () => root.render(null));
+ await show('pc/task/b');
+ expect(container.querySelector('button')?.getAttribute('aria-expanded')).toBe(String(defaultExpanded));
+ await act(async () => root.render(null));
+ await show('pc/task/a');
+ expect(container.querySelector('button')?.getAttribute('aria-expanded')).toBe(String(!defaultExpanded));
+ expect(container.textContent?.includes('Long report')).toBe(!defaultExpanded);
+ generation = 2; await show('pc/task/a');
+ expect(container.querySelector('button')?.getAttribute('aria-expanded')).toBe(String(defaultExpanded));
+ } finally { await act(async () => root.unmount()); __test_internals.reset(); }
+ });
+});
diff --git a/apps/mobile/src/__tests__/orcaCollab.test.ts b/apps/mobile/src/__tests__/orcaCollab.test.ts
index b8e60ce029..aac4775e71 100644
--- a/apps/mobile/src/__tests__/orcaCollab.test.ts
+++ b/apps/mobile/src/__tests__/orcaCollab.test.ts
@@ -213,8 +213,10 @@ describe('MessageRenderer wires the orca card', () => {
const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
expect(source).toContain('item.message.orcaCard');
// F4:透传 screenWidth,使 CollabCardShell layout 随屏宽响应(与 SubagentCard 一致)。
- expect(source).toContain('<OrcaCollabCard card={item.message.orcaCard} screenWidth={actions.screenWidth} />');
- expect(source).toContain('function OrcaCollabCard({ card, screenWidth }: { card: OrcaCollabCardModel; screenWidth?: number })');
+ expect(source).toContain('<OrcaCollabCard card={item.message.orcaCard} screenWidth={actions.screenWidth}');
+ expect(source).toContain('blockKey={JSON.stringify([actions.remoteDeviceId, item.key])}');
+ expect(source).toContain("controlledExpanded={(card.variant === 'dispatch') !== toggled}");
+ expect(source).toContain('onControlledToggle={toggleExpanded}');
expect(source).toContain('testID={`message.orcaCard.${card.variant}`}');
});
});
diff --git a/apps/mobile/src/__tests__/recentMessageHistories.test.tsx b/apps/mobile/src/__tests__/recentMessageHistories.test.tsx
new file mode 100644
index 0000000000..46749baba6
--- /dev/null
+++ b/apps/mobile/src/__tests__/recentMessageHistories.test.tsx
@@ -0,0 +1,188 @@
+// @vitest-environment jsdom
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { act, createContext, useEffect, useImperativeHandle, useState, type ReactNode, type Ref } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
+const state = vi.hoisted(() => ({ focused: true, onTask: true, width: 390, height: 844, native: false, upgrade: false }));
+vi.mock('@/session/NativeResidentHistory', () => {
+ const Host = ({ children, surfaceId }: { children: ReactNode; surfaceId: string }) => <div data-host={surfaceId}>{children}</div>;
+ const Slot = ({ surfaceId, selected }: { surfaceId: string; selected: boolean }) => <div data-slot={surfaceId} data-selected={selected} />;
+ return { get NativeHistoryHost() { return state.native ? Host : null; },
+ get NativeHistorySlot() { return state.native ? Slot : null; },
+ get needsResidentHistoryUpgrade() { return state.upgrade; } };
+});
+vi.mock('expo-router', () => ({ useSegments: () => state.onTask ? ['sessions', '[sessionId]'] : ['index'] }));
+vi.mock('expo-router/react-navigation', () => ({ useIsFocused: () => state.focused,
+ NavigationContext: createContext(null), NavigationRouteContext: createContext(null) }));
+vi.mock('@/platform/AdaptiveWindowContext', () => ({
+ usePaneViewport: () => ({ width: state.width, height: state.height }),
+ PaneViewportProvider: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock('react-native', () => ({
+ StyleSheet: { create: (styles: unknown) => styles },
+ View: ({ children, pointerEvents, accessibilityElementsHidden, ref, style, onLayout }: {
+ children: ReactNode; pointerEvents?: string; accessibilityElementsHidden?: boolean; ref: Ref<unknown>; style?: unknown; onLayout?: () => void;
+ }) => {
+ useImperativeHandle(ref, () => ({ measureInWindow: (fn: (...args: number[]) => void) => fn(0, 0, state.width, state.height) }));
+ useEffect(() => { onLayout?.(); }, [onLayout]);
+ return <div data-input={pointerEvents} aria-hidden={accessibilityElementsHidden} data-layout={JSON.stringify(style)}>{children}</div>;
+ },
+}));
+import { RecentMessageHistories, RecentMessageHistoriesProvider, MessageHistoryOverlay, useMessageHistoryActive, useMessageHistoryPositioning } from '@/session/RecentMessageHistories';
+import { recentTaskKey, rememberRecentTask } from '@/session/recentTasks';
+const key = (id: string) => recentTaskKey({ deviceId: 'pc', sessionId: id });
+const remember = (id: string) => rememberRecentTask({ pathname: '/sessions/[sessionId]', params: { deviceId: 'pc', deviceName: 'PC', sessionId: id } });
+
+describe('resident five-task message lists outside route lifetimes', () => {
+ let root: Root;
+ let container: HTMLDivElement;
+ const mounts = new Map<string, number>();
+ const unmounts: string[] = [];
+ function History({ id, text }: { id: string; text: string }) {
+ const active = useMessageHistoryActive();
+ const positioning = useMessageHistoryPositioning();
+ const [position, setPosition] = useState(0);
+ useEffect(() => {
+ mounts.set(id, (mounts.get(id) ?? 0) + 1);
+ return () => { unmounts.push(id); };
+ }, [id]);
+ return <button data-task={id} data-active={active} data-positioning={positioning} onClick={() => setPosition(420)}>{text}:{position}</button>;
+ }
+ async function show(id: string | null, text = id ?? '', ready = true) {
+ state.onTask = id !== null;
+ await act(async () => {
+ if (id) remember(id);
+ root.render(<RecentMessageHistoriesProvider>{id ?
+ <RecentMessageHistories key={id} activeKey={key(id)} ready={ready} topInset={ready ? 90 : 0} bottomInset={ready ? 80 : 0}>
+ <History id={id} text={text} />
+ </RecentMessageHistories> : <p>Home</p>}
+ </RecentMessageHistoriesProvider>);
+ });
+ }
+ beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ setMobileAuthOwner(null); setMobileAuthOwner('one'); state.focused = true; state.onTask = true;
+ state.width = 390; state.height = 844;
+ state.native = false; state.upgrade = false;
+ mounts.clear(); unmounts.length = 0;
+ container = document.createElement('div'); root = createRoot(container);
+ });
+ afterEach(async () => { await act(async () => root.unmount()); });
+ it('keeps the exact list instance after its route is destroyed, then publishes fresh props', async () => {
+ await show('a');
+ const original = container.querySelector<HTMLButtonElement>('[data-task="a"]')!;
+ await act(async () => original.click());
+ await show(null);
+ expect(original.dataset.active).toBe('false');
+ expect(original.dataset.positioning).toBe('false');
+ expect(unmounts).toEqual([]);
+ await show('b'); await show(null); await show('a', 'updated');
+ expect(container.querySelector('[data-task="a"]')).toBe(original);
+ expect(original.textContent).toBe('updated:420');
+ expect(mounts.get('a')).toBe(1);
+ });
+ it('resizes the same list on rotation without changing its state', async () => {
+ await show('a');
+ const original = container.querySelector<HTMLButtonElement>('button')!;
+ await act(async () => original.click());
+ state.width = 844; state.height = 390; await show('a');
+ expect(container.querySelector('button')).toBe(original);
+ expect(original.textContent).toBe('a:420');
+ expect(original.closest('[data-layout*="844"]')).not.toBeNull();
+ expect(mounts.get('a')).toBe(1);
+ });
+ it('keeps native-host children when route slots disappear and reconnects the same surface', async () => {
+ state.native = true;
+ await show('a');
+ const original = container.querySelector<HTMLButtonElement>('[data-task="a"]')!;
+ const host = container.querySelector('[data-host]');
+ const surface = host?.getAttribute('data-host');
+ expect(container.querySelector('[data-slot]')?.getAttribute('data-slot')).toBe(surface);
+ await act(async () => original.click());
+ await show(null);
+ expect(container.querySelector('[data-slot]')).toBeNull();
+ expect(container.querySelector('[data-host]')).toBe(host);
+ await show('b'); await show('a');
+ expect(container.querySelector('[data-task="a"]')).toBe(original);
+ expect(original.textContent).toBe('a:420');
+ expect(container.querySelector('[data-slot]')?.getAttribute('data-slot')).toBe(surface);
+ expect(unmounts).toEqual([]);
+ });
+ it('keeps old iOS binaries route-local instead of blocking native gestures with an overlay', async () => {
+ state.upgrade = true;
+ await show('a'); await show(null);
+ expect(container.querySelector('button')).toBeNull();
+ expect(unmounts).toEqual(['a']);
+ });
+ it('shows cached native content before new route data and chrome are ready', async () => {
+ state.native = true;
+ await show('a', 'cached');
+ const original = container.querySelector<HTMLButtonElement>('[data-task="a"]')!;
+ await act(async () => original.click());
+ await show('b'); await show(null); await show('a', 'loading', false);
+ expect(container.querySelector('[data-slot]')?.getAttribute('data-selected')).toBe('true');
+ expect(container.querySelector('[data-task="a"]')).toBe(original);
+ expect(original.textContent).toBe('cached:420');
+ expect(original.dataset.positioning).toBe('false');
+ expect(unmounts).toEqual([]);
+ await show('a', 'fresh');
+ expect(original.textContent).toBe('fresh:420');
+ expect(mounts.get('a')).toBe(1);
+ });
+ it('evicts only the least recently used task when opening a sixth', async () => {
+ for (const id of ['a','b','c','d','e','a','f']) await show(id);
+ expect(unmounts).toEqual(['b']);
+ expect(container.querySelectorAll('button')).toHaveLength(5);
+ await show('b'); expect(mounts.get('b')).toBe(2);
+ });
+ it('pauses hidden lists and disables their input/accessibility without removing them', async () => {
+ await show('a'); await show(null);
+ const original = container.querySelector<HTMLButtonElement>('button')!;
+ expect(original.dataset.active).toBe('false');
+ expect(original.closest('[data-input="none"]')).not.toBeNull();
+ expect(original.closest('[aria-hidden="true"]')).not.toBeNull();
+ expect(unmounts).toEqual([]);
+ });
+ it('does not replace retained content with a new route loading shell', async () => {
+ await show('a', 'cached'); await show(null); await show('a', 'loading', false);
+ const original = container.querySelector<HTMLButtonElement>('button')!;
+ expect(original.textContent).toBe('cached:0');
+ expect(original.dataset.active).toBe('false');
+ expect(original.parentElement?.parentElement?.getAttribute('data-layout')).toContain('\"top\":90');
+ expect(original.closest('[data-input="none"]')).not.toBeNull();
+ await show('a', 'fresh'); expect(original.textContent).toBe('fresh:0');
+ });
+ it('keeps route drawers above the retained list and removes them on route exit', async () => {
+ await show('a');
+ await act(async () => root.render(<RecentMessageHistoriesProvider>
+ <MessageHistoryOverlay><button data-drawer="true">Drawer</button></MessageHistoryOverlay>
+ </RecentMessageHistoriesProvider>));
+ const nodes = container.querySelectorAll('button');
+ expect(nodes[0]?.dataset.task).toBe('a');
+ expect(nodes[1]?.dataset.drawer).toBe('true');
+ await show(null);
+ expect(container.querySelector('[data-drawer]')).toBeNull();
+ expect(container.querySelector('[data-task="a"]')).not.toBeNull();
+ });
+ it('does not keep the old route preloading mechanism alongside the resident host', () => {
+ const home = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');
+ expect(home).not.toContain('useRecentTaskPreload');
+ expect(home).not.toContain('router.prefetch');
+ const layout = readFileSync(resolve(process.cwd(), 'app/_layout.tsx'), 'utf8');
+ // Source structure is independent of checkout line endings.
+ for (const source of [layout.replace(/\r\n/g, '\n'), layout.replace(/\r?\n/g, '\r\n')]) {
+ const provider = source.indexOf('<RecentMessageHistoriesProvider>');
+ const stack = source.search(/<Stack\s/);
+ expect(provider).toBeGreaterThanOrEqual(0);
+ expect(stack).toBeGreaterThan(provider);
+ }
+ });
+ it('clears all instances at an account boundary', async () => {
+ await show('a'); await show('b');
+ await act(async () => setMobileAuthOwner('two'));
+ expect(container.querySelectorAll('button')).toHaveLength(0);
+ expect(unmounts).toEqual(['a','b']);
+ });
+});
diff --git a/apps/mobile/src/__tests__/remoteHistoryDiskCache.test.ts b/apps/mobile/src/__tests__/remoteHistoryDiskCache.test.ts
index e9fa1f1bd5..9cb3240143 100644
--- a/apps/mobile/src/__tests__/remoteHistoryDiskCache.test.ts
+++ b/apps/mobile/src/__tests__/remoteHistoryDiskCache.test.ts
@@ -1,10 +1,11 @@
+import { MAX_RECENT_TASKS, rememberRecentTask } from '@/session/recentTasks';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { HistoryViewController, projectHistoryView, type HistoryViewSnapshot, type HistoryWorkSummary } from '@cindy/maker-shared/message-window';
import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
import { clearHistoryDisk, historyDiskAuthority, readHistoryDisk, writeHistoryDisk } from '@/session/remoteHistoryDiskCache';
import type { RemoteMessage } from '@/session/types';
import { clearRemoteHistoryViews, findRemoteHistoryView, getRemoteHistoryView,
- mountRemoteHistoryView, MAX_INACTIVE_HISTORY_VIEWS } from '@/session/remoteHistoryViews';
+ mountRemoteHistoryView } from '@/session/remoteHistoryViews';
const files = vi.hoisted(() => new Map<string, string>());
vi.mock('@/session/historyDiskStoreExpo', () => ({ createHistoryDiskIO: () => ({
@@ -22,6 +23,7 @@ const snapshot = (text: string): HistoryViewSnapshot<RemoteMessage> => ({
});
const releases: Array<() => void> = [];
function mount(entry: ReturnType<typeof getRemoteHistoryView>, source: ReturnType<typeof transport>) {
+ rememberRecentTask({ pathname: '/sessions/[sessionId]', params: { deviceId: entry.deviceId, sessionId: entry.sessionId, deviceName: 'PC' } });
const release = mountRemoteHistoryView(entry, source, true);
releases.push(release);
return () => { releases.splice(releases.indexOf(release), 1); release(); };
@@ -35,6 +37,29 @@ function transport() {
}
afterEach(async () => { releases.splice(0).forEach(release => release()); clearRemoteHistoryViews(); await clearHistoryDisk(); setMobileAuthOwner(null); });
describe('persistent history integration', () => {
+ it('restores an evicted sixth task from disk without a network request', async () => {
+ setMobileAuthOwner('five-task-cache');
+ const source = transport();
+ const entry = getRemoteHistoryView('d', 'saved-task', source);
+ const leave = mount(entry, source);
+ await entry.view.refresh();
+ leave();
+ for (let i = 0; i < MAX_RECENT_TASKS; i++) {
+ rememberRecentTask({ pathname: '/sessions/[sessionId]', params: {
+ deviceId: 'd', deviceName: 'PC', sessionId: `recent-${i}`,
+ } });
+ }
+ expect(findRemoteHistoryView('d', 'saved-task')).toBeUndefined();
+ expect(await readHistoryDisk(historyDiskAuthority('d', 'saved-task'))).not.toBeNull();
+ const offline = transport();
+ const reopened = getRemoteHistoryView('d', 'saved-task', offline);
+ expect(reopened.view).not.toBe(entry.view);
+ reopened.view.setNetworkAvailable(false);
+ mount(reopened, offline);
+ await vi.waitFor(() => expect(reopened.view.getSnapshot().ready).toBe(true));
+ expect(JSON.stringify(reopened.view.getSnapshot().items)).toContain('network');
+ expect(offline.readHistoryView).not.toHaveBeenCalled();
+ });
it.each(['UNSUPPORTED_CAPABILITY', 'CHANNEL_NOT_ALLOWED'])('removes %s disk projection before LRU recreation and fences old writes', async (code) => {
setMobileAuthOwner('a');
const old = historyDiskAuthority('d', 's');
@@ -51,7 +76,7 @@ describe('persistent history integration', () => {
expect(old.current()).toBe(false);
release();
await writeHistoryDisk(old, snapshot('late old write'));
- for (let n = 0; n < MAX_INACTIVE_HISTORY_VIEWS; n++) {
+ for (let n = 0; n < MAX_RECENT_TASKS; n++) {
const nextSource = transport();
const next = getRemoteHistoryView('d', `other-${n}`, nextSource);
const leave = mount(next, nextSource);
diff --git a/apps/mobile/src/__tests__/remoteHistoryReentry.test.ts b/apps/mobile/src/__tests__/remoteHistoryReentry.test.ts
index a6fcd223a1..ff4f681134 100644
--- a/apps/mobile/src/__tests__/remoteHistoryReentry.test.ts
+++ b/apps/mobile/src/__tests__/remoteHistoryReentry.test.ts
@@ -1,8 +1,9 @@
+import { MAX_RECENT_TASKS, rememberRecentTask } from '@/session/recentTasks';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import { projectHistoryView, type HistoryViewPage } from '@cindy/maker-shared/message-window';
import { clearRemoteHistoryViews, findRemoteHistoryView, getRemoteHistoryView,
- mountRemoteHistoryView, MAX_INACTIVE_HISTORY_VIEWS } from '../session/remoteHistoryViews';
+ mountRemoteHistoryView } from '../session/remoteHistoryViews';
import { remoteSessionStore } from '../session/remoteSessionStore';
import { buildMobileHistoryRenderItems } from '../session/mobileHistoryRender';
import type { RemoteMessage, RemoteSession } from '../session/types';
@@ -16,6 +17,7 @@ const reader = () => ({ readHistoryView: vi.fn(async () => page()),
setHistoryExpanded: vi.fn(async () => undefined) });
const releases: Array<() => void> = [];
function mount(entry: ReturnType<typeof getRemoteHistoryView>, source = reader()) {
+ rememberRecentTask({ pathname: '/sessions/[sessionId]', params: { deviceId: entry.deviceId, sessionId: entry.sessionId, deviceName: 'PC' } });
const release = mountRemoteHistoryView(entry, source, true);
releases.push(release);
return () => { releases.splice(releases.indexOf(release), 1); release(); };
@@ -152,24 +154,30 @@ describe('history reentry', () => {
it('isolates device identities and evicts oldest detached views without removing the mounted view', async () => {
const active = getRemoteHistoryView('other', 's', reader());
mount(active);
- for (let i = 0; i <= MAX_INACTIVE_HISTORY_VIEWS; i++) {
+ for (let i = 0; i <= MAX_RECENT_TASKS; i++) {
const entry = getRemoteHistoryView('d', String(i), reader());
const release = mount(entry);
await entry.view.refresh();
release();
}
expect(findRemoteHistoryView('d', '0')).toBeUndefined();
- expect(findRemoteHistoryView('d', String(MAX_INACTIVE_HISTORY_VIEWS))).toBeDefined();
+ expect(findRemoteHistoryView('d', String(MAX_RECENT_TASKS))).toBeDefined();
expect(findRemoteHistoryView('other', 's')).toBe(active.view);
});
- it('does not retain an oversized history window after unmount', async () => {
+ it('keeps large histories with the five resident lists and drops them on shared eviction', async () => {
const source = reader();
source.readHistoryView.mockResolvedValue(page('x'.repeat(3 * 1024 * 1024)));
const entry = getRemoteHistoryView('d', 's', source);
const release = mount(entry, source);
await entry.view.refresh();
release();
+ expect(findRemoteHistoryView('d', 's')).toBe(entry.view);
+ for (let i = 0; i < MAX_RECENT_TASKS; i++) {
+ rememberRecentTask({ pathname: '/sessions/[sessionId]', params: {
+ deviceId: 'd', deviceName: 'PC', sessionId: `replacement-${i}`,
+ } });
+ }
expect(findRemoteHistoryView('d', 's')).toBeUndefined();
});
diff --git a/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts b/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts
index 5c8980ca0f..b5078e6991 100644
--- a/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts
+++ b/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts
@@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest';
describe('mobile remote session bootstrap', () => {
it('asks the controlled desktop to include active pinned sessions outside the recent window', () => {
- const homeSource = readFileSync(resolve(process.cwd(), 'app/devices/index.tsx'), 'utf8');
+ const homeSource = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');
const detailSource = readFileSync(resolve(process.cwd(), 'app/devices/[deviceId].tsx'), 'utf8');
const listWithPinned =
/local-db:sessions:list'[\s\S]{0,280}\{ includePinned: true, fresh: true \}/;
diff --git a/apps/mobile/src/__tests__/remoteTaskSuggestions.test.ts b/apps/mobile/src/__tests__/remoteTaskSuggestions.test.ts
index 94df6ea662..397cfe3e61 100644
--- a/apps/mobile/src/__tests__/remoteTaskSuggestions.test.ts
+++ b/apps/mobile/src/__tests__/remoteTaskSuggestions.test.ts
@@ -106,7 +106,7 @@ describe("suggestion route IDs", () => {
describe("home recommendation connection readiness", () => {
it("hides both modes after disconnect despite a retained online device snapshot", () => {
- const source = readTextLf(resolve(process.cwd(), "app/devices/index.tsx"), "utf8");
+ const source = readTextLf(resolve(process.cwd(), "src/session/HomeSurface.tsx"), "utf8");
const expression = source.match(/ready: ([\s\S]*?),\n \}\);\n const newSessionDeviceOptions/)?.[1];
expect(expression).toBeTruthy();
const evaluateReady = new Function("status", "activeConnectionIssue", "recoveringDeviceIds", "selectedDeviceId", `
@@ -138,7 +138,7 @@ describe("home recommendation connection readiness", () => {
describe("recommendation route target", () => {
it("passes the checked computer explicitly for both empty and template actions", () => {
- const source = readTextLf(resolve(process.cwd(), "app/devices/index.tsx"), "utf8");
+ const source = readTextLf(resolve(process.cwd(), "src/session/HomeSurface.tsx"), "utf8");
const openBody = source.match(/const openNewSession = useCallback\([^\n]*=> \{([\s\S]*?)\n \}, \[guardedPush, home.primaryDevice/)?.[1];
const suggestedBody = source.match(/const openSuggestedSession = useCallback\([^\n]*=> \{([\s\S]*?)\n \}, \[openNewSession/)?.[1];
expect(openBody).toBeTruthy();
diff --git a/apps/mobile/src/__tests__/residentHomeList.test.tsx b/apps/mobile/src/__tests__/residentHomeList.test.tsx
new file mode 100644
index 0000000000..a8dcaaf396
--- /dev/null
+++ b/apps/mobile/src/__tests__/residentHomeList.test.tsx
@@ -0,0 +1,90 @@
+// @vitest-environment jsdom
+import { act, memo, useEffect, useState } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, expect, it, vi } from 'vitest';
+import { homeRowPropsEqual } from '../session/homeRowPropsEqual';
+import { ResidentHomeList, ResidentHomeListProvider } from '../session/ResidentHomeList';
+
+const state = vi.hoisted(() => ({
+ segments: ['devices'], width: 1000, anchorWidth: 1000, mounts: 0, unmounts: 0,
+}));
+vi.mock('expo-router', () => ({ useSegments: () => state.segments }));
+vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => true }));
+vi.mock('@/platform/AdaptiveWindowContext', () => ({ useAdaptiveWindow: () => ({
+ width: state.width, height: 800, regularWidth: true, regularHeight: true,
+ barEdge: 'right', insets: { top: 0, bottom: 0, left: 0, right: 80 },
+ regions: [], reservedRegionsSupported: false,
+}) }));
+vi.mock('../session/remoteSessionStore', () => ({
+ RemoteSessionStoreSubscriptionGate: ({ children, enabled }: any) => <div data-subscriptions={enabled}>{children}</div>,
+}));
+vi.mock('react-native', async () => {
+ const React = await import('react');
+ return {
+ StyleSheet: { create: (v: any) => v },
+ View: React.forwardRef(({ children, onLayout, ...props }: any, ref) => {
+ React.useImperativeHandle(ref, () => ({
+ measureLayout: (_: any, callback: any) => callback(0, 80, state.anchorWidth, 720),
+ }));
+ React.useEffect(() => { onLayout?.(); }, [onLayout]);
+ return <div data-pointer={props.pointerEvents}>{children}</div>;
+ }),
+ };
+});
+vi.mock('react-native-reanimated', () => ({
+ default: { View: ({ children, pointerEvents }: any) => <div data-host data-pointer={pointerEvents}>{children}</div> },
+}));
+const roots: ReturnType<typeof createRoot>[] = [];
+afterEach(() => {
+ act(() => roots.splice(0).forEach(root => root.unmount()));
+ state.segments = ['devices']; state.width = 1000; state.anchorWidth = 1000;
+ state.mounts = 0; state.unmounts = 0;
+});
+const ListProbe = memo(function ListProbe({ onSelect }: { onSelect(): void }) {
+ const [position, setPosition] = useState(0);
+ useEffect(() => { state.mounts++; return () => { state.unmounts++; }; }, []);
+ return <><button data-scroll onClick={() => setPosition(240)}>scroll</button>
+ <button data-select onClick={onSelect}>{position}</button></>;
+}, homeRowPropsEqual);
+function Scene({ detail, homeSelect, detailSelect }: any) {
+ return <ResidentHomeListProvider>
+ <ResidentHomeList focused={!detail} top={80} left={0} right={0}>
+ <ListProbe onSelect={homeSelect} />
+ </ResidentHomeList>
+ {detail ? <ResidentHomeList focused top={80} left={0} right={0}>
+ <ListProbe onSelect={detailSelect} />
+ </ResidentHomeList> : null}
+ </ResidentHomeListProvider>;
+}
+it.each([{ homeSegments: [] }, { homeSegments: ['index'] }, { homeSegments: ['devices'] }])('keeps one visible list through home %j → detail → home, while switching actions', ({ homeSegments }) => {
+ state.segments = homeSegments;
+ const host = document.createElement('div');
+ const root = createRoot(host); roots.push(root);
+ const homeSelect = vi.fn(), detailSelect = vi.fn();
+ const render = (detail: boolean) => act(() => root.render(<Scene {...{ detail, homeSelect, detailSelect }} />));
+ render(false);
+ expect(host.querySelector('[data-host]')?.getAttribute('data-pointer')).toBe('box-none');
+ expect(host.querySelector('[data-subscriptions]')?.getAttribute('data-subscriptions')).toBe('true');
+ act(() => (host.querySelector('[data-scroll]') as HTMLButtonElement).click());
+ state.segments = ['sessions', '[sessionId]']; state.anchorWidth = 320;
+ render(true);
+ expect(host.querySelectorAll('[data-select]')).toHaveLength(1);
+ expect(host.querySelector('[data-select]')?.textContent).toBe('240');
+ act(() => (host.querySelector('[data-select]') as HTMLButtonElement).click());
+ expect(detailSelect).toHaveBeenCalledOnce(); expect(homeSelect).not.toHaveBeenCalled();
+ state.segments = homeSegments; state.anchorWidth = 1000;
+ render(false);
+ expect(host.querySelector('[data-host]')?.getAttribute('data-pointer')).toBe('box-none');
+ expect(host.querySelector('[data-select]')?.textContent).toBe('240');
+ expect(state.mounts).toBe(1); expect(state.unmounts).toBe(0);
+});
+it('hides the resident list and pauses row subscriptions on other routes without destroying it', () => {
+ const host = document.createElement('div');
+ const root = createRoot(host); roots.push(root);
+ const render = () => act(() => root.render(<Scene detail={false} homeSelect={() => {}} />));
+ render();
+ state.segments = ['settings']; render();
+ expect(host.querySelector('[data-host]')?.getAttribute('data-pointer')).toBe('none');
+ expect(host.querySelector('[data-subscriptions]')?.getAttribute('data-subscriptions')).toBe('false');
+ expect(state.mounts).toBe(1); expect(state.unmounts).toBe(0);
+});
diff --git a/apps/mobile/src/__tests__/screenEdgeInsets.test.ts b/apps/mobile/src/__tests__/screenEdgeInsets.test.ts
index b4ab99d9ea..354bdf1daa 100644
--- a/apps/mobile/src/__tests__/screenEdgeInsets.test.ts
+++ b/apps/mobile/src/__tests__/screenEdgeInsets.test.ts
@@ -1,6 +1,11 @@
-import { beforeEach, describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+vi.mock('react-native', () => ({
+ Platform: { OS: 'android', Version: 36 },
+ Dimensions: { get: () => ({ width: 400, height: 800 }) },
+}));
import {
getStablePortraitTopMemory,
+ isLegacyPhoneWindow,
recordStablePortraitTop,
resetStablePortraitTopMemoryForTests,
resolveScreenEdgePadding,
@@ -31,6 +36,7 @@ describe('screenEdgeInsets', () => {
it('clamps the stale landscape residue shape in portrait and falls back top', () => {
// 复现 bug 形态:横屏 insets(top=0、左右 59)残留到竖屏;侧边清零,top 用兜底值。
expect(resolveScreenEdgePadding({
+ legacyPhoneLayout: true,
fallbackPortraitTop: 59,
insets: { top: 0, left: 59, right: 59 },
windowHeight: 874,
@@ -41,12 +47,21 @@ describe('screenEdgeInsets', () => {
it('clamps single-side landscape residue without a fallback top', () => {
// Android 横屏单侧挖孔的残留形态;无兜底值时 top 为 0(与残留原值一致,不发明数据)。
expect(resolveScreenEdgePadding({
+ legacyPhoneLayout: true,
insets: { top: 0, left: 30, right: 0 },
windowHeight: 800,
windowWidth: 400,
})).toEqual({ paddingLeft: 0, paddingRight: 0, paddingTop: 0 });
});
+ it('preserves asymmetric side safe areas in a tall resizable window', () => {
+ expect(resolveScreenEdgePadding({
+ fallbackPortraitTop: 59,
+ insets: { top: 0, left: 0, right: 64 },
+ windowHeight: 800, windowWidth: 420,
+ })).toEqual({ paddingLeft: 0, paddingRight: 64, paddingTop: 0 });
+ });
+
it('keeps side insets in landscape untouched', () => {
expect(resolveScreenEdgePadding({
insets: { top: 0, left: 59, right: 59 },
@@ -78,6 +93,7 @@ describe('screenEdgeInsets', () => {
// 对新实例的残留过渡帧依然可用(实例级 ref 会归零,模块级记忆不会)。
recordStablePortraitTop({ top: 59, windowHeight: 874, windowWidth: 402 });
expect(resolveScreenEdgePadding({
+ legacyPhoneLayout: true,
fallbackPortraitTop: getStablePortraitTopMemory(),
insets: { top: 0, left: 59, right: 59 },
windowHeight: 874,
@@ -85,3 +101,26 @@ describe('screenEdgeInsets', () => {
})).toEqual({ paddingLeft: 0, paddingRight: 0, paddingTop: 59 });
});
});
+
+
+describe('legacy phone window eligibility', () => {
+ const phone = { platform: 'android', version: 36, iosPad: false,
+ windowWidth: 400, windowHeight: 776, screenWidth: 400, screenHeight: 800 };
+ it('repairs Android full-screen single-cutout rotation residue', () => {
+ expect(resolveScreenEdgePadding({ legacyPhoneLayout: isLegacyPhoneWindow(phone),
+ fallbackPortraitTop: 24, insets: { top: 0, left: 30, right: 0 },
+ windowWidth: 400, windowHeight: 776,
+ })).toEqual({ paddingLeft: 0, paddingRight: 0, paddingTop: 24 });
+ });
+ it.each([
+ { windowWidth: 320 }, { windowHeight: 400 },
+ { screenWidth: 800, screenHeight: 1000, windowWidth: 800, windowHeight: 1000 },
+ { platform: 'ios', version: 27 }, { platform: 'ios', version: 26, iosPad: true },
+ { platform: 'web' },
+ ])('keeps independent edges outside legacy phone windows: %o', (overrides) => {
+ expect(isLegacyPhoneWindow({ ...phone, ...overrides })).toBe(false);
+ });
+ it('retains the pre-27 iPhone workaround', () => {
+ expect(isLegacyPhoneWindow({ ...phone, platform: 'ios', version: 26 })).toBe(true);
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts
index 1ce93f4f99..37e9975cbf 100644
--- a/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts
@@ -9,7 +9,7 @@ const readTextLf = (...args: Parameters<typeof readFileSync>): string =>
describe('mobile session header desktop-first surface', () => {
it('preserves title status in the iOS branch, not only in the legacy header', () => {
const source = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
- const start = source.indexOf('{nativeHeader ? <SessionHeaderNativeTitle');
+ const start = source.indexOf('nativeHeader ? <SessionHeaderNativeTitle');
const nativeBranch = source.slice(start, source.indexOf('/> : (', start));
expect(start).toBeGreaterThan(-1);
for (const prop of ['syncing={syncing}', 'syncingImmediately={syncingImmediately}',
@@ -55,7 +55,7 @@ describe('mobile session header desktop-first surface', () => {
// 会被静默吞掉,收敛到 useGuardedBack(back 后校验 pathname,没走成 replace 兜底)。
expect(source).toContain('const goBackToHome = useGuardedBack();');
expect(source).toContain("import { useGuardedBack } from '@/utils/useGuardedBack';");
- expect(source).toContain('onBack={goBackToHome}');
+ expect(source).toContain('onBack={sessionListDrawerOverlayMounted ? closeSessionListDrawer : goBackToHome}');
expect(source).toContain('<Icon color={color} size={iconSize.action} strokeWidth={iconStroke.regular} />');
expect(source).toContain('testID="session.controlsToggle"');
expect(source).toContain('const insets = useSafeAreaInsets();');
@@ -70,7 +70,7 @@ describe('mobile session header desktop-first surface', () => {
const chromeStyle = source.slice(source.indexOf(' sessionChrome: {'), source.indexOf(' sessionChromeContent: {'));
expect(chromeStyle).toContain("backgroundColor: Platform.OS === 'ios' ? 'transparent' : colors.surface");
expect(source).toContain('<View ref={topOverlayRef} onLayout={handleTopOverlayLayout} pointerEvents="box-none" style={styles.sessionChrome} testID="session.chrome">');
- expect(source).toContain('<View style={[styles.sessionChromeContent, { paddingTop: insets.top }]}>');
+ expect(source).toContain('<View style={[styles.sessionChromeContent, { paddingTop: horizontalSystemHeader ? nativeHeaderHeight : insets.top + (paneLayout.persistent ? spacing.lg : 0) }]}>');
expect(chromeStyle).toContain("position: 'absolute'");
// Let native glass press feedback extend beyond the 44pt iOS header.
expect(chromeStyle).toContain("overflow: Platform.OS === 'ios' ? 'visible' : 'hidden'");
@@ -90,22 +90,25 @@ describe('mobile session header desktop-first surface', () => {
expect(source).not.toContain('minHeight: 54');
});
- it('switches the leading control to the session-list hamburger on wide-screen navigation', () => {
+ it('keeps narrow navigation back-only and the persistent Home column', () => {
const source = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
- // 宽屏(iPad / 折叠屏展开 / 横屏手机)导航形态:断点判定走 wideSessionNav 纯函数,
- // 左上角三条杠替代返回,抽屉在当前 native Screen 内切任务;窄屏保持 ScreenBackButton。
+ // 窄窗口仅保留返回;主页列仅在宽窗口常驻。
+ expect(source).toContain('onOpenSessionList={!paneLayout.persistent && wideSessionNav.enabled ? openSessionListDrawer : undefined}');
+ expect(source).toContain('setSessionListDrawerOverlayMounted(true);');
+ expect(source).toContain('setSessionListDrawerOpen(true);');
+ expect(source).toContain('session.sessionListButton');
+ expect(source).toContain('{sessionListButton ? <Stack.Toolbar.View hidesSharedBackground>{sessionListButton}</Stack.Toolbar.View> : null}');
expect(source).toContain("import { buildWideSessionNavLayout } from '@/session/wideSessionNav';");
expect(source).toContain("import { SessionListDrawer } from '@/session/SessionListDrawer';");
expect(source).toContain('switchDrawerSessionInPlace,');
expect(source).toContain("from '@/session/sessionDrawerNavigation';");
- // 按平台分闸(发布策略):iOS 只发 iPad,iPhone 横屏也保持返回键;安卓纯宽度闸。
+ // 同一宽度计算兼容现有调用参数。
expect(source).toContain('iosPad: Platform.OS === \'ios\' && Platform.isPad,');
expect(source).toContain('platform: Platform.OS,');
- expect(source).toContain('onOpenSessionList={wideSessionNav.enabled ? openSessionListDrawer : undefined}');
- expect(source).toContain('icon={Menu}');
- expect(source).toContain('testID="session.sessionListButton"');
- expect(source).toContain('{onOpenSessionList ? (');
+ expect(source).toContain('{systemBack ? null : nativeHeader ? (');
+ expect(source).toContain('onBack={sessionListDrawerOverlayMounted ? closeSessionListDrawer : goBackToHome}');
+ expect(source).toContain('gestureEnabled: !sessionListDrawerOverlayMounted');
// 抽屉切任务只替换当前 route params:不压栈,也不派发会创建新 route key 的
// NativeStack REPLACE(后者正是 Android crash / 白屏仍存的生命周期入口)。
expect(source).toContain('const handleDrawerSelectSession = useCallback((item: RemoteSessionListItem) => {');
@@ -115,7 +118,7 @@ describe('mobile session header desktop-first surface', () => {
expect(drawerSelectionSource).toContain('switchDrawerSessionInPlace(navigation, {');
expect(drawerSelectionSource).not.toContain('router.replace');
expect(drawerSelectionSource).not.toContain("pathname: '/sessions/[sessionId]'");
- // 三个导航入口都等 drawer overlay 完整卸载;新建 / 回主页可能原生换屏,
+ // 导航入口等 drawer overlay 完整卸载;新建可能原生换屏,
// 切任务虽已改为 replaceParams,也不和 Reanimated 子树退场抢同一帧。
expect(source).toContain('const pendingDrawerNavigationRef = useRef<(() => void) | null>(null);');
expect(source).toContain('const sessionListDrawerClosingRef = useRef(false);');
@@ -125,14 +128,14 @@ describe('mobile session header desktop-first surface', () => {
// 同步锁住约 200ms 退场期;快速二次导航不能登记或改写首次关闭意图。
expect(source).toContain('if (sessionListDrawerClosingRef.current || pendingDrawerNavigationRef.current) return;');
expect(source).toContain('sessionListDrawerClosingRef.current = true;\n pendingDrawerNavigationRef.current = action;');
- expect(source).toContain('const closeSessionListDrawer = useCallback(() => {\n if (sessionListDrawerClosingRef.current) return;\n sessionListDrawerClosingRef.current = true;');
+ expect(source).toContain('const closeSessionListDrawer = useCallback(() => {\n if (!sessionListDrawerOverlayMounted) return;\n if (sessionListDrawerClosingRef.current) return;\n sessionListDrawerClosingRef.current = true;');
expect(source).toContain('if (targetSession.id === sessionId && !focusClientId) {\n closeSessionListDrawer();');
expect(source).toContain('onClosed={handleSessionListDrawerClosed}');
- expect(source).toContain('const action = pendingDrawerNavigationRef.current;\n sessionListDrawerClosingRef.current = false;\n if (!action) returnDrawerFocusAfterCloseRef.current = true;\n setSessionListDrawerOverlayMounted(false);');
+ expect(source).toContain('const action = pendingDrawerNavigationRef.current;\n sessionListDrawerClosingRef.current = false;\n setSessionListDrawerOverlayMounted(false);');
expect(source).toContain('pendingDrawerNavigationRef.current = null;\n action();');
expect(source).toContain('queueDrawerNavigation(() => {\n // 必须早于 replaceParams');
expect(source).toContain('queueDrawerNavigation(() => {\n guardedPush({');
- expect(source).toContain("queueDrawerNavigation(() => router.dismissTo('/'));");
+ expect(source).not.toContain('handleDrawerGoHome');
// 旋转 / 分屏收窄回窄屏时抽屉必须自动收起(没有入口的悬空 overlay)。
expect(source).toContain('if (!wideSessionNav.enabled && sessionListDrawerOverlayMounted) closeSessionListDrawer();');
// Android 退场期(open=false 但 overlay 仍 mounted)必须临时吞掉系统返回;
@@ -140,22 +143,15 @@ describe('mobile session header desktop-first surface', () => {
expect(source).toContain("if (Platform.OS !== 'android' || !sessionListDrawerOverlayMounted || sessionListDrawerOpen) return;");
expect(source).toContain("BackHandler.addEventListener('hardwareBackPress', () => true)");
expect(source).toContain('}, [sessionListDrawerOpen, sessionListDrawerOverlayMounted]);');
- // 打开抽屉先收键盘(树内 overlay 盖不住键盘)。
- expect(source).toContain('Keyboard.dismiss();\n setSessionListDrawerOverlayMounted(true);\n setSessionListDrawerOpen(true);');
// 读屏模态语义双平台配对:iOS accessibilityElementsHidden + Android importantForAccessibility
// (accessibilityViewIsModal 只对 iOS 生效,安卓优先发布不能漏 TalkBack);必须覆盖完整退场期。
expect(source).toContain('accessibilityElementsHidden={sessionListDrawerOverlayMounted}');
expect(source).toContain("importantForAccessibility={sessionListDrawerOverlayMounted ? 'no-hide-descendants' : 'auto'}");
- // 非导航关闭的焦点归还必须由父级在背景隔离解除后的 commit effect 执行;
- // 导航型关闭及页面已失焦时都不能把焦点抢回旧页面。
- expect(source).toContain('if (sessionListDrawerOverlayMounted || !returnDrawerFocusAfterCloseRef.current) return;');
- expect(source).toContain('if (!navigation.isFocused()) return;');
- expect(source).toContain('AccessibilityInfo.setAccessibilityFocus(returnNode)');
// 退场期间旋转/折叠/收窄不能直接卸载 Drawer:保留到 onClosed,三类 pending 导航
// 才都能执行;宽屏 layout 失效后 drawerWidth=0,退场继续用最后有效宽度。
- expect(source).toContain('{wideSessionNav.enabled || sessionListDrawerOverlayMounted ? (');
+ expect(source).toContain('persistent={paneLayout.persistent && !sessionListDrawerOverlayMounted}');
expect(source).toContain('if (wideSessionNav.enabled) sessionListDrawerWidthRef.current = wideSessionNav.drawerWidth;');
- expect(source).toContain('width={sessionListDrawerWidthRef.current}');
+ expect(source).toContain('width={paneLayout.persistent && !sessionListDrawerOverlayMounted ? paneLayout.sidebarWidth : sessionListDrawerWidthRef.current}');
// 选任务失败路径:校验先于关闭动画——先关再弹 Alert 会让焦点归还抢走弹窗焦点。
expect(source).toContain("Alert.alert(t('devices.list.error.sessionDeviceNotFound'));\n return;\n }\n // 不派发 NativeStack REPLACE");
});
diff --git a/apps/mobile/src/__tests__/sessionHeaderHeight.test.tsx b/apps/mobile/src/__tests__/sessionHeaderHeight.test.tsx
new file mode 100644
index 0000000000..0cae9eb0f2
--- /dev/null
+++ b/apps/mobile/src/__tests__/sessionHeaderHeight.test.tsx
@@ -0,0 +1,59 @@
+// @vitest-environment jsdom
+import { act, useEffect } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+const state = vi.hoisted(() => ({ focused: true, height: 82,
+ listener: undefined as undefined | ((event: { data: { closing: boolean } }) => void),
+ navigation: { addListener: vi.fn() },
+}));
+vi.mock('expo-router/react-navigation', () => ({ useHeaderHeight: () => state.height }));
+vi.mock('expo-router', () => ({
+ useNavigation: () => state.navigation,
+ useFocusEffect: (callback: () => void | (() => void)) => {
+ useEffect(() => state.focused ? callback() : undefined, [callback, state.focused]);
+ },
+}));
+import { useSessionHeaderHeight } from '@/session/useSessionHeaderHeight';
+
+describe('task header geometry during native preload', () => {
+ let root: Root;
+ let height = 0;
+ let key = '';
+ function Probe() { height = useSessionHeaderHeight(key); return null; }
+ async function render() { await act(async () => root.render(<Probe />)); }
+ async function settle() { await act(async () => state.listener?.({ data: { closing: false } })); }
+ beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ state.focused = true; state.height = 82; state.listener = undefined;
+ state.navigation.addListener.mockImplementation((_event, listener) => {
+ state.listener = listener; return () => { state.listener = undefined; };
+ });
+ key = expect.getState().currentTestName!;
+ root = createRoot(document.createElement('div'));
+ });
+ afterEach(async () => { await act(async () => root.unmount()); });
+ it('keeps the measured height through preload and push instead of adopting the estimate', async () => {
+ await render(); await settle(); expect(height).toBe(82);
+ await act(async () => root.render(null));
+ state.focused = false; state.height = 120.67;
+ await render(); expect(height).toBe(82);
+ state.focused = true; await render(); expect(height).toBe(82);
+ state.height = 82; await render(); await settle(); expect(height).toBe(82);
+ });
+ it('does not share measurements across window geometry and follows later real resize', async () => {
+ await render(); await settle();
+ await act(async () => root.render(null));
+ key += '-rotated'; state.focused = false; state.height = 44;
+ await render(); expect(height).toBe(44);
+ state.focused = true; await render(); await settle();
+ state.height = 50; await render(); expect(height).toBe(50);
+ });
+ it('does not record offscreen estimates or a closing transition as measured geometry', async () => {
+ await render();
+ await act(async () => state.listener?.({ data: { closing: true } }));
+ await act(async () => root.render(null));
+ state.focused = false; state.height = 120;
+ await render(); expect(height).toBe(120);
+ state.height = 130; await render(); expect(height).toBe(130);
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionListDrawer.test.ts b/apps/mobile/src/__tests__/sessionListDrawer.test.ts
index 9be1e4487e..e31b9df4dd 100644
--- a/apps/mobile/src/__tests__/sessionListDrawer.test.ts
+++ b/apps/mobile/src/__tests__/sessionListDrawer.test.ts
@@ -20,8 +20,6 @@ describe('mobile session list drawer', () => {
expect(text).not.toContain('elevation:');
expect(text).not.toMatch(/#[0-9a-fA-F]{3,8}\b/);
expect(text).not.toMatch(/borderRadius:\s*\d/);
- expect(text).toContain('borderRadius: radius.pill');
- expect(text).toContain('borderRadius: radius.container');
// 主题接入模式:模块级 makeStyles + useThemedStyles,不用静态色。
expect(text).toContain('const makeStyles = (colors: ThemeColors) =>');
expect(text).toContain('useThemedStyles(makeStyles)');
@@ -40,7 +38,6 @@ describe('mobile session list drawer', () => {
expect(text).toContain('duration: motionDuration.enter');
expect(text).toContain('duration: motionDuration.exit');
expect(text).toContain('duration: motionDuration.fast');
- expect(text).toContain('duration: motionDuration.spinnerCycle');
expect(text).toContain('Easing.bezier(...motionEasing.out)');
expect(text).toContain('Easing.bezier(...motionEasing.in)');
expect(text).toContain('Easing.bezier(...motionEasing.move)');
@@ -60,29 +57,24 @@ describe('mobile session list drawer', () => {
expect(text).toContain('.failOffsetY([-16, 16])');
// 关闭动画期间 overlay 恒拦截,不放行点击穿透半透明 scrim(review #1328)。
expect(text).toContain('pointerEvents="auto"');
- // 抽屉 presentation 必须带权威设备身份,防 canonicalDeviceId 被弱推断覆盖(review #1328)。
- expect(text).toContain('const devices = useRemoteDeviceIdentity();');
- expect(text).toMatch(/buildMobileHomePresentation\(\{(?:(?!\}\);)[\s\S])*?\n\s*devices,/);
- // 行内状态与标题兜底与首页同口径:pending/liveActivity 索引 + 已解析 unnamedLabel(review #1328)。
- expect(text).toContain('remoteSessionStore.getPendingInteractions(session.id).length');
- expect(text).toContain('remoteSessionStore.getSessionLiveActivity(session.id)');
- expect(text).toContain("unnamedLabel: t('session.menu.unnamedTitle')");
- // 底部主操作行触控目标 >=44。
- expect(text).toContain('minHeight: 44,');
+ // 临时面板使用主页的关闭入口,不再有重复主页底栏。
+ expect(text).not.toContain('sessionDrawer.home');
+ expect(text).toContain('onDismiss={persistent ? undefined : onClose}');
});
- it('keeps the drawer aligned with the home list presentation pipeline', () => {
+ it('uses the actual Home instead of maintaining a second list or data controller', () => {
const text = source();
- // 与首页同一套共享层口径:排序 / 置顶 / 自动化折叠 / Orca worker 过滤 / 右槽状态档位。
- expect(text).toContain('excludeOrcaWorkerSessions(sessions)');
- expect(text).toContain('buildMobileHomePresentation({');
- expect(text).toContain('buildHomeSections(home, false, false, { groupCindyMake: false })');
- expect(text).toContain('resolveMobileSessionRowStatus(item, sessionIsRunning)');
- expect(text).toMatch(/buildRemoteSessionCardPreview\((?:(?!\);)[\s\S])*?\{ running \},?\s*\)/);
- expect(text).toContain('formatRemoteSessionSidebarTime(lastActivityAt)');
- expect(text).toContain('conversationSearchOriginsFromDeviceModels');
- expect(text).toContain('useRemoteConversationSearchDeviceModels()');
- expect(text).toContain('useRemoteDeviceIdentity()');
+ const route = readTextLf(resolve(process.cwd(), 'app/devices/index.tsx'), 'utf8');
+ const home = readTextLf(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8');
+ expect(route).toContain('return <MobileHome />;');
+ expect(route).toContain("@/session/HomeSurface");
+ expect(text).toContain("import { MobileHome } from './HomeSurface'");
+ expect(text).toContain('<MobileHome');
+ expect(text).not.toMatch(/<SectionList|DrawerSessionRow|buildMobileHomePresentation|useRemoteSessions/);
+ expect(home).toContain('<SectionList');
+ expect(home).toContain('renderItem={renderHomeRow}');
+ expect(home).toContain('onSelectSession(item)');
+ expect(home).toContain('!embedded && usesNativeStackHeader()');
});
it('exposes stable testIDs and modal accessibility semantics', () => {
@@ -91,17 +83,16 @@ describe('mobile session list drawer', () => {
'sessionDrawer.overlay',
'sessionDrawer.scrim',
'sessionDrawer.panel',
- 'sessionDrawer.newSession',
- 'sessionDrawer.home',
]) {
expect(text).toContain(`testID="${testId}"`);
}
- expect(text).toContain('accessibilityViewIsModal={mounted}');
+ expect(text).toContain('accessibilityViewIsModal={mounted && !persistent}');
+ expect(text).toContain('if (!open || persistent) return;');
expect(text).toContain("t('home.drawer.closeA11y')");
// 打开时把读屏焦点移到面板首控件;关闭后的背景焦点归还由父级在解除
// accessibility 隔离后的 commit effect 负责。
expect(text).toContain('AccessibilityInfo.setAccessibilityFocus(node)');
- expect(text).toContain('ref={newSessionButtonRef}');
+ expect(text).toContain('ref={homeContentRef}');
// 导航动作必须等 overlay 的 mounted=false commit 后执行,不能与 Android 原生换屏同帧。
expect(text).toContain('onClosedRef.current?.();');
expect(text).not.toContain('returnFocusRef');
diff --git a/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx b/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx
index 762de0a97d..fd704ea3e1 100644
--- a/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx
+++ b/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx
@@ -2,30 +2,22 @@ vi.mock('@/session/SessionOptionsExpoSheet', () => ({ SessionOptionsPresenter: (
vi.mock('@/session/RenameSessionModal', () => ({ RenameSessionModal: () => null }));
vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: { id: 'test-owner' } }) }));
// @vitest-environment jsdom
-import { act, type ReactNode } from "react";
-import { createRoot, type Root } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { SESSION_ACTIVITY_CHANNEL } from "@cindy/device-link";
-import { SessionListDrawer } from "@/session/SessionListDrawer";
-import { remoteSessionStore } from "@/session/remoteSessionStore";
-import { buildMobileHomePresentation } from "@/session/mobileHome";
-import { buildRemoteSessionCardPreview } from "@/session/sessionList";
-import { clearSessionScheduleIndexCache } from "@/session/scheduleIndex";
-import { remoteScheduleEventStore } from "@/scheduler/remoteScheduleEvents";
-import { i18n } from "@/i18n";
-import type { HomeRow, HomeSection } from "@/session/homeSections";
-import type { RemoteMessage, RemoteSession } from "@/session/types";
-
-// Keep React, the store, search hook and presentation real. Only native views/gestures are
-// replaced: assertions observe committed rows and count actual presentation executions.
-const native = vi.hoisted(() => ({
- sections: [] as HomeSection[],
- search: { query: "", onChangeQuery: (_value: string) => {} },
- invoke: vi.fn(),
- appState: 'active',
- appStateListeners: new Set<(state: string) => void>(),
-}));
-
+import { act, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { SessionListDrawer } from '@/session/SessionListDrawer';
+import { motionDuration } from '@/theme/tokens';
+import type { MobileHomeProps } from '@/session/HomeSurface';
+const native = vi.hoisted(() => ({ home: null as MobileHomeProps | null, mounts: 0, unmounts: 0, reduceMotion: true }));
+vi.mock('@/session/HomeSurface', async () => {
+ const { useEffect } = await import('react');
+ return { MobileHome: (props: MobileHomeProps) => {
+ native.home = props;
+ useEffect(() => { native.mounts++; return () => { native.unmounts++; }; }, []);
+ return null;
+ } };
+});
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock("react-native", async () => {
const { createElement } = await import("react");
type Props = {
@@ -55,30 +47,11 @@ vi.mock("react-native", async () => {
return {
View,
Pressable: View,
- SectionList: ({
- sections,
- renderItem,
- }: {
- sections: HomeSection[];
- renderItem: (info: { item: HomeRow }) => ReactNode;
- }) => {
- native.sections = sections;
- return createElement(
- "div",
- {},
- sections.flatMap((section) =>
- section.data.map((item) =>
- createElement("div", { key: item.key }, renderItem({ item })),
- ),
- ),
- );
- },
AccessibilityInfo: { setAccessibilityFocus: vi.fn() },
AppState: {
- get currentState() { return native.appState; },
+ get currentState() { return 'active'; },
addEventListener: (_event: string, listener: (state: string) => void) => {
- native.appStateListeners.add(listener);
- return { remove: () => native.appStateListeners.delete(listener) };
+ return { remove() {} };
},
},
BackHandler: { addEventListener: () => ({ remove() {} }) },
@@ -113,6 +86,7 @@ vi.mock("@/platform/gestureHandler", () => ({
Gesture: {
Pan: () => {
const chain = {
+ enabled: () => chain,
activeOffsetX: () => chain,
failOffsetX: () => chain,
failOffsetY: () => chain,
@@ -124,6 +98,7 @@ vi.mock("@/platform/gestureHandler", () => ({
},
}));
vi.mock("lucide-react-native", () => ({
+ ChevronDown: () => null, ChevronRight: () => null, Folder: () => null, FolderOpen: () => null, MessagesSquare: () => null,
House: () => null,
LoaderCircle: () => null,
SquarePen: () => null,
@@ -139,413 +114,81 @@ vi.mock("@/theme", () => ({
useTheme: () => ({ colors: {} }),
}));
vi.mock("@/hooks/useReduceMotion", () => ({
- useReduceMotionEnabled: () => true,
-}));
-vi.mock("@/session/HomeSearchBar", () => ({
- HomeSearchBar: (props: typeof native.search) => {
- native.search = props;
- return null;
- },
-}));
-vi.mock("@/session/ConversationSearchFilterSheet", () => ({
- ConversationSearchFilterSheet: () => null,
-}));
-vi.mock("@/device-link/DeviceLinkContext", () => ({
- useDeviceLink: () => ({ invoke: native.invoke }),
+ useReduceMotionEnabled: () => native.reduceMotion,
}));
-vi.mock("@/session/mobileHome", async (importOriginal) => {
- const original =
- await importOriginal<typeof import("@/session/mobileHome")>();
- return {
- ...original,
- buildMobileHomePresentation: vi.fn(original.buildMobileHomePresentation),
- };
-});
-vi.mock("@/session/sessionList", async (importOriginal) => {
- const original =
- await importOriginal<typeof import("@/session/sessionList")>();
- return {
- ...original,
- buildRemoteSessionCardPreview: vi.fn(
- original.buildRemoteSessionCardPreview,
- ),
- };
-});
-
-function session(
- id: string,
- patch: Partial<RemoteSession> = {},
-): RemoteSession {
- return {
- id,
- userId: "user",
- title: id,
- workingDir: "/repo",
- workspaceKind: "project",
- model: "claude",
- effort: "medium",
- permissionMode: "default",
- fastMode: false,
- status: "active",
- agentKind: "cc",
- userSendAt: null,
- createdAt: "2026-09-01T00:00:00.000Z",
- updatedAt: "2026-09-01T00:00:00.000Z",
- ...patch,
- };
-}
-
-function message(sessionId: string, content: string): RemoteMessage {
- return {
- id: `m-${sessionId}`,
- clientId: `m-${sessionId}`,
- sessionId,
- role: "assistant",
- content,
- toolUseId: null,
- agentMeta: null,
- createdAt: "2026-09-01T00:00:01.000Z",
- };
-}
-
-function delta(sessionId: string, text: string) {
- remoteSessionStore.applyRemotePush("dev-1", "maker:event", {
- sessionId,
- persistId: `live-${sessionId}`,
- event: { type: "text", data: { text, isFinal: false } },
- });
-}
-describe("drawer selective updates", () => {
+describe('shared Home drawer host', () => {
let root: Root;
let container: HTMLDivElement;
- const onSelect = vi.fn();
- const onClosed = vi.fn();
- const props = {
- currentSessionId: "s1",
- onClose() {},
- onClosed,
- onGoHome() {},
- onNewSession() {},
- onSelectSession: onSelect,
- open: true,
- width: 360,
- };
- const render = async (open = true) => {
- await act(async () =>
- root.render(<SessionListDrawer {...props} open={open} />),
- );
- };
- const row = (id: string) =>
- container.querySelector(`[data-testid="sessionDrawer.row.${id}"]`);
- const status = (id: string, value: string) =>
- container.querySelector(
- `[data-testid="sessionDrawer.rowStatus.${value}.${id}"]`,
- );
- const tick = async (ms: number) => {
- await act(async () => {
- await vi.advanceTimersByTimeAsync(ms);
- });
- };
-
- beforeEach(async () => {
- native.appState = 'active';
- native.appStateListeners.clear();
- clearSessionScheduleIndexCache();
- remoteScheduleEventStore.clearAll();
+ const props = { currentSessionId: 's1', onClose: vi.fn(), onClosed: vi.fn(),
+ onSelectSession: vi.fn(), runNavigation: vi.fn((action: () => void) => action()), open: true, width: 320 };
+ beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ native.home = null; native.mounts = 0; native.unmounts = 0;
+ native.reduceMotion = true;
+ vi.clearAllMocks();
vi.useFakeTimers();
- remoteSessionStore.clear();
- native.invoke
- .mockReset()
- .mockResolvedValue({
- query: "needle",
- results: [],
- vectorUsed: false,
- vectorSkipReason: null,
- poolCapped: false,
- });
- onSelect.mockClear();
- onClosed.mockClear();
- await i18n.changeLanguage("zh-CN");
- container = document.createElement("div");
- document.body.appendChild(container);
- root = createRoot(container);
- remoteSessionStore.setDeviceIdentity([
- { deviceId: "dev-1", name: "Studio" },
- ]);
- remoteSessionStore.setConversationSearchDeviceModels([
- { deviceId: "dev-1", name: "Studio", canOpen: true, state: "ready" },
- ]);
- remoteSessionStore.setDeviceSessions("dev-1", "Studio", [
- session("s1"),
- session("s2"),
- ]);
- });
-
- afterEach(async () => {
- await act(async () => root.unmount());
- container.remove();
- remoteSessionStore.clear();
- vi.clearAllTimers();
- vi.useRealTimers();
- });
-
- it("updates only the changed preview without rebuilding sections, including a parent rerender", async () => {
- remoteSessionStore.setDeviceSessions(
- "dev-1",
- "Studio",
- Array.from({ length: 40 }, (_, i) => session(`s${i + 1}`)),
- );
- remoteSessionStore.setMessages("s2", [message("s2", "unchanged preview")]);
- await render();
- const sections = native.sections;
- vi.mocked(buildMobileHomePresentation).mockClear();
- vi.mocked(buildRemoteSessionCardPreview).mockClear();
- await act(async () => delta("s1", "first"));
- await tick(100);
- await act(async () => delta("s1", " second"));
- await tick(100);
- for (let index = 0; index < 98; index += 1) {
- await act(async () => delta("s1", "."));
- await tick(100);
- }
- expect(row("s1")?.textContent).toContain("first second");
- expect(row("s2")?.textContent).toContain("unchanged preview");
- expect(native.sections).toBe(sections);
- expect(buildMobileHomePresentation).not.toHaveBeenCalled();
- expect(buildRemoteSessionCardPreview).toHaveBeenCalled();
- expect(
- vi
- .mocked(buildRemoteSessionCardPreview)
- .mock.calls.every(([item]) => item.session.id === "s1"),
- ).toBe(true);
- await render(); // The surrounding session screen itself still renders while streaming.
- expect(buildMobileHomePresentation).not.toHaveBeenCalled();
- expect(native.sections).toBe(sections);
- });
-
- it("falls back to the host preview when loaded messages are cleared", async () => {
- remoteSessionStore.setDeviceSessions("dev-1", "Studio", [
- session("s1", { preview: "host preview" }),
- session("s2"),
- ]);
- await render();
- expect(row("s1")?.textContent).toContain("host preview");
- await act(async () => {
- remoteSessionStore.setMessages("s1", [message("s1", "loaded preview")]);
- });
- expect(row("s1")?.textContent).toContain("host preview");
- await act(async () => {
- remoteSessionStore.markSessionMessagesSynced(
- "s1",
- session("s1", { preview: "host preview" }),
- );
- });
- expect(row("s1")?.textContent).toContain("loaded preview");
- await act(async () => remoteSessionStore.setMessages("s1", []));
- expect(row("s1")?.textContent).toContain("host preview");
- expect(row("s1")?.textContent).not.toContain("loaded preview");
- });
-
- it("keeps pending, running, error and completed indicators current", async () => {
- await render();
- await act(async () => remoteSessionStore.setSessionRunning("s1", true));
- expect(status("s1", "running")).not.toBeNull();
- await act(async () =>
- remoteSessionStore.setPendingInteractions("s1", [
- { request: { kind: "permission", requestId: "p1" } },
- ]),
- );
- expect(status("s1", "awaiting")).not.toBeNull();
- await act(async () => remoteSessionStore.setPendingInteractions("s1", []));
- expect(status("s1", "running")).not.toBeNull();
- for (const [phase, rightStatus] of [
- ["error", "error"],
- ["completed", "done"],
- ] as const) {
- await act(async () =>
- remoteSessionStore.applyRemotePush("dev-1", SESSION_ACTIVITY_CHANNEL, {
- sessionId: "s1",
- phase,
- compactDetail: phase,
- attention: true,
- }),
- );
- expect(status("s1", rightStatus)).not.toBeNull();
- }
- });
-
- it("keeps the latest group run for an older waiting interaction, matching desktop", async () => {
- remoteSessionStore.setDeviceSessions("dev-1", "Studio", [
- session("old", { source: "scheduler", title: "daily" }),
- session("new", {
- source: "scheduler",
- title: "daily",
- updatedAt: "2026-09-02T00:00:00.000Z",
- }),
- ]);
- // Schedule histories are intentionally retained only while their detail is in use.
- remoteSessionStore.enterSessionMessageDetail("old");
- remoteSessionStore.enterSessionMessageDetail("new");
- remoteSessionStore.setMessages("old", [message("old", "older run")]);
- remoteSessionStore.setMessages("new", [message("new", "newer run")]);
- await render();
- expect(row("new")?.textContent).toContain("newer run");
- await act(async () =>
- remoteSessionStore.setPendingInteractions("old", [
- { request: { kind: "ask_user_question", requestId: "question" } },
- ]),
- );
- expect(row("old")).toBeNull();
- expect(row("new")?.textContent).toContain("newer run");
- await act(async () => (row("new") as HTMLElement).click());
- expect(onSelect.mock.calls.at(-1)?.[0].session.id).toBe("new");
- await act(async () => remoteSessionStore.setPendingInteractions("old", []));
- expect(row("new")?.textContent).toContain("newer run");
+ container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container);
});
-
- it("refreshes failed unread from the lightweight host index when read elsewhere", async () => {
- let readAt: number | undefined;
- native.invoke.mockImplementation(async (_device, channel) => {
- if (channel === 'maker:schedule:list') return [{ id: 'auto', name: 'auto', status: 'active', targetSessionId: 's1' }];
- expect(channel).toBe("maker:schedule:list-sidebar-index-runs");
- return { runs: [{ sessionId: "s1", scheduleId: "auto", runId: "run", scheduleName: "auto", scheduleStatus: "active", status: "failed", firedAt: 1, readAt }] };
- });
- await render();
- expect(status("s1", "error")).not.toBeNull();
- readAt = 10;
- await act(async () => remoteScheduleEventStore.apply("dev-1", { type: "read", scheduleId: "auto" }));
- expect(status("s1", "error")).toBeNull();
- expect(native.invoke).toHaveBeenCalledTimes(4);
+ afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.useRealTimers(); });
+ it('unmounts the invisible blocker even when the animation never calls completion', async () => {
+ native.reduceMotion = false;
+ await act(async () => root.render(<SessionListDrawer {...props} />));
+ await act(async () => root.render(<SessionListDrawer {...props} open={false} />));
+ expect(container.querySelector('[data-testid="sessionDrawer.overlay"]')).not.toBeNull();
+ expect(props.onClosed).not.toHaveBeenCalled();
+ // withTiming deliberately never delivers a completion in this test driver.
+ await act(async () => vi.advanceTimersByTime(motionDuration.exit));
+ expect(container.querySelector('[data-testid="sessionDrawer.overlay"]')).toBeNull();
+ expect(native.unmounts).toBe(1);
+ expect(props.onClosed).toHaveBeenCalledOnce();
});
-
- it('does not retry or start schedule scans in the background and refreshes on return', async () => {
- native.invoke.mockRejectedValue(new Error('[INVOKE_TIMEOUT] timeout'));
- await render();
- expect(native.invoke).toHaveBeenCalledTimes(1);
- native.appState = 'background';
- await act(async () => native.appStateListeners.forEach((listener) => listener('background')));
- await tick(5000);
- await act(async () => remoteScheduleEventStore.apply('dev-1', { type: 'read', scheduleId: 'auto' }));
- expect(native.invoke).toHaveBeenCalledTimes(1);
- native.invoke.mockImplementation(async (_device, channel) => channel === 'maker:schedule:list' ? [] : { runs: [] });
- native.appState = 'active';
- await act(async () => native.appStateListeners.forEach((listener) => listener('active')));
- expect(native.invoke).toHaveBeenCalledTimes(3);
+ it('cancels pending close settlement when reopened, then closes the new presentation once', async () => {
+ native.reduceMotion = false;
+ await act(async () => root.render(<SessionListDrawer {...props} />));
+ await act(async () => root.render(<SessionListDrawer {...props} open={false} />));
+ await act(async () => vi.advanceTimersByTime(motionDuration.exit / 2));
+ await act(async () => root.render(<SessionListDrawer {...props} />));
+ await act(async () => vi.advanceTimersByTime(motionDuration.exit));
+ expect(container.querySelector('[data-testid="sessionDrawer.overlay"]')).not.toBeNull();
+ expect(props.onClosed).not.toHaveBeenCalled();
+ await act(async () => root.render(<SessionListDrawer {...props} open={false} />));
+ await act(async () => vi.advanceTimersByTime(motionDuration.exit));
+ expect(props.onClosed).toHaveBeenCalledOnce();
+ expect(native.unmounts).toBe(1);
});
-
- it("refreshes device search reachability without a session-array change", async () => {
- remoteSessionStore.setConversationSearchDeviceModels([
- { deviceId: "dev-1", name: "Studio", canOpen: false, state: "offline" },
- ]);
- await render();
- await act(async () => native.search.onChangeQuery("needle"));
- await tick(300);
- expect(native.invoke.mock.calls.filter((call) => call[1] === "local-db:conversations:search")).toHaveLength(0);
- const sessions = remoteSessionStore.getSessions();
- await act(async () =>
- remoteSessionStore.setConversationSearchDeviceModels([
- { deviceId: "dev-1", name: "Studio", canOpen: true, state: "ready" },
- ]),
- );
- expect(remoteSessionStore.getSessions()).toBe(sessions);
- await tick(300);
- expect(native.invoke.mock.calls.filter((call) => call[1] === "local-db:conversations:search")).toHaveLength(1);
- expect(native.invoke.mock.calls.find((call) => call[1] === "local-db:conversations:search")?.slice(0, 2)).toEqual([
- "dev-1",
- "local-db:conversations:search",
- ]);
+ it('hosts the complete Home with container width, selection and the navigation coordinator', async () => {
+ await act(async () => root.render(<SessionListDrawer {...props} persistent newSessionInSystemBar />));
+ expect(native.home).toMatchObject({ width: 320, currentSessionId: 's1', newSessionInSystemBar: true,
+ onSelectSession: props.onSelectSession, runNavigation: props.runNavigation });
+ expect(container.querySelector('[data-testid="sessionDrawer.home"]')).toBeNull();
+ expect(container.querySelector('[data-testid="sessionDrawer.scrim"]')).toBeNull();
});
-
- it("refreshes device identity even when no session changes, with a stable empty snapshot", async () => {
- remoteSessionStore.clear();
- expect(remoteSessionStore.getDeviceIdentity()).toBe(
- remoteSessionStore.getDeviceIdentity(),
- );
- await render();
- const sessions = remoteSessionStore.getSessions();
- vi.mocked(buildMobileHomePresentation).mockClear();
- await act(async () =>
- remoteSessionStore.setDeviceIdentity([
- { deviceId: "empty-device", name: "Renamed" },
- ]),
- );
- expect(remoteSessionStore.getSessions()).toBe(sessions);
- expect(
- vi.mocked(buildMobileHomePresentation).mock.calls.at(-1)?.[0].devices,
- ).toEqual([{ deviceId: "empty-device", name: "Renamed" }]);
+ it('uses the Home leading close action and has no home footer in the temporary panel', async () => {
+ await act(async () => root.render(<SessionListDrawer {...props} />));
+ expect(container.querySelector('[data-testid="sessionDrawer.home"]')).toBeNull();
+ expect(native.home?.onDismiss).toBe(props.onClose);
+ await act(async () => native.home?.onDismiss?.());
+ expect(props.onClose).toHaveBeenCalledOnce();
});
-
- it("matches loaded text during search debounce without restarting the indexed request on each delta", async () => {
- await render();
- await act(async () => native.search.onChangeQuery("needle"));
- expect(row("s1")).toBeNull();
- await tick(100);
- await act(async () => delta("s1", "needle"));
- await tick(100);
- expect(row("s1")?.textContent).toContain("needle");
- await act(async () => delta("s1", " more"));
- await tick(100);
- expect(native.invoke.mock.calls.filter((call) => call[1] === "local-db:conversations:search")).toHaveLength(1);
- await tick(300);
- expect(native.invoke.mock.calls.filter((call) => call[1] === "local-db:conversations:search")).toHaveLength(1);
+ it('keeps Home mounted while changing task, width, or drawer presentation', async () => {
+ await act(async () => root.render(<SessionListDrawer {...props} persistent />));
+ await act(async () => root.render(<SessionListDrawer {...props} currentSessionId="s2" width={360} persistent={false} />));
+ expect(native.home).toMatchObject({ width: 360, currentSessionId: 's2' });
+ expect(native.mounts).toBe(1); expect(native.unmounts).toBe(0);
});
-
- it("preserves indexed hit snippets and message focus while newer loaded messages arrive", async () => {
- const contentHit = {
- messageClientId: "hit-message",
- preview: "needle in old message",
- role: "assistant",
- createdAt: "2026-09-01T00:00:01.000Z",
- };
- native.invoke.mockResolvedValue({
- query: "needle",
- results: [
- {
- session: session("s1"),
- matchKind: "content",
- titleMatchIndices: [],
- titleScore: 0,
- contentHit,
- contentHits: [contentHit],
- rankScore: 10,
- },
- ],
- vectorUsed: false,
- vectorSkipReason: null,
- poolCapped: false,
- });
- remoteSessionStore.setMessages("s1", [
- message("s1", "latest unrelated message"),
- ]);
- await render();
- await act(async () => native.search.onChangeQuery("needle"));
- await tick(300);
- expect(row("s1")?.textContent).toContain("needle in old message");
- await act(async () =>
- remoteSessionStore.setMessages("s1", [
- message("s1", "even newer unrelated message"),
- ]),
- );
- expect(row("s1")?.textContent).toContain("needle in old message");
- await act(async () => (row("s1") as HTMLElement).click());
- expect(onSelect.mock.calls.at(-1)?.[0].searchFocusClientId).toBe(
- "hit-message",
- );
+ it('collapses a persistent column without a modal exit or a leftover scrim', async () => {
+ await act(async () => root.render(<SessionListDrawer {...props} persistent />));
+ await act(async () => root.render(<SessionListDrawer {...props} persistent={false} open={false} />));
+ expect(container.querySelector('[data-testid="sessionDrawer.overlay"]')).toBeNull();
+ expect(props.onClosed).not.toHaveBeenCalled();
+ expect(native.unmounts).toBe(1);
});
-
- it("reads current previews when reopened and keeps the active selection and close callback", async () => {
- await render();
- await render(false);
- expect(onClosed).toHaveBeenCalledTimes(1);
- vi.mocked(buildMobileHomePresentation).mockClear();
- await act(async () => delta("s1", "received while closed"));
- await tick(100);
- expect(row("s1")).toBeNull();
- expect(buildMobileHomePresentation).not.toHaveBeenCalled();
- await render();
- expect(row("s1")?.textContent).toContain("received while closed");
- expect(row("s1")?.getAttribute("aria-selected")).toBe("true");
+ it('finishes an overlay exit after unmount so queued navigation cannot race its native views', async () => {
+ await act(async () => root.render(<SessionListDrawer {...props} />));
+ await act(async () => root.render(<SessionListDrawer {...props} open={false} />));
+ expect(native.unmounts).toBe(1);
+ expect(props.onClosed).toHaveBeenCalledTimes(1);
+ expect(container.querySelector('[data-testid="sessionDrawer.overlay"]')).toBeNull();
});
});
diff --git a/apps/mobile/src/__tests__/wideSessionNav.test.ts b/apps/mobile/src/__tests__/wideSessionNav.test.ts
index 5828093d26..3f2f581c24 100644
--- a/apps/mobile/src/__tests__/wideSessionNav.test.ts
+++ b/apps/mobile/src/__tests__/wideSessionNav.test.ts
@@ -1,63 +1,22 @@
import { describe, expect, it } from 'vitest';
-import {
- WIDE_SESSION_NAV_MIN_WIDTH,
- buildWideSessionNavLayout,
-} from '@/session/wideSessionNav';
-
-describe('buildWideSessionNavLayout', () => {
- it('keeps portrait phones on the classic back-button navigation', () => {
- // iPhone SE / 15 Pro / 16 Pro Max 竖屏与 iPad 窄分屏(约 1/3)都必须回退返回键。
- for (const windowWidth of [320, 375, 393, 440]) {
- expect(buildWideSessionNavLayout({ windowHeight: 852, windowWidth })).toEqual({
- drawerWidth: 0,
- enabled: false,
- });
+import { buildWideSessionNavLayout } from '@/session/wideSessionNav';
+
+describe('quick-switch panel sizing', () => {
+ it.each([600, 744, 852, 1366])('offers switching at width %i without replacing back', (windowWidth) => {
+ for (const platform of ['ios', 'android']) {
+ const layout = buildWideSessionNavLayout({ windowWidth, windowHeight: 852, platform });
+ expect(layout.enabled).toBe(true);
+ expect(layout.drawerWidth).toBeLessThanOrEqual(windowWidth - 24);
+ expect(layout.drawerWidth).toBeLessThanOrEqual(360);
+ expect(layout.drawerWidth).toBeGreaterThan(0);
}
});
-
- it('enables drawer navigation for iPad both orientations', () => {
- // iPad mini 竖屏(744)/ iPad Pro 横屏(1366)。
- expect(buildWideSessionNavLayout({ iosPad: true, platform: 'ios', windowHeight: 1133, windowWidth: 744 }).enabled).toBe(true);
- expect(buildWideSessionNavLayout({ iosPad: true, platform: 'ios', windowHeight: 1024, windowWidth: 1366 }).enabled).toBe(true);
- // iPad 窄分屏(~1/3)回退返回键。
- expect(buildWideSessionNavLayout({ iosPad: true, platform: 'ios', windowHeight: 1024, windowWidth: 320 }).enabled).toBe(false);
- });
-
- it('keeps iPhone on back-button navigation even in landscape (per-platform rollout)', () => {
- // 发布策略:iOS 只发 iPad;iPhone 横屏达宽也不启用宽屏形态。
- expect(buildWideSessionNavLayout({ iosPad: false, platform: 'ios', windowHeight: 393, windowWidth: 852 }).enabled).toBe(false);
- expect(buildWideSessionNavLayout({ platform: 'ios', windowHeight: 393, windowWidth: 852 }).enabled).toBe(false);
+ it('keeps the existing tablet sizing and fits narrow split windows', () => {
+ expect(buildWideSessionNavLayout({ windowWidth: 800 }).drawerWidth).toBe(320);
+ expect(buildWideSessionNavLayout({ windowWidth: 1366 }).drawerWidth).toBe(360);
+ expect(buildWideSessionNavLayout({ windowWidth: 600 }).drawerWidth).toBe(300);
});
-
- it('enables drawer navigation for unfolded foldables even in portrait (android)', () => {
- // Pixel Fold 内屏竖持(约 648×672)——宽度已达 medium 档,不要求 landscape。
- const layout = buildWideSessionNavLayout({ platform: 'android', windowHeight: 672, windowWidth: 648 });
- expect(layout.enabled).toBe(true);
- });
-
- it('enables drawer navigation for android landscape phones', () => {
- const layout = buildWideSessionNavLayout({ platform: 'android', windowHeight: 393, windowWidth: 852 });
- expect(layout.enabled).toBe(true);
- });
-
- it('clamps drawer width to a readable range', () => {
- // 断点下缘:0.4×600=240 < 300,顶到下限。
- expect(buildWideSessionNavLayout({ windowHeight: 900, windowWidth: 600 }).drawerWidth).toBe(300);
- // 大屏:0.4×1366=546 > 360,压到上限。
- expect(buildWideSessionNavLayout({ windowHeight: 1024, windowWidth: 1366 }).drawerWidth).toBe(360);
- // 区间内按比例取整。
- expect(buildWideSessionNavLayout({ windowHeight: 1133, windowWidth: 800 }).drawerWidth).toBe(320);
- });
-
- it('treats missing or invalid dimensions as narrow (fail closed to back button)', () => {
- expect(buildWideSessionNavLayout({}).enabled).toBe(false);
- expect(buildWideSessionNavLayout({ windowHeight: Number.NaN, windowWidth: Number.NaN }).enabled).toBe(false);
- expect(buildWideSessionNavLayout({ windowHeight: 800, windowWidth: -1 }).enabled).toBe(false);
- });
-
- it('keeps the breakpoint constant aligned with the documented medium window class', () => {
- expect(WIDE_SESSION_NAV_MIN_WIDTH).toBe(600);
- expect(buildWideSessionNavLayout({ windowHeight: 900, windowWidth: 599 }).enabled).toBe(false);
- expect(buildWideSessionNavLayout({ windowHeight: 900, windowWidth: 600 }).enabled).toBe(true);
+ it.each([undefined, Number.NaN, -1, 0, 280, 393, 599])('does not open before a valid layout (%s)', (windowWidth) => {
+ expect(buildWideSessionNavLayout({ windowWidth }).enabled).toBe(false);
});
});
diff --git a/apps/mobile/src/__tests__/windowGeometry.test.ts b/apps/mobile/src/__tests__/windowGeometry.test.ts
new file mode 100644
index 0000000000..aeb44996aa
--- /dev/null
+++ b/apps/mobile/src/__tests__/windowGeometry.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest';
+import { keyboardControlRegion, controlRegion, windowDivision, type WindowGeometry } from '@/platform/windowGeometry';
+import { foldDesktopLayout } from '@/remote-desktop/foldDesktopLayout';
+import { sessionPaneLayout } from '@/session/sessionPaneLayout';
+
+const window = (patch: Partial<WindowGeometry> = {}): WindowGeometry => ({
+ width: 900, height: 700, insets: { top: 0, left: 0, right: 60, bottom: 20 },
+ regularWidth: true, regularHeight: true, barEdge: 'right', regions: [], reservedRegionsSupported: true, ...patch,
+});
+describe('adaptive window regions', () => {
+ it('reserves independent safe edges and room for both navigation and content', () => {
+ const p = sessionPaneLayout(window());
+ expect(p.persistent).toBe(true);
+ expect(p.detail.x).toBe(p.sidebarWidth);
+ expect(p.detail.x + p.detail.width).toBe(840);
+ });
+ it('collapses in either side of Split View, regardless of phone/tablet identity', () => {
+ for (const insets of [{ top: 0, left: 60, right: 0, bottom: 20 }, { top: 0, left: 0, right: 60, bottom: 20 }]) {
+ const p = sessionPaneLayout(window({ width: 430, insets }));
+ expect(p.persistent).toBe(false);
+ expect(p.detail.width).toBe(370);
+ }
+ });
+ it('aligns two panes to an off-centre fold instead of assuming equal halves', () => {
+ const p = sessionPaneLayout(window({ regions: [{ kind: 'division', x: 360, y: 0, width: 32, height: 700 }] }));
+ expect(p.persistent).toBe(true);
+ expect(p.sidebarWidth).toBe(360);
+ expect(p.detail.x).toBe(392);
+ expect(p.detail.width).toBe(448);
+ });
+ it('uses the lower region for controls and leaves the hinge untouchable', () => {
+ const g = window({ regions: [{ kind: 'division', x: 0, y: 300, width: 900, height: 30 }] });
+ expect(windowDivision(g)?.first.height).toBe(300);
+ expect(controlRegion(g)).toEqual({ x: 0, y: 330, width: 840, height: 350 });
+ expect(sessionPaneLayout(g).persistent).toBe(false);
+ });
+ it('moves a floating group away from an active camera without reserving the whole screen', () => {
+ const area = controlRegion(window({ regions: [{ kind: 'occlusion', x: 390, y: 0, width: 60, height: 40 }] }));
+ expect(area).toEqual({ x: 0, y: 40, width: 840, height: 640 });
+ });
+ it('ignores a fold outside this window and restores ordinary geometry when flat', () => {
+ const g = window({ regions: [{ kind: 'division', x: 950, y: 0, width: 20, height: 700 }] });
+ expect(windowDivision(g)).toBeNull();
+ expect(controlRegion(window())).toEqual({ x: 0, y: 0, width: 840, height: 680 });
+ });
+});
+
+
+describe('folded desktop keyboard geometry', () => {
+ const folded = window({ regions: [{ kind: 'division', x: 0, y: 300, width: 900, height: 30 }] });
+ it('keeps video above the hinge and controls below it', () => {
+ const layout = foldDesktopLayout(folded, 0, 240, false)!;
+ expect(layout.media).toEqual({ x: 0, y: 0, width: 840, height: 300 });
+ expect(layout.controls).toEqual({ x: 0, y: 330, width: 840, height: 350 });
+ });
+ it('keeps an input sheet in the upper region when the keyboard covers the lower half', () => {
+ expect(keyboardControlRegion(folded, 350)).toEqual({ x: 0, y: 0, width: 840, height: 300 });
+ });
+ it('moves custom keys above the fold when the system keyboard covers the lower region', () => {
+ const layout = foldDesktopLayout(folded, 350, 180, true)!;
+ expect(layout.controls).toEqual({ x: 0, y: 0, width: 840, height: 300 });
+ expect(layout.media.height).toBe(120);
+ });
+ it('keeps controls above a bottom camera occlusion', () => {
+ const layout = foldDesktopLayout(window({ regions: [
+ ...folded.regions, { kind: 'occlusion', x: 0, y: 600, width: 900, height: 100 },
+ ] }), 0, 240, false)!;
+ expect(layout.controls.y + layout.controls.height).toBe(600);
+ });
+ it('returns to ordinary layout after unfolding without a synthetic half-screen split', () => {
+ expect(foldDesktopLayout(window(), 0, 240, false)).toBeNull();
+ });
+});
diff --git a/apps/mobile/src/auth/LoginCaptchaWebView.tsx b/apps/mobile/src/auth/LoginCaptchaWebView.tsx
index e9ff027c92..6a1b56eab6 100644
--- a/apps/mobile/src/auth/LoginCaptchaWebView.tsx
+++ b/apps/mobile/src/auth/LoginCaptchaWebView.tsx
@@ -9,6 +9,7 @@ import {
} from '@/auth/loginCaptchaUrl';
import { loginText } from '@/auth/loginMessages';
import { Text } from '@/components/AppText';
+import { hasNativeLoginButtons, LoginNativeButton } from '@/components/LoginNativeButton';
import { useTheme } from '@/theme';
import { fontWeight, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
@@ -119,6 +120,10 @@ export function LoginCaptchaWebView({
<Text style={{ color: login.loginError, fontSize: typeScale.footnote, textAlign: 'center' }}>
{loginText('captchaFailed')}
</Text>
+ {hasNativeLoginButtons ? <LoginNativeButton
+ label={loginText('captchaRetry')} onPress={retry} variant="text"
+ height={44} fontSize={typeScale.footnote} style={{ marginTop: spacing.md }}
+ testID="login.captcha.retry" /> : (
<Pressable
accessibilityRole="button"
onPress={retry}
@@ -135,6 +140,7 @@ export function LoginCaptchaWebView({
{loginText('captchaRetry')}
</Text>
</Pressable>
+ )}
</View>
) : (
<View style={{ alignSelf: 'stretch', height: 220, marginTop: 8 }}>
@@ -180,7 +186,11 @@ export function LoginCaptchaWebView({
) : null}
</View>
)}
- <Pressable
+ {hasNativeLoginButtons ? <LoginNativeButton
+ label={loginText('captchaCancel')} onPress={() => onResult(null)} variant="text"
+ height={44} fontSize={typeScale.footnote} style={{ marginTop: spacing.sm }}
+ testID="login.captcha.cancel" /> : (
+ <Pressable
accessibilityRole="button"
onPress={() => onResult(null)}
style={{
@@ -196,6 +206,7 @@ export function LoginCaptchaWebView({
{loginText('captchaCancel')}
</Text>
</Pressable>
+ )}
</View>
</View>
);
diff --git a/apps/mobile/src/auth/__tests__/loginCaptcha.test.ts b/apps/mobile/src/auth/__tests__/loginCaptcha.test.ts
index 67caee9261..9687d228f3 100644
--- a/apps/mobile/src/auth/__tests__/loginCaptcha.test.ts
+++ b/apps/mobile/src/auth/__tests__/loginCaptcha.test.ts
@@ -247,7 +247,11 @@ describe('AuthContext captcha 闸接线(静态源码断言)', () => {
it('captcha 重试与取消动作都提供至少 44×44 的触控目标', () => {
for (const testId of ['login.captcha.retry', 'login.captcha.cancel']) {
const marker = `testID="${testId}"`;
- const markerIndex = captchaWebViewSource.indexOf(marker);
+ const nativeMarkerIndex = captchaWebViewSource.indexOf(marker);
+ const nativeStart = captchaWebViewSource.lastIndexOf('<LoginNativeButton', nativeMarkerIndex);
+ expect(nativeStart).toBeGreaterThan(-1);
+ expect(captchaWebViewSource.slice(nativeStart, nativeMarkerIndex)).toContain('height={44}');
+ const markerIndex = captchaWebViewSource.lastIndexOf(marker);
const actionStart = captchaWebViewSource.lastIndexOf('<Pressable', markerIndex);
const actionSource = captchaWebViewSource.slice(actionStart, markerIndex);
expect(markerIndex).toBeGreaterThan(-1);
diff --git a/apps/mobile/src/auth/__tests__/loginGroupPlacement.test.ts b/apps/mobile/src/auth/__tests__/loginGroupPlacement.test.ts
new file mode 100644
index 0000000000..973db96455
--- /dev/null
+++ b/apps/mobile/src/auth/__tests__/loginGroupPlacement.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+import type { WindowGeometry } from '../../platform/windowGeometry';
+import { resolveLoginGroupPlacement, resolveLoginWindowSurface } from '../loginGroupPlacement';
+import { resolveLoginSurface } from '../loginSkinLayout';
+
+const closed: WindowGeometry = {
+ width: 466, height: 678, insets: { top: 0, right: 0, bottom: 20, left: 0 },
+ regularWidth: false, regularHeight: true, barEdge: 'none', reservedRegionsSupported: true,
+ regions: [{ kind: 'occlusion', x: 382, y: 0, width: 84, height: 170 }],
+};
+const place = (g: WindowGeometry, keyboard = 0) =>
+ resolveLoginGroupPlacement(g, resolveLoginSurface(g.width, g.height), 622, keyboard);
+
+describe('login group placement', () => {
+ it.each(['left', 'right'] as const)('fits the outer landscape form with the %s safe edge', (edge) => {
+ const g = { ...closed, width: 678, height: 466, regions: [],
+ insets: { top: 0, bottom: 34, left: 0, right: 0, [edge]: 84 } };
+ const stage = resolveLoginWindowSurface(g);
+ const frame = resolveLoginGroupPlacement(g, stage, 622, 0);
+ expect(stage.mode).toBe('compact-wide');
+ expect(frame.scale * 80).toBeGreaterThanOrEqual(44);
+ expect(frame.x).toBeGreaterThan(stage.offsetX + (stage.cindy.x + stage.cindy.w) * stage.scale);
+ expect(frame.x + frame.width).toBeLessThanOrEqual(g.width - g.insets.right);
+ expect(frame.height).toBeCloseTo(622 * frame.scale);
+ expect(frame.y + frame.height).toBeLessThanOrEqual(g.height - g.insets.bottom);
+ const keyboard = resolveLoginGroupPlacement(g, stage, 622, 230);
+ expect(keyboard.scale).toBe(frame.scale);
+ expect(keyboard.y + keyboard.height).toBeLessThanOrEqual(236);
+ expect(keyboard.height).toBeLessThan(622 * keyboard.scale);
+ });
+ it.each(['left', 'right'] as const)('aligns brand and form beside the %s system bar', (barEdge) => {
+ const g = { ...closed, barEdge, insets: { ...closed.insets, [barEdge]: 84 } };
+ const stage = resolveLoginWindowSurface(g);
+ const content = g;
+ const frame = resolveLoginGroupPlacement(content, stage, 622, 0);
+ const centre = content.insets.left + (g.width - content.insets.left - content.insets.right) / 2;
+ expect(frame.x + frame.width / 2).toBeCloseTo(centre);
+ expect(stage.offsetX + 375 * stage.scale).toBeCloseTo(centre);
+ expect(stage.viewportWidth).toBe(g.width);
+ });
+ it('keeps the closed outer-screen form centred below the camera', () => {
+ const frame = place(closed);
+ expect(frame.x + frame.width / 2).toBeCloseTo(closed.width / 2);
+ expect(frame.y).toBeGreaterThanOrEqual(170);
+ expect(frame).toEqual(place({ ...closed, regions: [] }));
+ });
+ it('still avoids a camera that actually overlaps the form', () => {
+ const frame = place({ ...closed, regions: [{ ...closed.regions[0]!, height: 400 }] });
+ expect(frame.x + frame.width).toBeLessThanOrEqual(382);
+ });
+ it('respects asymmetric safe edges without a camera', () => {
+ const frame = place({ ...closed, insets: { top: 40, right: 60, bottom: 20, left: 0 }, regions: [] });
+ expect(frame.x + frame.width).toBeLessThanOrEqual(406);
+ expect(frame.y).toBeGreaterThanOrEqual(40);
+ expect(frame.y + frame.height).toBeLessThanOrEqual(658);
+ });
+ it('keeps the form below a fold, then above it when the keyboard covers the lower pane', () => {
+ const folded = { ...closed, width: 900, height: 700,
+ regions: [{ kind: 'division' as const, x: 0, y: 300, width: 900, height: 30 }] };
+ expect(place(folded).y).toBeGreaterThanOrEqual(330);
+ const raised = place(folded, 350);
+ expect(raised.y + raised.height).toBeLessThanOrEqual(300);
+ });
+});
diff --git a/apps/mobile/src/auth/__tests__/loginSkinLayout.test.ts b/apps/mobile/src/auth/__tests__/loginSkinLayout.test.ts
index 08587f1b26..6a9bd5b6c0 100644
--- a/apps/mobile/src/auth/__tests__/loginSkinLayout.test.ts
+++ b/apps/mobile/src/auth/__tests__/loginSkinLayout.test.ts
@@ -40,6 +40,19 @@ function expectBox(actual: LoginStageBox, expected: LoginStageBox) {
}
describe("loginSkin 750 stage 布局引擎", () => {
+ it('keeps the full login flow inside medium landscape windows', () => {
+ for (const [width, height] of [[800, 600], [900, 680], [760, 480]]) {
+ const surface = resolveLoginSurface(width!, height!);
+ expect(surface.mode).toBe('compact-wide');
+ const left = surface.offsetX + surface.loginX * surface.scale;
+ const top = surface.offsetY + surface.loginY * surface.scale;
+ const scale = surface.scale * surface.loginGroupScale;
+ expect(left).toBeGreaterThanOrEqual(width! / 2);
+ expect(left + 680 * scale).toBeLessThanOrEqual(width!);
+ expect(top).toBeGreaterThanOrEqual(100);
+ expect(top + 622 * scale).toBeLessThanOrEqual(height!);
+ }
+ });
it("scale 与 designHeight clamp:vw/750 缩放,dh clamp [600,1800]", () => {
const layout = resolveLoginStage(390, 844);
expect(layout.scale).toBeCloseTo(390 / 750, 10);
@@ -285,6 +298,12 @@ describe("loginSkin §3.6 平板/横竖屏 surface 构图(PR4b Step 5b.3;adaptat
])("%i×%i 启动立绘按实际视口居中,字标与加载圈不越出屏幕", (width, height) => {
const surface = resolveLoginSurface(width, height);
const { scale, splashOffset, cindy, word, spinner } = surface;
+ if (surface.mode === 'compact-wide') {
+ expect(surface.offsetY + cindy.y * scale).toBeGreaterThanOrEqual(0);
+ expect(surface.offsetY + (cindy.y + cindy.h) * scale).toBeLessThanOrEqual(height);
+ expect(surface.offsetY + (spinner.y + spinner.size) * scale).toBeLessThanOrEqual(height);
+ return;
+ }
expect(surface.mode).toBe("phone");
const heroTop = (cindy.y + splashOffset) * scale;
const heroBottom = heroTop + cindy.h * scale;
@@ -324,16 +343,16 @@ describe("loginSkin §3.6 平板/横竖屏 surface 构图(PR4b Step 5b.3;adaptat
// 手机竖屏 → phone
expect(resolveLoginSurfaceMode(393, 852)).toBe("phone");
// 手机横屏(landscape 但 w<1000)→ phone 回退(§3.6 条4:不满足横屏断点落竖排)
- expect(resolveLoginSurfaceMode(852, 393)).toBe("phone");
+ expect(resolveLoginSurfaceMode(852, 393)).toBe("compact-wide");
// landscape 满足宽但不满足高(600<690)→ phone 回退
- expect(resolveLoginSurfaceMode(1100, 600)).toBe("phone");
+ expect(resolveLoginSurfaceMode(1100, 600)).toBe("compact-wide");
// portrait 窄窗(Split View 320pt)→ phone
expect(resolveLoginSurfaceMode(320, 768)).toBe("phone");
// 断点边界含等号:恰好 1000×690 → pad-landscape;700×1000 → pad-portrait
expect(resolveLoginSurfaceMode(1000, 690)).toBe("pad-landscape");
expect(resolveLoginSurfaceMode(700, 1000)).toBe("pad-portrait");
// 边界外一点:999×690 landscape → phone;699×1000 portrait → phone
- expect(resolveLoginSurfaceMode(999, 690)).toBe("phone");
+ expect(resolveLoginSurfaceMode(999, 690)).toBe("compact-wide");
expect(resolveLoginSurfaceMode(699, 1000)).toBe("phone");
});
@@ -423,9 +442,9 @@ describe("loginSkin §3.6 平板/横竖屏 surface 构图(PR4b Step 5b.3;adaptat
expect(s.scale).toBeCloseTo(393 / 750, 10); // resolveLoginStage 750 stage scale
// 手机横屏(landscape w<1000)→ phone 回退,非 pad-landscape
const horiz = resolveLoginSurface(852, 393);
- expect(horiz.mode).toBe("phone");
- expect(horiz.loginGroupScale).toBe(1);
- expect(horiz.phone).toBeDefined();
+ expect(horiz.mode).toBe("compact-wide");
+ expect(horiz.scale * horiz.loginGroupScale * LOGIN_CONTROL.height).toBeGreaterThanOrEqual(44);
+ expect(horiz.phone).toBeNull();
});
});
diff --git a/apps/mobile/src/auth/loginGroupPlacement.ts b/apps/mobile/src/auth/loginGroupPlacement.ts
new file mode 100644
index 0000000000..8dabce83d8
--- /dev/null
+++ b/apps/mobile/src/auth/loginGroupPlacement.ts
@@ -0,0 +1,43 @@
+import { keyboardControlRegion, type LayoutRect, type WindowGeometry } from '../platform/windowGeometry';
+import { LOGIN_GROUP, resolveLoginSurface, type LoginSurfaceLayout } from './loginSkinLayout';
+
+/** The brand and form share the usable column beside a vertical system bar. */
+export function resolveLoginWindowSurface(window: WindowGeometry): LoginSurfaceLayout {
+ if (window.width > window.height && (window.width < 760 || window.height < 480)) {
+ const stage = resolveLoginSurface(Math.max(1, window.width - window.insets.left - window.insets.right),
+ Math.max(1, window.height - window.insets.top - window.insets.bottom));
+ return { ...stage, viewportWidth: window.width, viewportHeight: window.height,
+ offsetX: stage.offsetX + window.insets.left, offsetY: stage.offsetY + window.insets.top };
+ }
+ if (window.barEdge === 'none') return resolveLoginSurface(window.width, window.height);
+ const width = Math.max(1, window.width - window.insets.left - window.insets.right);
+ const stage = resolveLoginSurface(width, window.height);
+ return { ...stage, viewportWidth: window.width, offsetX: stage.offsetX + window.insets.left };
+}
+
+/** Reserve camera space only when the visible form actually occupies it. */
+export function resolveLoginGroupPlacement(
+ window: WindowGeometry,
+ stage: LoginSurfaceLayout,
+ flowHeight: number,
+ keyboardBottom: number,
+): LayoutRect & { scale: number } {
+ const fit = (region: LayoutRect) => {
+ const scale = Math.min(stage.scale * stage.loginGroupScale, region.width / LOGIN_GROUP.width);
+ const width = LOGIN_GROUP.width * scale;
+ const height = Math.min(flowHeight * scale, region.height);
+ return {
+ x: Math.max(region.x, Math.min(stage.offsetX + stage.loginX * stage.scale, region.x + region.width - width)),
+ y: Math.max(region.y, Math.min(stage.offsetY + stage.loginY * stage.scale, region.y + region.height - height)),
+ width, height, scale,
+ };
+ };
+ const preferred = fit(keyboardControlRegion({ ...window,
+ regions: window.regions.filter(r => r.kind === 'division'),
+ }, keyboardBottom));
+ const overlapsCamera = window.regions.some(r => r.kind === 'occlusion'
+ && r.width > 0 && r.height > 0
+ && r.x < preferred.x + preferred.width && r.x + r.width > preferred.x
+ && r.y < preferred.y + preferred.height && r.y + r.height > preferred.y);
+ return overlapsCamera ? fit(keyboardControlRegion(window, keyboardBottom)) : preferred;
+}
diff --git a/apps/mobile/src/auth/loginHandoff.ts b/apps/mobile/src/auth/loginHandoff.ts
index 71c2d67370..6fd670feb8 100644
--- a/apps/mobile/src/auth/loginHandoff.ts
+++ b/apps/mobile/src/auth/loginHandoff.ts
@@ -138,7 +138,7 @@ export const LOGIN_HANDOFF_EASING = {
/** 立绘/字标位移时长:iPad 横屏(358:833 定稿)无位移段 → 0;其余 650ms。 */
export function loginHandoffMoveMs(mode: LoginSurfaceMode): number {
- return mode === 'pad-landscape' ? 0 : LOGIN_HANDOFF_TIMING.brandMoveMs;
+ return (mode === 'pad-landscape' || mode === 'compact-wide') ? 0 : LOGIN_HANDOFF_TIMING.brandMoveMs;
}
/** 面板入场起步时刻(相对 handoff-start;demo 300 + moveMs)。 */
diff --git a/apps/mobile/src/auth/loginSkinLayout.ts b/apps/mobile/src/auth/loginSkinLayout.ts
index 162eb20be6..e4665cb61e 100644
--- a/apps/mobile/src/auth/loginSkinLayout.ts
+++ b/apps/mobile/src/auth/loginSkinLayout.ts
@@ -190,7 +190,7 @@ export function resolveLoginStage(
demo resolveMobileStage()/ipadPortrait()/ipadLandscape() 仲裁,纯函数零 RN) ── */
/** 登录 surface 构图模式(§3.6 条4 断点三分支)。 */
-export type LoginSurfaceMode = 'phone' | 'pad-portrait' | 'pad-landscape';
+export type LoginSurfaceMode = 'phone' | 'pad-portrait' | 'pad-landscape' | 'compact-wide';
/** 横屏左右构图断点(§3.6 条4:landscape ∧ w≥1000pt ∧ h≥690pt;dp/pt 归一)。 */
export const PAD_LANDSCAPE_MIN_WIDTH = 1000;
@@ -216,6 +216,7 @@ export function resolveLoginSurfaceMode(
) {
return 'pad-landscape';
}
+ if (landscape && viewportWidth >= 560) return 'compact-wide';
if (!landscape && viewportWidth >= PAD_PORTRAIT_MIN_WIDTH) return 'pad-portrait';
return 'phone';
}
@@ -360,6 +361,40 @@ export function resolveLoginSurface(
if (mode === 'pad-landscape') {
return padSurface(mode, LOGIN_PAD_LANDSCAPE_STAGE, viewportWidth, viewportHeight);
}
+ if (mode === 'compact-wide') {
+ if (viewportWidth < 760 || viewportHeight < 480) {
+ // Short landscape keeps readable controls; overflow belongs to the form's scroll view.
+ const groupScale = Math.min(0.58, (viewportWidth - 192) / 680);
+ const groupWidth = 680 * groupScale;
+ const brandWidth = Math.min(200, viewportWidth - groupWidth - 48);
+ const heroHeight = brandWidth * 579 / 481.430176;
+ const brandTop = Math.max(16, (viewportHeight - heroHeight - 76) / 2);
+ return {
+ ...padSurface('pad-landscape', LOGIN_PAD_LANDSCAPE_STAGE, viewportWidth, viewportHeight),
+ mode, scale: 1, offsetX: 0, offsetY: 0,
+ stageWidth: viewportWidth, stageHeight: viewportHeight,
+ cindy: { x: 16, y: brandTop, w: brandWidth, h: heroHeight },
+ word: { x: 16, y: brandTop + heroHeight - 8, w: brandWidth, h: brandWidth / 2.93 },
+ slogan: { x: 16, y: brandTop + heroHeight + brandWidth / 2.93, w: brandWidth, h: brandWidth * 97.2 / 339.16 },
+ loginX: viewportWidth - groupWidth - 16,
+ loginY: Math.max(16, (viewportHeight - 622 * groupScale) / 2),
+ loginGroupScale: groupScale,
+ spinner: { x: 16 + brandWidth / 2 - 12, y: Math.min(viewportHeight - 32, brandTop + heroHeight + 60), size: 24 },
+ };
+ }
+ // Preserve control sizes on medium, short windows instead of magnifying the phone artwork.
+ const base = padSurface('pad-landscape', LOGIN_PAD_LANDSCAPE_STAGE, viewportWidth, viewportHeight);
+ const scale = Math.min(viewportWidth / 1180, viewportHeight / 820);
+ const groupScale = Math.min(0.58, (viewportWidth / 2 - 24) / 680, (viewportHeight - 120) / 622);
+ const offsetX = (viewportWidth - 1180 * scale) / 2;
+ const offsetY = (viewportHeight - 820 * scale) / 2;
+ return { ...base, mode, scale, offsetX, offsetY,
+ loginGroupScale: groupScale / scale,
+ loginX: (viewportWidth * 0.75 - 340 * groupScale - offsetX) / scale,
+ loginY: (Math.max(108, (viewportHeight - 622 * groupScale) / 2) - offsetY) / scale,
+ word: { ...base.word, y: (32 - offsetY) / scale },
+ };
+ }
const stage = resolveLoginStage(viewportWidth, viewportHeight);
// designHeight 的上下限只约束登录构图。横屏时它可能高于可见视口,
// 用它居中会把启动立绘、字标和 spinner 一起推到屏幕下方。
@@ -602,12 +637,18 @@ export function resolveDeletionBubbleFrame(
if (surface.mode === 'phone') {
const width = phone.width * scale;
return {
- left: clampLeft((surface.viewportWidth - width) / 2, width),
+ left: clampLeft(surface.offsetX + phone.x * scale, width),
top: safeTop,
width,
scale,
};
}
+ if (surface.mode === 'compact-wide') {
+ const groupScale = surface.scale * surface.loginGroupScale;
+ const width = 680 * groupScale;
+ return { left: clampLeft(surface.offsetX + surface.loginX * scale, width),
+ top: Math.max(safeTop, 8), width, scale: width / padLandscape.width };
+ }
if (surface.mode === 'pad-landscape') {
const width = padLandscape.width * scale;
const left = surface.offsetX + padLandscape.x * scale;
diff --git a/apps/mobile/src/components/ConnectionNoticeOverlay.tsx b/apps/mobile/src/components/ConnectionNoticeOverlay.tsx
index b2882074d8..472e9b945d 100644
--- a/apps/mobile/src/components/ConnectionNoticeOverlay.tsx
+++ b/apps/mobile/src/components/ConnectionNoticeOverlay.tsx
@@ -13,7 +13,8 @@ export function useDelayedConnectionNotice(active: boolean, immediate = false):
return active && (immediate || ready);
}
-type Notice = { top: number; children: ReactNode };
+type NoticeFrame = { top: number; left: number; width: number };
+type Notice = NoticeFrame & { children: ReactNode };
const NoticeContext = createContext<{ publish: (id: string, notice: Notice | null) => void; host: RefObject<View | null> } | null>(null);
/** Render outside clipped headers, with real touch bounds and no modal input capture. */
@@ -33,7 +34,7 @@ export function ConnectionNoticeProvider({ children }: { children: ReactNode })
<View ref={host} collapsable={false} style={styles.host}>
{children}
<View pointerEvents="box-none" style={styles.layer}>
- {[...notices].map(([id, notice]) => <View key={id} style={[styles.overlay, { top: notice.top }]}>{notice.children}</View>)}
+ {[...notices].map(([id, notice]) => <View key={id} pointerEvents="box-none" style={[styles.overlay, { top: notice.top, left: notice.left, width: notice.width }]}>{notice.children}</View>)}
</View>
</View>
</NoticeContext.Provider>;
@@ -44,7 +45,7 @@ export function ConnectionNoticeOverlay({ children }: { children: ReactNode }) {
const context = useContext(NoticeContext);
const id = useId();
const anchor = useRef<View>(null);
- const [top, setTop] = useState<number | null>(null);
+ const [frame, setFrame] = useState<NoticeFrame | null>(null);
const [focused, setFocused] = useState(false);
useFocusEffect(useCallback(() => {
setFocused(true);
@@ -52,14 +53,17 @@ export function ConnectionNoticeOverlay({ children }: { children: ReactNode }) {
}, []));
const { width, height } = useWindowDimensions();
const measure = useCallback(() => {
- if (context?.host.current) anchor.current?.measureLayout(context.host.current, (_x, y) => setTop(y + spacing.sm));
+ if (context?.host.current) anchor.current?.measureLayout(context.host.current, (x, y, width) => {
+ const next = { top: y + spacing.sm, left: x + spacing.md, width: Math.max(0, width - spacing.md * 2) };
+ setFrame(previous => previous?.top === next.top && previous.left === next.left && previous.width === next.width ? previous : next);
+ });
}, [context]);
useEffect(() => { measure(); }, [measure, width, height, focused]);
useEffect(() => {
- if (focused && top !== null) context?.publish(id, { top, children });
+ if (focused && frame !== null) context?.publish(id, { ...frame, children });
else context?.publish(id, null);
return () => context?.publish(id, null);
- }, [children, focused, id, context, top]);
+ }, [children, focused, id, context, frame]);
return <View ref={anchor} collapsable={false} pointerEvents="none" onLayout={measure} style={styles.anchor} />;
}
@@ -67,5 +71,5 @@ const styles = StyleSheet.create({
host: { flex: 1 },
layer: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, zIndex: 20 },
anchor: { height: 0 },
- overlay: { position: 'absolute', left: spacing.md, right: spacing.md },
+ overlay: { position: 'absolute' },
});
diff --git a/apps/mobile/src/components/LoginNativeButton.ios.tsx b/apps/mobile/src/components/LoginNativeButton.ios.tsx
new file mode 100644
index 0000000000..d15c332dff
--- /dev/null
+++ b/apps/mobile/src/components/LoginNativeButton.ios.tsx
@@ -0,0 +1,54 @@
+import { Host } from '@expo/ui';
+import { Button, HStack, Image, ProgressView, RNHostView, Text, VStack } from '@expo/ui/swift-ui';
+import {
+ accessibilityLabel, accessibilityAddTraits, buttonStyle, contentShape, disabled as disabledModifier,
+ font, foregroundStyle, frame, lineLimit, shapes,
+} from '@expo/ui/swift-ui/modifiers';
+import { View } from 'react-native';
+import { useTheme } from '@/theme';
+import { useNativeGlassButtonStyle } from '@/platform/chrome/nativeGlassButtonStyle.ios';
+import type { LoginNativeButtonProps } from './LoginNativeButton';
+
+export const hasNativeLoginButtons = true;
+
+/** Login's scaled layout owns the frame; SwiftUI owns activation and feedback.
+ * RNHostView is reserved for existing brand artwork, never an inner Pressable. */
+export function LoginNativeButton({ label, onPress, disabled, busy, testID,
+ width, height, fontSize, style, variant = 'secondary', subtitle, children, trailingArtwork,
+ artworkSize = fontSize, showLabel = !children, accessibilityLabel: spokenLabel, selected,
+}: LoginNativeButtonProps) {
+ const { colors, mode } = useTheme();
+ const prominent = variant === 'primary' || variant === 'circle';
+ const inert = !!(disabled || busy);
+ const foreground = inert ? colors.textSecondary : prominent ? colors.ctaText : colors.textPrimary;
+ const glassStyle = useNativeGlassButtonStyle({
+ shape: variant === 'circle' ? 'circle' : 'capsule', prominent: prominent && (!inert || variant === 'circle'),
+ dimensions: { width, height },
+ });
+ return <Host colorScheme={mode} seedColor={colors.cta} ignoreSafeArea="all"
+ style={[{ width: width ?? '100%', height }, style]}>
+ <Button testID={testID} onPress={() => { if (!inert) onPress?.(); }} modifiers={[
+ ...(variant === 'text'
+ ? [buttonStyle('borderless'), frame({ width, height, ...(width == null ? { maxWidth: Infinity } : {}) }), contentShape(shapes.capsule())]
+ : glassStyle),
+ font({ size: fontSize, weight: prominent ? 'bold' : 'regular' }),
+ foregroundStyle(foreground), accessibilityLabel(spokenLabel ?? label), disabledModifier(inert),
+ ...(selected ? [accessibilityAddTraits(['isSelected'])] : []),
+ ]}>
+ <HStack spacing={fontSize / 2}>
+ {children ? <VStack modifiers={[frame({ width: artworkSize, height: artworkSize })]}>
+ <RNHostView><View pointerEvents="none" style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>{children}</View></RNHostView>
+ </VStack> : null}
+ {showLabel ? <VStack modifiers={width ? [frame({ maxWidth: width - artworkSize * 3 })] : []}>
+ <Text modifiers={[lineLimit(1)]}>{label}</Text>
+ {subtitle ? <Text modifiers={[font({ size: fontSize * 5 / 6 }), foregroundStyle(colors.textSecondary), lineLimit(1)]}>{subtitle}</Text> : null}
+ </VStack> : null}
+ {busy ? <ProgressView /> : null}
+ {trailingArtwork ? <VStack modifiers={[frame({ width: artworkSize, height: artworkSize })]}>
+ <RNHostView><View pointerEvents="none" style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>{trailingArtwork}</View></RNHostView>
+ </VStack> : null}
+ {selected ? <Image systemName="checkmark" size={fontSize} /> : null}
+ </HStack>
+ </Button>
+ </Host>;
+}
diff --git a/apps/mobile/src/components/LoginNativeButton.tsx b/apps/mobile/src/components/LoginNativeButton.tsx
new file mode 100644
index 0000000000..9526abf0de
--- /dev/null
+++ b/apps/mobile/src/components/LoginNativeButton.tsx
@@ -0,0 +1,26 @@
+import type { ReactNode } from 'react';
+import type { StyleProp, ViewStyle } from 'react-native';
+
+export interface LoginNativeButtonProps {
+ label: string;
+ accessibilityLabel?: string;
+ onPress?: () => void;
+ disabled?: boolean;
+ busy?: boolean;
+ testID?: string;
+ width?: number;
+ height: number;
+ fontSize: number;
+ style?: StyleProp<ViewStyle>;
+ variant?: 'primary' | 'secondary' | 'text' | 'circle';
+ subtitle?: string;
+ children?: ReactNode;
+ trailingArtwork?: ReactNode;
+ showLabel?: boolean;
+ selected?: boolean;
+ artworkSize?: number;
+}
+
+// Other platforms keep LoginSkinControls' existing React Native controls.
+export const hasNativeLoginButtons = false;
+export function LoginNativeButton(_props: LoginNativeButtonProps) { return null; }
diff --git a/apps/mobile/src/components/LoginSkinControls.tsx b/apps/mobile/src/components/LoginSkinControls.tsx
index e7690e9f19..7f579bd4f9 100644
--- a/apps/mobile/src/components/LoginSkinControls.tsx
+++ b/apps/mobile/src/components/LoginSkinControls.tsx
@@ -33,12 +33,14 @@ import {
} from '@/auth/loginSkinLayout';
import { parseLegalSegments } from '@/auth/legalText';
import { Text, TextInput } from '@/components/AppText';
+import { hasNativeLoginButtons, LoginNativeButton } from './LoginNativeButton';
import { useTheme, useThemedStyles } from '@/theme';
import { fontWeight, loginSizes, radius, type ThemeColors } from '@/theme/tokens';
/**
- * LoginSkinControls —— 移动端登录皮肤组件库(figma-component-spec §4 RN 重建,
- * PR4a Step 5 WHAT2;与桌面 LoginControls.tsx 同参数源对齐)。
+ * LoginSkinControls —— 登录布局与跨平台入口。iOS 按钮交给 LoginNativeButton,
+ * 共用应用的原生玻璃样式、SwiftUI 点击反馈与 ProgressView;以下手绘态系仅为
+ * 非 iOS 回退。输入框、协议勾选与内联法律链接仍沿用 RN 实现。
*
* 态系(design.md §2,移动无 hover):
* - pressed = 叠遮罩不改布局:主钮/圆钮亮色叠黑 50% / 暗色叠黑 10%(figma
@@ -271,6 +273,10 @@ function ConsentDialogButton({
const B = LOGIN_CONSENT_DIALOG.button;
const [pressed, setPressed] = useState(false);
const primary = kind === 'primary';
+ if (hasNativeLoginButtons) return <LoginNativeButton label={label} onPress={onPress}
+ testID={testID} variant={primary ? 'primary' : 'secondary'}
+ width={B.width} height={B.height} fontSize={B.font}
+ style={{ position: 'absolute', left: x, top: B.y }} />;
return (
<Pressable
accessibilityRole="button"
@@ -598,6 +604,10 @@ export function LoginSsoOrgHistoryList({
>
{entries.map((entry, index) => {
const selected = entry.toLowerCase() === selectedKey;
+ if (hasNativeLoginButtons) return <LoginNativeButton key={entry.toLowerCase()}
+ label={entry} onPress={() => onSelect(entry)} selected={selected} variant="text"
+ width={LOGIN_SSO_ORG_HISTORY.width} height={LOGIN_SSO_ORG_HISTORY.rowMinHeight}
+ fontSize={LOGIN_SSO_ORG_HISTORY.font} testID={`login.ssoOrgHistoryOption.${index}`} />;
return (
<Pressable
accessibilityRole="menuitem"
@@ -781,6 +791,10 @@ export function LoginPrimaryButton({
const inert = disabled || busy;
const { colors } = useTheme();
const styles = useThemedStyles(makeStyles);
+ if (hasNativeLoginButtons) return <LoginNativeButton label={label} onPress={onPress}
+ disabled={disabled} busy={busy} testID={testID} variant="primary"
+ width={LOGIN_CONTROL.width} height={LOGIN_CONTROL.height} fontSize={LOGIN_CONTROL.font}
+ style={{ position: 'absolute', left: LOGIN_CONTROL.x, top }} />;
return (
<Pressable
accessibilityRole="button"
@@ -885,6 +899,7 @@ export function LoginSocialButton({
* 圆钮无 disabled 视觉态(§10 拍板 2026-07-21 移除 loading/disabled 态),视觉/交互态不变;
* 交互 guard 由调用方 onPress 闭包兜(login.tsx SC-SOC-7:`if (disabled) return`),
* 与本组件对称的桌面 LoginSocialButton `aria-disabled` 语义一致。
+ * iOS 原生路径同时禁用 Button,阻止飞行中的重复激活,保留品牌图标。
*/
busy?: boolean;
/** 'apple' = ADR 官方配色圆钮(纯黑/白底 appleCircleBg、无描边 borderWidth 0);
@@ -895,6 +910,10 @@ export function LoginSocialButton({
const { colors } = useTheme();
const styles = useThemedStyles(makeStyles);
const isApple = variant === 'apple';
+ if (hasNativeLoginButtons) return <LoginNativeButton label={label} onPress={onPress}
+ disabled={busy} testID={testID} variant="circle"
+ width={LOGIN_SOCIAL.size} height={LOGIN_SOCIAL.size} fontSize={LOGIN_CONTROL.font}
+ artworkSize={LOGIN_SOCIAL.icon}>{children}</LoginNativeButton>;
return (
<Pressable
accessibilityLabel={label}
@@ -942,6 +961,14 @@ export function LoginBackButton({
}) {
const { colors } = useTheme();
const styles = useThemedStyles(makeStyles);
+ if (hasNativeLoginButtons) return <LoginNativeButton label={label} onPress={onPress}
+ disabled={disabled} testID={testID} width={LOGIN_BACK.size} height={LOGIN_BACK.size}
+ fontSize={LOGIN_BACK.icon} artworkSize={LOGIN_BACK.icon}
+ style={{ position: 'absolute', left: LOGIN_BACK.x, top: LOGIN_BACK.y, zIndex: 2 }}>
+ <Svg width={LOGIN_BACK.icon} height={LOGIN_BACK.icon} viewBox="0 0 24 24" fill="none" aria-hidden>
+ <Path d="M14.5 5.5 8 12l6.5 6.5" stroke={colors.textPrimary} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
+ </Svg>
+ </LoginNativeButton>;
return (
<Pressable
accessibilityLabel={label}
@@ -1030,6 +1057,14 @@ export function LoginMethodRow({
accessibilityLabel?: string;
}) {
const styles = useThemedStyles(makeStyles);
+ if (hasNativeLoginButtons) return <LoginNativeButton label={title} subtitle={subtitle}
+ accessibilityLabel={accessibilityLabel} showLabel artworkSize={LOGIN_METHOD_ROW.leftIcon.size}
+ trailingArtwork={<ShareIcon />}
+ onPress={onPress} disabled={disabled} testID={testID}
+ width={LOGIN_METHOD_ROW.width} height={LOGIN_METHOD_ROW.height} fontSize={LOGIN_METHOD_ROW.titleFont}
+ style={{ position: 'absolute', left: LOGIN_METHOD_ROW.x, top }}>
+ {icon === 'person' ? <PersonIcon /> : <EnterpriseIcon />}
+ </LoginNativeButton>;
return (
<Pressable
accessibilityLabel={accessibilityLabel ?? title}
@@ -1195,6 +1230,10 @@ export function LoginTextAction({
top?: number;
}) {
const styles = useThemedStyles(makeStyles);
+ if (hasNativeLoginButtons) return <LoginNativeButton label={label} onPress={onPress}
+ disabled={disabled} testID={testID} variant="text"
+ width={LOGIN_TEXT_LINK.width} height={LOGIN_TEXT_LINK.height} fontSize={LOGIN_TEXT_LINK.font}
+ style={{ position: 'absolute', left: LOGIN_TEXT_LINK.x, top: top ?? LOGIN_TEXT_LINK.y }} />;
return (
<Pressable
accessibilityRole="button"
diff --git a/apps/mobile/src/components/MobileLoginHandoffStage.tsx b/apps/mobile/src/components/MobileLoginHandoffStage.tsx
index 66b656faa3..3b340f984e 100644
--- a/apps/mobile/src/components/MobileLoginHandoffStage.tsx
+++ b/apps/mobile/src/components/MobileLoginHandoffStage.tsx
@@ -13,7 +13,6 @@ import Svg, { Circle, Path } from 'react-native-svg';
import {
resolveLoginStage,
- resolveLoginSurface,
type LoginStageBox,
type LoginStageLayout,
type LoginSurfaceLayout,
@@ -28,6 +27,8 @@ import { useLoginHandoffOptional } from '@/auth/MobileLoginHandoffContext';
import { useLoginFirstLaunchLight } from '@/auth/loginFirstLaunchGate';
import { resolveStartupSplashHandoff } from '@/auth/startupSplashContinuity';
import { ThemeOverrideProvider, useTheme } from '@/theme';
+import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';
+import { resolveLoginWindowSurface } from '@/auth/loginGroupPlacement';
/**
* MobileLoginHandoffStage —— 白底体系登录/闸门**唯一 full-viewport 品牌宿主**
@@ -64,8 +65,8 @@ const heroPadLandscapeAsset = require('../../assets/login/login-hero-pad-landsca
/** hook:物理 viewport → §3.6 三构图 surface 布局(useWindowDimensions → resolveLoginSurface)。 */
export function useLoginSurface(): LoginSurfaceLayout {
- const { width, height } = useWindowDimensions();
- return useMemo(() => resolveLoginSurface(width, height), [width, height]);
+ const window = useAdaptiveWindow();
+ return useMemo(() => resolveLoginWindowSurface(window), [window]);
}
/** 兼容出口(PR4a 消费面):物理 viewport → 750 手机 stage 两档插值布局。 */
@@ -259,7 +260,7 @@ function MobileLoginHandoffStageInner({
const heroSource =
stage.mode === 'pad-portrait'
? heroPadPortraitAsset
- : stage.mode === 'pad-landscape'
+ : (stage.mode === 'pad-landscape' || stage.mode === 'compact-wide')
? heroPadLandscapeAsset
: heroAsset;
// 暗色画布用白字版字标/slogan;立绘两模式同资产(figma 532:585)
@@ -342,7 +343,7 @@ function MobileLoginHandoffStageInner({
) : null}
</View>
) : null}
- {children != null ? <View style={StyleSheet.absoluteFill}>{children}</View> : null}
+ {children != null ? <View collapsable={false} style={[StyleSheet.absoluteFill, { zIndex: 1 }]}>{children}</View> : null}
</View>
);
}
diff --git a/apps/mobile/src/components/screenEdgeInsets.ts b/apps/mobile/src/components/screenEdgeInsets.ts
index 4677de2d2e..623543944c 100644
--- a/apps/mobile/src/components/screenEdgeInsets.ts
+++ b/apps/mobile/src/components/screenEdgeInsets.ts
@@ -1,37 +1,34 @@
import { useEffect } from 'react';
+import { Dimensions, Platform } from 'react-native';
-/**
- * 页面级 safe-area padding 解析(top/left/right 三边;bottom 由各页按需自行兜底)。
- *
- * 为什么不用 react-native-safe-area-context 的原生 SafeAreaView:它的 Fabric 实现
- * 依赖「provider 通知 + didMoveToWindow」被动刷新,旋转若落在页面 detach / 视图回收
- * 的窗口期会漏更新,横屏 insets(top=0、左右 ~59pt)残留到竖屏,直到下一次无关的
- * React 提交才自愈(表现为首页竖屏后错位几秒)。这里改为消费 useSafeAreaInsets():
- * 数据源是根 provider 的布局事件,根 provider 永远挂在 window 上,旋转必触发。
- *
- * 另加一道确定性保险,但只精确狙击「横屏残留」形态,不误伤合法数据:
- * - insets 来自同一 provider 事件的原子快照,横屏残留必然是完整横屏形态——
- * top ≤ 0 且至少一侧 > 0(刘海机横屏 top 恒为 0、侧边为刘海/挖孔让位);
- * - 合法的竖屏侧边 inset(Android 瀑布屏 / 侧边挖孔 / 折叠屏等)必然伴随
- * 非零的状态栏 top,不会命中上述形态,原样透传(与原生 SafeAreaView 行为一致);
- * - 命中残留形态时侧边清零,top 用「最近一次稳定竖屏 top」兜底,避免尺寸先于
- * insets 更新的过渡帧里标题顶进状态栏。
- * 横屏值一律原样透传,不做假设。
- *
- * top 兜底记忆是模块级而非组件实例级:页面被路由 detach 后重挂时(典型路径
- * 「会话页横屏 → 返回首页 → 转竖屏」),实例级 ref 会归零导致首帧兜底失效;
- * 竖屏状态栏高度是设备级属性,进程内跨实例复用是安全的。冷启动首帧记忆为 0,
- * 但冷启动 insets 必然新鲜、不会命中残留形态,不受影响。
- */
+/** Four edges are independent on resizable displays. The old rotation workaround
+ * is opt-in for legacy phone layouts, never inferred from an inset's shape alone. */
export interface ScreenEdgeInsetsInput {
/** 残留形态下 top 的兜底值(最近一次稳定竖屏 top);不传则残留帧 top 为 0。 */
fallbackPortraitTop?: number;
+ legacyPhoneLayout?: boolean;
insets: { top: number; left: number; right: number };
windowHeight: number;
windowWidth: number;
}
+/** Only a compact, full-display Android window uses the legacy phone workaround.
+ * Split/freeform windows and tablet/foldable interiors retain independent edges. */
+export function isLegacyPhoneWindow(input: {
+ platform: string; iosPad: boolean; version: string | number;
+ windowWidth: number; windowHeight: number;
+ screenWidth: number; screenHeight: number;
+}): boolean {
+ if (input.platform === 'ios') return !input.iosPad && Number.parseInt(String(input.version), 10) < 27;
+ if (input.platform !== 'android') return false;
+ const { screenWidth, screenHeight, windowWidth, windowHeight } = input;
+ return Math.min(screenWidth, screenHeight) > 0 && Math.min(screenWidth, screenHeight) < 600
+ && Math.abs(windowWidth - screenWidth) < 1
+ // Android may exclude status/navigation bars from the application window.
+ && screenHeight >= windowHeight && screenHeight - windowHeight <= 96;
+}
+
export interface ScreenEdgePadding {
paddingLeft: number;
paddingRight: number;
@@ -46,7 +43,7 @@ export function resolveScreenEdgePadding(input: ScreenEdgeInsetsInput): ScreenEd
const left = sanitize(input.insets.left);
const right = sanitize(input.insets.right);
const portrait = input.windowHeight > input.windowWidth;
- const landscapeResidue = portrait && top <= 0 && (left > 0 || right > 0);
+ const landscapeResidue = input.legacyPhoneLayout === true && portrait && top <= 0 && (left > 0 || right > 0);
if (landscapeResidue) {
return {
paddingLeft: 0,
@@ -82,6 +79,7 @@ export function resetStablePortraitTopMemoryForTests(): void {
*/
export function useScreenEdgePadding(input: {
insets: { top: number; left: number; right: number };
+ legacyPhoneLayout?: boolean;
windowHeight: number;
windowWidth: number;
}): ScreenEdgePadding {
@@ -90,6 +88,11 @@ export function useScreenEdgePadding(input: {
recordStablePortraitTop({ top: insets.top, windowHeight, windowWidth });
}, [insets.top, windowHeight, windowWidth]);
return resolveScreenEdgePadding({
+ legacyPhoneLayout: input.legacyPhoneLayout ?? isLegacyPhoneWindow({
+ platform: Platform.OS, iosPad: Platform.OS === 'ios' && Platform.isPad,
+ version: Platform.Version, windowWidth, windowHeight,
+ screenWidth: Dimensions.get('screen').width, screenHeight: Dimensions.get('screen').height,
+ }),
fallbackPortraitTop: getStablePortraitTopMemory(),
insets,
windowHeight,
diff --git a/apps/mobile/src/platform/AdaptiveWindow.tsx b/apps/mobile/src/platform/AdaptiveWindow.tsx
new file mode 100644
index 0000000000..d0eb2034c8
--- /dev/null
+++ b/apps/mobile/src/platform/AdaptiveWindow.tsx
@@ -0,0 +1,34 @@
+import { useMemo, useState, type ReactNode } from 'react';
+import { Platform, StyleSheet, View, useWindowDimensions, type ViewProps } from 'react-native';
+import { requireNativeViewManager, requireOptionalNativeModule } from 'expo-modules-core';
+import { useSafeAreaInsets } from 'react-native-safe-area-context';
+import type { WindowGeometry } from './windowGeometry';
+
+import { GeometryContext } from './AdaptiveWindowContext';
+const native = Platform.OS === 'ios'
+ ? requireOptionalNativeModule<{ windowLayoutAvailable?: boolean }>('XdtIosActionSheet') : null;
+const Probe = native?.windowLayoutAvailable
+ ? requireNativeViewManager<ViewProps & { onGeometryChange(event: { nativeEvent: WindowGeometry }): void }>('XdtIosActionSheet') : null;
+
+/** One observation source per window; old packages and other platforms keep normal responsive layout. */
+export function AdaptiveWindowProvider({ children }: { children: ReactNode }) {
+ const window = useWindowDimensions();
+ const insets = useSafeAreaInsets();
+ const [geometry, setGeometry] = useState<WindowGeometry | null>(null);
+ const current = geometry && Math.abs(geometry.width - window.width) < 1 && Math.abs(geometry.height - window.height) < 1
+ ? geometry : null;
+ const value = useMemo<WindowGeometry>(() => current ?? ({
+ width: window.width, height: window.height, insets,
+ regularWidth: window.width >= 600, regularHeight: window.height >= 600,
+ barEdge: 'none', regions: [], reservedRegionsSupported: false,
+ }), [current, window.width, window.height, insets]);
+ return <GeometryContext.Provider value={value}>
+ <View style={styles.root}>
+ {children}
+ {Probe ? <Probe pointerEvents="none" style={StyleSheet.absoluteFill}
+ onGeometryChange={(event) => setGeometry(event.nativeEvent)} /> : null}
+ </View>
+ </GeometryContext.Provider>;
+}
+
+const styles = StyleSheet.create({ root: { flex: 1 } });
diff --git a/apps/mobile/src/platform/AdaptiveWindowContext.ts b/apps/mobile/src/platform/AdaptiveWindowContext.ts
new file mode 100644
index 0000000000..66517440c5
--- /dev/null
+++ b/apps/mobile/src/platform/AdaptiveWindowContext.ts
@@ -0,0 +1,25 @@
+import { createContext, useContext } from 'react';
+import { useWindowDimensions } from 'react-native';
+import { useSafeAreaInsets } from 'react-native-safe-area-context';
+import type { WindowGeometry } from './windowGeometry';
+
+export const GeometryContext = createContext<WindowGeometry | null>(null);
+const PaneContext = createContext<{ width: number; height: number } | null>(null);
+export const FloatingSheetContext = createContext(false);
+
+export function useAdaptiveWindow(): WindowGeometry {
+ const value = useContext(GeometryContext);
+ const window = useWindowDimensions();
+ const insets = useSafeAreaInsets();
+ return value ?? { width: window.width, height: window.height, insets,
+ regularWidth: window.width >= 600, regularHeight: window.height >= 600,
+ barEdge: 'none', regions: [], reservedRegionsSupported: false };
+}
+
+/** Descendants measure their pane, while independent export surfaces keep window dimensions. */
+export const PaneViewportProvider = PaneContext.Provider;
+export function usePaneViewport() {
+ const window = useWindowDimensions();
+ const pane = useContext(PaneContext);
+ return pane ? { ...window, ...pane } : window;
+}
diff --git a/apps/mobile/src/platform/ModalContentArea.tsx b/apps/mobile/src/platform/ModalContentArea.tsx
new file mode 100644
index 0000000000..f1e3945eeb
--- /dev/null
+++ b/apps/mobile/src/platform/ModalContentArea.tsx
@@ -0,0 +1,20 @@
+import type { ReactNode } from 'react';
+import { Platform, ScrollView, View } from 'react-native';
+import { useAdaptiveWindow } from './AdaptiveWindowContext';
+import { modalLayout } from './modalLayout';
+import { useMobileKeyboardState } from '@/session/useMobileKeyboardState';
+import { spacing } from '@/theme';
+
+/** The modal backdrop stays full-screen; form controls fit one usable, scrollable region. */
+export function ModalContentArea({ children }: { children: ReactNode }) {
+ const geometry = useAdaptiveWindow();
+ const keyboard = useMobileKeyboardState();
+ const { region: area } = modalLayout(geometry, Platform.OS === 'android' ? 0 : keyboard.height);
+ return <View pointerEvents="box-none" style={{ position: 'absolute', left: area.x, top: area.y,
+ width: area.width, height: area.height }}>
+ <ScrollView keyboardShouldPersistTaps="handled" style={{ flex: 1 }}
+ contentContainerStyle={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center', padding: spacing.lg }}>
+ {children}
+ </ScrollView>
+ </View>;
+}
diff --git a/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx b/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx
index c4702ffec8..db540d66e8 100644
--- a/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx
+++ b/apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx
@@ -1,7 +1,9 @@
+import type { ComponentProps, ReactNode } from "react";
import { Stack } from "expo-router";
+import { HomeHeaderGlassButton } from "@/session/HomeHeaderGlassButton";
import { BlurBackdrop } from "@/session/BlurBackdrop";
import { QuietSyncIndicator } from '@/components/QuietSyncIndicator';
-import { ChevronDown, Ellipsis, Menu, Monitor } from "lucide-react-native";
+import { ChevronDown, Menu } from "lucide-react-native";
import { Pressable, StyleSheet, View } from "react-native";
import { Text } from "@/components/AppText";
import {
@@ -31,7 +33,6 @@ export function HomeNativeStackHeader({
menuA11y,
onDisplayAction,
onOpenDeviceMenu,
- onOpenDisplaySettings,
onOpenMenu,
onOpenRemoteDesktop,
remoteDesktopA11y,
@@ -39,6 +40,7 @@ export function HomeNativeStackHeader({
scopeActions,
showRemoteGuide,
syncing = false,
+ keepMenuTopLeft = false,
title,
titleA11y,
}: {
@@ -55,6 +57,7 @@ export function HomeNativeStackHeader({
scopeActions: readonly NativePullDownAction[];
showRemoteGuide: boolean;
syncing?: boolean;
+ keepMenuTopLeft?: boolean;
title: string;
titleA11y: string;
}) {
@@ -106,6 +109,7 @@ export function HomeNativeStackHeader({
headerStyle: { backgroundColor: "transparent" },
headerTintColor: colors.textPrimary,
headerTransparent: true,
+ headerTitle: () => titleNode,
}}
/>
<Stack.Header
@@ -115,90 +119,51 @@ export function HomeNativeStackHeader({
shadowColor: "transparent",
}}
/>
- <Stack.Title asChild>{titleNode}</Stack.Title>
<Stack.Toolbar placement="left">
- <Stack.Toolbar.View>
- <Pressable
- accessibilityRole="button"
- style={({ pressed }) => [styles.iconHit, pressed && styles.pressed]}
- accessibilityLabel={menuA11y}
- onPress={onOpenMenu}
- testID="home.chromeMenu"
- >
- <Menu
- color={colors.textPrimary}
- size={iconSize.xl}
- strokeWidth={iconStroke.regular}
- />
- </Pressable>
- </Stack.Toolbar.View>
+ {keepMenuTopLeft ? (
+ // This home-only custom item stays at the top left on Duo. Hosting it
+ // in the native bar keeps its hit target above the transparent header.
+ <Stack.Toolbar.View hidesSharedBackground>
+ <HomeHeaderGlassButton accessibilityLabel={menuA11y} onPress={onOpenMenu} testID="home.chromeMenu">
+ <Menu color={colors.textPrimary} size={iconSize.action} strokeWidth={iconStroke.regular} />
+ </HomeHeaderGlassButton>
+ </Stack.Toolbar.View>
+ ) : (
+ <Stack.Toolbar.Button icon="line.3.horizontal" accessibilityLabel={menuA11y} onPress={onOpenMenu} />
+ )}
</Stack.Toolbar>
{showRemoteGuide ? null : (
<Stack.Toolbar placement="right">
- <Stack.Toolbar.View>
- <View style={styles.trailingActions}>
- {onOpenRemoteDesktop ? (
- <Pressable
- accessibilityRole="button"
- style={({ pressed }) => [
- styles.iconHit,
- pressed && styles.pressed,
- ]}
- accessibilityLabel={remoteDesktopA11y}
- onPress={onOpenRemoteDesktop}
- testID="home.remoteDesktopButton"
- >
- <Monitor
- color={colors.textPrimary}
- size={iconSize.xl}
- strokeWidth={iconStroke.regular}
- />
- </Pressable>
- ) : null}
- <NativePullDownMenu
- actions={displayActions}
- onAction={onDisplayAction}
- >
- <Pressable
- accessibilityRole="button"
- style={({ pressed }) => [
- styles.iconHit,
- pressed && styles.pressed,
- ]}
- accessibilityLabel={displayA11y}
- onPress={
- nativeMenus ? () => undefined : onOpenDisplaySettings
- }
- testID="home.displaySettingsButton"
- >
- <Ellipsis
- color={colors.textPrimary}
- size={iconSize.xl}
- strokeWidth={iconStroke.regular}
- />
- </Pressable>
- </NativePullDownMenu>
- </View>
- </Stack.Toolbar.View>
+ {onOpenRemoteDesktop ? <Stack.Toolbar.Button icon={require("../../../assets/navigation/monitor.png")} iconRenderingMode="template"
+ accessibilityLabel={remoteDesktopA11y} onPress={onOpenRemoteDesktop} /> : null}
+ <Stack.Toolbar.Menu icon="ellipsis" accessibilityLabel={displayA11y}>
+ {displayMenuItems(displayActions, onDisplayAction)}
+ </Stack.Toolbar.Menu>
</Stack.Toolbar>
)}
</>
);
}
+
+function displayMenuItems(actions: readonly NativePullDownAction[], onAction: (id: string) => void): ReactNode {
+ return actions.map(action => action.subactions?.length ? (
+ <Stack.Toolbar.Menu key={action.id} title={action.title} inline={action.displayInline}
+ disabled={action.disabled} destructive={action.destructive}>
+ {displayMenuItems(action.subactions, onAction)}
+ </Stack.Toolbar.Menu>
+ ) : (
+ <Stack.Toolbar.MenuAction key={action.id} disabled={action.disabled}
+ destructive={action.destructive} isOn={action.state === 'on'} subtitle={action.subtitle}
+ icon={action.image as ComponentProps<typeof Stack.Toolbar.MenuAction>['icon']}
+ unstable_keepPresented={action.keepPresented} onPress={() => onAction(action.id)}>
+ {action.title}
+ </Stack.Toolbar.MenuAction>
+ ));
+}
+
const makeStyles = (colors: ThemeColors) =>
StyleSheet.create({
- trailingActions: {
- flexDirection: "row",
- alignItems: "center",
- },
- iconHit: {
- alignItems: "center",
- justifyContent: "center",
- height: 44,
- width: 44,
- borderRadius: radius.pill,
- },
pressed: { opacity: 0.72 },
title: {
color: colors.textPrimary,
diff --git a/apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx b/apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx
new file mode 100644
index 0000000000..e7cb6b03d7
--- /dev/null
+++ b/apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx
@@ -0,0 +1,8 @@
+import type { ComponentProps } from "react";
+import { NativeChromeButton } from "./NativeChromeButton.ios";
+
+export function NativeChromeBackButton(
+ props: Omit<ComponentProps<typeof NativeChromeButton>, "children" | "systemImage">,
+) {
+ return <NativeChromeButton {...props} systemImage="chevron.backward" />;
+}
diff --git a/apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx b/apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx
new file mode 100644
index 0000000000..90196a58b0
--- /dev/null
+++ b/apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx
@@ -0,0 +1,77 @@
+import { Host } from "@expo/ui";
+import { Button, RNHostView, VStack } from "@expo/ui/swift-ui";
+import type { ComponentProps, ReactNode } from "react";
+import { View } from "react-native";
+import {
+ accessibilityElement,
+ accessibilityLabel,
+ disabled as disabledModifier,
+ frame,
+ font,
+ labelStyle,
+} from "@expo/ui/swift-ui/modifiers";
+import { useNativeGlassButtonStyle } from "./nativeGlassButtonStyle.ios";
+import { iconSize, navigationChrome, useTheme } from "@/theme";
+
+export function NativeChromeButton({
+ label,
+ systemImage,
+ children,
+ onPress,
+ testID,
+ disabled = false,
+ glassVariant = "regular",
+ prominent = false,
+ size = navigationChrome.target,
+ artworkSize = iconSize.action,
+}: {
+ testID: string;
+ disabled?: boolean;
+ systemImage?: ComponentProps<typeof Button>["systemImage"];
+ children?: ReactNode;
+ glassVariant?: "regular" | "clear";
+ prominent?: boolean;
+ size?: number;
+ artworkSize?: number;
+ label: string;
+ onPress(): void;
+}) {
+ const { colors, mode } = useTheme();
+ const clearPalette = navigationChrome.clear[mode];
+ const clearGlass = glassVariant === "clear";
+ const glassStyle = useNativeGlassButtonStyle({ shape: "circle", clear: clearGlass, prominent, size });
+
+ return (
+ <Host
+ colorScheme={mode}
+ seedColor={prominent ? colors.cta : clearGlass ? clearPalette.foreground : colors.textPrimary}
+ ignoreSafeArea="all"
+ style={{ width: size, height: size }}
+ >
+ <Button
+ label={children ? undefined : label}
+ systemImage={systemImage}
+ onPress={() => { if (!disabled) onPress(); }}
+ testID={testID}
+ modifiers={[
+ labelStyle("iconOnly"),
+ accessibilityElement("ignore"),
+ accessibilityLabel(label),
+ disabledModifier(disabled),
+ font({ size: artworkSize }),
+ ...glassStyle,
+ ]}
+ >
+ {children ? (
+ <VStack modifiers={[frame({ width: artworkSize, height: artworkSize })]}>
+ <RNHostView>
+ <View pointerEvents="none" style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
+ {children}
+ </View>
+ </RNHostView>
+ </VStack>
+ ) : undefined}
+ </Button>
+ </Host>
+ );
+}
diff --git a/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx b/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx
index 67c2f62cb0..56df46ad43 100644
--- a/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx
+++ b/apps/mobile/src/platform/chrome/SimpleStackHeader.tsx
@@ -1,4 +1,5 @@
import { Stack } from "expo-router";
+import { useTranslation } from 'react-i18next';
import { QuietSyncIndicator } from '@/components/QuietSyncIndicator';
import type { ReactNode } from "react";
import { Platform, StyleSheet, View } from "react-native";
@@ -55,6 +56,7 @@ export function SimpleStackHeader({
syncing?: boolean;
}) {
const { colors } = useTheme();
+ const { t } = useTranslation();
const styles = useThemedStyles(makeNativeTitleStyles);
if (!usesNativeStackHeader()) {
@@ -74,6 +76,7 @@ export function SimpleStackHeader({
}
return (
+ <>
<Stack.Screen
options={{
headerShown: true,
@@ -89,20 +92,15 @@ export function SimpleStackHeader({
{syncing !== undefined ? <QuietSyncIndicator active={syncing} /> : null}
</View>
),
- headerLeft: onBack
- ? () => (
- <ScreenBackButton
- compact
- onPress={onBack}
- testID={backTestID ?? "screen.backButton"}
- />
- )
- : undefined,
headerRight: right ? () => right : action
? () => <MainWindowActionButton action={action} density="compact" />
: undefined,
}}
/>
+ {onBack ? <Stack.Toolbar placement="left">
+ <Stack.Toolbar.Button icon="chevron.backward" onPress={onBack} accessibilityLabel={t('shared.back')} />
+ </Stack.Toolbar> : null}
+ </>
);
}
diff --git a/apps/mobile/src/platform/chrome/SystemNavigationBack.tsx b/apps/mobile/src/platform/chrome/SystemNavigationBack.tsx
new file mode 100644
index 0000000000..f3112a4f74
--- /dev/null
+++ b/apps/mobile/src/platform/chrome/SystemNavigationBack.tsx
@@ -0,0 +1,31 @@
+import { Stack } from 'expo-router';
+import { Platform } from 'react-native';
+import { useAdaptiveWindow } from '../AdaptiveWindowContext';
+import { useTheme } from '@/theme';
+
+export function useSystemNavigationBack() {
+ const window = useAdaptiveWindow();
+ return Platform.OS === 'ios' && window.barEdge !== 'none';
+}
+
+/** Keep real toolbar items: Toolbar.View custom content loses Duo's vertical
+ * adaptation and returns to the horizontal header, overlapping the sidebar. */
+export function SystemNavigationBack({ onPress, label, disabled = false, close = false, available = true, newTask }: {
+ newTask?: { onPress(): void; label: string };
+ onPress(): void; label: string; disabled?: boolean; close?: boolean; available?: boolean;
+}) {
+ const enabled = useSystemNavigationBack();
+ const { colors } = useTheme();
+ return <>
+ <Stack.Screen options={{ headerShown: enabled && available, headerTransparent: true,
+ headerShadowVisible: false, headerBackVisible: false, headerTitle: '',
+ headerTintColor: colors.textPrimary }} />
+ {enabled && available ? <Stack.Toolbar placement="left">
+ <Stack.Toolbar.Button icon={close ? 'xmark' : 'chevron.backward'}
+ accessibilityLabel={label} disabled={disabled} onPress={onPress} />
+ </Stack.Toolbar> : null}
+ {enabled && available && newTask ? <Stack.Toolbar placement="right">
+ <Stack.Toolbar.Button icon="square.and.pencil" accessibilityLabel={newTask.label} onPress={newTask.onPress} />
+ </Stack.Toolbar> : null}
+ </>;
+}
diff --git a/apps/mobile/src/platform/chrome/nativeGlassButtonStyle.ios.ts b/apps/mobile/src/platform/chrome/nativeGlassButtonStyle.ios.ts
new file mode 100644
index 0000000000..422effa2ef
--- /dev/null
+++ b/apps/mobile/src/platform/chrome/nativeGlassButtonStyle.ios.ts
@@ -0,0 +1,46 @@
+import {
+ background, buttonBorderShape, buttonStyle, contentShape, controlSize,
+ foregroundStyle, font, frame, glassEffect, shapes,
+} from '@expo/ui/swift-ui/modifiers';
+import { useLiquidGlassAvailable } from '@/session/useLiquidGlassAvailable';
+import { iconSize, navigationChrome, useTheme } from '@/theme';
+
+/** Shared native styling only. SwiftUI Button owns activation and feedback. */
+export function useNativeGlassButtonStyle({
+ shape = 'capsule', prominent = false, clear = false, size = navigationChrome.target, dimensions,
+}: { shape?: 'circle' | 'capsule'; prominent?: boolean; clear?: boolean; size?: number;
+ dimensions?: { width?: number; height: number } } = {}) {
+ const glass = useLiquidGlassAvailable();
+ const { colors, mode } = useTheme();
+ if (shape === 'circle' || dimensions) {
+ const palette = navigationChrome.clear[mode];
+ const outline = shape === 'circle' ? shapes.circle() : shapes.capsule();
+ // Explicit glass after the frame respects chrome and floating-action sizes. Adding
+ // the system's large button padding here enlarges the visible circle.
+ return [
+ buttonStyle('borderless'),
+ font({ size: iconSize.action }),
+ frame(dimensions ? { ...dimensions, ...(dimensions.width == null ? { maxWidth: Infinity } : {}) } : { width: size, height: size }),
+ contentShape(outline),
+ ...(glass ? [glassEffect({ glass: { variant: clear ? 'clear' : 'regular', interactive: true, ...(prominent ? { tint: colors.cta } : {}) }, shape })]
+ : [background(prominent ? colors.cta : colors.surfaceElevated, outline)]),
+ ...(clear && glass ? [foregroundStyle(palette.foreground), background(palette.scrim, outline)] : []),
+ ];
+ }
+ return [
+ buttonStyle(glass ? (prominent ? 'glassProminent' : 'glass') : (prominent ? 'borderedProminent' : 'bordered')),
+ buttonBorderShape(shape),
+ controlSize('regular'),
+ frame({ minHeight: navigationChrome.target }),
+ ];
+}
+
+/** A toolbar shares one material; its children remain native borderless Buttons. */
+export function useNativeGlassGroupStyle(variant: 'regular' | 'clear' = 'regular') {
+ const glass = useLiquidGlassAvailable();
+ const { colors, mode } = useTheme();
+ return glass
+ ? [glassEffect({ glass: { variant }, shape: 'capsule' }),
+ ...(variant === 'clear' ? [background(navigationChrome.clear[mode].scrim, shapes.capsule())] : [])]
+ : [background(colors.surfaceElevated, shapes.capsule())];
+}
diff --git a/apps/mobile/src/platform/modalLayout.ts b/apps/mobile/src/platform/modalLayout.ts
new file mode 100644
index 0000000000..ce8556155d
--- /dev/null
+++ b/apps/mobile/src/platform/modalLayout.ts
@@ -0,0 +1,16 @@
+import { keyboardControlRegion, type WindowGeometry } from './windowGeometry';
+
+/** Legacy custom panels float in roomy windows; navigation rails belong to the presenting page. */
+export function modalLayout(window: WindowGeometry, keyboardHeight = 0) {
+ const region = keyboardControlRegion(window, keyboardHeight);
+ const floating = window.width >= 600 || window.width > window.height;
+ if (!floating) return { floating, region };
+ const margin = 20;
+ const width = Math.min(560, Math.max(0, region.width - margin * 2));
+ const height = Math.min(640, Math.max(0, region.height - margin * 2));
+ return { floating, region: {
+ x: region.x + (region.width - width) / 2,
+ y: region.y + (region.height - height) / 2,
+ width, height,
+ } };
+}
diff --git a/apps/mobile/src/platform/windowGeometry.ts b/apps/mobile/src/platform/windowGeometry.ts
new file mode 100644
index 0000000000..d2acae7f4e
--- /dev/null
+++ b/apps/mobile/src/platform/windowGeometry.ts
@@ -0,0 +1,74 @@
+/** Geometry is local to the observed window container, in points, never pixels. */
+export interface LayoutRect { x: number; y: number; width: number; height: number }
+export interface ReservedRegion extends LayoutRect { kind: 'division' | 'occlusion' }
+export interface WindowGeometry {
+ width: number;
+ height: number;
+ insets: { top: number; right: number; bottom: number; left: number };
+ regularWidth: boolean;
+ regularHeight: boolean;
+ barEdge: 'none' | 'left' | 'right';
+ regions: ReservedRegion[];
+ reservedRegionsSupported: boolean;
+}
+
+export function safeWindowRect(g: WindowGeometry): LayoutRect {
+ return { x: g.insets.left, y: g.insets.top,
+ width: Math.max(0, g.width - g.insets.left - g.insets.right),
+ height: Math.max(0, g.height - g.insets.top - g.insets.bottom) };
+}
+
+/** Accept only divisions spanning the container; a clipped/offscreen fold is not a split. */
+export function windowDivision(g: WindowGeometry): { axis: 'vertical' | 'horizontal'; first: LayoutRect; second: LayoutRect } | null {
+ const safe = safeWindowRect(g);
+ for (const r of g.regions) {
+ if (r.kind !== 'division' || ![r.x, r.y, r.width, r.height].every(Number.isFinite)) continue;
+ if (r.height >= safe.height * 0.8 && r.width > 0 && r.x > safe.x && r.x + r.width < safe.x + safe.width) {
+ return { axis: 'vertical', first: { ...safe, width: r.x - safe.x },
+ second: { ...safe, x: r.x + r.width, width: safe.x + safe.width - r.x - r.width } };
+ }
+ if (r.width >= safe.width * 0.8 && r.height > 0 && r.y > safe.y && r.y + r.height < safe.y + safe.height) {
+ return { axis: 'horizontal', first: { ...safe, height: r.y - safe.y },
+ second: { ...safe, y: r.y + r.height, height: safe.y + safe.height - r.y - r.height } };
+ }
+ }
+ return null;
+}
+
+/** Keep a floating control group together, in the trailing/bottom region, clear of camera occlusions. */
+export function controlRegion(g: WindowGeometry): LayoutRect {
+ return avoidReservedRegions(windowDivision(g)?.second ?? safeWindowRect(g), g.regions.filter(r => r.kind === 'occlusion'));
+}
+
+/** Fit a complete control group into one remaining rectangle, never across a reservation. */
+export function avoidReservedRegions(initial: LayoutRect, regions: LayoutRect[]): LayoutRect {
+ let area = initial;
+ for (const r of regions) {
+ if (![r.x, r.y, r.width, r.height].every(Number.isFinite) || r.width <= 0 || r.height <= 0) continue;
+ const right = area.x + area.width, bottom = area.y + area.height;
+ if (r.x >= right || r.y >= bottom || r.x + r.width <= area.x || r.y + r.height <= area.y) continue;
+ const candidates: LayoutRect[] = [
+ { ...area, height: Math.max(0, r.y - area.y) },
+ { ...area, y: r.y + r.height, height: Math.max(0, bottom - r.y - r.height) },
+ { ...area, width: Math.max(0, r.x - area.x) },
+ { ...area, x: r.x + r.width, width: Math.max(0, right - r.x - r.width) },
+ ];
+ area = candidates.sort((a, b) => b.width * b.height - a.width * a.height)[0]!;
+ }
+ return area;
+}
+
+
+/** A docked keyboard can cover the lower fold region completely. Prefer a usable
+ * upper region then; callers using this rect must not apply keyboard padding twice. */
+export function keyboardControlRegion(g: WindowGeometry, keyboardBottom: number): LayoutRect {
+ const bottom = g.height - Math.max(0, keyboardBottom);
+ const clip = (r: LayoutRect) => ({ ...r, height: Math.max(0, Math.min(r.height, bottom - r.y)) });
+ const controls = clip(controlRegion(g));
+ const split = windowDivision(g);
+ if (controls.height >= 140 || split?.axis !== 'horizontal') return controls;
+ const upper = controlRegion({ ...g, insets: { ...g.insets, bottom: g.height - split.first.y - split.first.height },
+ regions: g.regions.filter(r => r.kind !== 'division') });
+ const alternative = clip(upper);
+ return alternative.height > controls.height ? alternative : controls;
+}
diff --git a/apps/mobile/src/remote-desktop/FoldTouchpad.tsx b/apps/mobile/src/remote-desktop/FoldTouchpad.tsx
new file mode 100644
index 0000000000..dd20ca2173
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/FoldTouchpad.tsx
@@ -0,0 +1,40 @@
+import { useEffect, useRef } from 'react';
+import { StyleSheet, View } from 'react-native';
+import { useTranslation } from 'react-i18next';
+import { Text } from '@/components/AppText';
+import { BlurBackdrop } from '@/session/BlurBackdrop';
+import { radius, spacing, useTheme } from '@/theme';
+
+/** Relative movement shares the viewer's cursor transform; lower-pane coordinates are never remote coordinates. */
+export function FoldTouchpad({ send, enabled }: { send(message: object): void; enabled: boolean }) {
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ const touch = useRef<{ x: number; y: number; distance: number; time: number } | null>(null);
+ useEffect(() => () => { touch.current = null; send({ type: 'releaseInput' }); }, [enabled, send]);
+ return <View testID="remoteDesktop.foldTouchpad"
+ accessibilityLabel={t('remoteDesktop.pointer')}
+ accessibilityHint={t('remoteDesktop.pointerHint')}
+ accessibilityState={{ disabled: !enabled }}
+ onStartShouldSetResponder={() => enabled}
+ onResponderGrant={(e) => { touch.current = { x: e.nativeEvent.pageX, y: e.nativeEvent.pageY, distance: 0, time: Date.now() }; }}
+ onResponderMove={(e) => {
+ const last = touch.current;
+ if (!last || !enabled) return;
+ const dx = e.nativeEvent.pageX - last.x, dy = e.nativeEvent.pageY - last.y;
+ last.x = e.nativeEvent.pageX; last.y = e.nativeEvent.pageY; last.distance += Math.abs(dx) + Math.abs(dy);
+ send({ type: 'nativeTouchpad', dx, dy });
+ }}
+ onResponderRelease={() => {
+ const last = touch.current; touch.current = null;
+ if (enabled && last && last.distance < 8 && Date.now() - last.time < 400) {
+ send({ type: 'nativeTouchpad', tap: true });
+ }
+ }}
+ onResponderTerminate={() => { touch.current = null; send({ type: 'releaseInput' }); }}
+ style={[styles.pad, { borderColor: colors.border }]}>
+ <BlurBackdrop intensity={60} overlayColor={colors.surfaceTranslucent} />
+ <Text style={{ color: colors.textTertiary }}>{t('remoteDesktop.pointer')}</Text>
+ </View>;
+}
+const styles = StyleSheet.create({ pad: { flex: 1, minHeight: 44, margin: spacing.sm,
+ overflow: 'hidden', borderWidth: StyleSheet.hairlineWidth, borderRadius: radius.container, alignItems: 'center', justifyContent: 'center' } });
diff --git a/apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx b/apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx
index d3f04fa4ef..28eb861fe6 100644
--- a/apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx
+++ b/apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx
@@ -9,9 +9,7 @@ import {
import {
accessibilityAddTraits,
background,
- buttonBorderShape,
buttonStyle,
- controlSize,
disabled,
fixedSize,
font,
@@ -24,15 +22,12 @@ import {
import { View } from "react-native";
import { Text as AppText } from "@/components/AppText";
import { radius, spacing, textStyles, useTheme } from "@/theme";
-import { useLiquidGlassAvailable } from "@/session/useLiquidGlassAvailable";
+import { useNativeGlassButtonStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";
import type { PermissionGuideViewProps } from "./PermissionGuideView";
export function PermissionGuideView(props: PermissionGuideViewProps) {
const { colors, mode } = useTheme();
- const glass = useLiquidGlassAvailable();
- const primaryStyle = buttonStyle(
- glass ? "glassProminent" : "borderedProminent",
- );
+ const primaryStyle = useNativeGlassButtonStyle({ prominent: true });
return (
<View
style={{
@@ -102,9 +97,7 @@ export function PermissionGuideView(props: PermissionGuideViewProps) {
<Button
onPress={props.onGuide}
modifiers={[
- primaryStyle,
- buttonBorderShape("capsule"),
- controlSize("large"),
+ ...primaryStyle,
disabled(props.pending),
]}
>
@@ -122,9 +115,7 @@ export function PermissionGuideView(props: PermissionGuideViewProps) {
<Button
onPress={props.onReconnect}
modifiers={[
- props.guideLabel ? buttonStyle("plain") : primaryStyle,
- buttonBorderShape("capsule"),
- controlSize("large"),
+ ...(props.guideLabel ? [buttonStyle("plain")] : primaryStyle),
]}
>
<Text
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx
index 4a4df29a39..07461c5ba7 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx
@@ -7,8 +7,6 @@ import {
accessibilityIdentifier,
accessibilityLabel,
buttonStyle,
- buttonBorderShape,
- controlSize,
contentShape,
disabled,
frame,
@@ -16,14 +14,14 @@ import {
} from "@expo/ui/swift-ui/modifiers";
import { StyleSheet, View } from "react-native";
import { useTheme } from "@/theme";
-import { useLiquidGlassAvailable } from "@/session/useLiquidGlassAvailable";
+import { useNativeGlassButtonStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";
import type { RemoteDesktopActionButtonProps } from "./RemoteDesktopActionButton";
export function RemoteDesktopActionButton(
props: RemoteDesktopActionButtonProps,
) {
const { mode, colors } = useTheme();
- const liquidGlass = useLiquidGlassAvailable();
+ const glassStyle = useNativeGlassButtonStyle();
const state = { pressed: false };
const style = StyleSheet.flatten(
typeof props.style === "function" ? props.style(state) : props.style,
@@ -48,9 +46,7 @@ export function RemoteDesktopActionButton(
if (!props.disabled) props.onPress();
}}
modifiers={[
- buttonStyle(liquidGlass ? "glass" : "bordered"),
- buttonBorderShape("capsule"),
- controlSize("large"),
+ ...glassStyle,
frame({ maxWidth: Infinity, minHeight: 44 }),
disabled(Boolean(props.disabled)),
accessibilityIdentifier(props.testID ?? ""),
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx
index cf921ebab0..58d9a12005 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx
@@ -1,45 +1,5 @@
-import { Host } from "@expo/ui";
-import { Button } from "@expo/ui/swift-ui";
-import {
- buttonBorderShape,
- buttonStyle,
- controlSize,
- frame,
- labelStyle,
-} from "@expo/ui/swift-ui/modifiers";
-import { useLiquidGlassAvailable } from "@/session/useLiquidGlassAvailable";
-import { useTheme } from "@/theme";
+import { NativeChromeBackButton } from "@/platform/chrome/NativeChromeBackButton.ios";
-export function RemoteDesktopBackButton({
- label,
- onPress,
-}: {
- label: string;
- onPress(): void;
-}) {
- const { colors, mode } = useTheme();
- const liquidGlass = useLiquidGlassAvailable();
-
- return (
- <Host
- colorScheme={mode}
- seedColor={colors.textPrimary}
- ignoreSafeArea="all"
- style={{ width: 44, height: 44 }}
- >
- <Button
- label={label}
- systemImage="chevron.backward"
- onPress={onPress}
- testID="remoteDesktop.back"
- modifiers={[
- labelStyle("iconOnly"),
- buttonStyle(liquidGlass ? "glass" : "bordered"),
- buttonBorderShape("circle"),
- controlSize("large"),
- frame({ width: 44, height: 44 }),
- ]}
- />
- </Host>
- );
+export function RemoteDesktopBackButton(props: { label: string; onPress(): void }) {
+ return <NativeChromeBackButton {...props} testID="remoteDesktop.back" glassVariant="clear" />;
}
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx
index 5e84e210d6..2f2f80f255 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx
@@ -1,3 +1,4 @@
+import { useNativeGlassGroupStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";
import type { ComponentProps } from "react";
import { ScrollView, View, useWindowDimensions } from "react-native";
import { Host } from "@expo/ui";
@@ -20,7 +21,6 @@ import {
contentShape,
disabled,
frame,
- glassEffect,
padding,
presentationDetents,
presentationDragIndicator,
@@ -30,6 +30,7 @@ import { Keyboard, SlidersHorizontal } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
+ navigationChrome,
fontWeight,
iconSize,
iconStroke,
@@ -52,14 +53,16 @@ import type {
RemoteDesktopToolbar as Toolbar,
} from "./RemoteDesktopChrome";
-// 44pt native hit targets with a 4pt inset inside one glass capsule.
-const target = 44;
-const inset = 4;
+// Match the task/header controls: no extra ring around the glass capsule.
+const target = navigationChrome.target;
+const inset = 0;
const breadth = target + inset * 2;
export function RemoteDesktopToolbar(props: ComponentProps<typeof Toolbar>) {
const { colors, mode } = useTheme();
+ const clearPalette = navigationChrome.clear[mode];
const { t } = useTranslation();
+ const groupStyle = useNativeGlassGroupStyle("clear");
const glass = useLiquidGlassAvailable();
const actions = [
{
@@ -107,7 +110,7 @@ export function RemoteDesktopToolbar(props: ComponentProps<typeof Toolbar>) {
return (
<Host
colorScheme={mode}
- seedColor={colors.textPrimary}
+ seedColor={glass ? clearPalette.foreground : colors.textPrimary}
ignoreSafeArea="all"
testID="remoteDesktop.toolbar"
style={{
@@ -119,9 +122,7 @@ export function RemoteDesktopToolbar(props: ComponentProps<typeof Toolbar>) {
spacing={0}
modifiers={[
padding({ all: inset }),
- ...(glass
- ? [glassEffect({ glass: { variant: "regular" }, shape: "capsule" })]
- : [background(colors.surfaceElevated, shapes.capsule())]),
+ ...groupStyle,
]}
>
{(props.landscape ? [...actions].reverse() : actions).map(
@@ -135,7 +136,7 @@ export function RemoteDesktopToolbar(props: ComponentProps<typeof Toolbar>) {
disabled(unavailable),
frame({ width: target, height: target }),
...(selected
- ? [background(colors.surfaceChip, shapes.circle())]
+ ? [background(glass ? clearPalette.selected : colors.surfaceChip, shapes.circle())]
: []),
accessibilityElement("ignore"),
accessibilityLabel(t(`remoteDesktop.${key}`)),
@@ -162,7 +163,7 @@ export function RemoteDesktopToolbar(props: ComponentProps<typeof Toolbar>) {
<Icon
size={iconSize.action}
strokeWidth={iconStroke.regular}
- color={colors.textPrimary}
+ color={glass ? clearPalette.foreground : colors.textPrimary}
/>
</View>
</RNHostView>
@@ -183,6 +184,10 @@ export function RemoteDesktopPanel(props: ComponentProps<typeof Panel>) {
const visible = props.visible ?? true;
const toolbarOnLeft = props.toolbarOnLeft ?? false;
const length = target * (props.toolbarActionCount ?? 4) + inset * 2;
+ const preferredPanelHeight = Math.max(
+ target,
+ size.height - safe.top - safe.bottom - spacing.lg,
+ );
const railTop =
safe.top + Math.max(0, (size.height - safe.top - safe.bottom - length) / 2);
// Keep one RN surface for header and body. Changing SwiftUI siblings while
@@ -197,6 +202,7 @@ export function RemoteDesktopPanel(props: ComponentProps<typeof Panel>) {
>
<View
style={{
+ flexShrink: 0,
flexDirection: "row",
alignItems: "center",
padding: spacing.md,
@@ -238,7 +244,7 @@ export function RemoteDesktopPanel(props: ComponentProps<typeof Panel>) {
<ScrollView
key={props.page}
testID="remoteDesktop.panelScroll"
- style={{ flex: 1 }}
+ style={{ flex: 1, minHeight: 0 }}
removeClippedSubviews={false}
keyboardShouldPersistTaps="handled"
contentContainerStyle={{
@@ -270,6 +276,7 @@ export function RemoteDesktopPanel(props: ComponentProps<typeof Panel>) {
left: toolbarOnLeft ? spacing.lg + inset : undefined,
right: toolbarOnLeft ? undefined : spacing.lg + inset,
top: railTop + inset,
+ ...(props.railAnchor ?? {}),
width: target,
height: target,
}}
@@ -291,10 +298,16 @@ export function RemoteDesktopPanel(props: ComponentProps<typeof Panel>) {
360,
size.width - safe.left - safe.right - breadth - spacing.lg,
),
- height: Math.max(
- target,
- size.height - safe.top - safe.bottom - spacing.lg,
- ),
+ }),
+ // A popover can offer less height than the window (Duo reserves
+ // its status rail). Let RNHostView receive that actual proposal
+ // instead of centering an oversized fixed frame and clipping the header.
+ frame({
+ minHeight: target,
+ // Popover asks for an ideal size before assigning its bounds.
+ // RN's flex ScrollView has no intrinsic height to offer here.
+ idealHeight: preferredPanelHeight,
+ maxHeight: preferredPanelHeight,
}),
]}
>
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx
index 5f1bc74d69..822c3ce152 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx
@@ -154,6 +154,7 @@ export function RemoteDesktopPanel({
topInset: number;
toolbarOnLeft?: boolean;
toolbarActionCount?: number;
+ railAnchor?: { top: number; right: number };
title: string;
caption: string;
onClose(): void;
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx
index 9a746e44e3..046d7b5426 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx
@@ -1,42 +1,7 @@
-import { Host } from "@expo/ui";
-import { Button } from "@expo/ui/swift-ui";
-import {
- buttonBorderShape,
- buttonStyle,
- controlSize,
- frame,
- labelStyle,
-} from "@expo/ui/swift-ui/modifiers";
-import { useLiquidGlassAvailable } from "@/session/useLiquidGlassAvailable";
-import { useTheme } from "@/theme";
-import type { PanelButtonProps } from "./RemoteDesktopPanelButton";
+import { NativeChromeButton } from '@/platform/chrome/NativeChromeButton.ios';
+import type { PanelButtonProps } from './RemoteDesktopPanelButton';
-export function RemoteDesktopPanelButton({
- back,
- label,
- onPress,
-}: PanelButtonProps) {
- const { colors, mode } = useTheme();
- const glass = useLiquidGlassAvailable();
- return (
- <Host
- colorScheme={mode}
- seedColor={colors.textPrimary}
- ignoreSafeArea="all"
- style={{ width: 44, height: 44 }}
- >
- <Button
- label={label}
- systemImage={back ? "chevron.backward" : "xmark"}
- onPress={onPress}
- modifiers={[
- labelStyle("iconOnly"),
- buttonStyle(glass ? "glass" : "bordered"),
- buttonBorderShape("circle"),
- controlSize("large"),
- frame({ width: 44, height: 44 }),
- ]}
- />
- </Host>
- );
+export function RemoteDesktopPanelButton({ back, label, onPress }: PanelButtonProps) {
+ return <NativeChromeButton label={label} onPress={onPress}
+ systemImage={back ? 'chevron.backward' : 'xmark'} testID="remoteDesktop.panel.back" />;
}
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
index 9ccaa9c404..b58abcd8fd 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
@@ -1,3 +1,7 @@
+import { foldDesktopLayout } from './foldDesktopLayout';
+import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';
+import { windowDivision, controlRegion } from '@/platform/windowGeometry';
+import { FoldTouchpad } from './FoldTouchpad';
import {
useCallback,
useMemo,
@@ -109,6 +113,7 @@ import { useRemoteDesktopSafety } from "./useRemoteDesktopSafety";
import { useVideoSettingsPreference } from "./useVideoSettingsPreference";
import { usePictureInPicturePreference } from "./usePictureInPicturePreference";
import { PermissionGuide } from "./PermissionGuide";
+import { navigationChrome } from "@/theme/tokens";
import { RemoteDesktopBackButton } from "./RemoteDesktopBackButton";
import { RemoteDesktopWindows } from "./RemoteDesktopWindows";
import { RemoteDesktopNetworkStatus } from "./RemoteDesktopNetworkStatus";
@@ -259,23 +264,40 @@ export function RemoteDesktopSession({
windowWidth: windowSize.width,
windowHeight: windowSize.height,
});
- const screenSize = Dimensions.get("screen");
- const landscape = screenSize.width > screenSize.height;
+ const screenSize = windowSize;
+ const geometry = useAdaptiveWindow();
+ const division = windowDivision(geometry);
+ const tableRegion = division && division.first.height >= 160 && division.second.height >= 160 && division.first.width >= 160 && division.second.width >= 160 ? division : null;
+
+ const systemSideRail = Platform.OS === 'ios' && !tableRegion && (geometry.barEdge !== 'none' || (geometry.reservedRegionsSupported && geometry.regularWidth && windowSize.width > windowSize.height));
+ // Android adjustResize shrinks the window for the IME, not the display.
+ // Keep its device orientation stable; iOS/Duo still use the adaptive window.
+ const orientationSize = Platform.OS === 'android' ? Dimensions.get('screen') : windowSize;
+ const landscape = systemSideRail || (!tableRegion && orientationSize.width > orientationSize.height);
+ const sideRailWidth = Math.max(60, geometry.insets.right + spacing.md);
+ // The native status/navigation center sits 6pt inward from the safe strip center.
+ // Use the reported status reservation for vertical clearance when available.
+ const statusReservation = geometry.regions.filter(r => r.kind === 'occlusion' && r.y === 0 && r.x + r.width >= geometry.width);
+ const sideRailTop = Math.max(insets.top, statusReservation.length ? Math.max(...statusReservation.map(r => r.y + r.height)) : 120);
const [interfaceAngle, setInterfaceAngle] = useState<number | null>(null);
const toolbarOnLeft =
+ systemSideRail ? false :
Platform.OS === "ios" &&
landscape &&
(interfaceAngle === 270 ||
(interfaceAngle === null && insets.right > insets.left));
const webview = useRef<ComponentRef<typeof WebView>>(null);
const nativeViewer = useRef<NativeRemoteDesktopHandle>(null);
- const html = useRef(
+ // Memo survives ordinary renders, but Fast Refresh invalidates it when the
+ // bundled viewer changes. A ref kept the old script alongside new RN layout.
+ const html = useMemo(() =>
remoteDesktopViewerHtml(
colors.surface,
colors.textPrimary,
Boolean(NativeRemoteDesktopView),
),
- ).current;
+ []);
+ const [viewerReadyRevision, setViewerReadyRevision] = useState(0);
const active = useRef<RemoteDesktopLease | null>(null);
const wantsControl = useRef(true);
const [viewOnlySelected, setViewOnlySelected] = useState(false);
@@ -427,6 +449,9 @@ export function RemoteDesktopSession({
landscape && (Platform.OS === "ios" || fullKeys);
const keyboardBottom =
Platform.OS === "ios" && keyboard && !fullKeys ? nativeKeyboardHeight : 0;
+ const foldLayout = foldDesktopLayout(geometry, keyboardBottom, keyboardPanelHeight, keyboard);
+ const fullScreenFoldBackground = Boolean(foldLayout && division?.axis === 'horizontal');
+ const foldControls = foldLayout?.controls ?? controlRegion(geometry);
const heldKeys = useRef(new Map<string, string[]>());
const [keyPage, setKeyPage] = useState(0);
const [comboMode, setComboMode] = useState(true);
@@ -648,7 +673,7 @@ export function RemoteDesktopSession({
const updateFrame = (event: KeyboardEvent) => {
const height = Math.max(
0,
- Dimensions.get("screen").height - event.endCoordinates.screenY,
+ Dimensions.get("window").height - event.endCoordinates.screenY,
);
setNativeKeyboardHeight(height);
setNativeKeyboard(height > 0);
@@ -1200,7 +1225,7 @@ export function RemoteDesktopSession({
};
useEffect(() => {
send({ type: "viewport", fillHeight: landscape });
- }, [landscape, send]);
+ }, [landscape, send, viewerReadyRevision]);
useEffect(() => {
alive.current = true;
@@ -1449,8 +1474,10 @@ export function RemoteDesktopSession({
send({
type: "mouseButtons",
native: Platform.OS === "ios",
- topInset: edgePadding.paddingTop,
- bottomInset:
+ fitToInsets: fullScreenFoldBackground,
+ topInset: fullScreenFoldBackground ? foldLayout!.media.y : tableRegion ? 0 : edgePadding.paddingTop,
+ bottomInset: fullScreenFoldBackground
+ ? Math.max(0, geometry.height - foldLayout!.media.y - foldLayout!.media.height) : tableRegion ? 0 :
keyboard && landscapeKeyboardOverlay
? keyboardPanelHeight + keyboardBottom
: !keyboard && !landscape
@@ -1458,19 +1485,13 @@ export function RemoteDesktopSession({
: 0,
keyboardOpen: keyboard && landscapeKeyboardOverlay,
portraitKeyboardTopInset:
- keyboard && !landscape
+ keyboard && !landscape && !tableRegion
? edgePadding.paddingTop + spacing.xs + backControlHeight + spacing.sm
: 0,
- rightInset: landscape
- ? !keyboard && !toolbarOnLeft
- ? toolbarSize.width
- : insets.right
- : 0,
- leftInset: landscape
- ? !keyboard && toolbarOnLeft
- ? toolbarSize.width
- : insets.left
- : 0,
+ // Side controls float over the desktop; fit against the full canvas width
+ // in either landscape direction, including while the keyboard is open.
+ rightInset: 0,
+ leftInset: 0,
enabled:
showMouseButtons &&
focused &&
@@ -1484,12 +1505,12 @@ export function RemoteDesktopSession({
},
});
}, [
+ tableRegion?.first.height, tableRegion?.first.width,
+ fullScreenFoldBackground, foldLayout?.media.y, foldLayout?.media.height, geometry.height,
+ viewerReadyRevision,
showMouseButtons,
edgePadding.paddingTop,
backControlHeight,
- insets.left,
- insets.right,
- toolbarOnLeft,
toolbarSize,
keyboardPanelHeight,
landscapeKeyboardOverlay,
@@ -1543,6 +1564,7 @@ export function RemoteDesktopSession({
}
if (message.type === "ready") {
ready.current = true;
+ setViewerReadyRevision(revision => revision + 1);
void connectRef.current();
return;
}
@@ -2572,7 +2594,7 @@ export function RemoteDesktopSession({
return (
<KeyboardAvoidingView
testID="remoteDesktop.layout"
- enabled={!landscapeKeyboardOverlay}
+ enabled={!landscapeKeyboardOverlay && !foldLayout}
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={styles.root}
>
@@ -2581,7 +2603,9 @@ export function RemoteDesktopSession({
<View
style={[
styles.canvas,
- { marginLeft: landscape ? 0 : edgePadding.paddingLeft },
+ { marginLeft: landscape ? 0 : edgePadding.paddingLeft, marginRight: landscape ? 0 : edgePadding.paddingRight },
+ fullScreenFoldBackground ? { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, marginLeft: 0, marginRight: 0 } : foldLayout && { position: 'absolute', flex: 0, left: foldLayout.media.x, top: foldLayout.media.y,
+ width: foldLayout.media.width, height: foldLayout.media.height, marginLeft: 0, marginRight: 0 },
]}
>
<Animated.View
@@ -2642,6 +2666,7 @@ export function RemoteDesktopSession({
</Animated.View>
{frameReady &&
Platform.OS === "ios" &&
+ !tableRegion &&
showMouseButtons &&
focused &&
!operations &&
@@ -2823,6 +2848,10 @@ export function RemoteDesktopSession({
]}
>
<RemoteDesktopPanel
+ railAnchor={systemSideRail ? {
+ right: (sideRailWidth - navigationChrome.target) / 2,
+ top: (sideRailTop + navigationChrome.target + spacing.lg + windowSize.height - insets.bottom - navigationChrome.target * (caps?.omarchyMenu ? 5 : 4)) / 2,
+ } : undefined}
toolbarOnLeft={toolbarOnLeft}
toolbarActionCount={caps?.omarchyMenu ? 5 : 4}
visible={operations && focused}
@@ -2868,7 +2897,7 @@ export function RemoteDesktopSession({
}
presentation={{
enabled: pipEnabled,
- canRotate: typeof remotePresentation?.rotate === "function",
+ canRotate: typeof remotePresentation?.rotate === "function" && !(geometry.reservedRegionsSupported && Platform.OS === "ios" && !Platform.isPad && geometry.regularWidth && geometry.regularHeight),
canPip: Boolean(
remotePresentation &&
caps?.backgroundViewing &&
@@ -2924,6 +2953,16 @@ export function RemoteDesktopSession({
</View>
)}
</View>
+ {tableRegion && frameReady && focused && !keyboard && !operations ? (
+ <View testID="remoteDesktop.foldControls" style={{ position: 'absolute', left: foldControls.x,
+ top: foldControls.y, width: foldControls.width, height: foldControls.height,
+ paddingBottom: toolbarSize.height + (showMouseButtons ? 80 : 0) }}>
+ <FoldTouchpad send={send} enabled={Boolean(lease?.controlling)} />
+ {showMouseButtons && lease?.controlling ? <RemoteDesktopMouseControls send={send}
+ bottom={toolbarSize.height} right={0} compact labels={{ left: t("remoteDesktop.leftClick"),
+ right: t("remoteDesktop.rightClick"), wheel: t("remoteDesktop.mouseWheel") }} /> : null}
+ </View>
+ ) : null}
{!keyboard && (
<Animated.View
key={landscape ? "landscape-toolbar" : "portrait-toolbar"}
@@ -2975,10 +3014,25 @@ export function RemoteDesktopSession({
paddingBottom: Math.max(spacing.sm, insets.bottom),
}),
},
+ tableRegion && { left: foldControls.x, right: undefined, width: foldControls.width,
+ bottom: geometry.height - foldControls.y - foldControls.height, paddingBottom: spacing.sm },
+ systemSideRail && {
+ left: toolbarOnLeft ? 0 : undefined,
+ right: toolbarOnLeft ? undefined : 0,
+ width: sideRailWidth,
+ // Leave room for the system clock/signal and the 44pt Back control.
+ top: sideRailTop + navigationChrome.target + spacing.lg,
+ bottom: insets.bottom,
+ paddingLeft: 0,
+ paddingRight: 0,
+ paddingBottom: 0,
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
]}
>
<RemoteDesktopToolbar
- landscape={landscape}
+ landscape={landscape || systemSideRail}
onWorkspaceLeft={
caps?.workspaceNavigation
? () => workspaceAction("workspaceLeft")
@@ -3065,11 +3119,16 @@ export function RemoteDesktopSession({
// occupying the corner, not a centered island. Android left
// insets are an unsafe strip (cutout/curve), not an island.
left: landscape
- ? (Platform.OS === "ios" && insets.top === 0 ? 0 : insets.left) +
+ ? (Platform.OS === "ios" && !geometry.reservedRegionsSupported && insets.top === 0 ? 0 : insets.left) +
spacing.lg +
(Platform.OS === "ios" ? spacing.xs : 0)
: edgePadding.paddingLeft + spacing.lg,
},
+ systemSideRail && {
+ top: sideRailTop,
+ left: windowSize.width - (sideRailWidth + navigationChrome.target) / 2,
+ width: navigationChrome.target,
+ },
]}
>
<RemoteDesktopBackButton
@@ -3096,6 +3155,9 @@ export function RemoteDesktopSession({
? Math.max(spacing.sm, insets.bottom)
: spacing.xs,
},
+ foldLayout && { position: 'absolute', left: foldControls.x, width: foldControls.width,
+ bottom: geometry.height - foldControls.y - foldControls.height,
+ maxHeight: foldControls.height, paddingLeft: spacing.xs, paddingRight: spacing.sm, paddingBottom: 0 },
]}
>
<View style={styles.keyboardHeader}>
@@ -3245,7 +3307,7 @@ export function RemoteDesktopSession({
</View>
<ScrollView
testID="remoteDesktop.keyPageViewport"
- style={{ maxHeight: landscape ? 156 : 300 }}
+ style={{ flexShrink: 1, maxHeight: landscape ? 156 : 300 }}
keyboardShouldPersistTaps="always"
>
<View style={styles.tools}>
diff --git a/apps/mobile/src/remote-desktop/__tests__/nativeChrome.test.tsx b/apps/mobile/src/remote-desktop/__tests__/nativeChrome.test.tsx
index c2dcc17792..61796d5399 100644
--- a/apps/mobile/src/remote-desktop/__tests__/nativeChrome.test.tsx
+++ b/apps/mobile/src/remote-desktop/__tests__/nativeChrome.test.tsx
@@ -2,6 +2,7 @@
import { act, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { expect, it, vi } from "vitest";
+import { frame } from "@expo/ui/swift-ui/modifiers";
import {
RemoteDesktopPanel,
RemoteDesktopToolbar,
@@ -88,7 +89,7 @@ vi.mock("@expo/ui/swift-ui/modifiers", () =>
"presentationDetents",
"presentationDragIndicator",
]
- .map((name) => [name, (value: unknown) => ({ name, value })])
+ .map((name) => [name, vi.fn((value: unknown) => ({ name, value }))])
.concat([
["shapes", { capsule: vi.fn(), circle: vi.fn(), rectangle: vi.fn() }],
] as any),
@@ -115,6 +116,7 @@ vi.mock("react-native-safe-area-context", () => ({
useSafeAreaInsets: () => state.safe,
}));
vi.mock("@/theme", () => ({
+ navigationChrome: { target: 44, clear: { dark: { foreground: '#FFFFFF', scrim: 'rgba(0, 0, 0, 0.35)', selected: 'rgba(255, 255, 255, 0.18)' }, light: { foreground: '#000000', scrim: 'rgba(255, 255, 255, 0.35)', selected: 'rgba(0, 0, 0, 0.10)' } } },
iconSize: { action: 24 },
typeScale: { body: 16, caption: 12 },
iconStroke: { regular: 2 },
@@ -212,7 +214,7 @@ it.each([false, true])(
expect(v.host.querySelectorAll("button")).toHaveLength(5);
const surface = v.host.firstElementChild as HTMLElement;
expect(landscape ? surface.style.height : surface.style.width).toBe(
- "228px",
+ "220px",
);
expect(
v.host.querySelector('[data-testid="remoteDesktop.showDesktop"]'),
@@ -316,8 +318,8 @@ it("anchors the popover to the centered rail and opens inward after either rotat
v.render(<RemoteDesktopPanel {...props} toolbarOnLeft={islandRight} />);
const anchor = v.host.firstElementChild as HTMLElement;
expect(anchor.style.top).toBe("102.5px");
- expect(anchor.style.left).toBe(islandRight ? "20px" : "");
- expect(anchor.style.right).toBe(islandRight ? "" : "20px");
+ expect(anchor.style.left).toBe(islandRight ? "16px" : "");
+ expect(anchor.style.right).toBe(islandRight ? "" : "16px");
expect(state.presentation.attachmentAnchor).toBe(
islandRight ? "trailing" : "leading",
);
@@ -329,3 +331,22 @@ it("anchors the popover to the centered rail and opens inward after either rotat
expect((v.host.firstElementChild as HTMLElement).style.top).toBe("80.5px");
v.close();
});
+
+it("offers a useful ideal popover height without forcing that height on a smaller presentation", () => {
+ vi.mocked(frame).mockClear();
+ state.safe = { top: 0, bottom: 21, left: 62, right: 0 };
+ const v = mount(
+ <RemoteDesktopPanel landscape topInset={0} title="Operations" caption="Computer" onClose={vi.fn()}>
+ <span>Controls</span>
+ </RemoteDesktopPanel>,
+ );
+ const frames = vi.mocked(frame).mock.calls.map(([value]) => value);
+ // The RN scroll view has no intrinsic preferred height. Only a maximum
+ // collapses it; a fixed height instead overflows the system popover bounds.
+ expect(frames).toContainEqual({ minHeight: 44, idealHeight: 365, maxHeight: 365 });
+ expect(frames.filter((value) => value.height !== undefined)).toEqual([
+ { width: 44, height: 44 },
+ ]);
+ expect(v.host.textContent).toContain("Controls");
+ v.close();
+});
diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
index 4125415f7f..ff72f9be30 100644
--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
@@ -1,3 +1,5 @@
+import { GeometryContext } from '@/platform/AdaptiveWindowContext';
+import type { WindowGeometry } from '@/platform/windowGeometry';
// @vitest-environment jsdom
import {
act,
@@ -16,6 +18,8 @@ import { AppState } from "react-native";
import { goBackGuarded } from "@/utils/backGuard";
import AsyncStorage from "@react-native-async-storage/async-storage";
+vi.mock('expo-blur', async () => ({ BlurView: (await import('react-native')).View }));
+
vi.mock("react-native-reanimated", async () => {
const { View } = await import("react-native");
return { default: { View } };
@@ -66,6 +70,7 @@ vi.mock("../usePictureInPicturePreference", () => ({
const fixture = vi.hoisted(() => ({
nativeMedia: false,
+ iosVersion: 26,
pipEnabled: false,
nativeReceive: vi.fn(async (_message: object) => {}),
nativeInput: vi.fn(async (_message: object) => true),
@@ -96,6 +101,7 @@ const fixture = vi.hoisted(() => ({
reload: vi.fn(),
message: null as null | ((e: unknown) => void),
size: { width: 390, height: 844 },
+ displaySize: null as { width: number; height: number } | null,
canControl: true,
systemAudio: false,
playback: vi.fn(async (_enabled: boolean) => {}),
@@ -156,9 +162,11 @@ vi.mock("react-native", async () => {
return { remove() {} };
},
},
- Dimensions: { get: () => fixture.size },
+ Dimensions: { get: (kind: string) => kind === "screen" ? fixture.displaySize ?? fixture.size : fixture.size },
useWindowDimensions: () => fixture.size,
Platform: {
+ get Version() { return fixture.iosVersion; },
+ isPad: false,
get OS() {
return fixture.platform;
},
@@ -375,6 +383,7 @@ beforeEach(async () => {
() => fixture.finishBackgroundTransition,
);
fixture.nativeMedia = false;
+ fixture.iosVersion = 26;
fixture.pipEnabled = false;
fixture.nativeReceive.mockReset().mockResolvedValue(undefined);
fixture.nativeInput.mockReset().mockResolvedValue(true);
@@ -398,6 +407,7 @@ beforeEach(async () => {
fixture.canControl = true;
fixture.trickleIce = false;
fixture.size = { width: 390, height: 844 };
+ fixture.displaySize = null;
fixture.openLink.mockResolvedValue({});
fixture.apiFetch
.mockReset()
@@ -2217,7 +2227,7 @@ describe("remote desktop controls", () => {
act(() => button("keyboard").click());
act(() => button("computerKeyboard").click());
const style = fixture.views["remoteDesktop.keyPageViewport"].style;
- expect(style).toEqual({ maxHeight: landscape ? 156 : 300 });
+ expect(style).toEqual({ flexShrink: 1, maxHeight: landscape ? 156 : 300 });
act(() => button("functionKeys").click());
expect(fixture.views["remoteDesktop.keyPageViewport"].style).toEqual(
style,
@@ -2535,8 +2545,8 @@ describe("remote desktop controls", () => {
.filter((m) => m.type === "mouseButtons")
.at(-1),
).toMatchObject({
- leftInset: islandRight ? 68 : 62,
- rightInset: islandRight ? 62 : 68,
+ leftInset: 0,
+ rightInset: 0,
});
}
});
@@ -2673,6 +2683,25 @@ describe("remote desktop controls", () => {
host.querySelector('[data-testid="remoteDesktop.toolbarPosition"]'),
).not.toBe(firstToolbar);
});
+ it("keeps Android portrait fit when the IME shrinks the window, but follows real rotation", async () => {
+ fixture.platform = "android";
+ fixture.displaySize = { width: 390, height: 640 };
+ fixture.size = { width: 390, height: 616 };
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ expect(sent().find(message => message.type === "init")).toMatchObject({ fillHeight: false });
+ const viewer = host.querySelector('[data-testid="remoteDesktop.viewer"]');
+ for (const height of [300, 616, 280]) {
+ fixture.size = { width: 390, height };
+ act(() => root.render(<RemoteDesktopScreen />));
+ expect(sent().filter(message => message.type === "viewport").at(-1)).toMatchObject({ fillHeight: false });
+ expect(host.querySelector('[data-testid="remoteDesktop.viewer"]')).toBe(viewer);
+ }
+ fixture.displaySize = { width: 640, height: 390 };
+ fixture.size = { width: 640, height: 200 };
+ act(() => root.render(<RemoteDesktopScreen />));
+ expect(sent().filter(message => message.type === "viewport").at(-1)).toMatchObject({ fillHeight: true });
+ });
it("restores the portrait top inset while the native safe area still reports landscape", async () => {
await connect();
const topInset = () =>
@@ -2690,6 +2719,14 @@ describe("remote desktop controls", () => {
act(() => root.render(<RemoteDesktopScreen />));
expect(topInset()).toBe(59);
});
+ it('preserves a valid side safe area on a modern tall window', async () => {
+ fixture.iosVersion = 27;
+ fixture.size = { width: 600, height: 900 };
+ fixture.safe = { top: 0, bottom: 20, left: 60, right: 0 };
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ expect(sent().filter(message => message.type === 'mouseButtons').at(-1)?.topInset).toBe(0);
+ });
it("overlays landscape keyboards and includes their measured occlusion", async () => {
fixture.size = { width: 844, height: 390 };
act(() => root.render(<RemoteDesktopScreen />));
@@ -3744,6 +3781,66 @@ describe("remote desktop controls", () => {
takeover: true,
});
});
+ it('resends the upper-pane bounds whenever a folded viewer becomes ready', async () => {
+ fixture.size = { width: 900, height: 1400 };
+ const geometry: WindowGeometry = {
+ ...fixture.size, insets: { top: 80, left: 0, right: 0, bottom: 20 },
+ regularWidth: true, regularHeight: true, barEdge: 'none', reservedRegionsSupported: true,
+ regions: [{ kind: 'division', x: 0, y: 680, width: 900, height: 30 }],
+ };
+ act(() => root.render(<GeometryContext.Provider value={geometry}><RemoteDesktopScreen /></GeometryContext.Provider>));
+ await connect();
+ fixture.post.mockClear();
+ // On reload the WebView loses all JS state even though React geometry and
+ // the active lease have not changed. Do not rely on a lease update to resend.
+ await act(async () => fixture.message!({ nativeEvent: { data: '{"type":"ready"}' } }));
+ expect(sent()).toContainEqual(expect.objectContaining({
+ type: 'mouseButtons', fitToInsets: true, topInset: 80, bottomInset: 720,
+ }));
+ });
+ it('folding and unfolding preserve the viewer and control lease', async () => {
+ const geometry: WindowGeometry = {
+ width: 900, height: 700, insets: { top: 0, left: 0, right: 60, bottom: 20 },
+ regularWidth: true, regularHeight: true, barEdge: 'right', regions: [], reservedRegionsSupported: true,
+ };
+ fixture.size = { width: 900, height: 700 };
+ const renderGeometry = (g: WindowGeometry) => act(() => root.render(
+ <GeometryContext.Provider value={g}><RemoteDesktopScreen /></GeometryContext.Provider>,
+ ));
+ renderGeometry(geometry);
+ await connect();
+ const rail = Object.assign({}, ...fixture.views['remoteDesktop.toolbarPosition'].style.flat(Infinity).filter(Boolean));
+ expect(rail).toMatchObject({ right: 0, left: undefined, width: 72, paddingRight: 0, alignItems: 'center' });
+ const backStyle = Object.assign({}, ...fixture.views['remoteDesktop.backPosition'].style.flat(Infinity).filter(Boolean));
+ expect(backStyle).toMatchObject({ top: 120, left: 842, width: 44 });
+ act(() => fixture.views['remoteDesktop.toolbarPosition'].onLayout({
+ nativeEvent: { layout: { width: 72, height: 300 } },
+ }));
+ expect(sent().filter(m => m.type === 'mouseButtons').at(-1)).toMatchObject({ rightInset: 0 });
+ // Rotating to the opposite landscape must not send custom chrome to the left.
+ renderGeometry({ ...geometry, barEdge: 'left', insets: { ...geometry.insets, left: 60, right: 0 } });
+ const rotatedRail = Object.assign({}, ...fixture.views['remoteDesktop.toolbarPosition'].style.flat(Infinity).filter(Boolean));
+ const rotatedBack = Object.assign({}, ...fixture.views['remoteDesktop.backPosition'].style.flat(Infinity).filter(Boolean));
+ expect(rotatedRail).toMatchObject({ right: 0, left: undefined, width: 60, alignItems: 'center' });
+ expect(rotatedBack).toMatchObject({ left: 848, width: 44 });
+ expect(sent().filter(m => m.type === 'mouseButtons').at(-1)).toMatchObject({ rightInset: 0 });
+ renderGeometry({ ...geometry, barEdge: 'none' });
+ const noPreferredEdge = Object.assign({}, ...fixture.views['remoteDesktop.backPosition'].style.flat(Infinity).filter(Boolean));
+ expect(noPreferredEdge).toMatchObject({ left: 842, width: 44 });
+ const viewerNode = host.querySelector('[data-testid="remoteDesktop.viewer"]');
+ const starts = requests().filter(r => r.op === 'start').length;
+ const stops = requests().filter(r => r.op === 'stop').length;
+ renderGeometry({ ...geometry, regions: [{ kind: 'division', x: 0, y: 300, width: 900, height: 30 }] });
+ expect(sent().filter(m => m.type === 'mouseButtons').at(-1)).toMatchObject({
+ fitToInsets: true, topInset: 0, bottomInset: 400,
+ });
+ expect(host.querySelector('[data-testid="remoteDesktop.viewer"]')).toBe(viewerNode);
+ renderGeometry(geometry);
+ expect(sent().filter(m => m.type === 'mouseButtons').at(-1)).toMatchObject({ fitToInsets: false });
+ expect(host.querySelector('[data-testid="remoteDesktop.viewer"]')).toBe(viewerNode);
+ expect(requests().filter(r => r.op === 'start')).toHaveLength(starts);
+ expect(requests().filter(r => r.op === 'stop')).toHaveLength(stops);
+ });
it("rotation preserves the viewer and control lease", async () => {
await connect();
expect(button("back")).not.toBeNull();
diff --git a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts b/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
index 1a0d798c2d..3923916e50 100644
--- a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
+++ b/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
@@ -268,9 +268,9 @@ describe("native media overlay", () => {
expect(viewport()).toMatchObject({ fillHeight: false });
v.send({ type: "nativeVideo", epoch: "native", active: true });
v.send({ type: "viewport", fillHeight: true });
- expect(viewport()).toMatchObject({ fillHeight: true });
+ expect(viewport()).toMatchObject({ fillHeight: false });
v.send({ type: "fit" });
- expect(viewport()).toMatchObject({ fillHeight: true });
+ expect(viewport()).toMatchObject({ fillHeight: false });
expect(v.elements.bg.style.display).toBe("none");
v.send({ type: "viewport", fillHeight: false });
expect(viewport()).toMatchObject({ fillHeight: false });
@@ -296,6 +296,46 @@ describe("native media overlay", () => {
});
describe("remote desktop viewport", () => {
+ it('maps lower-pane relative motion against the upper video viewport and rejects invalid input', () => {
+ const v = viewer();
+ v.elements.stage.clientWidth = 800;
+ v.elements.stage.clientHeight = 400;
+ v.send({ type: 'init', epoch: 'fold', width: 1600, height: 800 });
+ v.send({ type: 'control', enabled: true });
+ v.send({ type: 'mouseButtons', native: true, enabled: true, topInset: 0, bottomInset: 0 });
+ v.send({ type: 'nativeTouchpad', dx: 80, dy: 40 });
+ v.flush();
+ expect(v.messages.flatMap(m => m.events ?? [])).toContainEqual({ kind: 'move', x: 0.6, y: 0.6 });
+ v.ack();
+ const count = v.messages.flatMap(m => m.events ?? []).length;
+ v.send({ type: 'nativeTouchpad', dx: Number.NaN, dy: 20 });
+ v.flush();
+ expect(v.messages.flatMap(m => m.events ?? [])).toHaveLength(count);
+ v.send({ type: 'control', enabled: false });
+ const afterRelease = v.messages.flatMap(m => m.events ?? []).length;
+ v.send({ type: 'nativeTouchpad', dx: 80, dy: 40 });
+ v.flush();
+ expect(v.messages.flatMap(m => m.events ?? [])).toHaveLength(afterRelease);
+ });
+ it('allows touchpad taps with hidden buttons and does not release an active drag', () => {
+ const v = viewer();
+ v.send({ type: 'control', enabled: true });
+ v.send({ type: 'mouseButtons', native: true, enabled: false });
+ v.send({ type: 'nativeTouchpad', tap: true });
+ v.flush();
+ expect(v.messages.flatMap(m => m.events ?? [])).toEqual([
+ { kind: 'button', button: 0, down: true, x: 0.5, y: 0.5 },
+ { kind: 'button', button: 0, down: false, x: 0.5, y: 0.5 },
+ ]);
+ v.ack();
+ v.send({ type: 'mouseButtons', native: true, enabled: true });
+ v.send({ type: 'nativeMouse', control: 'left', event: 'pointerdown', id: 0, y: 100 });
+ v.ack();
+ const beforeTap = v.messages.flatMap(m => m.events ?? []).length;
+ v.send({ type: 'nativeTouchpad', tap: true });
+ v.flush();
+ expect(v.messages.flatMap(m => m.events ?? [])).toHaveLength(beforeTap);
+ });
it.each([0, 59])(
"fits between the top safe area (%s) and toolbar with correct touch coordinates",
(topInset) => {
@@ -503,10 +543,25 @@ describe("remote desktop viewport", () => {
{ kind: "scroll", dx: 0, dy: -30 },
]);
});
- it("fills landscape height for wide desktops and restores portrait fitting", () => {
- const v = viewer();
- v.elements.stage.clientWidth = 678;
- v.elements.stage.clientHeight = 402;
+ it('fits the folded desktop above the touchpad without shrinking the background stage', () => {
+ const v = viewer(false, true, true);
+ v.elements.stage.clientWidth = 900;
+ v.elements.stage.clientHeight = 1400;
+ v.send({ type: 'init', epoch: 'fold', width: 1920, height: 1080 });
+ v.send({ type: 'mouseButtons', fitToInsets: true, topInset: 80, bottomInset: 720 });
+ expect(v.messages.findLast(m => m.type === 'nativeViewport')).toMatchObject({
+ x: 0, y: 126.875, width: 900, height: 506.25,
+ });
+ expect(v.elements.stage.clientHeight).toBe(1400);
+ v.send({ type: 'mouseButtons', fitToInsets: false, topInset: 0, bottomInset: 0 });
+ expect(v.messages.findLast(m => m.type === 'nativeViewport')).toMatchObject({
+ x: 0, y: 446.875, width: 900, height: 506.25,
+ });
+ });
+ it.each([[678, 402], [1366, 1024]])("fits the complete desktop in landscape %sx%s and after rotation", (vw, vh) => {
+ const v = viewer(false, true, true);
+ v.elements.stage.clientWidth = vw;
+ v.elements.stage.clientHeight = vh;
v.send({
type: "init",
epoch: "landscape",
@@ -515,12 +570,16 @@ describe("remote desktop viewport", () => {
fillHeight: true,
});
for (const element of [v.elements.image, v.elements.video]) {
- expect(element.style.height).toBe("402px");
- expect(element.style.top).toBe("0px");
- expect(parseFloat(element.style.width)).toBeGreaterThan(678);
+ expect(parseFloat(element.style.width)).toBe(vw);
+ expect(parseFloat(element.style.height)).toBeCloseTo(vw * 1080 / 2560);
+ expect(parseFloat(element.style.left)).toBe(0);
+ expect(parseFloat(element.style.top)).toBeCloseTo((vh - vw * 1080 / 2560) / 2);
}
+ expect(v.messages.findLast(m => m.type === "nativeViewport")).toMatchObject({
+ fillHeight: false, width: vw, height: vw * 1080 / 2560,
+ });
v.send({ type: "fit" });
- expect(v.elements.image.style.top).toBe("0px");
+ expect(parseFloat(v.elements.image.style.top)).toBeGreaterThan(0);
v.elements.stage.clientWidth = 400;
v.elements.stage.clientHeight = 700;
v.send({ type: "viewport", fillHeight: false });
@@ -581,7 +640,7 @@ describe("remote desktop viewport", () => {
for (let i = 0; i < 30; i++) v.frame();
const width = v.elements.image.style.width;
expect(parseFloat(v.elements.image.style.height)).toBeCloseTo(
- 400 * scale,
+ (800 - 50 - 80) * 1080 / 1920 * scale,
);
// Removing the toolbar before the keyboard has a measured height must not shift the image.
const originalLeft = v.elements.image.style.left;
@@ -615,7 +674,7 @@ describe("remote desktop viewport", () => {
for (let i = 0; i < 30; i++) v.frame();
const image = v.elements.image.style;
expect(image.width).toBe(width);
- expect(parseFloat(image.height)).toBeCloseTo(400 * scale);
+ expect(parseFloat(image.height)).toBeCloseTo((800 - 50 - 80) * 1080 / 1920 * scale);
expect(
parseFloat(image.left) + cursorX * parseFloat(image.width),
).toBeCloseTo(expectedCursorX);
@@ -653,6 +712,12 @@ describe("remote desktop viewport", () => {
rightInset: 80,
});
const before = { ...v.elements.image.style };
+ const expectUnchanged = () => {
+ for (const key of ["left", "top", "width", "height"]) {
+ expect(parseFloat(v.elements.image.style[key])).toBeCloseTo(parseFloat(before[key]));
+ }
+ expect(v.elements.image.style.visibility).toBe(before.visibility);
+ };
for (let i = 0; i < 2; i++) {
v.send({
type: "mouseButtons",
@@ -668,10 +733,10 @@ describe("remote desktop viewport", () => {
leftInset: 50,
rightInset: 80,
});
- expect(v.elements.image.style).toEqual(before);
+ expectUnchanged();
v.blur();
for (let j = 0; j < 30; j++) v.frame();
- expect(v.elements.image.style).toEqual(before);
+ expectUnchanged();
}
});
it("initializes when the native engine cannot serialize function source", () => {
@@ -1112,7 +1177,7 @@ describe("remote desktop three-segment backdrop", () => {
it("hides the backdrop when the fitted picture covers the whole stage", () => {
const v = landscapeViewer();
v.bgDraws.length = 0;
- v.send({ type: "init", epoch: "bg-wide", width: 2560, height: 1080 });
+ v.send({ type: "init", epoch: "bg-wide", width: 1748, height: 804 });
v.send({ type: "viewport", fillHeight: true });
v.frame();
expect(v.elements.bg.style.display).toBe("none");
diff --git a/apps/mobile/src/remote-desktop/foldDesktopLayout.ts b/apps/mobile/src/remote-desktop/foldDesktopLayout.ts
new file mode 100644
index 0000000000..2aeae3dcc8
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/foldDesktopLayout.ts
@@ -0,0 +1,21 @@
+import { controlRegion, windowDivision, type WindowGeometry } from '@/platform/windowGeometry';
+
+/** Both media layers receive this same rect. Software keyboard occlusion never changes the lease. */
+export function foldDesktopLayout(g: WindowGeometry, keyboardBottom: number, panelHeight: number, keyboard: boolean) {
+ const split = windowDivision(g);
+ if (!split || split.first.width < 160 || split.second.width < 160 || split.first.height < 160 || split.second.height < 160) return null;
+ const bottom = g.height - Math.max(0, keyboardBottom);
+ let controls = controlRegion(g);
+ controls = { ...controls, height: Math.max(0, Math.min(controls.height, bottom - controls.y)) };
+ // A tall system keyboard may cover the lower half. Keep custom controls above
+ // the fold in that case, and fit the video above those controls in the same region.
+ if (keyboard && controls.height < 140 && split.axis === 'horizontal') {
+ controls = { ...split.first, height: Math.max(0, Math.min(split.first.height, bottom - split.first.y)) };
+ }
+ const panel = keyboard ? Math.min(Math.max(0, panelHeight), controls.height) : 0;
+ const panelTop = controls.y + controls.height - panel;
+ const overlappingColumns = controls.x < split.first.x + split.first.width && controls.x + controls.width > split.first.x;
+ const mediaBottom = keyboard && overlappingColumns ? Math.min(bottom, panelTop) : bottom;
+ const media = { ...split.first, height: Math.max(1, Math.min(split.first.height, mediaBottom - split.first.y)) };
+ return { media, controls };
+}
diff --git a/apps/mobile/src/session/AccountSwitcherSheet.tsx b/apps/mobile/src/session/AccountSwitcherSheet.tsx
index 1e0f09de67..f9f62c28ab 100644
--- a/apps/mobile/src/session/AccountSwitcherSheet.tsx
+++ b/apps/mobile/src/session/AccountSwitcherSheet.tsx
@@ -1,9 +1,10 @@
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import {
ActivityIndicator,
Alert,
Image,
+ Platform,
Pressable,
StyleSheet,
View,
@@ -14,10 +15,13 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useAuth } from '@/auth/AuthContext';
import { Text } from '@/components/AppText';
+import { hasNativeLoginButtons, LoginNativeButton } from '@/components/LoginNativeButton';
import { formatRemoteError } from '@/device-link/remoteStatus';
import { computeContextSheetSnapHeights, type ContextSheetSnap } from '@/session/contextSheetModel';
import { SheetModal } from '@/session/SheetModal';
import { SheetSurface } from '@/session/SheetSurface';
+import { ComposerSheet } from '@/session/ComposerSheet';
+import type { SheetSurfaceProps } from '@/session/SheetSurface';
import { presentSavedAccount } from '@/session/accountSwitcherPresentation';
import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import {
@@ -98,7 +102,13 @@ export function AccountSwitcherSheet({
});
};
- const footer = (
+ const footer = hasNativeLoginButtons ? (
+ <LoginNativeButton label={t('devices.list.accounts.add')} height={48} fontSize={typeScale.body}
+ disabled={switchingKey !== null} onPress={() => confirmBoundary(onAddAccount)}
+ testID="accountSwitcher.addAccount" showLabel artworkSize={iconSize.md}>
+ <UserPlus color={colors.textPrimary} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ </LoginNativeButton>
+ ) : (
<Pressable
accessibilityRole="button"
disabled={switchingKey !== null}
@@ -119,18 +129,13 @@ export function AccountSwitcherSheet({
);
return (
- <SheetModal
- backdropTestID="accountSwitcher.backdrop"
- onBackdropPress={onClose}
+ <AccountSwitcherContainer
+ onClose={onClose}
onClosed={onClosed}
- onRequestClose={onClose}
visible={visible}
- >
- <SheetSurface
bottomInset={insets.bottom}
footer={footer}
heights={heights}
- onClose={onClose}
onSnapChange={setSnap}
snap={snap}
testID="accountSwitcher.sheet"
@@ -141,6 +146,18 @@ export function AccountSwitcherSheet({
const { imageUrl, isOrg, subtitle, title } =
presentSavedAccount(account);
const switching = switchingKey === account.accountKey;
+ if (hasNativeLoginButtons) return <LoginNativeButton key={account.accountKey}
+ label={title} subtitle={subtitle ?? undefined} height={64} fontSize={typeScale.body}
+ accessibilityLabel={subtitle ? `${title}, ${subtitle}` : title}
+ onPress={() => switchTo(account.accountKey)} variant="text" showLabel artworkSize={44}
+ disabled={account.isCurrent || switchingKey !== null} busy={switching}
+ selected={account.isCurrent} testID={`accountSwitcher.account.${account.membershipId}`}>
+ <View style={styles.avatar}>
+ {imageUrl ? <Image source={{ uri: imageUrl }} style={styles.avatarImage} />
+ : isOrg ? <Building2 color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ : <UserRound color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />}
+ </View>
+ </LoginNativeButton>;
return (
<Pressable
accessibilityLabel={subtitle ? `${title}, ${subtitle}` : title}
@@ -196,11 +213,23 @@ export function AccountSwitcherSheet({
<Text style={styles.error}>{t('devices.list.accounts.syncFailed')}</Text>
) : null}
</View>
- </SheetSurface>
- </SheetModal>
+ </AccountSwitcherContainer>
);
}
+function AccountSwitcherContainer({ visible, onClosed, children, ...surface }: SheetSurfaceProps & {
+ visible: boolean; onClosed?: () => void; children: ReactNode;
+}) {
+ if (Platform.OS === 'ios') return <ComposerSheet
+ visible={visible} onClose={surface.onClose} onClosed={onClosed}
+ title={surface.title} footer={surface.footer} testID={surface.testID}
+ >{children}</ComposerSheet>;
+ return <SheetModal visible={visible} onRequestClose={surface.onClose}
+ onBackdropPress={surface.onClose} onClosed={onClosed} backdropTestID="accountSwitcher.backdrop">
+ <SheetSurface {...surface}>{children}</SheetSurface>
+ </SheetModal>;
+}
+
const makeStyles = (colors: ThemeColors) =>
StyleSheet.create({
list: {
diff --git a/apps/mobile/src/session/ComposerSheet.ios.tsx b/apps/mobile/src/session/ComposerSheet.ios.tsx
index 59ee11e433..b0ede23e52 100644
--- a/apps/mobile/src/session/ComposerSheet.ios.tsx
+++ b/apps/mobile/src/session/ComposerSheet.ios.tsx
@@ -26,7 +26,7 @@ import {
scrollContentBackground,
} from "@expo/ui/swift-ui/modifiers";
import { useTranslation } from "react-i18next";
-import { ScrollView, View } from "react-native";
+import { ScrollView, View, useWindowDimensions } from "react-native";
import { useTheme } from "@/theme";
import type { ComposerSheetProps } from "./ComposerSheet";
@@ -48,6 +48,10 @@ export function ComposerSheet({
}: ComposerSheetProps) {
const { mode, colors } = useTheme();
const { t } = useTranslation();
+ const { width, height } = useWindowDimensions();
+ // UIKit disables the medium detent in compact-height landscape. Never bind
+ // selection to an unavailable detent, including after rotating an open sheet.
+ const landscape = width > height;
return (
<Host
colorScheme={mode}
@@ -64,7 +68,7 @@ export function ComposerSheet({
>
<Group
modifiers={[
- presentationDetents(["medium", "large"], { selection: "medium" }),
+ presentationDetents(landscape ? ["large"] : ["medium", "large"], { selection: landscape ? "large" : "medium" }),
presentationDragIndicator("visible"),
]}
>
diff --git a/apps/mobile/src/session/ContextSheet.ios.tsx b/apps/mobile/src/session/ContextSheet.ios.tsx
index 4013cfc8fd..9a59e54722 100644
--- a/apps/mobile/src/session/ContextSheet.ios.tsx
+++ b/apps/mobile/src/session/ContextSheet.ios.tsx
@@ -1,3 +1,4 @@
+import { useNativeGlassButtonStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";
import { iconSize, useTheme } from '@/theme';
import { ComposerNativeSection as Section } from './ComposerNativeSection';
import {
@@ -116,12 +117,13 @@ export function ContextSheetRow(props: ContextSheetRowProps) {
);
}
export function ContextSheetFooterButton(props: ContextSheetFooterButtonProps) {
+ const glassStyle = useNativeGlassButtonStyle({ prominent: true });
return (
<Button
onPress={props.onPress}
testID={props.testID}
modifiers={[
- buttonStyle("glassProminent"),
+ ...glassStyle,
disable(!!props.disabled || !!props.busy),
frame({ maxWidth: Infinity, minHeight: 44 }),
]}
diff --git a/apps/mobile/src/session/ContextSheetGoalView.ios.tsx b/apps/mobile/src/session/ContextSheetGoalView.ios.tsx
index 5c52512f3c..e68e7673b4 100644
--- a/apps/mobile/src/session/ContextSheetGoalView.ios.tsx
+++ b/apps/mobile/src/session/ContextSheetGoalView.ios.tsx
@@ -1,3 +1,4 @@
+import { useNativeGlassButtonStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";
import { useState, type ComponentProps } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, DisclosureGroup, Picker, ProgressView, Text, TextField, useNativeState } from '@expo/ui/swift-ui';
@@ -12,6 +13,7 @@ export { GOAL_STATUS_LABEL, goalReasonText, goalStatusLabel } from './goalStatus
export function ContextSheetGoalCreateForm({ busy, disabled = false, disabledHint, error, initial, onSetGoal, testID }: ComponentProps<typeof GoalCreateForm>) {
const { t } = useTranslation();
const { colors } = useTheme();
+ const glassStyle = useNativeGlassButtonStyle({ prominent: true });
const text = useNativeState(initial?.objective ?? '');
const [objective, setObjective] = useState(initial?.objective ?? '');
const [limits, setLimits] = useState<MobileGoalLimitsInput>(initial?.limits ?? { maxTurns: null, budgetTokens: null, noProgressLimit: 3 });
@@ -47,7 +49,7 @@ export function ContextSheetGoalCreateForm({ busy, disabled = false, disabledHin
{error || (disabled && disabledHint) ? <Section><Text modifiers={[foregroundStyle(error ? colors.errorText : colors.textSecondary)]}>{error || disabledHint}</Text></Section> : null}
<Section>
<Button onPress={submit} testID="contextSheet.goalStartButton" modifiers={[
- buttonStyle('glassProminent'), frame({ maxWidth: Infinity, minHeight: 44 }),
+ ...glassStyle, frame({ maxWidth: Infinity, minHeight: 44 }),
disable(busy || disabled || !objective.trim()),
...(disabled && disabledHint ? [accessibilityHint(disabledHint)] : []),
accessibilityLabel(t('interaction.contextSheet.startGoal')),
diff --git a/apps/mobile/src/session/HomeChromeDrawer.tsx b/apps/mobile/src/session/HomeChromeDrawer.tsx
index b5ebc075cc..34282691f8 100644
--- a/apps/mobile/src/session/HomeChromeDrawer.tsx
+++ b/apps/mobile/src/session/HomeChromeDrawer.tsx
@@ -281,7 +281,7 @@ export function HomeChromeDrawer({
{
paddingBottom: insets.bottom,
paddingLeft: insets.left,
- paddingTop: insets.top,
+ paddingTop: insets.top + spacing.xl,
width: panelWidth,
},
panelStyle,
diff --git a/apps/mobile/src/session/HomeGlassMenuPanel.tsx b/apps/mobile/src/session/HomeGlassMenuPanel.tsx
index 57ffa362c9..242dfbb767 100644
--- a/apps/mobile/src/session/HomeGlassMenuPanel.tsx
+++ b/apps/mobile/src/session/HomeGlassMenuPanel.tsx
@@ -5,8 +5,10 @@
* 无系统玻璃时回退 BlurBackdrop + sheet 色卡片。
*/
import { GlassView } from 'expo-glass-effect';
+import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';
+import { controlRegion } from '@/platform/windowGeometry';
import type { ReactNode } from 'react';
-import { Animated, Modal, Pressable, StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
+import { Animated, Modal, Pressable, ScrollView, StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
import { BlurBackdrop } from '@/session/BlurBackdrop';
import { useLiquidGlassAvailable } from '@/session/useLiquidGlassAvailable';
import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
@@ -30,7 +32,7 @@ export function HomeGlassMenuPanel({
return (
<Pressable
onPress={() => undefined}
- style={[styles.shell, liquidGlass ? styles.shellGlass : styles.shellSolid, style]}
+ style={[styles.shell, liquidGlass ? styles.shellGlass : styles.shellSolid, style, { maxWidth: '100%' }]}
testID={testID}
>
{liquidGlass ? (
@@ -71,16 +73,20 @@ export function HomeMenuScrim({
visible: boolean;
}) {
const styles = useThemedStyles(makeStyles);
+ const geometry = useAdaptiveWindow();
+ const region = controlRegion(geometry);
return (
- <Modal animationType="none" onShow={onShow} transparent visible={visible} onRequestClose={onClose}>
+ <Modal supportedOrientations={["portrait", "portrait-upside-down", "landscape-left", "landscape-right"]} animationType="none" onShow={onShow} transparent visible={visible} onRequestClose={onClose}>
<View style={styles.layer}>
<Animated.View pointerEvents="none" style={[styles.dim, { opacity: progress }]} />
<Pressable
onPress={onClose}
- style={[styles.hit, { paddingTop: topOffset }]}
+ style={[styles.hit, { paddingTop: Math.max(region.y, Math.min(topOffset, region.y + region.height - 100)),
+ paddingLeft: region.x + spacing.lg, paddingRight: geometry.width - region.x - region.width + spacing.lg,
+ paddingBottom: geometry.height - region.y - region.height }]}
testID={backdropTestID}
>
- {children}
+ <ScrollView keyboardShouldPersistTaps="handled" showsVerticalScrollIndicator={false}>{children}</ScrollView>
</Pressable>
</View>
</Modal>
@@ -102,6 +108,7 @@ const makeStyles = (colors: ThemeColors) =>
borderWidth: StyleSheet.hairlineWidth,
},
glass: {
+ maxWidth: '100%',
borderRadius: radius.container,
overflow: 'hidden',
width: MENU_WIDTH,
diff --git a/apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx b/apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx
new file mode 100644
index 0000000000..162abaa591
--- /dev/null
+++ b/apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx
@@ -0,0 +1,11 @@
+import type { ComponentProps } from "react";
+import { NativeChromeButton } from "@/platform/chrome/NativeChromeButton.ios";
+import type { HomeHeaderGlassButton as FallbackButton } from "./HomeHeaderGlassButton";
+
+/** Preserve the existing artwork inside the same native glass button as Back. */
+export function HomeHeaderGlassButton({
+ accessibilityLabel,
+ ...props
+}: ComponentProps<typeof FallbackButton>) {
+ return <NativeChromeButton {...props} label={accessibilityLabel} />;
+}
diff --git a/apps/mobile/src/session/HomeHeaderGlassButton.tsx b/apps/mobile/src/session/HomeHeaderGlassButton.tsx
index 6b4e117f19..a41c4778ab 100644
--- a/apps/mobile/src/session/HomeHeaderGlassButton.tsx
+++ b/apps/mobile/src/session/HomeHeaderGlassButton.tsx
@@ -6,20 +6,27 @@ import type { ReactNode } from "react";
import { Pressable, StyleSheet, View } from "react-native";
import { useLiquidGlassAvailable } from "@/session/useLiquidGlassAvailable";
import { useTheme, useThemedStyles, type ThemeColors } from "@/theme";
-import { radius } from "@/theme/tokens";
+import { navigationChrome, radius } from "@/theme/tokens";
export function HomeHeaderGlassButton({
accessibilityLabel,
children,
onPress,
testID,
+ disabled = false,
+ prominent = false,
+ size = navigationChrome.target,
}: {
accessibilityLabel: string;
children: ReactNode;
onPress(): void;
testID: string;
+ disabled?: boolean;
+ prominent?: boolean;
+ size?: number;
+ artworkSize?: number;
}) {
- const { colors, mode } = useTheme();
+ const { mode, colors } = useTheme();
const styles = useThemedStyles(makeStyles);
const liquidGlass = useLiquidGlassAvailable();
@@ -27,8 +34,10 @@ export function HomeHeaderGlassButton({
<Pressable
accessibilityLabel={accessibilityLabel}
accessibilityRole="button"
+ disabled={disabled}
+ accessibilityState={{ disabled }}
onPress={onPress}
- style={({ pressed }) => [styles.hit, pressed && styles.pressed]}
+ style={({ pressed }) => [styles.hit, { width: size, height: size }, prominent && { backgroundColor: colors.cta, borderRadius: radius.pill }, pressed && styles.pressed, disabled && styles.disabled]}
testID={testID}
>
{liquidGlass ? (
@@ -37,7 +46,6 @@ export function HomeHeaderGlassButton({
glassEffectStyle="regular"
isInteractive
style={styles.glass}
- tintColor={colors.surface}
>
<View pointerEvents="none" style={styles.iconSlot}>
{children}
@@ -54,8 +62,8 @@ const makeStyles = (_colors: ThemeColors) =>
StyleSheet.create({
hit: {
flexShrink: 0,
- height: 44,
- width: 44,
+ height: navigationChrome.target,
+ width: navigationChrome.target,
},
glass: {
alignItems: "center",
@@ -69,6 +77,7 @@ const makeStyles = (_colors: ThemeColors) =>
flex: 1,
justifyContent: "center",
},
+ disabled: { opacity: 0.46 },
pressed: {
opacity: 0.72,
},
diff --git a/apps/mobile/src/session/HomeListVisuals.tsx b/apps/mobile/src/session/HomeListVisuals.tsx
new file mode 100644
index 0000000000..31f864881d
--- /dev/null
+++ b/apps/mobile/src/session/HomeListVisuals.tsx
@@ -0,0 +1,244 @@
+import { useEffect, useRef, type ReactNode } from 'react';
+import { Animated, Easing, StyleSheet, View } from 'react-native';
+import { Archive, UsersRound, RadioTower, Pencil } from 'lucide-react-native';
+import { MobileVendorIcon } from '@/components/MobileVendorIcon';
+import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
+import { spacing, typeScale, lineHeight, fontWeight, iconSize, iconStroke } from '@/theme/tokens';
+import type { RemoteSessionListItem } from './sessionList';
+const HOME_SESSION_ROW_HEIGHT = 78;
+const HOME_SESSION_SINGLE_LINE_ROW_HEIGHT = 60;
+/** Shared by the full home list and its persistent, narrow task pane. */
+export function SessionStatusMark({
+ item,
+ running,
+ showDraftIndicator,
+}: {
+ item: RemoteSessionListItem;
+ running: boolean;
+ showDraftIndicator: boolean;
+}) {
+ const styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
+ const archived = item.session.status === 'archived';
+ const orcaLead = item.session.orcaRole === 'lead';
+ const attached = readBooleanField(item.session, 'attached') || readBooleanField(item.session, 'deviceLinkAttached');
+ // 用户拍板 2026-07-20(对齐桌面):running 一律 Thinking Orange(statusAccent)。
+ const glyphColor = running ? colors.statusAccent : colors.textTertiary;
+ return (
+ <View style={styles.sessionStatusMark}>
+ {archived ? (
+ <Archive color={colors.textTertiary} size={iconSize.lg} strokeWidth={iconStroke.thin} />
+ ) : orcaLead ? (
+ // 与桌面 SessionStatusIcon /「+」菜单协同项同款 UsersRound,不再用旧 Puzzle。
+ <SessionStatusPulse running={running}>
+ <UsersRound color={glyphColor} size={iconSize.action} strokeWidth={iconStroke.thin} />
+ </SessionStatusPulse>
+ ) : attached ? (
+ <SessionStatusPulse running={running}>
+ <RadioTower color={glyphColor} size={iconSize.lg} strokeWidth={iconStroke.thin} />
+ </SessionStatusPulse>
+ ) : (
+ <MobileVendorIcon
+ color={glyphColor}
+ running={running}
+ // Claude 星标 logo 视觉重量偏小,+1px 光学补偿对齐 Codex 标(刻意非阶梯值)。
+ size={isClaudeCodeAgentKind(item.session.agentKind) ? 19 : iconSize.lg}
+ vendor={item.session.agentKind}
+ />
+ )}
+ {!archived && showDraftIndicator ? (
+ <View style={styles.sessionDraftIndicator}>
+ {/* 9px:Pencil 微徽标,徽标容器几何依赖(designTokenDiscipline ALLOWLIST 登记豁免)。 */}
+ <Pencil color={colors.textSecondary} size={9} strokeWidth={iconStroke.medium} />
+ </View>
+ ) : null}
+ </View>
+ );
+}
+
+function SessionStatusPulse({ children, running }: { children: ReactNode; running: boolean }) {
+ const opacity = useRef(new Animated.Value(running ? 0.3 : 1)).current;
+ useEffect(() => {
+ opacity.stopAnimation();
+ if (!running) {
+ opacity.setValue(1);
+ return;
+ }
+ opacity.setValue(0.3);
+ const loop = Animated.loop(
+ Animated.sequence([
+ Animated.timing(opacity, {
+ duration: 750,
+ easing: Easing.inOut(Easing.ease),
+ toValue: 1,
+ useNativeDriver: true,
+ }),
+ Animated.timing(opacity, {
+ duration: 750,
+ easing: Easing.inOut(Easing.ease),
+ toValue: 0.3,
+ useNativeDriver: true,
+ }),
+ ]),
+ );
+ loop.start();
+ return () => {
+ loop.stop();
+ };
+ }, [opacity, running]);
+
+ return <Animated.View style={{ opacity }}>{children}</Animated.View>;
+}
+
+
+function readBooleanField(value: unknown, key: string): boolean {
+ return !!value && typeof value === 'object' && (value as Record<string, unknown>)[key] === true;
+}
+function isClaudeCodeAgentKind(agentKind: string): boolean {
+ return agentKind === 'cc' || agentKind === 'claude-code';
+}
+
+export const homeListStyles = (colors: ThemeColors) => StyleSheet.create({
+ sessionListRow: {
+ alignItems: 'stretch',
+ backgroundColor: colors.surface,
+ flexDirection: 'row',
+ gap: spacing.md,
+ height: HOME_SESSION_ROW_HEIGHT,
+ paddingLeft: spacing.md,
+ },
+ sessionListRowSingleLine: {
+ height: HOME_SESSION_SINGLE_LINE_ROW_HEIGHT,
+ },
+ sessionListRowIndented: {
+ // 项目下属会话向右多缩进一档,让"隶属于该项目"在视觉上更明显
+ // (连同行内分割线一起右移,形成嵌套层级感)。
+ paddingLeft: spacing.md + spacing.lg,
+ },
+ sessionListRowDeepIndented: {
+ // 自动化组子行:比 indented 再深一档(缩进全部收在行内,滑动包装全宽才能贴屏边),
+ // 保证子行始终比组行(无论组行在 chats 还是项目组内)更深一层。
+ paddingLeft: spacing.md + spacing.lg * 2,
+ },
+ sessionIconCell: {
+ alignItems: 'center',
+ justifyContent: 'flex-start',
+ paddingTop: 22,
+ width: 24,
+ },
+ sessionIconCellSingleLine: {
+ justifyContent: 'center',
+ paddingTop: 0,
+ },
+ sessionListContent: {
+ borderBottomColor: colors.border,
+ borderBottomWidth: StyleSheet.hairlineWidth,
+ flex: 1,
+ justifyContent: 'center',
+ minWidth: 0,
+ paddingBottom: spacing.sm,
+ paddingRight: spacing.lg,
+ paddingTop: spacing.sm,
+ },
+ sessionListContentNoDivider: {
+ // 紧邻块(项目组 / 自动化组)边界的行不画自己的缩进线:块的全宽 border 已经是这根线,
+ // 两根 hairline 相邻会叠成一根明显更粗的线(即「项目组上边线偏粗」的根因)。
+ borderBottomWidth: 0,
+ },
+ sessionTitleRow: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ gap: spacing.sm,
+ height: 30,
+ },
+ sessionStatusMark: {
+ alignItems: 'center',
+ height: 24,
+ justifyContent: 'center',
+ overflow: 'visible',
+ position: 'relative',
+ width: 24,
+ },
+ sessionDraftIndicator: {
+ alignItems: 'center',
+ bottom: -3,
+ height: 12,
+ justifyContent: 'center',
+ position: 'absolute',
+ right: -3,
+ width: 12,
+ },
+ sessionTitle: {
+ color: colors.textPrimary,
+ flex: 1,
+ fontSize: typeScale.subtitle,
+ fontWeight: fontWeight.semibold,
+ lineHeight: lineHeight.listTitle,
+ minWidth: 0,
+ },
+ sessionPreviewRow: {
+ alignItems: 'flex-start',
+ flexDirection: 'row',
+ gap: spacing.sm,
+ height: lineHeight.subtitle,
+ },
+ sessionPreview: {
+ color: colors.textSecondary,
+ flex: 1,
+ fontSize: typeScale.code,
+ fontWeight: fontWeight.regular,
+ lineHeight: lineHeight.subtitle,
+ minWidth: 0,
+ },
+ sessionTrailingIcons: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ gap: spacing.sm,
+ justifyContent: 'flex-end',
+ minHeight: lineHeight.subtitle,
+ paddingTop: 3,
+ },
+ sessionTime: {
+ color: colors.textTertiary,
+ flexShrink: 0,
+ fontSize: typeScale.footnote,
+ fontWeight: fontWeight.regular,
+ lineHeight: lineHeight.body,
+ },
+ projectRow: {
+ alignItems: 'center',
+ backgroundColor: colors.surface,
+ flexDirection: 'row',
+ gap: 8,
+ minHeight: 56,
+ paddingLeft: spacing.md,
+ paddingRight: spacing.lg,
+ paddingVertical: spacing.sm,
+ },
+ projectLabel: {
+ alignItems: 'center',
+ flex: 1,
+ flexDirection: 'row',
+ gap: 6, // Desktop ProjectNode name / remote icon / machine label gap-1.5.
+ minWidth: 0,
+ },
+ projectTitle: {
+ color: colors.textPrimary,
+ flex: 1,
+ fontSize: typeScale.body,
+ fontWeight: fontWeight.medium,
+ lineHeight: lineHeight.listTitle,
+ minWidth: 0,
+ },
+ projectFolderTitle: {
+ flex: 0,
+ flexShrink: 1,
+ },
+ projectCount: {
+ color: colors.textTertiary,
+ fontSize: typeScale.footnote,
+ fontWeight: fontWeight.regular,
+ lineHeight: lineHeight.subtitle,
+ },
+});
+const makeStyles = homeListStyles;
diff --git a/apps/mobile/src/session/HomeNewTaskButton.tsx b/apps/mobile/src/session/HomeNewTaskButton.tsx
new file mode 100644
index 0000000000..d8f541c35d
--- /dev/null
+++ b/apps/mobile/src/session/HomeNewTaskButton.tsx
@@ -0,0 +1,22 @@
+import { View } from 'react-native';
+import { SquarePen } from 'lucide-react-native';
+import { useTranslation } from 'react-i18next';
+import { iconSize, iconStroke, useTheme } from '@/theme';
+import { HomeHeaderGlassButton } from './HomeHeaderGlassButton';
+
+const HOME_NEW_TASK_SIZE = 55;
+
+/** Shared home/detail floating action: keep the circle, artwork and placement together. */
+export function HomeNewTaskButton({ onPress, bottomInset, disabled = false }: {
+ onPress(): void; bottomInset: number; disabled?: boolean;
+}) {
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ return <View style={{ position: 'absolute', right: 20, bottom: 45 + bottomInset, width: HOME_NEW_TASK_SIZE, height: HOME_NEW_TASK_SIZE }}>
+ <HomeHeaderGlassButton accessibilityLabel={t('devices.list.a11y.newRemoteConversation')}
+ onPress={onPress} disabled={disabled} prominent size={HOME_NEW_TASK_SIZE} artworkSize={iconSize.xxl}
+ testID="home.newChatButton">
+ <SquarePen color={colors.ctaText} size={iconSize.xxl} strokeWidth={iconStroke.regular} />
+ </HomeHeaderGlassButton>
+ </View>;
+}
diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsx
new file mode 100644
index 0000000000..95ff8b7aa4
--- /dev/null
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@ -0,0 +1,4859 @@
+import { TaskTagDots } from '@/session/TaskTags';
+import { ResidentHomeList, useResidentHomeList } from './ResidentHomeList';
+import { HomeNewTaskButton } from './HomeNewTaskButton';
+import { useRetainedHomeState, getHomeViewSession } from './homeViewSession';
+import { rememberRecentTask } from './recentTasks';
+import { homeListStyles, SessionStatusMark } from '@/session/HomeListVisuals';
+import { useHeaderHeight } from "expo-router/react-navigation";
+import { SessionHeaderNativeBlur } from "@/session/SessionHeaderNativeControls";
+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 } 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,
+ Easing,
+ 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, type DeviceView, type PresenceSnapshot } from '@cindy/device-link';
+import {
+ Archive,
+ Check,
+ ChevronDown,
+ ChevronRight,
+ Ellipsis,
+ Folder,
+ FolderOpen,
+ Hammer,
+ LoaderCircle,
+ Menu,
+ Monitor,
+ MessagesSquare,
+ Lock,
+ Pin,
+ RefreshCw,
+ 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 { configureCollapseAnimation } from '@/utils/collapseAnimation';
+import { useGuardedPush } from '@/utils/useGuardedPush';
+import {
+ MainWindowActionGroup,
+ MainWindowEmptyState,
+ StatusDot,
+} from '@/components/MobilePrimitives';
+import { RemoteAccessGuide } from '@/components/RemoteAccessGuide';
+import { HomeChromeDrawer } from '@/session/HomeChromeDrawer';
+import { AccountSwitcherSheet } from '@/session/AccountSwitcherSheet';
+import { HomeChromeFrost } from '@/session/HomeChromeFrost';
+import { HomeGlassMenuPanel, HomeMenuScrim } from '@/session/HomeGlassMenuPanel';
+import { HomeHeaderGlassButton } from '@/session/HomeHeaderGlassButton';
+import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';
+import { HomeSearchBar } from '@/session/HomeSearchBar';
+import { HomeProjectMachineLabel } from '@/session/HomeProjectMachineLabel';
+import { buildHomeProjectMachineIdentities, type HomeProjectMachineIdentity } from '@/session/homeProjectMachineIdentity';
+import {
+ HomeNativeStackHeader,
+ NativePullDownMenu,
+ usesNativePullDownMenu,
+ usesNativeStackHeader,
+ usesSystemActionMenu,
+} from '@/platform/chrome';
+import {
+ buildHomeDisplayPullDownActions,
+ buildHomeScopePullDownActions,
+ parseHomeScopePullDownAction,
+ homeDisplayMenuPatch,
+ type HomeDisplayMenuKey,
+} from '@/session/homeChromeMenus';
+import { useConversationSearchFilterMenu } from '@/session/useConversationSearchFilterMenu';
+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,
+ serializeRemoteResourceTargets,
+ 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 {
+ connectionIssueHint,
+ connectionIssueTitle,
+ describeRemoteError,
+ formatRemoteError,
+} from '@/device-link/remoteStatus';
+import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
+import { ConnectionRecoveryProgress } from '@/components/ConnectionBanner';
+import { ConnectionNoticeOverlay, useDelayedConnectionNotice } from '@/components/ConnectionNoticeOverlay';
+import { resolveConnectionBannerVisibility, resolveConnectionBannerSyncActionVisibility, resolveHomeConnectionFeedback, 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 {
+ 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 {
+ readHomeViewPreferences,
+ saveHomeViewPreferences,
+ type HomeViewPreferences,
+} from '@/session/homeViewPreferenceStore';
+import {
+ getCachedHomeListSnapshot,
+ scheduleHomeListSnapshotPersist,
+} from '@/session/mobileHomeListCache';
+import { startBoundedStartupRead } from '@/session/mobileHomeStartup';
+import {
+ diffHomeDeviceSyncScope,
+ HomeDeviceSyncLimiter,
+ resolveHomeDeviceSyncIds,
+ runHomeDeviceSyncBatch,
+} from '@/session/homeDeviceSync';
+import { serializeNewSessionDeviceOptions } from '@/session/newSession';
+import {
+ buildRemoteSessionCardPreview,
+ formatRemoteSessionSidebarTime,
+ getRemoteSessionPreviewCollapse,
+ type RemoteAutomationSessionGroup,
+ type RemoteSessionListItem,
+ type RemoteSessionLiveActivity,
+ type RemoteSessionScheduleInfo,
+ type RemoteSessionStatusFilter,
+} from '@/session/sessionList';
+import {
+ RemoteSessionStoreSubscriptionGate,
+ remoteSessionStore,
+ useRemoteHomeStatusVersion,
+ useRemoteMessageVersion,
+ useRemoteSessionMessagePreview,
+ useRemoteSessions,
+ useSessionRunning,
+} from '@/session/remoteSessionStore';
+import { mapContentEqual } from '@/utils/valueEquality';
+import { homeRowPropsEqual } from './homeRowPropsEqual';
+import { useStableValue } from '@/utils/useStableValue';
+import { useMinuteNow } from '@/utils/useMinuteNow';
+import {
+ getScheduleIndexInvalidationVersion,
+ invalidateOfflineScheduleIndexFailureFor,
+ invalidateRunningSessionScheduleEntries,
+ invalidateScheduleIndexForDevice,
+ loadDeviceSessionScheduleIndex,
+ replaceSessionScheduleIndexEntries,
+} from '@/session/scheduleIndex';
+import { createScheduleIndexDeferRegistry } from '@/session/scheduleIndexDefer';
+import { latestMobileSessionRow, resolveMobileSessionRowStatus } from '@/session/sessionRightStatus';
+import { AutomationTimerIcon } from '@/session/AutomationTimerIcon';
+import { RenameSessionModal } from '@/session/RenameSessionModal';
+import { SessionOptionsPresenter } from '@/session/SessionOptionsExpoSheet';
+import { SwipeableSessionRow, type SessionSwipeControls } from '@/session/SwipeableSessionRow';
+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, radius, spacing, typeScale } from '@/theme/tokens';
+
+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;
+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;
+const CINDY_LIST_GUTTER = 20;
+const CINDY_LIST_FAB_BOTTOM = 45;
+const HOME_HEADER_MIN_HEIGHT = 48;
+const AnimatedPressable = Animated.createAnimatedComponent(Pressable);
+
+function estimateHomeSessionRowHeight(item: RemoteSessionListItem): number {
+ 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>,
+): number {
+ const rowHeight = estimateHomeSessionRowHeight(item);
+ 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),
+ 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 {
+ /** The same Home surface, constrained by its host rather than the screen width. */
+ width?: number;
+ currentSessionId?: string;
+ onDismiss?: () => void;
+ newSessionInSystemBar?: boolean;
+ onSelectSession?: (item: RemoteSessionListItem) => void;
+ runNavigation?: (action: () => void) => void;
+ newSessionActionRef?: MutableRefObject<(() => void) | null>;
+}
+const ActiveHomeSession = createContext<string | undefined>(undefined);
+
+export function MobileHome(props: MobileHomeProps) {
+ const screenFocused = useIsFocused();
+ const { accountGeneration } = useAuth();
+ return <RemoteSessionStoreSubscriptionGate enabled={screenFocused}>
+ <ActiveHomeSession.Provider value={props.currentSessionId}>
+ <HomeScreenContent key={accountGeneration} {...props} />
+ </ActiveHomeSession.Provider>
+ </RemoteSessionStoreSubscriptionGate>;
+}
+
+function HomeScreenContent({ width, onDismiss, newSessionInSystemBar = false, onSelectSession, runNavigation, newSessionActionRef }: MobileHomeProps) {
+ // 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();
+ const activeHomeSession = useContext(ActiveHomeSession);
+ const rememberTask = rememberRecentTask;
+ const viewSession = getHomeViewSession();
+ const [restoredView] = useState(() => viewSession.has('preferencesHydrated'));
+ const screenFocused = useIsFocused();
+ const screenFocusedRef = useRef(screenFocused);
+ screenFocusedRef.current = screenFocused;
+ const styles = useThemedStyles(makeStyles);
+ const { colors, mode } = useTheme();
+ const { t, i18n: i18nInstance } = useTranslation();
+ // 所有前进导航(进会话 / 新建 / 设置 / 组页面)统一走守卫 push:列表卡顿时的
+ // 连点会各自触发一次裸 push,把同一页压进栈 N 层(返回也要 N 次)。
+ const push = useGuardedPush();
+ const navigationHost = useRef({ runNavigation, onSelectSession });
+ navigationHost.current = { runNavigation, onSelectSession };
+ 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,
+ invoke,
+ lastPresenceSnapshot,
+ recoveringDeviceIds,
+ readDeviceList,
+ status,
+ subscribe,
+ unsubscribe,
+ } = useDeviceLink();
+ const revokedDevices = useRevokedDevices();
+ const sessions = useRemoteSessions();
+ 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>());
+ 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);
+ selectedDeviceIdRef.current = selectedDeviceId;
+ 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 [displaySettingsOpen, setDisplaySettingsOpen] = useState(false);
+ const [chromeMenuOpen, setChromeMenuOpen] = useState(false);
+ const [accountSwitcherOpen, setAccountSwitcherOpen] = useState(false);
+ const [chromeMenuCloseInstant, setChromeMenuCloseInstant] = 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);
+ const {
+ actionSheetSession,
+ archiveSession,
+ closeRenameSession,
+ confirmRenameSession,
+ handleSessionSheetAction,
+ handleSessionSheetClosed,
+ renameSessionDraft,
+ renameSessionTarget,
+ sessionSwipeControls,
+ setActionSheetSession,
+ setRenameSessionDraft,
+ showSessionOptions,
+ swipeRegistry,
+ toggleSessionPinned,
+ } = useSessionListActions();
+ // 实测 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 [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 [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 [collapsedProjectKeys, setCollapsedProjectKeys] = useRetainedHomeState<string[]>(viewSession, 'collapsedProjectKeys', []);
+ const [pinnedCollapsed, setPinnedCollapsed] = useRetainedHomeState(viewSession, 'pinnedCollapsed', false);
+ // 已展开的自动化组 key(页面级 state:SectionList 虚拟化回收行组件时展开态不丢)。
+ const [expandedAutomationGroups, setExpandedAutomationGroups] = useRetainedHomeState<string[]>(viewSession, 'expandedAutomationGroups', []);
+ 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();
+ 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);
+ releaseHomeListOwner(deviceId);
+ }
+ for (const deviceId of diff.acquire) {
+ advanceHomeSyncGeneration(deviceId);
+ }
+ return diff;
+ }, [advanceHomeSyncGeneration, releaseHomeListOwner]);
+
+ 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 再补最新窗口。
+ 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 },
+ ) => {
+ if (!screenFocusedRef.current || AppState.currentState !== 'active') return;
+ const expectedAccountGeneration = options?.accountGeneration ?? accountGeneration;
+ const expectedHomeSyncGeneration = options?.homeSyncGeneration
+ ?? homeSyncGenerationByDeviceRef.current.get(deviceId);
+ if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
+ 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,
+ ));
+ })
+ .catch(() => {
+ // 网络失败时保留旧数据,不清零已有徽标——数据清零只应由明确的"已读"事件触发。
+ });
+ }, [accountGeneration, invoke, isCurrentHomeSyncTarget]);
+
+ 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');
+ 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,
+ remoteListStatusFilter(statusFilter),
+ { includePinned: true, fresh: true },
+ ]);
+ return [list, 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 },
+ ]).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 (Array.isArray(activeSessions)) {
+ remoteSessionStore.setActiveSessionSnapshots(
+ device.deviceId,
+ activeSessions,
+ activeSessionSnapshotEpoch,
+ );
+ }
+ });
+ // schedule-index(1+N 个 listRuns)是次要徽标数据,延后发,避开"开 app→立刻点会话"时和会话关键读
+ // 抢同一条 WS 管道(见 scheduleIndexDefer / issue #324)。home 自动化分组与名称已由 fallbackScheduleInfo
+ // 兜底,徽标晚半拍出现即可。
+ // 按设备 id 登记:同设备上一轮还没执行的延后任务会被先取消,避免较早回调用旧 nextSessions 覆盖新状态。
+ 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,
+ });
+ })();
+ });
+ 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);
+ 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, refreshDeviceScheduleIndex, statusFilter, subscribe, updateDeviceConnectionState]);
+
+ const hydrateDeviceSessions = useCallback((
+ device: DeviceView,
+ expectedAccountGeneration = accountGeneration,
+ options: { trailingIfInFlight?: boolean } = {},
+ ): Promise<HydrateDeviceSessionsResult> => {
+ const expectedHomeSyncGeneration = homeSyncGenerationByDeviceRef.current.get(device.deviceId);
+ if (
+ expectedHomeSyncGeneration === undefined
+ || 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, 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 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');
+ }
+ return readDeviceList();
+ },
+ { 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 && !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 (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]);
+ 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(),
+ null,
+ );
+ 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);
+ if (preferences.selectedDevice) {
+ setSelectedDeviceId(preferences.selectedDevice.deviceId);
+ setRestoredDeviceName(preferences.selectedDevice.name);
+ restoredSelectionUnvalidatedRef.current = true;
+ }
+ };
+ 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;
+ }
+ refreshDeviceScheduleIndex(deviceId, sessionIds);
+ }
+ }), [refreshDeviceScheduleIndex]);
+
+ // 从自动化 / 会话页返回首页时,兜底刷新一次 scheduleIndex:
+ // markScheduleRunsRead 的桌面广播若在导航切换途中丢失(silent swallow / 弱网 / tap listener
+ // 未挂),之前依赖 remoteScheduleEventStore.subscribe 的路径就永远不会补跑,首页那颗
+ // "已完成未读"绿点会一直挂着。useFocusEffect 每次 focus 都按当前设备清一遍未读徽标,
+ // 命中真实变化才会 setScheduleIndex(entries 等值比较),不触发无谓 re-render。
+ useFocusEffect(
+ useCallback(() => {
+ for (const device of devicesRef.current) {
+ if (!homeSyncTargetDeviceIdsRef.current.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 种回去。
+ const startSilentHomeSync = useCallback(() => {
+ if (!screenFocusedRef.current) return;
+ if (!deviceIdentityCacheReady || !homeListCacheHydrated || !homeViewPreferencesHydrated) return;
+ void loadHome({ visible: false });
+ }, [deviceIdentityCacheReady, homeListCacheHydrated, homeViewPreferencesHydrated, loadHome]);
+
+ // 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(() => {
+ startSilentHomeSync();
+ }, [startSilentHomeSync]),
+ );
+
+ useEffect(() => {
+ startSilentHomeSync();
+ const subscription = AppState.addEventListener('change', (nextState) => {
+ 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;
+ setDisplaySettingsOpen(false);
+ setChromeMenuOpen(false);
+ setDeviceMenuOpen(true);
+ }, []);
+
+ const openChromeMenu = useCallback(() => {
+ pendingMenuActionRef.current = null;
+ setDeviceMenuOpen(false);
+ setDisplaySettingsOpen(false);
+ setChromeMenuCloseInstant(false);
+ setChromeMenuOpen(true);
+ }, []);
+
+ const openDisplaySettings = useCallback(() => {
+ pendingMenuActionRef.current = null;
+ setDeviceMenuOpen(false);
+ setChromeMenuOpen(false);
+ setDisplaySettingsOpen(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],
+ );
+ const homeSyncDeviceIds = useMemo(() => screenFocused ? resolveHomeDeviceSyncIds(
+ deviceRows.map((item) => ({
+ canOpen: item.canOpen,
+ deviceId: item.device.deviceId,
+ })),
+ selectedDeviceId,
+ ) : [], [deviceRows, screenFocused, selectedDeviceId]);
+ const homeSyncDeviceIdSet = useMemo(() => new Set(homeSyncDeviceIds), [homeSyncDeviceIds]);
+ const homeSyncRows = useMemo(
+ () => deviceRows.filter((item) => homeSyncDeviceIdSet.has(item.device.deviceId)),
+ [deviceRows, homeSyncDeviceIdSet],
+ );
+
+ useEffect(() => {
+ const expectedAccountGeneration = accountGeneration;
+ const selectedDeviceIdAtStart = selectedDeviceId;
+ 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, () => {
+ 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(
+ invoke,
+ 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)),
+ ),
+ [searchOrigins, sessions],
+ );
+ const indexedSearch = useConversationSearch({
+ enabled: true,
+ retainedState: viewSession,
+ origins: searchOrigins,
+ projects: deviceIdentityCacheReady ? searchProjects : undefined,
+ });
+ 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({
+ 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],
+ );
+ const projectMachineIdentities = useMemo(
+ () => buildHomeProjectMachineIdentities(home, deviceConnectionStates),
+ [home, deviceConnectionStates],
+ );
+ 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],
+ );
+ 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 = selectedDeviceId && selectedHostOrder
+ ? controllerKeysFromHost(selectedDeviceId, selectedHostOrder)
+ : [];
+ const displayed = resolveDisplayedProjectOrder(
+ resolveProjectOrderWriteScope(selectedDeviceId ? [selectedDeviceId] : 'all', 'local'),
+ selectedHostOrder,
+ { manualProjectOrder, projectOrder },
+ hostManualProjectOrder,
+ );
+ const displayedProjectOrder = displayed.projectOrder;
+ const displayedManualProjectOrder = displayed.manualProjectOrder;
+ const homeSections = useMemo(
+ () => buildHomeSections(home, groupByProject, pinnedCollapsed, {
+ dialogueTitle: t('devices.list.menu.dialogueFolder'),
+ groupDialogue,
+ manualProjectOrder: displayedManualProjectOrder,
+ priorityContext,
+ projectOrder: displayedProjectOrder,
+ sortBy,
+ }),
+ [displayedManualProjectOrder, displayedProjectOrder, groupByProject, groupDialogue, home, pinnedCollapsed, priorityContext, 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]);
+ const initialHomeLoading = !initialHomeSettled && !connectionError;
+ const initialHomeError = !initialHomeSettled && !!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 selectedDeviceDisconnected = status !== 'connecting' && home.deviceFilters.some((item) => item.deviceId !== null
+ && (!selectedDeviceId || item.deviceId === selectedDeviceId) && item.sessionCount > 0)
+ && !home.deviceFilters.some((item) => item.deviceId !== null
+ && (!selectedDeviceId || item.deviceId === selectedDeviceId) && item.available);
+ const showConnectionRow = 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 = 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 = (!activeConnectionIssue
+ || activeConnectionIssue.kind === 'unstable' || activeConnectionIssue.kind === 'replaced')
+ && (status === 'connecting' || homeDeviceRecovery);
+ const connectionTone = activeConnectionIssue
+ ? 'off'
+ : homeDeviceRecovery ? 'busy' : selectedDeviceDisconnected ? 'off' : connectionError ? 'muted' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';
+ const connectionTitle = activeConnectionIssue
+ ? connectionIssueTitle(activeConnectionIssue.kind)
+ : homeDeviceRecovery ? t(homeDeviceUnresponsive ? 'deviceLink.deviceUnresponsiveTitle' : 'deviceLink.recovery.syncing')
+ : selectedDeviceDisconnected ? t('deviceLink.cachedHistory.title') : connectionError ? t('devices.list.syncFailed') : homeConnectionTitle(status, t);
+ const connectionCopy = activeConnectionIssue
+ ? connectionIssueHint(activeConnectionIssue.kind)
+ : homeDeviceRecovery ? t(homeDeviceUnresponsive ? 'deviceLink.deviceUnresponsiveHint' : 'deviceLink.recovery.syncingHint') : selectedDeviceDisconnected ? t('deviceLink.cachedHistory.hint') : connectionError;
+ const emptyStateTitle = initialHomeError ? t('devices.list.syncFailed') : home.emptyTitle;
+ const emptyStateCopy = initialHomeError ? (connectionError ?? t('devices.list.requestFailed')) : home.emptyCopy;
+ // 无可控制电脑的引导态(landing)可见性,与 ListEmptyComponent 的分支同口径。
+ // 引导态下首页没有可筛选的对话:表头「所有对话 ▾」退化为纯品牌标题、新建 FAB 隐藏,
+ // 避免在产品说明页上摆一堆无意义的入口。
+ const homeListItemCount = 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',
+ // 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,
+ });
+ 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 openSession = useCallback((item: RemoteSessionListItem) => {
+ // 有行处于滑开状态时,点击(本行或他行)只负责收起,不进会话(iOS 列表滑动操作惯例)。
+ if (swipeRegistry.closeOpenRow()) return;
+ holdViewedPriorityRank(homeViewedPriorityHold, item.session.id, priorityContext);
+ advanceViewedPriorityHold(homeViewedPriorityHold, item.session.id, priorityContext, 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: session.deviceLinkDeviceName ?? deviceId,
+ sessionId: session.id,
+ ...(focusClientId ? { focusClientId } : {}),
+ },
+ } as const;
+ rememberTask(href);
+ guardedPush(href);
+ }, [guardedPush, priorityContext, rememberTask, swipeRegistry, t]);
+
+ const openNewSession = useCallback((project?: MobileHomeProjectGroup, suggestion?: RemoteTaskSuggestionId, explicitDeviceId?: string) => {
+ const deviceId = project?.deviceId ?? explicitDeviceId ?? home.primaryDevice?.deviceId;
+ const deviceName = project?.deviceName ?? newSessionDeviceOptions.find((device) => device.deviceId === deviceId)?.name ?? home.primaryDevice?.label ?? deviceId ?? '';
+ if (!deviceId) {
+ setError(t('devices.list.error.noDevice'));
+ return;
+ }
+ guardedPush({
+ pathname: '/sessions/new',
+ params: {
+ deviceId,
+ deviceName,
+ deviceOptions: serializeNewSessionDeviceOptions(newSessionDeviceOptions),
+ ...(suggestion ? { suggestion } : {}),
+ ...(project?.workingDir ? { workingDir: project.workingDir } : {}),
+ // 列表正筛选某台电脑时,新建默认跟随这台电脑(显式指定,盖过"上次选择"的
+ // 记忆);推荐入口固定使用已通过就绪检查的电脑,普通新建仍可恢复记忆设备。
+ ...(selectedDeviceId || explicitDeviceId ? { deviceExplicit: '1' } : {}),
+ },
+ });
+ }, [guardedPush, home.primaryDevice, newSessionDeviceOptions, selectedDeviceId, 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();
+ } catch (error) {
+ Alert.alert(t('devices.list.alert.actionFailed'), formatRemoteError(error));
+ } finally {
+ setLoggingOut(false);
+ }
+ }, [auth, loggingOut, t]);
+
+ const toggleProject = useCallback((key: string) => {
+ configureCollapseAnimation();
+ setCollapsedProjectKeys((current) =>
+ current.includes(key) ? current.filter((item) => item !== key) : [...current, key]);
+ }, []);
+
+ const showAllDialogueSessions = useCallback(() => {
+ setDialogueShowAll(true);
+ }, []);
+
+ const applyDisplayView = useCallback((patch: {
+ groupByProject?: boolean;
+ groupDialogue?: boolean;
+ sortBy?: HomeListSortBy;
+ statusFilter?: HomeStatusFilter;
+ projectOrder?: HomeProjectOrder;
+ 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 (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;
+ }) => {
+ 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]);
+
+ 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) {
+ const visibleKeys = home.projects
+ .filter((item) => item.kind !== 'cindy-make' && item.deviceId === selectedDeviceId)
+ .map((item) => item.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) => {
+ configureCollapseAnimation();
+ setExpandedAutomationGroups((current) =>
+ current.includes(key) ? current.filter((item) => item !== key) : [...current, key]);
+ }, []);
+
+ // 自动化组「查看全部 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: session.deviceLinkDeviceName ?? deviceId,
+ automationGroupKey: group.baseKey,
+ automationName: group.title,
+ ...(workingDir ? { automationWorkingDir: workingDir } : {}),
+ // 快照兜底:目标页 scheduleIndex 尚未加载完成时,先按这批 id 立即显示组内运行,
+ // index 就绪后再与组键匹配结果取并集(能捕获新产生的 run)。
+ automationSessionIds: JSON.stringify(group.sessionIds),
+ },
+ });
+ }, [guardedPush, t]);
+
+ // 置顶组与项目组一致:点表头收起/展开,共用同一条收起动画。
+ const togglePinned = useCallback(() => {
+ configureCollapseAnimation();
+ setPinnedCollapsed((collapsed) => !collapsed);
+ }, []);
+
+ const openProjectSessions = useCallback((project: MobileHomeProjectGroup) => {
+ if (!project.deviceId) return;
+ guardedPush({
+ pathname: '/devices/[deviceId]',
+ // 带上 workingDir + 项目名,让目标页只显示「这个项目」的会话(名副其实地"查看全部 N 条")。
+ // 未归类组(workingDir 为空)不传过滤参数,退化为整台设备的会话列表。
+ // statusFilter 跟首页当前筛选走,归档/全部入口不能掉回默认 active。
+ params: {
+ deviceId: project.deviceId,
+ name: project.deviceName,
+ statusFilter,
+ ...(project.workingDir
+ ? { workingDir: project.workingDir, projectName: project.title }
+ : {}),
+ },
+ });
+ }, [guardedPush, statusFilter]);
+
+ // 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}
+ 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,
+ 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,
+ });
+
+ const selectHomeScope = useCallback((item: MobileHomeDeviceFilterItem) => {
+ if (item.deviceId && item.state === 'access_revoked') {
+ const deviceId = item.deviceId;
+ if (usesSystemActionMenu()) {
+ setRevokedTipDeviceId(deviceId);
+ return;
+ }
+ 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,
+ });
+ }, []);
+
+ const nativeHomeMenus = usesNativePullDownMenu();
+ const homeScopePullDownActions = useMemo(
+ () => buildHomeScopePullDownActions(
+ home.deviceFilters,
+ t('devices.list.allConversations'),
+ remoteHomeCollections.map((collection) => ({
+ id: collection.id,
+ title: collection.title,
+ })),
+ ),
+ [home.deviceFilters, remoteHomeCollections, t],
+ );
+ const handleHomeScopeAction = useCallback((id: string) => {
+ const parsed = parseHomeScopePullDownAction(id);
+ if (parsed.kind === 'collection') {
+ const collection = remoteHomeCollections.find((item) => item.id === parsed.collectionId);
+ if (!collection) return;
+ guardedPush({
+ pathname: '/resources/[collectionId]',
+ params: {
+ collectionId: collection.id,
+ title: collection.title,
+ targets: serializeRemoteResourceTargets(collection.targets),
+ },
+ });
+ return;
+ }
+ const item = home.deviceFilters.find((filter) => filter.id === parsed.filterId);
+ if (item) selectHomeScope(item);
+ }, [guardedPush, home.deviceFilters, remoteHomeCollections, selectHomeScope]);
+ const homeDisplayPullDownActions = useMemo(
+ () => buildHomeDisplayPullDownActions({
+ groupByProject,
+ groupByProjectLabel: t('devices.list.menu.groupByProject'),
+ groupDialogue,
+ groupDialogueLabel: t('devices.list.menu.groupDialogue'),
+ groupHeading: t('devices.list.menu.groupHeading'),
+ projectOrder: displayedProjectOrder,
+ projectOrderActivityLabel: t('devices.list.menu.projectOrderActivity'),
+ projectOrderCustomLabel: t('devices.list.menu.projectOrderManual'),
+ projectOrderHeading: t('devices.list.menu.projectOrderHeading'),
+ showProjectOrder: true,
+ sortBy,
+ sortByPriorityLabel: t('devices.list.menu.sortByPriority'),
+ sortByTimeLabel: t('devices.list.menu.sortByTime'),
+ sortHeading: t('devices.list.menu.sortHeading'),
+ statusActiveLabel: t('devices.list.menu.statusActive'),
+ statusAllLabel: t('devices.list.menu.statusAll'),
+ statusArchivedLabel: t('devices.list.menu.statusArchived'),
+ statusFilter,
+ statusHeading: t('devices.list.menu.statusHeading'),
+ }),
+ [displayedProjectOrder, groupByProject, groupDialogue, sortBy, statusFilter, t],
+ );
+ 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 = useHeaderHeight();
+ const chromeHeight = nativeHomeHeader
+ ? nativeHeaderHeight + (headerHeight ?? 0)
+ : (headerHeight ?? edgePadding.paddingTop + HOME_HEADER_MIN_HEIGHT);
+ const homeListNode = (
+ <SectionList
+ ref={attachHomeList}
+ onLayout={(event) => {
+ listViewportHeight.current = event.nativeEvent.layout.height;
+ restoreListPosition();
+ }}
+ onContentSizeChange={(_, height) => {
+ listContentHeight.current = height;
+ restoreListPosition();
+ }}
+ sections={sections}
+ style={styles.homeList}
+ keyExtractor={(item) => item.key}
+ initialNumToRender={HOME_LIST_INITIAL_RENDER_COUNT}
+ maxToRenderPerBatch={HOME_LIST_RENDER_BATCH_SIZE}
+ updateCellsBatchingPeriod={32}
+ windowSize={HOME_LIST_WINDOW_SIZE}
+ refreshControl={
+ <RefreshControl
+ progressViewOffset={residentList.enabled ? 0 : chromeHeight}
+ refreshing={refreshing}
+ onRefresh={() => void loadHome({ visible: true })}
+ />
+ }
+ scrollEnabled={projectDrag === null}
+ stickySectionHeadersEnabled={false}
+ contentContainerStyle={[
+ styles.listContent,
+ {
+ paddingBottom: (newSessionInSystemBar ? spacing.sm : 83) + insets.bottom,
+ paddingTop: residentList.enabled ? 0 : chromeHeight,
+ },
+ ]}
+ onScroll={onListScroll}
+ 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: home.pinned.length })}
+ accessibilityRole="button"
+ accessibilityState={{ expanded: !pinnedCollapsed }}
+ onPress={togglePinned}
+ 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}>{home.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={
+ initialHomeLoading || taskSuggestionsPending ? (
+ <HomeInitialLoadingState
+ style={{
+ marginTop: spacing.xxl,
+ minHeight: windowLayout.emptyMinHeight,
+ padding: windowLayout.emptyPadding,
+ }}
+ />
+ ) : home.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}
+ />
+ ) : 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}
+ />
+ );
+ 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 || showRemoteGuide || taskSuggestionsPending || taskSuggestionsMode === 'empty' ? null : (
+ // 无可控电脑时不提供入口;完整空态已有主按钮,避免重复显示新建 CTA。
+ <HomeNewTaskButton bottomInset={insets.bottom} disabled={newSessionDisabled}
+ onPress={() => openNewSession()} />
+ )}
+
+ </>);
+ return (
+ <View
+ ref={homeRootRef}
+ style={[styles.safeArea, { paddingLeft: embedded ? 0 : edgePadding.paddingLeft, paddingRight: embedded ? 0 : edgePadding.paddingRight }]}
+ testID="devices.screen"
+ >
+ {nativeHomeHeader ? <SessionHeaderNativeBlur height={nativeHeaderHeight + spacing.xxl} /> : null}
+ {nativeHomeHeader ? (
+ <HomeNativeStackHeader
+ keepMenuTopLeft={keepMenuTopLeft}
+ syncing={quietSyncing}
+ displayA11y={t('devices.list.a11y.openDisplaySettings')}
+ displayActions={homeDisplayPullDownActions}
+ menuA11y={t('devices.list.a11y.openMenu')}
+ onDisplayAction={(id) => {
+ applyDisplayView(homeDisplayMenuPatch(id as HomeDisplayMenuKey, {
+ groupByProject,
+ groupDialogue,
+ }));
+ }}
+ onOpenDeviceMenu={openDeviceMenu}
+ onOpenDisplaySettings={openDisplaySettings}
+ 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 style={styles.homeHeader}>
+ <HomeHeaderGlassButton
+ accessibilityLabel={onDismiss ? t('home.drawer.closeA11y') : t('devices.list.a11y.openMenu')}
+ onPress={onDismiss ?? openChromeMenu}
+ testID="home.chromeMenu"
+ >
+ <>{onDismiss ? <X color={colors.textPrimary} size={iconSize.action} strokeWidth={iconStroke.regular} /> : <Menu color={colors.textPrimary} size={iconSize.action} strokeWidth={iconStroke.regular} />}</>
+ </HomeHeaderGlassButton>
+ {showRemoteGuide ? (
+ // 引导态没有可筛选的范围:正中只留品牌标题。
+ <View style={styles.headerTitleWrap} testID="devices.title">
+ <Text style={styles.headerTitle} numberOfLines={1}>Cindy</Text>
+ </View>
+ ) : (
+ <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, pressed && styles.pressed]}
+ testID="devices.title"
+ >
+ <View style={styles.headerTitleCluster}>
+ <Text style={styles.headerTitle} numberOfLines={1}>{selectedDeviceLabel}</Text>
+ <ChevronDown color={colors.textSecondary} size={iconSize.xs} strokeWidth={iconStroke.medium} />
+ <QuietSyncIndicator active={quietSyncing} />
+ </View>
+ </Pressable>
+ </NativePullDownMenu>
+ )}
+ {showRemoteGuide ? (
+ <View style={styles.headerIconButton} />
+ ) : (
+ <View style={styles.headerActions}>
+ {selectedDeviceId && !embedded ? (
+ <HomeHeaderGlassButton accessibilityLabel={t('remoteDesktop.title')} onPress={openSelectedRemoteDesktop} testID="home.remoteDesktopButton">
+ <Monitor color={colors.textPrimary} size={iconSize.action} strokeWidth={iconStroke.regular} />
+ </HomeHeaderGlassButton>
+ ) : null}
+ <NativePullDownMenu
+ actions={homeDisplayPullDownActions}
+ onAction={(id) => applyDisplayView(homeDisplayMenuPatch(id as HomeDisplayMenuKey, { groupByProject, groupDialogue }))}
+ >
+ <HomeHeaderGlassButton accessibilityLabel={t('devices.list.a11y.openDisplaySettings')} onPress={nativeHomeMenus ? () => undefined : openDisplaySettings} testID="home.displaySettingsButton">
+ <Ellipsis color={colors.textPrimary} size={iconSize.action} strokeWidth={iconStroke.regular} />
+ </HomeHeaderGlassButton>
+ </NativePullDownMenu>
+ </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={!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}
+ onPress={() => void loadHome({ visible: true })}
+ 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} 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}</>}
+
+ <RevokedAccessTip
+ deviceName={revokedTipDeviceName}
+ retrying={revokedTipDeviceId !== null && retryingDeviceIds.has(revokedTipDeviceId)}
+ onClose={() => setRevokedTipDeviceId(null)}
+ onRetry={() => {
+ if (revokedTipDeviceId) void retryRevokedDevice(revokedTipDeviceId);
+ }}
+ />
+ <DeviceMenuModal
+ collections={remoteHomeCollections}
+ connectionStates={deviceConnectionStates}
+ filters={home.deviceFilters}
+ onClose={() => setDeviceMenuOpen(false)}
+ onClosed={handleDeviceMenuClosed}
+ onSelectCollection={(collection) => {
+ setDeviceMenuOpen(false);
+ guardedPush({
+ pathname: '/resources/[collectionId]',
+ params: {
+ collectionId: collection.id,
+ title: collection.title,
+ targets: serializeRemoteResourceTargets(collection.targets),
+ },
+ });
+ }}
+ 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}
+ />
+ <HomeChromeDrawer
+ closeInstant={chromeMenuCloseInstant}
+ loggingOut={loggingOut}
+ onClose={() => {
+ setChromeMenuCloseInstant(false);
+ setChromeMenuOpen(false);
+ }}
+ onClosed={() => {
+ setChromeMenuCloseInstant(false);
+ handleChromeMenuClosed();
+ }}
+ onOpenSearch={() => {
+ setSearchOpen(true);
+ setChromeMenuCloseInstant(false);
+ setChromeMenuOpen(false);
+ }}
+ onOpenAccounts={() => {
+ pendingMenuActionRef.current = () => setAccountSwitcherOpen(true);
+ setChromeMenuCloseInstant(false);
+ setChromeMenuOpen(false);
+ }}
+ onOpenDevices={() => {
+ pendingMenuActionRef.current = null;
+ guardedPush('/devices/manage');
+ setChromeMenuCloseInstant(true);
+ setChromeMenuOpen(false);
+ }}
+ onOpenSettings={() => {
+ pendingMenuActionRef.current = null;
+ guardedPush('/settings');
+ setChromeMenuCloseInstant(true);
+ setChromeMenuOpen(false);
+ }}
+ onLogout={() => void logout()}
+ open={chromeMenuOpen}
+ user={user}
+ />
+ <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}
+ />
+ <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}
+ />
+ <HomeDisplaySettingsModal
+ groupByProject={groupByProject}
+ groupDialogue={groupDialogue}
+ onChangeView={applyDisplayView}
+ onClose={() => setDisplaySettingsOpen(false)}
+ projectOrder={displayedProjectOrder}
+ sortBy={sortBy}
+ statusFilter={statusFilter}
+ topOffset={chromeHeight}
+ visible={displaySettingsOpen}
+ />
+ <SessionOptionsPresenter
+ session={actionSheetSession}
+ onAction={handleSessionSheetAction}
+ onClose={() => setActionSheetSession(null)}
+ onClosed={handleSessionSheetClosed}
+ pinnedAt={actionSheetSession?.pinnedAt}
+ status={actionSheetSession?.status}
+ visible={actionSheetSession !== null}
+ />
+ <RenameSessionModal
+ draft={renameSessionDraft}
+ onCancel={closeRenameSession}
+ onChangeDraft={setRenameSessionDraft}
+ onConfirm={confirmRenameSession}
+ // 乐观提交:确认即关弹窗,不存在挂起中的保存态。
+ saving={false}
+ visible={renameSessionTarget !== null}
+ />
+ </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,
+ connectionStates,
+ filters,
+ onClose,
+ onClosed,
+ onSelect,
+ onSelectCollection,
+ topOffset,
+ visible,
+}: {
+ collections: readonly RemoteHomeCollection[];
+ connectionStates: Record<string, HomeDeviceConnectionState>;
+ 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:展开用 ≤150ms 纯透明度过渡(不做位移/缩放),关闭淡出后再卸载 Modal。
+ // mounted/progress/进场时机(onShow)/onClosed 延迟触发(等 Modal 真正卸载的 commit
+ // 完成,避免 iOS present-during-dismiss 吞掉第二个弹窗)统一走 useModalFadeLifecycle。
+ const { mounted, progress, onShowStartIn } = useModalFadeLifecycle(visible, {
+ inMs: 140,
+ outMs: 110,
+ onClosed,
+ });
+ const allFilter = filters.find((item) => item.deviceId === null) ?? null;
+ // 离线电脑保留缓存入口;关远控和撤权不由缓存恢复访问权限。
+ 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
+ connectionState={item.deviceId ? connectionStates[item.deviceId] ?? 'idle' : 'idle'}
+ dimmed={!canBrowseMobileHomeDevice(item)}
+ key={item.id}
+ label={item.label}
+ onPress={() => onSelect(item)}
+ selected={item.selected}
+ status={deviceMenuStatus(item)}
+ testID={item.deviceId ? `home.deviceChip.${sanitizeDeviceChipTestId(item.deviceId)}` : undefined}
+ />
+ ))}
+ </ScrollView>
+ </HomeGlassMenuPanel>
+ </HomeMenuScrim>
+ );
+}
+
+function HomeDisplaySettingsModal({
+ groupByProject,
+ groupDialogue,
+ onChangeView,
+ onClose,
+ projectOrder,
+ showProjectOrder = true,
+ sortBy,
+ statusFilter,
+ topOffset,
+ visible,
+}: {
+ groupByProject: boolean;
+ groupDialogue: boolean;
+ onChangeView(patch: {
+ groupByProject?: boolean;
+ groupDialogue?: boolean;
+ sortBy?: HomeListSortBy;
+ statusFilter?: HomeStatusFilter;
+ projectOrder?: HomeProjectOrder;
+ manualProjectOrder?: string[];
+ }): void;
+ onClose(): void;
+ projectOrder: HomeProjectOrder;
+ showProjectOrder?: boolean;
+ sortBy: HomeListSortBy;
+ statusFilter: HomeStatusFilter;
+ topOffset: number;
+ visible: boolean;
+}) {
+ const styles = useThemedStyles(makeStyles);
+ const { t } = useTranslation();
+ const { height: screenHeight } = useWindowDimensions();
+ const insets = useSafeAreaInsets();
+ const scrollMaxHeight = Math.max(200, screenHeight - topOffset - insets.bottom - 24);
+ const { mounted, progress, onShowStartIn } = useModalFadeLifecycle(visible, {
+ inMs: 140,
+ outMs: 110,
+ });
+ return (
+ <HomeMenuScrim
+ backdropTestID="home.displaySettings.backdrop"
+ onClose={onClose}
+ onShow={onShowStartIn}
+ progress={progress}
+ topOffset={topOffset}
+ visible={mounted}
+ >
+ <HomeGlassMenuPanel style={styles.deviceMenuPanelEnd} testID="home.displaySettings">
+ <ScrollView style={[styles.deviceMenuScroll, { maxHeight: scrollMaxHeight }]} showsVerticalScrollIndicator>
+ <Text style={styles.deviceMenuSectionLabel}>{t('devices.list.menu.groupHeading')}</Text>
+ <DeviceMenuItem
+ checked={groupByProject}
+ label={t('devices.list.menu.groupByProject')}
+ onPress={() => onChangeView({ groupByProject: !groupByProject })}
+ selected={false}
+ testID="home.deviceMenu.groupByProject"
+ />
+ <DeviceMenuItem
+ checked={groupDialogue}
+ label={t('devices.list.menu.groupDialogue')}
+ onPress={() => onChangeView({ groupDialogue: !groupDialogue })}
+ selected={false}
+ testID="home.deviceMenu.groupDialogue"
+ />
+ <View style={styles.deviceMenuDivider} />
+ <Text style={styles.deviceMenuSectionLabel}>{t('devices.list.menu.sortHeading')}</Text>
+ <DeviceMenuItem
+ label={t('devices.list.menu.sortByTime')}
+ onPress={() => onChangeView({ sortBy: 'recency' })}
+ selected={sortBy === 'recency'}
+ testID="home.deviceMenu.sort.recency"
+ />
+ <DeviceMenuItem
+ label={t('devices.list.menu.sortByPriority')}
+ onPress={() => onChangeView({ sortBy: 'priority' })}
+ selected={sortBy === 'priority'}
+ testID="home.deviceMenu.sort.priority"
+ />
+ {groupByProject && showProjectOrder ? (
+ <>
+ <View style={styles.deviceMenuDivider} />
+ <Text style={styles.deviceMenuSectionLabel}>{t('devices.list.menu.projectOrderHeading')}</Text>
+ <DeviceMenuItem
+ label={t('devices.list.menu.projectOrderActivity')}
+ onPress={() => onChangeView({ projectOrder: 'activity' })}
+ selected={projectOrder === 'activity'}
+ testID="home.deviceMenu.projectOrder.activity"
+ />
+ <DeviceMenuItem
+ label={t('devices.list.menu.projectOrderManual')}
+ onPress={() => onChangeView({ projectOrder: 'custom' })}
+ selected={projectOrder === 'custom'}
+ testID="home.deviceMenu.projectOrder.custom"
+ />
+ {projectOrder === 'custom' ? (
+ <Text style={styles.deviceMenuHint}>{t('devices.list.menu.projectOrderManualTip')}</Text>
+ ) : null}
+ </>
+ ) : null}
+ <View style={styles.deviceMenuDivider} />
+ <Text style={styles.deviceMenuSectionLabel}>{t('devices.list.menu.statusHeading')}</Text>
+ <DeviceMenuItem
+ label={t('devices.list.menu.statusActive')}
+ onPress={() => onChangeView({ statusFilter: 'active' })}
+ selected={statusFilter === 'active'}
+ testID="home.deviceMenu.status.active"
+ />
+ <DeviceMenuItem
+ label={t('devices.list.menu.statusArchived')}
+ onPress={() => onChangeView({ statusFilter: 'archived' })}
+ selected={statusFilter === 'archived'}
+ testID="home.deviceMenu.status.archived"
+ />
+ <DeviceMenuItem
+ label={t('devices.list.menu.statusAll')}
+ onPress={() => onChangeView({ statusFilter: 'all' })}
+ selected={statusFilter === 'all'}
+ testID="home.deviceMenu.status.all"
+ />
+ </ScrollView>
+ </HomeGlassMenuPanel>
+ </HomeMenuScrim>
+ );
+}
+
+function DeviceMenuItem({
+ checked = false,
+ connectionState,
+ dimmed = false,
+ icon,
+ label,
+ onPress,
+ selected,
+ status,
+ testID,
+}: {
+ checked?: boolean;
+ connectionState?: HomeDeviceConnectionState;
+ dimmed?: boolean;
+ icon?: ReactNode;
+ label: string;
+ onPress(): void;
+ selected: boolean;
+ status?: 'online' | 'offline';
+ 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>
+ {status ? (
+ <View style={styles.deviceMenuStatusSlot}>
+ <StatusDot tone={status === 'online' ? 'ready' : 'off'} pulsing={connectionState === 'syncing'} />
+ {connectionState === 'failed' ? <View style={styles.deviceConnectionFailedRing} /> : null}
+ </View>
+ ) : null}
+ </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 (
+ <Modal animationType="fade" transparent visible={deviceName != null} onRequestClose={onClose}>
+ <Pressable style={styles.revokedTipBackdrop} onPress={onClose} testID="home.revokedTip.backdrop">
+ {/* Inner press swallow keeps taps on the card from dismissing via the backdrop. */}
+ <Pressable style={styles.revokedTipCard} onPress={() => undefined}>
+ <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>
+ <Pressable
+ accessibilityLabel={t('devices.list.revoked.retry')}
+ accessibilityRole="button"
+ accessibilityState={{ busy: retrying, disabled: retrying }}
+ disabled={retrying}
+ onPress={onRetry}
+ style={({ pressed }) => [styles.revokedTipRetry, pressed && styles.pressed, retrying && styles.disabled]}
+ testID="home.revokedTip.retry"
+ >
+ {retrying ? (
+ <ActivityIndicator color={colors.ctaText} size="small" />
+ ) : (
+ <Text style={styles.revokedTipRetryText}>{t('devices.list.revoked.retry')}</Text>
+ )}
+ </Pressable>
+ </Pressable>
+ </Pressable>
+ </Modal>
+ );
+}
+
+function sanitizeDeviceChipTestId(value: string): string {
+ return value.replace(/[^A-Za-z0-9_-]/g, '_');
+}
+
+function deviceMenuStatus(item: MobileHomeDeviceFilterItem): 'online' | 'offline' {
+ return item.available && (item.state === 'ready' || item.state === 'busy') ? 'online' : 'offline';
+}
+
+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,
+ onAnchorChange,
+ projectHeaderHeight,
+ projectLayoutRevision,
+ projectRef,
+ scrollY,
+ viewportHeight,
+}: {
+ childOffsets: readonly number[];
+ 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,
+ projectHeaderHeight: projectHeaderHeight.value,
+ projectTop: layout.pageY,
+ shift: PROJECT_CHILD_WINDOW_SHIFT,
+ viewportHeight,
+ viewportTop: 0,
+ });
+ },
+ (next, previous) => {
+ // A temporarily unavailable native view is not evidence that its rows
+ // left the viewport. Keep the last bounded window until measured again.
+ if (next === null || next === previous) return;
+ runOnJS(onAnchorChange)(next);
+ },
+ [childOffsets, onAnchorChange, projectHeaderHeight, projectLayoutRevision, projectRef, scrollY, viewportHeight],
+ );
+ return null;
+}
+
+function ProjectRow({
+ collapsed,
+ dragging = false,
+ expandedAutomationGroups,
+ headerRefs,
+ kind = 'project',
+ machineIdentity,
+ onDragEnd,
+ onDragMove,
+ onDragStart,
+ onOpenAutomationGroup,
+ onOpenProject,
+ 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;
+ 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),
+ },
+ );
+ const projectHeaderHeight = useSharedValue(HOME_PROJECT_HEADER_HEIGHT);
+ const projectRef = useAnimatedRef<View>();
+ const [windowAnchor, setWindowAnchor] = useState(-1);
+ const projectLayoutRevision = useSharedValue(0);
+ const estimatedChildHeights = useMemo(() => {
+ const expandedKeys = new Set(expandedAutomationGroups);
+ return visibleSessions.map((item) => estimateHomeProjectChildHeight(item, expandedKeys));
+ }, [expandedAutomationGroups, homeStatusVersion, visibleSessions]);
+ const estimatedChildOffsets = useMemo(
+ () => buildHomeProjectChildOffsets(estimatedChildHeights),
+ [estimatedChildHeights],
+ );
+ // Keep the common five-row preview unchanged. A large expanded group keeps
+ // its complete estimated height as a spacer until native layout establishes
+ // that its child area intersects the viewport. This avoids mounting an
+ // off-screen child window just because the folder header entered the outer
+ // SectionList render window.
+ const windowingEnabled = shouldWindowHomeProjectChildren({
+ collapsed,
+ itemCount: visibleSessions.length,
+ scrollTrackingAvailable: !!homeScrollY,
+ threshold: PROJECT_CHILD_WINDOW_THRESHOLD,
+ });
+ const scrollY = homeScrollY;
+ const childContentHeight = estimatedChildOffsets[estimatedChildOffsets.length - 1] ?? 0;
+ const childWindow = windowingEnabled
+ ? windowAnchor >= 0
+ ? resolveHomeProjectChildWindow({
+ anchor: windowAnchor,
+ childOffsets: estimatedChildOffsets,
+ overscan: PROJECT_CHILD_WINDOW_OVERSCAN,
+ windowSize: PROJECT_CHILD_WINDOW_SIZE,
+ })
+ : {
+ end: 0,
+ leadingSpacerHeight: 0,
+ start: 0,
+ trailingSpacerHeight: childContentHeight,
+ }
+ : {
+ 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 dragGesture = useMemo(() => {
+ if (!onDragStart || !onDragMove || !onDragEnd || kind !== 'project') return null;
+ const start = onDragStart;
+ const move = onDragMove;
+ const finish = onDragEnd;
+ return Gesture.Pan()
+ .activateAfterLongPress(380)
+ .onStart((event) => {
+ runOnJS(start)({
+ absoluteY: event.absoluteY,
+ count: project.sessionCount,
+ key: project.key,
+ 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"
+ accessibilityState={{ expanded: !collapsed }}
+ onLayout={(event) => {
+ const height = event.nativeEvent.layout.height;
+ if (Number.isFinite(height) && height > 0) projectHeaderHeight.value = height;
+ }}
+ onPress={dragging ? undefined : onToggle}
+ 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} />
+ )}
+ {kind === 'dialogue' ? (
+ <MessagesSquare color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.thin} />
+ ) : kind === 'cindy-make' ? (
+ <Hammer color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.thin} />
+ ) : collapsed ? (
+ <Folder color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.thin} />
+ ) : (
+ <FolderOpen color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.thin} />
+ )}
+ <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>
+ </Pressable>
+ );
+ return (
+ <Reanimated.View
+ 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}
+ {dragGesture ? <GestureDetector gesture={dragGesture}>{header}</GestureDetector> : header}
+
+ {collapsed ? null : (
+ <View 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 内的透传包裹)。
+ if (!swipeable) {
+ return <Fragment key={reactKey}>{row}</Fragment>;
+ }
+ return (
+ <SwipeableSessionRow
+ key={reactKey}
+ onArchive={swipe.onArchive}
+ onShowOptions={swipe.onShowOptions}
+ onTogglePin={swipe.onTogglePin}
+ registry={swipe.registry}
+ session={item.session as RemoteSession}
+ testID={`${childTestID}.swipe`}
+ >
+ {row}
+ </SwipeableSessionRow>
+ );
+ })}
+ {trailingSpacerHeight > 0 ? <View pointerEvents="none" style={{ height: trailingSpacerHeight }} /> : null}
+ {hiddenRowCount > 0 ? (
+ <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>
+ ) : null}
+ </View>
+ )}
+ </Reanimated.View>
+ );
+}
+
+/**
+ * 首页 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,
+ 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): 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)}
+ 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}
+ 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,
+ 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;
+ /** 平铺时标题旁的来源标签(项目名 /「对话」);分组模式下不传。 */
+ 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 styles = useThemedStyles(makeStyles);
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ // 运行态走订阅而非命令式读取:行已 memo 化,父层不再逐 emit 重渲染,命令式读取会 stale。
+ const latestItem = latestMobileSessionRow(item);
+ 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 { 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;
+ // 自动化组行:同一任务的多次运行折叠而成(共享层 groupAutomationListItems 产出)。
+ // 没接展开回调的调用点退化为普通行为(点击打开 primary 会话)。
+ // 块模式:组行 + 展开的子行整体包在一个上下全宽线的块里;组行自身不再画缩进分割线
+ // (收起时块底线紧贴行底,展开时组头与子行之间保持连续无线,均与项目组语义一致)。
+ const blockMode = asBlock && !!group;
+ // 预览走共享 buildRemoteSessionCardPreview(已并入 #368 的 liveActivity),运行中会显示实时活动;
+ // 组行的预览位改为任务态摘要(需关注数 / 执行中 / 共 N 次运行),对齐桌面版组头 meta。
+ const preview = group
+ ? automationGroupPreview(item, group.sessionCount, t)
+ : buildRemoteSessionCardPreview(
+ loadedMessagePreview === undefined || loadedMessagePreview === item.messagePreview
+ ? item
+ : { ...item, messagePreview: loadedMessagePreview },
+ { running },
+ );
+ // 零消息会话没有摘要。此时不要保留双行列表的空白第二行;但定时任务与置顶
+ // 标记仍占用右下状态槽,因此继续使用双行布局。
+ const showPreviewLine = !!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 handlePress = selectionMode && onPressSelection
+ ? onPressSelection
+ : group
+ ? groupRowOpensPrimary ? openGroupPrimary : () => onToggleAutomationGroup?.(group.key)
+ : () => onOpenSession(item);
+ return (
+ <View
+ style={blockMode
+ ? [
+ styles.automationGroupBlock,
+ suppressBlockTopBorder && styles.automationGroupBlockNoTop,
+ ]
+ : undefined}
+ >
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={group
+ ? groupRowOpensPrimary ? t('devices.list.a11y.openAutomationLatest', { title: item.title }) : t('devices.list.a11y.automationTask', { title: item.title })
+ : t('devices.list.a11y.openConversation', { title: item.title })}
+ accessibilityState={group ? { expanded: groupExpanded, selected: selected || active } : { selected: selected || active }}
+ delayLongPress={400}
+ onLongPress={
+ !selectionMode && !group && swipe && conversationSearchAllowsLocalWrites(item)
+ ? () => {
+ swipe.registry.closeOpenRow();
+ swipe.onShowOptions(latestMobileSessionRow(item).session as RemoteSession);
+ }
+ : onLongPress}
+ onPress={handlePress}
+ 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}
+ {group && !selectionMode ? (
+ // 展开箭头放行首,与项目组的折叠交互一致(chevron → 图标 → 标题);
+ // 独立热区:即使组行点击直开会话(有需关注内容时),点箭头仍然是展开 / 收起。
+ <Pressable
+ accessibilityLabel={groupExpanded ? t('devices.list.a11y.collapse', { title: item.title }) : t('devices.list.a11y.expand', { title: item.title })}
+ accessibilityRole="button"
+ hitSlop={{ bottom: 12, left: 12, right: 4, top: 12 }}
+ onPress={(event) => {
+ // 防御性阻断:避免 chevron 点击同时触发父行 onPress(有需关注内容时父行
+ // 是"直开 primary 会话",双触发会边展开边跳页)。与设备菜单重命名按钮同款处理。
+ event.stopPropagation();
+ onToggleAutomationGroup?.(group.key);
+ }}
+ style={styles.sessionGroupChevronCell}
+ testID={`${testID}.automationGroupChevron`}
+ >
+ {groupExpanded ? (
+ <ChevronDown color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
+ ) : (
+ <ChevronRight color={colors.textSecondary} size={iconSize.xl} strokeWidth={iconStroke.regular} />
+ )}
+ </Pressable>
+ ) : null}
+ <View style={[
+ styles.sessionIconCell,
+ !showPreviewLine && styles.sessionIconCellSingleLine,
+ ]}>
+ <SessionStatusMark
+ item={item}
+ running={running}
+ showDraftIndicator={showDraftIndicator}
+ />
+ </View>
+ <View style={[
+ styles.sessionListContent,
+ (hideDivider || blockMode || (!!group && groupExpanded)) && styles.sessionListContentNoDivider,
+ ]}>
+ <View style={styles.sessionTitleRow}>
+ <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} />
+ {sourceLabel ? (
+ <Text
+ ellipsizeMode="tail"
+ numberOfLines={1}
+ style={styles.sessionSourceLabel}
+ testID={`home.sessionSourceLabel.${item.session.id}`}
+ >
+ {sourceLabel}
+ </Text>
+ ) : null}
+ {rightStatus === 'time' ? (
+ <SessionRelativeTime lastActivityAt={item.lastActivityAt} style={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 ? (
+ <View style={styles.sessionPreviewRow}>
+ <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 ? (
+ <AutomationGroupChildren
+ childTestID={automationChildTestID}
+ childrenTestID={automationChildrenTestID}
+ group={group}
+ inBlock={blockMode}
+ suppressTrailingDivider={hideDivider}
+ onOpenGroup={onOpenAutomationGroup}
+ onOpenSession={onOpenSession}
+ swipe={swipe}
+ testID={testID}
+ titleTestIDPrefix={titleTestIDPrefix}
+ />
+ ) : null}
+ </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;
+ return (
+ <View style={styles.automationGroupChildren} testID={childrenTestID ?? `${testID}.automationGroupChildren`}>
+ {visibleItems.map((child, index) => {
+ 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={child.session.id}>{row}</Fragment>;
+ return (
+ <SwipeableSessionRow
+ key={child.session.id}
+ onArchive={swipe.onArchive}
+ onShowOptions={swipe.onShowOptions}
+ onTogglePin={swipe.onTogglePin}
+ registry={swipe.registry}
+ session={child.session as RemoteSession}
+ testID={`${testID}.automationChild.swipe`}
+ >
+ {row}
+ </SwipeableSessionRow>
+ );
+ })}
+ {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}
+ </View>
+ );
+}
+
+/** 自动化组行的预览位文案:需关注数 > 执行中 > 共 N 次运行(对齐桌面版组头 meta 的优先级)。 */
+function automationGroupPreview(item: RemoteSessionListItem, sessionCount: number, t: TFunction): string {
+ const unread = item.scheduleInfo?.unreadCount ?? 0;
+ const waiting = item.pendingInteractionCount;
+ if (unread > 0 || waiting > 0) {
+ return [
+ unread > 0 ? t('devices.list.preview.needAttention', { count: unread }) : null,
+ waiting > 0 ? t('devices.list.preview.waiting', { count: waiting }) : null,
+ ].filter(Boolean).join(' · ');
+ }
+ if (item.scheduleInfo?.running) return t('devices.list.preview.automationRunning');
+ return t('devices.list.preview.totalRuns', { count: sessionCount });
+}
+
+// 状态提醒点已移到行右侧(替代时间位,与桌面一致),行首图标只保留 vendor 标识 +
+// running 呼吸 + 草稿铅笔,不再叠角标点。
+/** 行右侧 running spinner —— 与桌面 SessionItem 右槽同款:LoaderCircle(即桌面的
+ * lucide Loader2)圆弧图标,1s linear 无限旋转(Tailwind animate-spin 同参数)。 */
+/**
+ * 行右侧相对时间标签(「刚刚 / N 分钟前」)的独家保鲜叶子:行主体 memo 化后不再逐
+ * emit 重渲染,时间标签失去偶然保鲜会无限期冻结(review P1);而把分钟订阅挂在行
+ * 本体又等于每分钟重画全列表重型子树(review 复核 P1)。下沉到只渲染一个 Text 的
+ * 叶子组件独家订阅 useMinuteNow:每分钟只重渲染 ~百个纯 Text,行主体纹丝不动。
+ */
+function SessionRelativeTime({ lastActivityAt, style }: { lastActivityAt: string; style: StyleProp<TextStyle> }) {
+ useMinuteNow();
+ return (
+ <Text style={style} numberOfLines={1}>
+ {formatRemoteSessionSidebarTime(lastActivityAt)}
+ </Text>
+ );
+}
+
+function SessionRightSpinner({ testID }: { testID?: string }) {
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ const spin = useRef(new Animated.Value(0)).current;
+ useEffect(() => {
+ const loop = Animated.loop(
+ Animated.timing(spin, {
+ duration: 1000,
+ easing: Easing.linear,
+ toValue: 1,
+ useNativeDriver: true,
+ }),
+ );
+ loop.start();
+ return () => {
+ loop.stop();
+ };
+ }, [spin]);
+ const rotate = spin.interpolate({ inputRange: [0, 1], outputRange: ['0deg', '360deg'] });
+ return (
+ <Animated.View
+ accessibilityLabel={t('devices.list.a11y.running')}
+ style={{ transform: [{ rotate }] }}
+ testID={testID}
+ >
+ <LoaderCircle color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />
+ </Animated.View>
+ );
+}
+
+/** 该首页行是否以「块」呈现(上下全宽线):项目组,或自动化组行(顶层 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: { opacity: 0.72 },
+ 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,
+ },
+ headerIconButton: {
+ alignItems: 'center',
+ flexShrink: 0,
+ height: 44,
+ justifyContent: 'center',
+ width: 44,
+ },
+ headerActions: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ gap: spacing.xs,
+ },
+ headerTitleWrap: {
+ alignItems: 'center',
+ flex: 1,
+ justifyContent: 'center',
+ minHeight: 44,
+ minWidth: 0,
+ paddingHorizontal: spacing.sm,
+ },
+ headerTitleCluster: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ flexShrink: 1,
+ gap: 6,
+ maxWidth: '100%',
+ minWidth: 0,
+ },
+ headerTitle: {
+ color: colors.textPrimary,
+ flexShrink: 1,
+ fontSize: typeScale.listTitle,
+ fontWeight: fontWeight.semibold,
+ lineHeight: lineHeight.listTitleCompact,
+ },
+ deviceMenuPanelCenter: {
+ alignSelf: 'center',
+ },
+ deviceMenuPanelEnd: {
+ alignSelf: 'flex-end',
+ },
+ 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.caption,
+ fontWeight: fontWeight.medium,
+ minWidth: 0,
+ },
+ connectionIconButton: {
+ alignItems: 'center',
+ borderRadius: radius.pill,
+ height: 28,
+ justifyContent: 'center',
+ width: 28,
+ },
+ deviceConnectionFailedRing: {
+ borderColor: colors.errorBorder,
+ // 16×16 圆环:语义是正圆,用 pill(RN 钳制到半高)而非碰巧同值的 control 档。
+ borderRadius: radius.pill,
+ borderWidth: 1.5,
+ height: 16,
+ position: 'absolute',
+ width: 16,
+ },
+ 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,
+ },
+ deviceMenuSectionLabel: {
+ color: colors.textTertiary,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.medium,
+ lineHeight: lineHeight.caption,
+ paddingHorizontal: spacing.md,
+ paddingTop: spacing.sm,
+ },
+ deviceMenuHint: {
+ color: colors.textTertiary,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.regular,
+ lineHeight: lineHeight.caption,
+ paddingHorizontal: spacing.md,
+ paddingVertical: spacing.sm,
+ },
+ deviceMenuStatusSlot: {
+ alignItems: 'center',
+ height: 20,
+ justifyContent: 'center',
+ position: 'relative',
+ width: 20,
+ },
+ deviceMenuDivider: {
+ backgroundColor: colors.border,
+ height: StyleSheet.hairlineWidth,
+ marginHorizontal: spacing.sm,
+ marginVertical: spacing.sm,
+ },
+ 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.medium,
+ lineHeight: lineHeight.subtitle,
+ },
+ revokedTipBody: {
+ color: colors.textSecondary,
+ fontSize: typeScale.body,
+ lineHeight: lineHeight.body,
+ },
+ revokedTipRetry: {
+ alignItems: 'center',
+ backgroundColor: colors.cta,
+ borderRadius: radius.pill,
+ height: 44,
+ justifyContent: 'center',
+ marginTop: spacing.sm,
+ },
+ revokedTipRetryText: {
+ color: colors.ctaText,
+ fontSize: typeScale.body,
+ fontWeight: fontWeight.semibold,
+ },
+ homeList: {
+ backgroundColor: colors.surface,
+ flex: 1,
+ },
+ listContent: {
+ backgroundColor: colors.surface,
+ flexGrow: 1,
+ paddingBottom: 83,
+ 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.caption,
+ fontWeight: fontWeight.medium,
+ lineHeight: lineHeight.code,
+ },
+ 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: 8,
+ 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: 54,
+ paddingLeft: 48,
+ 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: {
+ // 自动化组行行首的展开箭头列:与项目组行首 chevron 对齐(尺寸 22、次级色),
+ // 垂直对齐标题行(与 sessionIconCell 同一基线)。
+ alignItems: 'center',
+ justifyContent: 'flex-start',
+ marginRight: -spacing.xs,
+ paddingTop: 23,
+ width: 22,
+ },
+
+ // 右侧状态槽(替代时间位):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,
+ },
+
+ 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,
+ },
+});
diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsx
index e8137dc891..1ae2406216 100644
--- a/apps/mobile/src/session/InteractionPanel.tsx
+++ b/apps/mobile/src/session/InteractionPanel.tsx
@@ -1,3 +1,4 @@
+import { usePaneViewport } from '@/platform/AdaptiveWindowContext';
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { mobilePresentationLocalizer } from '@/i18n/presentationLocalizer';
@@ -163,7 +164,7 @@ export function InteractionPanel({
if (!activeRequestId) return fallbackInteraction;
return sortedInteractions.find((item) => readRequestId(item) === activeRequestId) ?? fallbackInteraction;
}, [activeRequestId, fallbackInteraction, sortedInteractions]);
- const { width: screenWidth } = useWindowDimensions();
+ const { width: screenWidth } = usePaneViewport();
useEffect(() => {
if (!activeRequestId) return;
if (!sortedInteractions.some((item) => readRequestId(item) === activeRequestId)) {
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index f1bbe6b593..dc9d5add4b 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -1,3 +1,6 @@
+import { useMessageHistoryActive, useMessageHistoryPositioning } from './messageHistoryActivity';
+import { usePaneViewport } from '@/platform/AdaptiveWindowContext';
+import { messageReadingPosition } from './messageReadingPosition';
import { PluginInvocationHeader } from './PluginInvocationHeader';
import { useAuth } from '@/auth/AuthContext';
import { downloadRemoteMediaShareTemp } from './remoteMediaDiskCacheExpo';
@@ -707,11 +710,14 @@ export function MessageRenderer({
focusedRequestKey,
queueFooter,
scrollResetKey,
+ isReadingPositionActive,
syncingWhileEmpty,
testID,
devExposeList,
devRecycleItems = false,
}: {
+ /** Offscreen preload and disappearing native screens must not replace the user's bookmark. */
+ isReadingPositionActive?: () => boolean;
bottomOverlayHeight?: number;
/** Floating composers reserve a stable tail gap while their expanded surface overlays history. */
contentBottomInset?: number;
@@ -761,6 +767,17 @@ export function MessageRenderer({
const { colors } = useTheme();
const { t } = useTranslation();
const styles = useThemedStyles(makeStyles);
+ const historyActive = useMessageHistoryActive();
+ const historyPositioning = useMessageHistoryPositioning();
+ const historyPositioningRef = useRef(historyPositioning);
+ historyPositioningRef.current = historyPositioning;
+ const historyActiveRef = useRef(historyActive);
+ historyActiveRef.current = historyActive;
+ const readingPosition = useMemo(() => scrollResetKey && remoteDeviceId
+ ? messageReadingPosition(remoteDeviceId, scrollResetKey) : null, [remoteDeviceId, scrollResetKey]);
+ const reopeningPosition = useMemo(() => readingPosition?.read(), [readingPosition]);
+ const readingPositionActiveRef = useRef(isReadingPositionActive);
+ readingPositionActiveRef.current = isReadingPositionActive;
const itemStructureIdentity = itemsStructureKey ?? items;
const itemsForStructureRef = useRef(items);
itemsForStructureRef.current = items;
@@ -780,7 +797,7 @@ export function MessageRenderer({
const listTopPaddingRef = useRef(0);
const listBottomPaddingRef = useRef(0);
const shareableMessageViewsRef = useRef(new Map<string, View>());
- const windowDimensions = useWindowDimensions();
+ const windowDimensions = usePaneViewport();
const viewportLayout = useMemo(() => buildMobileReadableViewportLayout({
screenHeight: windowDimensions.height,
screenWidth: windowDimensions.width,
@@ -788,7 +805,7 @@ export function MessageRenderer({
const wideContentInset = viewportLayout.wideViewport
? Math.max(0, (windowDimensions.width - viewportLayout.contentMaxWidth) / 2)
: 0;
- const nearBottomRef = useRef(true);
+ const nearBottomRef = useRef(reopeningPosition?.atEnd ?? true);
// ── 拖动手势追踪(贴底跟随的意图解除用)──
// 拖动期间(onScrollBeginDrag ~ onScrollEndDrag)相对起点累计上移超过死区
// → 立即解除跟随(shouldUnpinMobileFollowOnDrag),不看近底距离阈值——
@@ -856,6 +873,8 @@ export function MessageRenderer({
// 实际定位完成就直接显示;UI 线程只负责 300ms 兜底,不让繁忙 JS 无限延长隐藏。
// 揭示沿用唯一 tail follower 的位置校验,不再额外等待或对旧消息做淡入。
const initialAnchorDoneRef = useRef(false);
+ const reopeningAnchorRef = useRef<{ anchor: MobileHistoryAnchor; expires: number; corrections: number } | null>(null);
+ const reopeningFrameRef = useRef<number | null>(null);
const initialRevealGenerationRef = useRef(0);
const initialRevealAnimationRef = useRef<Animated.CompositeAnimation | null>(null);
const initialRevealProgress = useMemo(
@@ -882,7 +901,7 @@ export function MessageRenderer({
if (prevScrollResetKeyRef.current !== scrollResetKey) {
prevScrollResetKeyRef.current = scrollResetKey;
listMetricsRef.current = { footerSize: 0, headerSize: 0 };
- nearBottomRef.current = true;
+ nearBottomRef.current = reopeningPosition?.atEnd ?? true;
isDraggingRef.current = false;
isMomentumScrollingRef.current = false;
dragStartOffsetYRef.current = null;
@@ -927,6 +946,7 @@ export function MessageRenderer({
tailFollowerRef.current?.reset();
tailFollowerRef.current = null;
initialAnchorDoneRef.current = false;
+ reopeningAnchorRef.current = null;
initialRevealGenerationRef.current += 1;
initialRevealAnimationRef.current?.stop();
initialRevealAnimationRef.current = null;
@@ -957,16 +977,21 @@ export function MessageRenderer({
const handleMessageActionSheetOpenChange = useCallback((clientId: string, open: boolean) => {
if (open) openMessageActionSheetsRef.current.add(clientId);
else openMessageActionSheetsRef.current.delete(clientId);
+ if (!historyActiveRef.current) return;
onBlockingOverlayChange?.(
payloadRef.current !== null || openMessageActionSheetsRef.current.size > 0,
);
}, [onBlockingOverlayChange]);
useEffect(() => {
+ if (!historyActive) {
+ setPayload(null);
+ return;
+ }
onBlockingOverlayChange?.(
payload !== null || openMessageActionSheetsRef.current.size > 0,
);
return () => onBlockingOverlayChange?.(false);
- }, [onBlockingOverlayChange, payload]);
+ }, [historyActive, onBlockingOverlayChange, payload]);
// 关闭回调必须引用稳定:内联闭包每次渲染换新,会经 ImageLightbox 透传成
// LightboxPage 手势 useMemo 的依赖,流式回复期间每 token 重建手势图,
// 可能打断进行中的捏合/拖动手势(rule 7)。
@@ -1034,7 +1059,7 @@ export function MessageRenderer({
metrics: scrollMetricsRef.current,
stickToLatest: nearBottomRef.current,
userControllingScroll: isUserControllingScroll(),
- preservingHistory: readingOlderRef.current,
+ preservingHistory: readingOlderRef.current || !historyPositioningRef.current,
layoutSettleAt: mvcpSettleAtRef.current,
animatedScrollUntil: programmaticAnimatedScrollInFlightRef.current
? programmaticScrollSettleAtRef.current : 0,
@@ -1061,9 +1086,13 @@ export function MessageRenderer({
intent: 'follow' | 'explicit' = 'follow',
) => {
// Only an explicit destination supersedes a pending final drag sample.
- if (intent === 'explicit') dragStartOffsetYRef.current = null;
+ if (intent === 'explicit') {
+ reopeningAnchorRef.current = null;
+ dragStartOffsetYRef.current = null;
+ readingPosition?.write({ anchor: null, atEnd: true });
+ }
getTailFollower().requestEnd(animated, intent === 'explicit');
- }, [getTailFollower]);
+ }, [getTailFollower, readingPosition]);
const scrollToOffsetProgrammatically = useCallback((offset: number, animated: boolean) => {
markProgrammaticScroll(animated);
@@ -1108,6 +1137,34 @@ export function MessageRenderer({
: null;
}, [getCurrentHistoryTopOffsetAdjustment]);
+ // A seek first uses estimated heights. Correct it only when layout supplies
+ // real positions; never retry from onScroll (which can create a scroll storm).
+ const reconcileReopeningAnchor = useCallback(() => {
+ if (!historyPositioningRef.current || !reopeningAnchorRef.current || reopeningFrameRef.current !== null) return;
+ reopeningFrameRef.current = requestAnimationFrame(() => {
+ reopeningFrameRef.current = null;
+ const pending = reopeningAnchorRef.current;
+ if (!pending || !historyPositioningRef.current) return;
+ if (Date.now() > pending.expires || pending.corrections >= 20) {
+ reopeningAnchorRef.current = null;
+ return;
+ }
+ const state = listRef.current?.getState();
+ if (!state || state.scrollLength <= 0) return;
+ const key = pending.anchor.identityKey
+ ? mobileMessageHistoryRowKeyByIdentity(state.data, pending.anchor.identityKey) ?? pending.anchor.key
+ : pending.anchor.key;
+ const index = state.data.findIndex(item => item.key === key);
+ if (index < 0 || !Number.isFinite(state.sizeAtIndex(index))) return;
+ const target = resolveMobileMessageHistoryAnchorOffset(pending.anchor, state,
+ getCurrentHistoryTopOffsetAdjustment());
+ if (target === null || Math.abs(state.scroll - target) <= MOBILE_ANCHOR_VERIFY_TOLERANCE) return;
+ pending.corrections++;
+ markProgrammaticScroll(false);
+ listRef.current?.scrollToOffset({ offset: target, animated: false });
+ });
+ }, [getCurrentHistoryTopOffsetAdjustment, markProgrammaticScroll]);
+
const finishHistoryPrependTransaction = useCallback((generation: number) => {
const transaction = historyPrependTransactionRef.current;
if (!transaction || transaction.generation !== generation) return;
@@ -1491,7 +1548,7 @@ export function MessageRenderer({
// hydrate / 新注册后 gallery 需要重建,否则点开气泡本地图时 initialUrl 对不上图集条目。
const sentThumbsVersion = useSentAttachmentThumbsVersion();
const chatFilePathContext = useContext(ChatFilePathContext);
- const imageLightboxOpen = payload?.kind === 'media' && payload.media.kind === 'image';
+ const imageLightboxOpen = historyActive && payload?.kind === 'media' && payload.media.kind === 'image';
const galleryImages = useMemo(
() => (imageLightboxOpen
? collectMobileMessageGalleryImages(
@@ -1762,9 +1819,10 @@ export function MessageRenderer({
.map((item) => item.clientId);
}, []);
useEffect(() => {
+ if (!historyActive) return;
onVisibleShareableMessageIdsReaderChange?.(readActuallyVisibleShareableMessageIds);
return () => onVisibleShareableMessageIdsReaderChange?.(null);
- }, [onVisibleShareableMessageIdsReaderChange, readActuallyVisibleShareableMessageIds]);
+ }, [historyActive, onVisibleShareableMessageIdsReaderChange, readActuallyVisibleShareableMessageIds]);
// 贴底跟随由 handleContentSize 的手动补滚承担(nearBottomRef 是跟随意图的唯一真相);
// 跳底先命令式 scrollToEnd,随后复用同一轮有界落底校验。
@@ -1794,13 +1852,21 @@ export function MessageRenderer({
scrollToIndexProgrammatically(target.index, 0.12);
}, [scrollToIndexProgrammatically]);
+ // A retained list must not replay requests issued while another task was active.
+ const followRequestWasActiveRef = useRef(historyActive);
// Sending and the jump button share the same explicit follow action.
useEffect(() => {
+ const wasActive = followRequestWasActiveRef.current;
+ followRequestWasActiveRef.current = historyActive;
+ if (!historyActive || !wasActive) {
+ previousFollowLatestRequestKeyRef.current = followLatestRequestKey;
+ return;
+ }
if (previousFollowLatestRequestKeyRef.current === followLatestRequestKey) return;
previousFollowLatestRequestKeyRef.current = followLatestRequestKey;
if (followLatestRequestKey === null || followLatestRequestKey === undefined) return;
scrollToBottom();
- }, [followLatestRequestKey, scrollToBottom]);
+ }, [historyActive, followLatestRequestKey, scrollToBottom]);
// 自动加载更早:电平触发判定(shouldAutoLoadEarlier),在所有可能改变判定结果的时机重评估
// (scroll 事件 / LegendList onStartReached 边沿 / eligibility 变化 effect)。
@@ -1814,7 +1880,7 @@ export function MessageRenderer({
// 冷开只在列表同时位于 start/end(内容未撑满首屏)时有界补页;真实上翻意图继续沿用
// 不限页的近顶预取。两条路径都受首项进展去重保护,失败/重复页不会循环打 host。
const beginLoadEarlier = useCallback(() => {
- if (!onLoadEarlier) return;
+ if (!historyActiveRef.current || !onLoadEarlier) return;
const generation = readingOlderRequestGenerationRef.current + 1;
readingOlderRequestGenerationRef.current = generation;
const listState = listRef.current?.getState();
@@ -1925,7 +1991,7 @@ export function MessageRenderer({
}, [flushQueuedLoadEarlier, historyPrependNativeMvcpDisabled]);
const attemptAutoLoadEarlier = useCallback((nativeMetrics?: MessageScrollMetrics) => {
- if (!onLoadEarlier) return;
+ if (!historyActiveRef.current || !onLoadEarlier) return;
if (readingOlderRef.current || queuedLoadEarlierRef.current) return;
// 热路径前置短路(滚动事件每 16ms 评估一次,getState() 每次新建状态对象):没有用户浏览意图
// 且冷开预算已耗尽、或当前首项已尝试过时不碰 getState。完整判定仍以
@@ -2040,6 +2106,7 @@ export function MessageRenderer({
event: NativeSyntheticEvent<NativeScrollEvent>,
isFinalDragSample = false,
) => {
+ if (!historyPositioningRef.current) return;
// Cancellation releases ownership immediately. Only endDrag may still consume its final
// sample; an ordinary layout/MVCP scroll cannot use the retained origin as user intent.
const isDragSample = isDraggingRef.current
@@ -2052,6 +2119,21 @@ export function MessageRenderer({
};
const previousOffsetY = scrollMetricsRef.current.offsetY;
scrollMetricsRef.current = metrics;
+ // A native acknowledgment ends reopening, not merely its reveal animation.
+ // Otherwise later measurements keep replaying the old bookmark after the
+ // viewport is already correct (including after the 300ms reveal fallback).
+ const reopening = reopeningAnchorRef.current;
+ if (reopening) {
+ const state = listRef.current?.getState();
+ const target = state ? resolveMobileMessageHistoryAnchorOffset(reopening.anchor,
+ state, getCurrentHistoryTopOffsetAdjustment()) : null;
+ if (target !== null && Math.abs(metrics.offsetY - target) <= MOBILE_ANCHOR_VERIFY_TOLERANCE) {
+ reopeningAnchorRef.current = null;
+ revealPositionedHistory();
+ }
+ }
+ // Preloads need real geometry, but must not publish bookmarks or trigger user work.
+ if (!historyActiveRef.current) return;
if (mobileDebugEnabled()) mobileDebugLog('debug', 'scroll', 'list scroll', {
...metrics, dragging: isDragSample, momentum: isMomentumScrollingRef.current,
readingOlder: readingOlderRef.current, nearBottom: nearBottomRef.current,
@@ -2063,6 +2145,15 @@ export function MessageRenderer({
|| historyTouchTriggeredRef.current
) {
handoffHistoryPrependToUser();
+ // Loading older messages must not discard the reader's latest position.
+ // Only native user movement may replace the bookmark during a prepend;
+ // layout-only/MVCP events are still ignored here.
+ if (metrics.viewportHeight > 0 && metrics.contentHeight >= metrics.viewportHeight
+ && !programmaticScrollInFlightRef.current
+ && (readingPositionActiveRef.current?.() ?? true)) {
+ const anchor = captureCurrentHistoryAnchor(true);
+ if (anchor) readingPosition?.write({ anchor, atEnd: false });
+ }
}
// Prepend layout can transiently report an empty/short content range. Never feed those
// metrics into near-bottom resolution: it would flip false→true and the next size event
@@ -2123,7 +2214,17 @@ export function MessageRenderer({
attemptAutoLoadEarlier(metrics);
// 分享模式:滚动驱动吸顶 check 的几何重判(内部节流,非分享模式直接返回)。
if (shareSelectionActiveRef.current) scheduleStickyShareCheck();
+ if (initialAnchorDoneRef.current && !programmaticScrollInFlightRef.current && !readingOlderRef.current
+ && (readingPositionActiveRef.current?.() ?? true)) {
+ const anchor = captureCurrentHistoryAnchor(true);
+ if (anchor && !reopeningAnchorRef.current) readingPosition?.write({ anchor, atEnd: nearBottomRef.current });
+ }
}, [
+ captureCurrentHistoryAnchor,
+ reopeningPosition,
+ getCurrentHistoryTopOffsetAdjustment,
+ revealPositionedHistory,
+ readingPosition,
attemptAutoLoadEarlier,
bottomOverlayHeight,
handoffHistoryPrependToUser,
@@ -2131,6 +2232,7 @@ export function MessageRenderer({
]);
const handleHistoryTouchStart = useCallback((event: GestureResponderEvent) => {
+ reopeningAnchorRef.current = null;
// Android may omit momentum-end when a new finger stops a fling. The new touch owns the
// ScrollView now, so the old momentum flag must not keep a queued history request suspended.
isMomentumScrollingRef.current = false;
@@ -2191,6 +2293,7 @@ export function MessageRenderer({
// 程序化 scrollToEnd 不会触发,故不会误置);同时记录拖动起点 offset,供
// shouldUnpinMobileFollowOnDrag 判「相对起点累计上移」。
const handleScrollBeginDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
+ reopeningAnchorRef.current = null;
const nativeMetrics = {
contentHeight: event.nativeEvent.contentSize.height,
offsetY: event.nativeEvent.contentOffset.y,
@@ -2235,19 +2338,30 @@ export function MessageRenderer({
isMomentumScrollingRef.current = true;
}, []);
- const handleMomentumScrollEnd = useCallback(() => {
+ const handleMomentumScrollEnd = useCallback((event?: NativeSyntheticEvent<NativeScrollEvent>) => {
+ // The final native sample can arrive without a matching onScroll event.
+ if (event) handleScroll(event);
isMomentumScrollingRef.current = false;
refreshPreviousUserTarget();
scheduleHistoryPrependUserHandoffSettle();
scheduleQueuedLoadEarlierFlush();
runStickToLatestVerify();
}, [
+ handleScroll,
refreshPreviousUserTarget,
runStickToLatestVerify,
scheduleHistoryPrependUserHandoffSettle,
scheduleQueuedLoadEarlierFlush,
]);
+ useEffect(() => {
+ if (!historyPositioning) {
+ tailFollowerRef.current?.reset();
+ return;
+ }
+ getTailFollower().reconcile();
+ }, [historyPositioning, getTailFollower]);
+
const handleStartReached = useCallback(() => {
attemptAutoLoadEarlier();
}, [attemptAutoLoadEarlier]);
@@ -2269,6 +2383,7 @@ export function MessageRenderer({
const handleListMetricsChange = useCallback((metrics: LegendListMetrics) => {
listMetricsRef.current = metrics;
+ reconcileReopeningAnchor();
if (!readingOlderRef.current) return;
const transaction = historyPrependTransactionRef.current;
if (!transaction) return;
@@ -2281,7 +2396,7 @@ export function MessageRenderer({
) {
restoreHistoryAnchorOnce(transaction.generation);
}
- }, [restoreHistoryAnchorOnce, scheduleHistoryAnchorRestore]);
+ }, [reconcileReopeningAnchor, restoreHistoryAnchorOnce, scheduleHistoryAnchorRestore]);
// 记录 contentHeight 供近底判定 fallback + DEV harness 就绪判定;并承担**唯一的贴底跟随**:
// 内容长高(流式增长、大块一帧撑高、冷开测量结算)时,用户本就贴底(nearBottomRef,与
@@ -2289,6 +2404,7 @@ export function MessageRenderer({
// 上翻历史时 nearBottomRef=false,不打断。animated:false → 即时跟随、不排队动画。
// LegendList 内置 maintainScrollAtEnd 已弃用(见 LegendList props 注释),不存在双机制叠加。
const handleContentSize = useCallback((_width: number, height: number) => {
+ reconcileReopeningAnchor();
markMobileMvcpSettle();
scrollMetricsRef.current = { ...scrollMetricsRef.current, contentHeight: height };
// readingOlderRef:load-earlier 的 prepend 也会撑高 contentHeight,但那是顶部增长、不该贴底(review P1)。
@@ -2312,6 +2428,7 @@ export function MessageRenderer({
getTailFollower().contentChanged();
}, [
getTailFollower,
+ reconcileReopeningAnchor,
markMobileMvcpSettle,
restoreHistoryAnchorOnce,
scheduleHistoryAnchorRestore,
@@ -2351,9 +2468,31 @@ export function MessageRenderer({
if (finished) finish();
});
- // The controller seeks unmeasured rows once and owns all subsequent native correction.
- scrollToEndProgrammatically(false);
+ // Seek once, then reconcile the bookmark as estimated row heights become measured.
+ const saved = !focusedItemKeyRef.current ? reopeningPosition : undefined;
+ const savedKey = saved?.anchor?.identityKey
+ ? mobileMessageHistoryRowKeyByIdentity(listData, saved.anchor.identityKey) ?? saved.anchor.key
+ : saved?.anchor?.key;
+ const savedIndex = savedKey ? listData.findIndex(item => item.key === savedKey) : -1;
+ if (saved && !saved.atEnd && savedIndex >= 0) {
+ reopeningAnchorRef.current = { anchor: saved.anchor!, expires: Date.now() + 1500, corrections: 0 };
+ nearBottomRef.current = false;
+ setIsAwayFromBottom(true);
+ markProgrammaticScroll(false);
+ // One positioning command, using the same list-owned measurement path as message links.
+ // Do not enable initialScrollIndex: it conflicts with this list's dynamic measurement.
+ void listRef.current?.scrollToIndex({ animated: false, index: savedIndex,
+ viewPosition: 0, viewOffset: saved.anchor!.viewportOffset });
+ reconcileReopeningAnchor();
+ } else {
+ nearBottomRef.current = true;
+ setIsAwayFromBottom(false);
+ scrollToEndProgrammatically(false);
+ }
}, [
+ reopeningPosition,
+ reconcileReopeningAnchor,
+ markProgrammaticScroll,
initialRevealProgress,
listData.length,
scrollResetKey,
@@ -2365,13 +2504,15 @@ export function MessageRenderer({
// 竞态误触发自动拉历史),此处不重复。
useEffect(() => {
lastAppliedFocusKeyRef.current = null;
- setIsAwayFromBottom(false);
+ setIsAwayFromBottom(!(reopeningPosition?.atEnd ?? true));
setPreviousUserTarget(null);
setHasNewMessages(false);
- }, [scrollResetKey]);
+ }, [scrollResetKey, reopeningPosition]);
// 卸载时清掉在飞的定时器/rAF(闭包引用 listRef,卸载后触发是无害 no-op,
// 但不留悬挂句柄)。
useEffect(() => () => {
+ reopeningAnchorRef.current = null;
+ if (reopeningFrameRef.current !== null) cancelAnimationFrame(reopeningFrameRef.current);
initialRevealGenerationRef.current += 1;
readingOlderRequestGenerationRef.current += 1;
historyPrependTransactionRef.current = null;
@@ -2395,9 +2536,16 @@ export function MessageRenderer({
prevTopPaddingRef.current = topPadding;
const delta = topPadding - prev;
if (delta === 0 || (nearBottomRef.current && !readingOlderRef.current)) return;
+ // The bookmark resolver already includes current top padding. A relative
+ // compensation here would cancel its scrollToIndex using stale native metrics.
+ if (reopeningAnchorRef.current) {
+ reconcileReopeningAnchor();
+ return;
+ }
+ if (!initialAnchorDoneRef.current || nativeScrollEventSequenceRef.current === 0) return;
const { offsetY } = scrollMetricsRef.current;
scrollToOffsetProgrammatically(Math.max(0, offsetY + delta), false);
- }, [scrollToOffsetProgrammatically, topPadding]);
+ }, [reconcileReopeningAnchor, scrollToOffsetProgrammatically, topPadding]);
// 深链/搜索:滚到指定消息(LegendList scrollToIndex 自带 offscreen 处理,无需 rAF/失败兜底)。
useEffect(() => {
@@ -2410,6 +2558,7 @@ export function MessageRenderer({
const index = listData.findIndex((item) => item.key === focusedItemKey);
if (index < 0) return;
lastAppliedFocusKeyRef.current = focusRunKey;
+ reopeningAnchorRef.current = null;
// 深链 / 搜索定位是明确的历史浏览意图。定位后落在近顶区时继续自动补页,
// 不要求用户再拖动一次才能看到目标上方上下文。
userScrollForOlderRef.current = true;
@@ -2501,6 +2650,7 @@ export function MessageRenderer({
data={listData}
extraData={messageListExtraData}
getItemType={mobileMessageListItemType}
+ onItemSizeChanged={reconcileReopeningAnchor}
keyExtractor={(item) => item.key}
renderItem={renderMessageItem}
recycleItems={recycleItems}
@@ -2600,7 +2750,7 @@ export function MessageRenderer({
{hasNewMessages ? <View style={styles.scrollToBottomDot} testID="message.newMessageDot" /> : null}
</MessageListActionButton>
) : null}
- {payload?.kind === 'media' && payload.media.kind === 'image' && lightboxImages ? (
+ {historyActive && payload?.kind === 'media' && payload.media.kind === 'image' && lightboxImages ? (
// 图片走 IM 级全屏查看器(手势缩放/下滑关闭/横滑翻页);其余 payload 走通用查看器。
<ImageLightbox
annotation={imageAnnotation}
@@ -2618,7 +2768,7 @@ export function MessageRenderer({
onReleaseRemoteMedia={onReleaseRemoteMedia}
onResolveRemoteMedia={onResolveRemoteMedia}
onShareImage={onShareImage}
- payload={payload}
+ payload={historyActive ? payload : null}
/>
)}
</View>
@@ -2669,7 +2819,8 @@ const RenderItemView = memo(function RenderItemView({
: item.message.companion
? <CompanionMessageCard message={item.message} />
: item.message.orcaCard
- ? <OrcaCollabCard card={item.message.orcaCard} screenWidth={actions.screenWidth} />
+ ? <OrcaCollabCard card={item.message.orcaCard} screenWidth={actions.screenWidth}
+ blockKey={JSON.stringify([actions.remoteDeviceId, item.key])} />
: <MessageBubble item={hookSourceUserItem ?? systemCardUserItem ?? item} actions={actions} />;
break;
case 'thinking':
@@ -2910,6 +3061,10 @@ function MessageBubble({
const { t, i18n: i18nInstance } = useTranslation();
const [copyState, setCopyState] = useRecyclingState<CopyMessageStatus | 'idle' | 'copying'>('idle');
const [actionSheetOpen, setActionSheetOpen] = useRecyclingState(false);
+ const historyActive = useMessageHistoryActive();
+ useEffect(() => {
+ if (!historyActive) setActionSheetOpen(false);
+ }, [historyActive, setActionSheetOpen]);
// chat-text-quote:只解析持久化 quotesEncoded 明确标记的产品引用消息,避免
// 把用户手写的 Markdown blockquote 误当产品引用。兼容 desktop 的交错
// marker 块和 mobile 的前置引用。旧 markerless 消息保持 leading-only,
@@ -2993,10 +3148,10 @@ function MessageBubble({
const isStreamingAssistant = item.message.kind === 'assistant' && item.message.isStreaming === true;
const clientId = messageClientId(item);
useEffect(() => {
- if (!actionSheetOpen) return undefined;
+ if (!historyActive || !actionSheetOpen) return undefined;
actions.onMessageActionSheetOpenChange?.(clientId, true);
return () => actions.onMessageActionSheetOpenChange?.(clientId, false);
- }, [actionSheetOpen, actions.onMessageActionSheetOpenChange, clientId]);
+ }, [historyActive, actionSheetOpen, actions.onMessageActionSheetOpenChange, clientId]);
const shareableMessage = isShareableMessage(item.message);
const handleShareableMessageViewChange = useCallback((view: View | null) => {
actions.onShareableMessageViewChange?.(clientId, view);
@@ -3549,7 +3704,7 @@ function MessageBubble({
items={messageMenu}
onAction={selectMenuAction}
onClose={() => setActionSheetOpen(false)}
- visible={actionSheetOpen}
+ visible={historyActive && actionSheetOpen}
/>
</View>
);
@@ -4591,6 +4746,8 @@ function Rail({ children, layout }: { children: ReactNode; layout: MessageHierar
// children 用 render-prop 拿到 layout(内层 stack 间距等)。
function CollabCardShell({
blockId,
+ controlledExpanded,
+ onControlledToggle,
leadingIcon,
title,
subtitle,
@@ -4600,6 +4757,8 @@ function CollabCardShell({
children,
}: {
blockId?: string;
+ controlledExpanded?: boolean;
+ onControlledToggle?: () => void;
leadingIcon: ReactNode;
title: string;
subtitle?: string;
@@ -4616,6 +4775,8 @@ function CollabCardShell({
return (
<FoldablePanel
blockId={blockId}
+ controlledExpanded={controlledExpanded}
+ onControlledToggle={onControlledToggle}
title={title}
subtitle={subtitle}
defaultExpanded={defaultExpanded}
@@ -4873,7 +5034,15 @@ function MobileAutoResumeActionRow({
// Orca 协同卡片:Lead 派活(dispatch)/ worker 回报(report)。与 SubagentCard 共用 CollabCardShell
// chrome(同款 leadingIcon+title+可折叠 body),视觉一致;数据路径仍是 message.orcaCard,不碰 parentUuid。
// worker 回报默认收起,Lead 派活保持默认展开;正文可选中(长按复制)。识别/文案抽取在 @/session/orcaCollab。
-function OrcaCollabCard({ card, screenWidth }: { card: OrcaCollabCardModel; screenWidth?: number }) {
+function OrcaCollabCard({ card, screenWidth, blockKey }: {
+ card: OrcaCollabCardModel; screenWidth?: number; blockKey: string;
+}) {
+ const { accountGeneration } = useAuth();
+ // Remember deviations from each variant's default using the
+ // existing bounded block store, including across native route reconstruction.
+ const [toggled, toggleExpanded] = useFoldableExpandedState(
+ `orca-toggled-${JSON.stringify([accountGeneration, blockKey, card.variant])}`, false,
+ );
const { colors } = useTheme();
const styles = useThemedStyles(makeStyles);
const body = card.body && card.body.trim() ? card.body : null;
@@ -4892,7 +5061,8 @@ function OrcaCollabCard({ card, screenWidth }: { card: OrcaCollabCardModel; scre
<CollabCardShell
leadingIcon={<Bot color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.regular} />}
title={card.title}
- defaultExpanded={card.variant === 'dispatch'}
+ controlledExpanded={(card.variant === 'dispatch') !== toggled}
+ onControlledToggle={toggleExpanded}
screenWidth={screenWidth}
testID={`message.orcaCard.${card.variant}`}
>
diff --git a/apps/mobile/src/session/NativeResidentHistory.tsx b/apps/mobile/src/session/NativeResidentHistory.tsx
new file mode 100644
index 0000000000..cb2cad6792
--- /dev/null
+++ b/apps/mobile/src/session/NativeResidentHistory.tsx
@@ -0,0 +1,12 @@
+import { Platform, type ViewProps } from 'react-native';
+import { requireNativeViewManager, requireOptionalNativeModule } from 'expo-modules-core';
+
+const native = Platform.OS === 'ios'
+ ? requireOptionalNativeModule<{ residentHistoryAvailable?: boolean }>('XdtIosActionSheet') : null;
+// An older installed iOS binary must retain normal navigation, never use a
+// root overlay that intercepts the native interactive-pop gesture.
+export const needsResidentHistoryUpgrade = Platform.OS === 'ios' && !native?.residentHistoryAvailable;
+export const NativeHistoryHost = native?.residentHistoryAvailable
+ ? requireNativeViewManager<ViewProps & { surfaceId: string }>('XdtIosActionSheet', 'ResidentHistoryHost') : null;
+export const NativeHistorySlot = native?.residentHistoryAvailable
+ ? requireNativeViewManager<ViewProps & { surfaceId: string; selected: boolean }>('XdtIosActionSheet', 'ResidentHistorySlot') : null;
diff --git a/apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx b/apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx
index 7b4bdf2a28..65dd599437 100644
--- a/apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx
+++ b/apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx
@@ -1,19 +1,19 @@
import { Button, Image, ProgressView, Text, Toggle } from '@expo/ui/swift-ui';
-import { buttonStyle, controlSize, disabled, font, foregroundStyle, frame } from '@expo/ui/swift-ui/modifiers';
+import { disabled, font, foregroundStyle, frame } from '@expo/ui/swift-ui/modifiers';
import { useTranslation } from 'react-i18next';
import { iconSize, useTheme } from '@/theme';
import { ComposerSheet } from './ComposerSheet';
import { ComposerNativeRow } from './ComposerNativeRow';
import { ComposerNativeSection as Section } from './ComposerNativeSection';
import { newSessionText } from './newSessionMessages';
-import { useLiquidGlassAvailable } from './useLiquidGlassAvailable';
+import { useNativeGlassButtonStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";
import type { NewTaskSelectionSheetProps } from './NewTaskSelectionSheet';
/** One full-width native presentation, including navigation into remote folders. */
export function NewTaskSelectionSheet(p: NewTaskSelectionSheetProps) {
const { t } = useTranslation();
const { colors } = useTheme();
- const glass = useLiquidGlassAvailable();
+ const glassStyle = useNativeGlassButtonStyle({ prominent: true });
const browsing = p.page === 'directory';
const unavailable = p.busy || p.loading;
const icon = (name: 'laptopcomputer' | 'folder' | 'bubble.left' | 'folder.badge.plus' | 'chevron.right' | 'arrow.up') =>
@@ -30,7 +30,7 @@ export function NewTaskSelectionSheet(p: NewTaskSelectionSheetProps) {
footer={browsing ? (
<Button
onPress={() => { if (p.path && !unavailable && !p.error) p.onChoose(p.path); }}
- modifiers={[buttonStyle(glass ? 'glassProminent' : 'borderedProminent'), controlSize('large'), disabled(unavailable || !p.path || !!p.error)]}
+ modifiers={[...glassStyle, disabled(unavailable || !p.path || !!p.error)]}
testID="newSession.remoteBrowseSelectCurrent"
>
<Text modifiers={[frame({ maxWidth: Infinity, minHeight: 44 })]}>{t('session.new.useCurrent')}</Text>
diff --git a/apps/mobile/src/session/RecentMessageHistories.tsx b/apps/mobile/src/session/RecentMessageHistories.tsx
new file mode 100644
index 0000000000..c4a12ec6ee
--- /dev/null
+++ b/apps/mobile/src/session/RecentMessageHistories.tsx
@@ -0,0 +1,175 @@
+import { createContext, useCallback, useContext, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';
+import { StyleSheet, View } from 'react-native';
+import { useSegments } from 'expo-router';
+import { NavigationContext, NavigationRouteContext, useIsFocused } from 'expo-router/react-navigation';
+import { PaneViewportProvider, usePaneViewport } from '@/platform/AdaptiveWindowContext';
+import { getRecentTasks, recentTaskKey, subscribeRecentTasks } from './recentTasks';
+import { NativeHistoryHost, NativeHistorySlot, needsResidentHistoryUpgrade } from './NativeResidentHistory';
+
+import { MessageHistoryActive, MessageHistoryPositioning } from './messageHistoryActivity';
+export { useMessageHistoryActive, useMessageHistoryPositioning } from './messageHistoryActivity';
+type Frame = { left: number; top: number; width: number; height: number };
+type Entry = { key: string; owner: string; children: ReactNode; frame: Frame;
+ focused: boolean; ready: boolean; topInset: number; bottomInset: number; interactive: boolean };
+const Context = createContext<{
+ host: React.RefObject<View | null>;
+ namespace: string;
+ publish(entry: Entry): void;
+ release(owner: string): void;
+ setOverlay(owner: string, children: ReactNode): void;
+} | null>(null);
+
+/** The only owner of mounted histories. Route slots may disappear; these keyed
+ * React children remain mounted until LRU eviction or sign-out. On iOS, a plain
+ * native content container docks into the route without moving React ownership. */
+export function RecentMessageHistoriesProvider({ children }: { children: ReactNode }) {
+ const host = useRef<View>(null);
+ const namespace = useId();
+ const [overlays, setOverlays] = useState<Map<string, ReactNode>>(() => new Map());
+ const setOverlay = useCallback((owner: string, content: ReactNode) => {
+ setOverlays(previous => {
+ const next = new Map(previous);
+ if (content === null) next.delete(owner); else next.set(owner, content);
+ return next;
+ });
+ }, []);
+ const tasks = useSyncExternalStore(subscribeRecentTasks, getRecentTasks, getRecentTasks);
+ const [entries, setEntries] = useState<Map<string, Entry>>(() => new Map());
+ const segments = useSegments() as string[];
+ const onTaskRoute = segments[0] === 'sessions' && segments[1] === '[sessionId]';
+ const allowed = useMemo(() => new Set(tasks.map(task => recentTaskKey(task.params))), [tasks]);
+ const publish = useCallback((entry: Entry) => {
+ setEntries(previous => {
+ if (previous.get(entry.key) === entry) return previous;
+ const cached = previous.get(entry.key);
+ if (!cached && !entry.ready) return previous;
+ // A blurred old route cannot overwrite a newer route for the same task.
+ if (cached?.focused && !entry.focused && cached.owner !== entry.owner) return previous;
+ const next = new Map(previous);
+ if (entry.focused) for (const [key, other] of next) {
+ if (key !== entry.key && other.focused) next.set(key, { ...other, focused: false });
+ }
+ // Do not resize a retained list with a route's initial zero-height chrome
+ // or replace its data with the loading shell while that route hydrates.
+ next.set(entry.key, cached && !entry.ready
+ ? { ...cached, owner: entry.owner, focused: entry.focused, ready: false, interactive: false }
+ : entry);
+ return next;
+ });
+ }, []);
+ const release = useCallback((owner: string) => {
+ setEntries(previous => {
+ const next = new Map(previous);
+ let changed = false;
+ for (const [key, entry] of next) if (entry.owner === owner && entry.focused) {
+ next.set(key, { ...entry, focused: false }); changed = true;
+ }
+ return changed ? next : previous;
+ });
+ }, []);
+ useLayoutEffect(() => {
+ setEntries(previous => {
+ const next = new Map([...previous].filter(([key]) => allowed.has(key)));
+ return next.size === previous.size ? previous : next;
+ });
+ }, [allowed]);
+ const context = useMemo(() => ({ host, namespace, publish, release, setOverlay }), [namespace, publish, release, setOverlay]);
+ return <Context.Provider value={context}>
+ <View ref={host} collapsable={false} style={styles.container}>
+ {children}
+ {[...entries].filter(([key]) => allowed.has(key)).map(([key, entry]) => {
+ const active = onTaskRoute && entry.focused;
+ if (NativeHistoryHost) return <NativeHistoryHost key={key} surfaceId={namespace + key}
+ pointerEvents="none" style={{ position: 'absolute', width: entry.frame.width, height: entry.frame.height }}>
+ <MessageHistoryPositioning.Provider value={active && entry.ready}>
+ <MessageHistoryActive.Provider value={active && entry.ready}>{entry.children}</MessageHistoryActive.Provider>
+ </MessageHistoryPositioning.Provider>
+ </NativeHistoryHost>;
+ // Keep the original list viewport/offset, but restrict this root layer's
+ // drawing and hit area to the message body. Native chrome/composer stay in
+ // their route and must remain above/outside the resident scroll surface.
+ const top = Math.min(entry.frame.height, Math.max(0, entry.topInset));
+ const bottom = Math.min(entry.frame.height - top, Math.max(0, entry.bottomInset));
+ return <View key={key} pointerEvents={active && entry.interactive ? 'auto' : 'none'}
+ accessibilityElementsHidden={!active} importantForAccessibility={active ? 'auto' : 'no-hide-descendants'}
+ style={[styles.clip, { left: entry.frame.left, top: entry.frame.top + top,
+ width: entry.frame.width, height: entry.frame.height - top - bottom, opacity: active ? 1 : 0 }]}>
+ <View style={{ position: 'absolute', top: -top, width: entry.frame.width, height: entry.frame.height }}>
+ <MessageHistoryPositioning.Provider value={active && entry.ready}>
+ <MessageHistoryActive.Provider value={active && entry.ready}>{entry.children}</MessageHistoryActive.Provider>
+ </MessageHistoryPositioning.Provider>
+ </View>
+ </View>;
+ })}
+ {onTaskRoute ? [...overlays].map(([owner, content]) => <View key={owner}
+ pointerEvents="box-none" style={StyleSheet.absoluteFill}>{content}</View>) : null}
+ </View>
+ </Context.Provider>;
+}
+
+/** A route publishes current props and a measuring slot; it never owns a list. */
+export function RecentMessageHistories({ activeKey, children, topInset = 0, bottomInset = 0, interactive = true, ready = true }: {
+ activeKey: string; children: ReactNode; topInset?: number; bottomInset?: number; interactive?: boolean; ready?: boolean;
+}) {
+ const context = useContext(Context);
+ if (!context) throw new Error('RecentMessageHistoriesProvider is missing');
+ const { host, publish, release } = context;
+ const owner = useId();
+ const focused = useIsFocused();
+ const navigation = useContext(NavigationContext);
+ const route = useContext(NavigationRouteContext);
+ const viewport = usePaneViewport();
+ const anchor = useRef<View>(null);
+ const [frame, setFrame] = useState<Frame | null>(null);
+ const revision = useRef(0);
+ const measure = useCallback(() => {
+ const version = ++revision.current;
+ anchor.current?.measureInWindow((x, y, width, height) => {
+ host.current?.measureInWindow((hostX, hostY) => {
+ if (version !== revision.current || width <= 0 || height <= 0) return;
+ const next = { left: x - hostX, top: y - hostY, width, height };
+ setFrame(previous => previous && Object.keys(next).every(k => previous[k as keyof Frame] === next[k as keyof Frame]) ? previous : next);
+ });
+ });
+ }, [host]);
+ useLayoutEffect(() => { measure(); return () => { ++revision.current; }; }, [measure, focused, viewport.width, viewport.height]);
+ useLayoutEffect(() => () => release(owner), [release, owner]);
+ useLayoutEffect(() => {
+ if (!frame || needsResidentHistoryUpgrade) return;
+ publish({ key: activeKey, owner, frame, focused, ready, topInset, bottomInset, interactive,
+ children: <NavigationContext.Provider value={navigation}>
+ <NavigationRouteContext.Provider value={route}>
+ <PaneViewportProvider value={{ width: viewport.width, height: viewport.height }}>{children}</PaneViewportProvider>
+ </NavigationRouteContext.Provider>
+ </NavigationContext.Provider> });
+ }, [publish, activeKey, owner, frame, focused, ready, topInset, bottomInset, interactive, navigation, route, viewport.width, viewport.height, children]);
+ if (needsResidentHistoryUpgrade) return <View style={styles.container}>
+ <MessageHistoryActive.Provider value={focused}>{children}</MessageHistoryActive.Provider>
+ </View>;
+ return <View ref={anchor} collapsable={false} pointerEvents={NativeHistorySlot ? 'auto' : 'none'} onLayout={measure} style={styles.container}>
+ {/* Dock retained content immediately. `ready` gates new props and positioning,
+ not visibility: a new route starts with unmeasured chrome even on a cache hit. */}
+ {NativeHistorySlot ? <NativeHistorySlot surfaceId={context.namespace + activeKey} selected={focused}
+ pointerEvents={interactive && ready ? 'auto' : 'none'} style={StyleSheet.absoluteFill} /> : null}
+ </View>;
+}
+const styles = StyleSheet.create({ container: { flex: 1 }, clip: { position: 'absolute', overflow: 'hidden' } });
+
+/** Route-owned drawers must be above the root-owned histories, not beneath them. */
+export function MessageHistoryOverlay({ children }: { children: ReactNode }) {
+ const context = useContext(Context);
+ if (!context) throw new Error('RecentMessageHistoriesProvider is missing');
+ const { setOverlay } = context;
+ const owner = useId();
+ const focused = useIsFocused();
+ const navigation = useContext(NavigationContext);
+ const route = useContext(NavigationRouteContext);
+ useLayoutEffect(() => {
+ if (NativeHistorySlot || needsResidentHistoryUpgrade) return;
+ setOverlay(owner, focused ? <NavigationContext.Provider value={navigation}>
+ <NavigationRouteContext.Provider value={route}>{children}</NavigationRouteContext.Provider>
+ </NavigationContext.Provider> : null);
+ }, [setOverlay, owner, focused, navigation, route, children]);
+ useLayoutEffect(() => () => setOverlay(owner, null), [setOverlay, owner]);
+ return NativeHistorySlot || needsResidentHistoryUpgrade ? children : null;
+}
diff --git a/apps/mobile/src/session/RenameDeviceModal.tsx b/apps/mobile/src/session/RenameDeviceModal.tsx
index 03dd24abf3..b1b241e990 100644
--- a/apps/mobile/src/session/RenameDeviceModal.tsx
+++ b/apps/mobile/src/session/RenameDeviceModal.tsx
@@ -1,4 +1,5 @@
import { Modal, Pressable, StyleSheet } from 'react-native';
+import { ModalContentArea } from '@/platform/ModalContentArea';
import { useTranslation } from 'react-i18next';
import { Text, TextInput } from '@/components/AppText';
import { MainWindowActionGroup } from '@/components/MobilePrimitives';
@@ -35,6 +36,7 @@ export function RenameDeviceModal({
const canSave = draft.trim().length > 0 && !saving;
return (
<Modal
+ supportedOrientations={['portrait', 'portrait-upside-down', 'landscape-left', 'landscape-right']}
animationType="fade"
transparent
visible={visible}
@@ -45,6 +47,7 @@ export function RenameDeviceModal({
onPress={onCancel}
testID="home.renameDevice.backdrop"
>
+ <ModalContentArea>
<Pressable
style={styles.renameDeviceCard}
onPress={() => undefined}
@@ -101,6 +104,7 @@ export function RenameDeviceModal({
testID="home.renameDevice.actions"
/>
</Pressable>
+ </ModalContentArea>
</Pressable>
</Modal>
);
diff --git a/apps/mobile/src/session/RenameSessionModal.tsx b/apps/mobile/src/session/RenameSessionModal.tsx
index 74f421b8d2..97aa7c7fbc 100644
--- a/apps/mobile/src/session/RenameSessionModal.tsx
+++ b/apps/mobile/src/session/RenameSessionModal.tsx
@@ -1,4 +1,5 @@
import { Modal, Pressable, StyleSheet } from 'react-native';
+import { ModalContentArea } from '@/platform/ModalContentArea';
import { useTranslation } from 'react-i18next';
import { Text, TextInput } from '@/components/AppText';
import { MainWindowActionGroup } from '@/components/MobilePrimitives';
@@ -26,8 +27,9 @@ export function RenameSessionModal({
const { t } = useTranslation();
const canSave = draft.trim().length > 0 && !saving;
return (
- <Modal animationType="fade" transparent visible={visible} onRequestClose={onCancel}>
+ <Modal supportedOrientations={["portrait", "portrait-upside-down", "landscape-left", "landscape-right"]} animationType="fade" transparent visible={visible} onRequestClose={onCancel}>
<Pressable style={styles.backdrop} onPress={onCancel} testID="home.renameSession.backdrop">
+ <ModalContentArea>
<Pressable style={styles.card} onPress={() => undefined} testID="home.renameSession.modal">
<Text style={styles.title}>{t('devices.list.renameSession.title')}</Text>
<TextInput
@@ -66,6 +68,7 @@ export function RenameSessionModal({
testID="home.renameSession.actions"
/>
</Pressable>
+ </ModalContentArea>
</Pressable>
</Modal>
);
diff --git a/apps/mobile/src/session/ResidentHomeList.tsx b/apps/mobile/src/session/ResidentHomeList.tsx
new file mode 100644
index 0000000000..2ba8b12dcc
--- /dev/null
+++ b/apps/mobile/src/session/ResidentHomeList.tsx
@@ -0,0 +1,90 @@
+import { createContext, useCallback, useContext, useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react';
+import { StyleSheet, View } from 'react-native';
+import Animated from 'react-native-reanimated';
+import { useSegments } from 'expo-router';
+import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';
+import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';
+import { motionDuration } from '@/theme/tokens';
+import { RemoteSessionStoreSubscriptionGate } from './remoteSessionStore';
+import { sessionPaneLayout } from './sessionPaneLayout';
+
+type Frame = { left: number; top: number; width: number; height: number };
+type Entry = { owner: string; frame: Frame; children: ReactNode };
+const Context = createContext<{
+ enabled: boolean;
+ mounted: { current: boolean };
+ publish(entry: Entry): void;
+ host: React.RefObject<View | null>;
+} | null>(null);
+
+export function useResidentHomeList() {
+ const context = useContext(Context);
+ return { enabled: context?.enabled ?? false, mounted: context?.mounted };
+}
+
+/** The list lives above route lifetimes. Owners only supply its frame and props;
+ * never key the host by route, session, or presentation width. */
+export function ResidentHomeListProvider({ children }: { children: ReactNode }) {
+ const geometry = useAdaptiveWindow();
+ const enabled = sessionPaneLayout(geometry).persistent;
+ const segments = useSegments() as string[];
+ // app/index.tsx renders MobileHome directly for the default home entry.
+ const visible = enabled && (segments.length === 0 || segments[0] === 'index' || (segments[0] === 'devices' && (segments.length === 1 || segments[1] === 'index'))
+ || (segments[0] === 'sessions' && segments[1] === '[sessionId]'));
+ const host = useRef<View>(null);
+ const mounted = useRef(false);
+ const [entry, setEntry] = useState<Entry | null>(null);
+ const reduceMotion = useReduceMotionEnabled();
+ const publish = useCallback((next: Entry) => { setEntry(next); }, []);
+ const context = useMemo(() => ({ enabled, mounted, publish, host }), [enabled, publish]);
+ useLayoutEffect(() => {
+ mounted.current = enabled && !!entry;
+ if (!enabled) setEntry(null);
+ }, [enabled, entry]);
+ return <Context.Provider value={context}>
+ <View ref={host} collapsable={false} style={styles.root}>
+ {children}
+ {entry ? <Animated.View pointerEvents={visible ? 'box-none' : 'none'}
+ accessibilityElementsHidden={!visible}
+ importantForAccessibility={visible ? 'auto' : 'no-hide-descendants'}
+ style={[styles.host, entry.frame, {
+ opacity: visible ? 1 : 0,
+ transitionProperty: ['left', 'top', 'width', 'height'],
+ transitionDuration: reduceMotion === false ? motionDuration.fast : 0,
+ }]}>
+ <RemoteSessionStoreSubscriptionGate enabled={visible}>{entry.children}</RemoteSessionStoreSubscriptionGate>
+ </Animated.View> : null}
+ </View>
+ </Context.Provider>;
+}
+
+/** A route supplies a measuring slot, not another native list. Its header stays
+ * in the native navigation hierarchy, outside the list's touch bounds. */
+export function ResidentHomeList({ children, focused, top, left, right }: {
+ children: ReactNode; focused: boolean; top: number; left: number; right: number;
+}) {
+ const context = useContext(Context);
+ const owner = useId();
+ const anchor = useRef<View>(null);
+ const latest = useRef({ children, focused });
+ latest.current = { children, focused };
+ const measureRevision = useRef(0);
+ const measure = useCallback(() => {
+ const revision = ++measureRevision.current;
+ if (!context?.enabled || !latest.current.focused || !context.host.current) return;
+ anchor.current?.measureLayout(context.host.current, (x, y, width, height) => {
+ if (revision !== measureRevision.current || !latest.current.focused || width <= 0 || height <= 0) return;
+ context.publish({ owner, frame: { left: x, top: y, width, height }, children: latest.current.children });
+ });
+ }, [context, owner]);
+ useLayoutEffect(() => {
+ measure();
+ return () => { ++measureRevision.current; };
+ }, [measure, children, focused, top, left, right]);
+ return <View ref={anchor} collapsable={false} pointerEvents="none" onLayout={measure}
+ style={{ flex: 1, marginTop: top, marginLeft: -left, marginRight: -right }} />;
+}
+const styles = StyleSheet.create({
+ root: { flex: 1 },
+ host: { position: 'absolute' },
+});
diff --git a/apps/mobile/src/session/SessionActionSheet.tsx b/apps/mobile/src/session/SessionActionSheet.tsx
index 6145a185e0..dff388261d 100644
--- a/apps/mobile/src/session/SessionActionSheet.tsx
+++ b/apps/mobile/src/session/SessionActionSheet.tsx
@@ -136,7 +136,13 @@ export function SessionActionSheet({
const menu = buildSessionActionMenu(pinnedAt, status);
return (
- <Modal animationType="none" onRequestClose={onClose} transparent visible={mounted}>
+ <Modal
+ supportedOrientations={["portrait", "portrait-upside-down", "landscape-left", "landscape-right"]}
+ animationType="none"
+ onRequestClose={onClose}
+ transparent
+ visible={mounted}
+ >
<GestureHandlerRootView style={styles.overlay}>
<Animated.View style={[StyleSheet.absoluteFill, { opacity: progress }]}>
<BlurBackdrop />
diff --git a/apps/mobile/src/session/SessionDetailsNative.ios.tsx b/apps/mobile/src/session/SessionDetailsNative.ios.tsx
index 989b5490ce..466fb02316 100644
--- a/apps/mobile/src/session/SessionDetailsNative.ios.tsx
+++ b/apps/mobile/src/session/SessionDetailsNative.ios.tsx
@@ -1,3 +1,4 @@
+import { useNativeGlassButtonStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";
import { Host } from "@expo/ui";
import {
BottomSheet,
@@ -174,6 +175,7 @@ export function SessionDetailsNativeHeading({
backLabel,
onBack,
}: Pick<SessionDetailsNativeProps, 'title' | 'backLabel' | 'onBack'>) {
+ const glassStyle = useNativeGlassButtonStyle({ shape: 'circle' });
return (
<HStack
modifiers={[
@@ -192,7 +194,7 @@ export function SessionDetailsNativeHeading({
onPress={onBack}
modifiers={[
labelStyle('iconOnly'),
- buttonStyle('glass'),
+ ...glassStyle,
frame({ width: 44, height: 44 }),
]}
/>
diff --git a/apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx b/apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx
index cce16639a9..647c7862ef 100644
--- a/apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx
+++ b/apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx
@@ -1,3 +1,6 @@
+import { useNativeGlassGroupStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";
+import { NativeChromeBackButton } from "@/platform/chrome/NativeChromeBackButton.ios";
+import { navigationChrome } from "@/theme/tokens";
import { Host } from "@expo/ui";
import {
Button,
@@ -17,14 +20,11 @@ import {
accessibilityElement,
accessibilityLabel,
background,
- buttonBorderShape,
buttonStyle,
- controlSize,
contentShape,
disabled,
frame,
foregroundStyle,
- glassEffect,
labelStyle,
shapes,
} from "@expo/ui/swift-ui/modifiers";
@@ -37,7 +37,6 @@ import {
fontWeight,
useTheme,
} from "@/theme";
-import { useLiquidGlassAvailable } from "./useLiquidGlassAvailable";
import { BlurBackdrop } from "./BlurBackdrop";
import type {
SessionHeaderNativeActionsProps,
@@ -93,6 +92,8 @@ export function SessionHeaderNativeTitle({ title,
pinned, syncing, syncingImmediately, notice }: SessionHeaderNativeTitleProps) {
const { colors } = useTheme();
const style = {
+ alignSelf: 'center' as const,
+ maxWidth: '100%' as const,
borderRadius: radius.pill,
minHeight: 44,
justifyContent: "center" as const,
@@ -117,7 +118,7 @@ export function SessionHeaderNativeTitle({ title,
</Text>
);
return (
- <View style={{ flex: 1, minWidth: 0 }}>
+ <View style={{ flex: 1, minWidth: 0, justifyContent: 'center' }}>
<View style={style}>
<BlurBackdrop intensity={20} overlayColor={colors.surfaceTranslucent} />
<View style={{ flexDirection: "row", alignItems: "center", justifyContent: "center", gap: spacing.xs }}>
@@ -146,30 +147,7 @@ export function SessionHeaderNativeBack({
label,
onPress,
}: SessionHeaderNativeBackProps) {
- const { colors, mode } = useTheme();
- const glass = useLiquidGlassAvailable();
- return (
- <Host
- colorScheme={mode}
- seedColor={colors.textPrimary}
- ignoreSafeArea="all"
- style={{ width: 44, height: 44 }}
- >
- <Button
- label={label}
- systemImage="chevron.backward"
- onPress={onPress}
- testID="session.backButton"
- modifiers={[
- labelStyle("iconOnly"),
- buttonStyle(glass ? "glass" : "bordered"),
- buttonBorderShape("circle"),
- controlSize("large"),
- frame({ width: 44, height: 44 }),
- ]}
- />
- </Host>
- );
+ return <NativeChromeBackButton label={label} onPress={onPress} testID="session.backButton" />;
}
/** Native SwiftUI buttons share one system capsule. */
@@ -184,27 +162,22 @@ export function SessionHeaderNativeActions({
onAction,
}: SessionHeaderNativeActionsProps) {
const { colors, mode } = useTheme();
- const glass = useLiquidGlassAvailable();
+ const groupStyle = useNativeGlassGroupStyle();
const iconModifiers = [
labelStyle("iconOnly"),
buttonStyle("borderless"),
- controlSize("large"),
- frame({ width: 44, height: 44 }),
+ frame({ width: navigationChrome.target, height: navigationChrome.target }),
];
return (
<Host
colorScheme={mode}
seedColor={colors.textPrimary}
ignoreSafeArea="all"
- style={{ width: 132, height: 44 }}
+ style={{ width: navigationChrome.target * 3, height: navigationChrome.target }}
>
<HStack
spacing={0}
- modifiers={[
- ...(glass
- ? [glassEffect({ glass: { variant: "regular" }, shape: "capsule" })]
- : [background(colors.surfaceElevated, shapes.capsule())]),
- ]}
+ modifiers={groupStyle}
>
<Button
onPress={onDesktop}
@@ -255,7 +228,7 @@ function SessionHeaderIcon({
<VStack
spacing={0}
modifiers={[
- frame({ width: 44, height: 44 }),
+ frame({ width: navigationChrome.target, height: navigationChrome.target }),
contentShape(shapes.rectangle()),
]}
>
diff --git a/apps/mobile/src/session/SessionListDrawer.tsx b/apps/mobile/src/session/SessionListDrawer.tsx
index e39142b586..4720fe5d7c 100644
--- a/apps/mobile/src/session/SessionListDrawer.tsx
+++ b/apps/mobile/src/session/SessionListDrawer.tsx
@@ -1,121 +1,30 @@
-import { TaskTagDots } from '@/session/TaskTags';
-import { loadDeviceSessionScheduleIndex } from './scheduleIndex';
-import { useDeviceLink } from '@/device-link/DeviceLinkContext';
-import { remoteScheduleEventStore } from '@/scheduler/remoteScheduleEvents';
-/**
- * SessionListDrawer —— 宽屏(iPad / 折叠屏展开 / 横屏手机)会话页的任务列表抽屉。
- *
- * 会话页左上角三条杠拉出:原地切任务 / 新建任务 / 回主页,不来回压导航栈。
- * 断点判定在 `wideSessionNav.ts`(纯函数),本组件只管呈现与手势。
- *
- * 结构取舍:
- * - **树内 overlay 而非 RN Modal**:会话页已有多个 sheet Modal,iOS 同级双 Modal
- * 有 present/dismiss 竞态(见 SheetSurface 头注释);树内层叠没有这些约束。新建 / 回主页
- * 仍必须等 overlay 退场并真正卸载后执行;任务切换则在当前原生 Screen 内只替换 route
- * params,完全绕开 Android NativeStack replace。代价是盖不住原生弹层,但抽屉打开前
- * 页面会先收键盘,且其它 sheet 与抽屉互斥(都由页面状态驱动)。
- * - **数据直读全局 remoteSessionStore**:与首页同一份 store(进会话页前已水合,
- * 设备订阅继续推增量),经共享层 buildMobileHomePresentation 复用首页的排序 /
- * 置顶 / 自动化折叠口径,不在抽屉里重建首页的设备同步机械。
- * - 动画走 reanimated(withTiming + Pan 手势拖拽关闭),遵循 reduce-motion 约定
- * (useReduceMotionEnabled === false 才播)。
- */
-import { House, LoaderCircle, SquarePen } from 'lucide-react-native';
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import {
- AccessibilityInfo,
- AppState,
- BackHandler,
- findNodeHandle,
- Pressable,
- SectionList,
- StyleSheet,
- View,
-} from 'react-native';
-import Animated, {
- cancelAnimation,
- Easing,
- runOnJS,
- useAnimatedStyle,
- useSharedValue,
- withRepeat,
- withTiming,
-} from 'react-native-reanimated';
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject } from 'react';
+import { AccessibilityInfo, BackHandler, findNodeHandle, Pressable, StyleSheet, View } from 'react-native';
+import Animated, { cancelAnimation, Easing, runOnJS, useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useTranslation } from 'react-i18next';
-import { Text } from '@/components/AppText';
-import { ConversationSearchFilterSheet } from '@/session/ConversationSearchFilterSheet';
-import { SessionOptionsPresenter } from '@/session/SessionOptionsExpoSheet';
-import { RenameSessionModal } from '@/session/RenameSessionModal';
-import { useSessionListActions } from '@/session/useSessionListActions';
-import type { RemoteSession } from '@/session/types';
-import { HomeSearchBar } from '@/session/HomeSearchBar';
-import {
- conversationSearchOriginsFromDeviceModels,
- conversationSearchAllowsLocalWrites,
- listConversationSearchProjects,
- shouldReplaceListWithSearchResults,
- type ConversationSearchDeviceModel,
- type ConversationSearchDeviceOrigin,
-} from '@/session/conversationSearch';
-import { useConversationSearch } from '@/session/useConversationSearch';
-import { useUnresponsiveDevices } from '@/device-link/unresponsiveDevicesStore';
import { Gesture, GestureDetector } from '@/platform/gestureHandler';
import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';
-import { buildHomeSections, type HomeRow, type HomeSection } from '@/session/homeSections';
-import { buildMobileHomePresentation, excludeOrcaWorkerSessions } from '@/session/mobileHome';
-import {
- remoteSessionStore,
- useRemoteConversationSearchDeviceModels,
- useRemoteDeviceIdentity,
- useRemoteHomeStatusVersion,
- useRemoteMessageVersion,
- useRemoteSessionMessagePreview,
- useRemoteSessions,
- useSessionRunning,
-} from '@/session/remoteSessionStore';
-import type { RemoteSessionLiveActivity } from '@/session/sessionList';
-import { latestMobileSessionRow, resolveMobileSessionRowStatus } from '@/session/sessionRightStatus';
-import {
- buildRemoteSessionCardPreview,
- formatRemoteSessionSidebarTime,
- type RemoteSessionListItem,
-} from '@/session/sessionList';
-import { useMinuteNow } from '@/utils/useMinuteNow';
import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
-import {
- fontWeight,
- iconSize,
- iconStroke,
- lineHeight,
- motionDuration,
- motionEasing,
- radius,
- spacing,
- typeScale,
-} from '@/theme/tokens';
+import { motionDuration, motionEasing } from '@/theme/tokens';
+import type { RemoteSessionListItem } from './sessionList';
+import { MobileHome } from './HomeSurface';
-/** 拖过面板宽度的 1/3 或甩速超阈即判定关闭(常见抽屉手感)。 */
const DRAWER_CLOSE_DISTANCE_RATIO = 1 / 3;
const DRAWER_CLOSE_VELOCITY = -800;
-export function SessionListDrawer({
- currentSessionId,
- onClose,
- onClosed,
- onGoHome,
- onNewSession,
- onSelectSession,
- open,
- width,
+/** Container only: Home owns every list row, search, group, menu and subscription. */
+export function SessionListDrawer({ currentSessionId, persistent = false, newSessionInSystemBar = false,
+ onClose, onClosed, onSelectSession, runNavigation, newSessionActionRef, open, width,
}: {
currentSessionId: string;
+ persistent?: boolean;
+ newSessionInSystemBar?: boolean;
onClose(): void;
- /** 关闭动画完成、overlay 真正卸载后触发。 */
onClosed?(): void;
- onGoHome(): void;
- onNewSession(): void;
onSelectSession(item: RemoteSessionListItem): void;
+ runNavigation(action: () => void): void;
+ newSessionActionRef?: MutableRefObject<(() => void) | null>;
open: boolean;
width: number;
}) {
@@ -124,12 +33,7 @@ export function SessionListDrawer({
const { t } = useTranslation();
const insets = useSafeAreaInsets();
const reduceMotion = useReduceMotionEnabled();
- const actions = useSessionListActions();
- // 抽屉贴左缘,横屏刘海侧的 left inset 并进面板总宽,内容用 padding 让出。
- // 下限 1 是除零保险:当前调用点 enabled=false 时本组件整个不渲染(width 恒 >=300),
- // 但 progress/scrim 多处除以 panelWidth,不把不变量寄托在调用方身上。
const panelWidth = Math.max(1, width + insets.left);
-
const [mounted, setMounted] = useState(open);
const mountedRef = useRef(mounted);
mountedRef.current = mounted;
@@ -138,7 +42,7 @@ export function SessionListDrawer({
// progress 0→1 = 收起→展开;dragX(≤0)是手势拖拽的临时位移,松手后归零或并入 progress。
const progress = useSharedValue(open ? 1 : 0);
const dragX = useSharedValue(0);
- // 关闭收尾统一走这里(动画完成回调 / reduce-motion 直跳两条路径):先只卸载 overlay。
+ // 关闭收尾由 JS 生命周期负责,动画只负责视觉;先卸载 overlay。
// onClosed 必须等 mounted=false 的 commit 完成,否则导航会和 GestureDetector/
// Reanimated 子树卸载挤进同一帧(Android 原生 Screen 存在崩溃竞态)。背景焦点归还
// 则由父级在 accessibility 隔离解除后的 commit effect 中完成。
@@ -146,6 +50,19 @@ export function SessionListDrawer({
if (openRef.current) return;
setMounted(false);
}, []);
+ const previousPersistent = useRef(persistent);
+ const columnCollapsed = useRef(false);
+ useLayoutEffect(() => {
+ if (previousPersistent.current && !persistent && !open) {
+ // A disappearing column is not a modal exit: no scrim or focus isolation.
+ columnCollapsed.current = true;
+ cancelAnimation(progress);
+ progress.value = 0;
+ dragX.value = 0;
+ setMounted(false);
+ }
+ previousPersistent.current = persistent;
+ }, [persistent, open, progress, dragX]);
const onClosedRef = useRef(onClosed);
onClosedRef.current = onClosed;
const wasMountedRef = useRef(mounted);
@@ -153,23 +70,24 @@ export function SessionListDrawer({
const wasMounted = wasMountedRef.current;
wasMountedRef.current = mounted;
if (!wasMounted || mounted) return;
+ if (columnCollapsed.current) { columnCollapsed.current = false; return; }
onClosedRef.current?.();
}, [mounted]);
- // 打开后把读屏焦点移进面板首控件(新建任务):背后内容已按模态摘出读屏树,不移焦
+ // 打开后把读屏焦点移进主页内容区域:背后内容已按模态摘出读屏树,不移焦
// VoiceOver/TalkBack 会停在已隐藏的节点上。延到入场动画结束再移,避免读出滑动中的几何。
- const newSessionButtonRef = useRef<View>(null);
+ const homeContentRef = useRef<View>(null);
useEffect(() => {
- if (!open) return;
+ if (!open || persistent) return;
const timer = setTimeout(() => {
- const node = findNodeHandle(newSessionButtonRef.current);
+ const node = findNodeHandle(homeContentRef.current);
if (node != null) AccessibilityInfo.setAccessibilityFocus(node);
}, motionDuration.enter);
return () => clearTimeout(timer);
- }, [open]);
+ }, [open, persistent]);
useEffect(() => {
// reduce-motion 约定:只有 === false 才播动画,null(首帧未知)按不播降级。
- const animate = reduceMotion === false;
+ const animate = reduceMotion === false && !persistent;
if (open) {
setMounted(true);
// 手势位移并回 progress,从当前视觉位置继续,不跳帧。
@@ -195,27 +113,27 @@ export function SessionListDrawer({
0,
// 重浮层退场档(motionDuration.exit + in 曲线)。
{ duration: motionDuration.exit, easing: Easing.bezier(...motionEasing.in) },
- (finished) => {
- 'worklet';
- if (finished) runOnJS(finishClose)();
- },
);
- }, [dragX, finishClose, open, panelWidth, progress, reduceMotion]);
+ // A cancelled/lost UI-thread completion must not leave an invisible modal eating taps.
+ // Cleanup on reopen or layout change; navigation still waits for the unmount commit above.
+ const closeTimer = setTimeout(finishClose, motionDuration.exit);
+ return () => clearTimeout(closeTimer);
+ }, [dragX, finishClose, open, panelWidth, progress, reduceMotion, persistent]);
// Android 系统返回键:抽屉开着时先关抽屉,不冒泡成页面返回。
useEffect(() => {
- if (!open) return;
+ if (!open || persistent) return;
const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
onClose();
return true;
});
return () => subscription.remove();
- }, [onClose, open]);
+ }, [onClose, open, persistent]);
const closeFromGesture = useCallback(() => onClose(), [onClose]);
const panGesture = useMemo(
() =>
- Gesture.Pan()
+ Gesture.Pan().enabled(!persistent)
// 与内部 SectionList 纵向滚动的协调全靠激活窗口收窄:
// - 只认「向左」(关闭方向)为激活条件,向右 16pt 直接判失败——右拖不该抢任何手势;
// - 纵向 16pt 先到即失败,滚动优先;斜向手势必须横向分量先赢才归抽屉。
@@ -241,7 +159,7 @@ export function SessionListDrawer({
});
}
}),
- [closeFromGesture, dragX, panelWidth],
+ [closeFromGesture, dragX, panelWidth, persistent],
);
const scrimStyle = useAnimatedStyle(() => ({
@@ -258,626 +176,32 @@ export function SessionListDrawer({
],
}));
- // 与首页同一套展示模型(排序 / 置顶区 / 自动化折叠);未挂载时跳过重建,
- // 常驻宽屏页面时不为收起的抽屉付 presentation 成本。
- const sessions = useRemoteSessions();
- // pending/live/running 才重建分组;普通消息预览由可见行按 session 订阅。
- const homeStatusVersion = useRemoteHomeStatusVersion();
- // 设备身份和搜索可达性可单独变化,不能依赖 sessions 数组顺便触发刷新。
- const devices = useRemoteDeviceIdentity();
- const searchDeviceModels = useRemoteConversationSearchDeviceModels() as readonly ConversationSearchDeviceModel[];
- const unresponsiveDevices = useUnresponsiveDevices();
- const searchOrigins = useMemo(() => {
- if (searchDeviceModels.length > 0) {
- return conversationSearchOriginsFromDeviceModels(searchDeviceModels, {
- unresponsiveDeviceIds: unresponsiveDevices,
- });
- }
- if (devices.length > 0) {
- return devices.map((device) => ({
- deviceId: device.deviceId,
- deviceName: device.name,
- reachable: false,
- }));
- }
- const byId = new Map<string, ConversationSearchDeviceOrigin>();
- for (const session of sessions) {
- const id = session.canonicalDeviceId ?? session.deviceLinkDeviceId;
- if (!id || byId.has(id)) continue;
- byId.set(id, {
- deviceId: id,
- deviceName: session.deviceLinkDeviceName ?? id,
- reachable: false,
- });
- }
- return [...byId.values()];
- }, [devices, searchDeviceModels, sessions, unresponsiveDevices]);
- const searchProjects = useMemo(
- () => listConversationSearchProjects(excludeOrcaWorkerSessions(sessions)),
- [sessions],
- );
- const indexedSearch = useConversationSearch({
- enabled: mounted,
- origins: searchOrigins,
- projects: searchProjects,
- });
- const searchQuery = indexedSearch.query;
- // 索引搜索就绪前的本地搜索仍须匹配已加载消息;普通列表不订阅全局消息版本。
- const messageSearchVersion = useRemoteMessageVersion(mounted && searchQuery.trim().length > 0);
- const [searchFilterOpen, setSearchFilterOpen] = useState(false);
- 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 { invoke } = useDeviceLink();
- const [scheduleIndex, setScheduleIndex] = useState<ReadonlyMap<string, import('./sessionList').RemoteSessionScheduleInfo>>(() => new Map());
- const scheduleDeviceIdsKey = devices.map((device) => device.deviceId).sort().join(',');
- useEffect(() => {
- if (!open) return;
- let cancelled = false;
- const perDevice = new Map<string, ReadonlyMap<string, import('./sessionList').RemoteSessionScheduleInfo>>();
- const requestVersions = new Map<string, number>();
- const ids = scheduleDeviceIdsKey.split(',').filter(Boolean);
- const versions = new Map(ids.map((id) => [id, remoteScheduleEventStore.getSnapshot(id).sessionIndexVersion]));
- const canStart = () => !cancelled && openRef.current && AppState.currentState === 'active';
- const refresh = (id: string) => {
- if (!canStart()) return;
- const request = (requestVersions.get(id) ?? 0) + 1;
- requestVersions.set(id, request);
- void loadDeviceSessionScheduleIndex(id, invoke, canStart).then((index) => {
- if (!canStart() || requestVersions.get(id) !== request) return;
- perDevice.set(id, index);
- setScheduleIndex(new Map([...perDevice.values()].flatMap((entries) => [...entries])));
- }).catch(() => undefined);
- };
- ids.forEach(refresh);
- const appStateSubscription = AppState.addEventListener('change', (state) => {
- if (state === 'active') ids.forEach(refresh);
- });
- const off = remoteScheduleEventStore.subscribe(() => {
- for (const id of ids) {
- const version = remoteScheduleEventStore.getSnapshot(id).sessionIndexVersion;
- const previous = versions.get(id) ?? 0;
- versions.set(id, version);
- if (version <= previous) continue;
- refresh(id);
- }
- });
- return () => { cancelled = true; off(); appStateSubscription.remove(); };
- }, [open, scheduleDeviceIdsKey, invoke]);
- const sections = useMemo<HomeSection[]>(() => {
- if (!mounted) return [];
- if (shouldReplaceListWithSearchResults(searchQuery, indexedSearch.status)) {
- 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,
- })),
- key: 'search',
- title: null,
- }];
- }
- void homeStatusVersion;
- void messageSearchVersion;
- const messagePreviewIndex = searchQuery.trim()
- ? remoteSessionStore.getSessionListMessagePreviewIndex(sessions)
- : undefined;
- // 与首页同口径的行内状态输入:等待授权/回复(awaiting)与 live error/done 都来自
- // 这两个 index,缺了会全部退化成普通时间行。
- const pendingInteractionIndex = new Map(
- sessions
- .map((session) => [session.id, remoteSessionStore.getPendingInteractions(session.id).length] as const)
- .filter(([, count]) => count > 0),
- );
- const liveActivityEntries: Array<[string, RemoteSessionLiveActivity]> = [];
- for (const session of sessions) {
- const liveActivity = remoteSessionStore.getSessionLiveActivity(session.id);
- if (liveActivity) liveActivityEntries.push([session.id, liveActivity]);
- }
- const home = buildMobileHomePresentation({
- searchQuery,
- // 权威设备身份必须随会话一起进 presentation:canonicalizeSessionDevice 会按传入
- // devices 重算并覆盖 canonicalDeviceId,空列表会把 store 已认领好的规范 id 打回
- // 弱推断(re-link 后点行路由到旧物理设备)。
- devices,
- liveActivityIndex: new Map(liveActivityEntries),
- messagePreviewIndex,
- pendingInteractionIndex,
- // Visible drawer state only; the lightweight status index never replaces the home binding cache.
- scheduleIndex,
- sessions: excludeOrcaWorkerSessions(sessions),
- statusFilter: 'active',
- // 已解析的 i18n 文案传给共享层(共享层不出中文串;en/ja/ko 不再回退「未命名任务」)。
- unnamedLabel: t('session.menu.unnamedTitle'),
- });
- return buildHomeSections(home, false, false, { groupCindyMake: false });
- }, [scheduleIndex, devices, homeStatusVersion, indexedSearch.results, indexedSearch.status, messageSearchVersion, mounted, searchQuery, sessions, t]);
- const hasRows = useMemo(
- () => sections.some((section) => section.data.length > 0),
- [sections],
- );
-
- const renderRow = useCallback(
- ({ item }: { item: HomeRow }) => {
- if (item.kind !== 'session') return null;
- const active =
- item.item.session.id === currentSessionId ||
- (item.item.automationGroup?.sessionIds.includes(currentSessionId) ?? false);
- return (
- <DrawerSessionRow
- active={active}
- item={item.item}
- onSelect={onSelectSession}
- onShowOptions={actions.showSessionOptions}
- searchResult={item.source === 'search'}
- />
- );
- },
- [currentSessionId, onSelectSession, actions.showSessionOptions],
- );
if (!mounted) return null;
+ return <View accessibilityViewIsModal={mounted && !persistent} pointerEvents="auto"
+ style={[styles.overlay, persistent && { width: panelWidth }]} testID="sessionDrawer.overlay">
+ {!persistent ? <Animated.View style={[styles.scrim, scrimStyle]}>
+ <Pressable accessibilityLabel={t('home.drawer.closeA11y')} accessibilityRole="button"
+ onPress={onClose} style={styles.scrimPressable} testID="sessionDrawer.scrim" />
+ </Animated.View> : null}
+ <GestureDetector gesture={panGesture}>
+ <Animated.View style={[styles.panel, { paddingLeft: insets.left, paddingTop: insets.top, width: panelWidth },
+ !persistent && panelStyle]} testID="sessionDrawer.panel">
+ <View ref={homeContentRef} style={styles.content}>
+ <MobileHome onDismiss={persistent ? undefined : onClose} newSessionActionRef={newSessionActionRef} width={width} currentSessionId={currentSessionId}
+ newSessionInSystemBar={newSessionInSystemBar} onSelectSession={onSelectSession} runNavigation={runNavigation} />
+ </View>
- return (
- <View
- // iOS VoiceOver:抽屉开着时按模态处理,不让焦点跑到被遮住的会话内容上。
- accessibilityViewIsModal={mounted}
- // mounted 期间恒拦截(含 200ms 关闭动画):此时 scrim 仍半透明盖着内容,放行
- // 点击会穿透误触;落在 scrim 上的点击只是幂等地再触发一次 onClose。
- pointerEvents="auto"
- style={styles.overlay}
- testID="sessionDrawer.overlay"
- >
- <Animated.View style={[styles.scrim, scrimStyle]}>
- <Pressable
- accessibilityLabel={t('home.drawer.closeA11y')}
- accessibilityRole="button"
- onPress={onClose}
- style={styles.scrimPressable}
- testID="sessionDrawer.scrim"
- />
</Animated.View>
- <GestureDetector gesture={panGesture}>
- <Animated.View
- style={[
- styles.panel,
- { paddingLeft: insets.left, paddingTop: insets.top + spacing.sm, width: panelWidth },
- panelStyle,
- ]}
- testID="sessionDrawer.panel"
- >
- <View style={styles.panelHeader}>
- <Text numberOfLines={1} style={styles.panelTitle} testID="sessionDrawer.title">
- {t('devices.list.allConversations')}
- </Text>
- <Pressable
- accessibilityLabel={t('devices.list.a11y.newRemoteConversation')}
- accessibilityRole="button"
- hitSlop={6}
- onPress={onNewSession}
- ref={newSessionButtonRef}
- style={({ pressed }) => [styles.panelIconButton, pressed && styles.pressed]}
- testID="sessionDrawer.newSession"
- >
- <SquarePen
- color={colors.textPrimary}
- size={iconSize.xl}
- strokeWidth={iconStroke.regular}
- />
- </Pressable>
- </View>
- <View style={styles.drawerSearchRow}>
- <HomeSearchBar
- autoFocus={false}
- filterA11y={searchFilterA11y}
- filterActive={indexedSearch.activeFilterCount > 0}
- onChangeQuery={indexedSearch.setQuery}
- onOpenFilter={() => setSearchFilterOpen(true)}
- padded={false}
- query={searchQuery}
- testIDs={{
- filter: 'sessionDrawer.searchFilterButton',
- input: 'sessionDrawer.searchInput',
- row: 'sessionDrawer.searchRow',
- }}
- />
- </View>
- {hasRows ? (
- <SectionList
- contentContainerStyle={styles.listContent}
- keyExtractor={(row) => row.key}
- keyboardShouldPersistTaps="handled"
- renderItem={renderRow}
- renderSectionHeader={({ section }) =>
- section.title ? (
- <Text style={styles.sectionTitle}>{section.title}</Text>
- ) : null
- }
- sections={sections}
- showsVerticalScrollIndicator={false}
- stickySectionHeadersEnabled={false}
- style={styles.list}
- testID="sessionDrawer.list"
- />
- ) : (
- <View style={styles.emptyState}>
- <Text style={styles.emptyStateText}>{t('home.drawer.empty')}</Text>
- </View>
- )}
- <View style={[styles.footer, { paddingBottom: insets.bottom + spacing.sm }]}>
- <Pressable
- accessibilityLabel={t('home.drawer.home')}
- accessibilityRole="button"
- onPress={onGoHome}
- style={({ pressed }) => [styles.footerRow, pressed && styles.pressed]}
- testID="sessionDrawer.home"
- >
- <House
- color={colors.textSecondary}
- size={iconSize.lg}
- strokeWidth={iconStroke.regular}
- />
- <Text style={styles.footerLabel}>{t('home.drawer.home')}</Text>
- </Pressable>
- </View>
- </Animated.View>
- </GestureDetector>
- <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={insets.top + spacing.sm}
- visible={searchFilterOpen}
- />
- <SessionOptionsPresenter
- session={actions.actionSheetSession}
- onAction={actions.handleSessionSheetAction}
- onClose={() => actions.setActionSheetSession(null)}
- onClosed={actions.handleSessionSheetClosed}
- pinnedAt={actions.actionSheetSession?.pinnedAt}
- status={actions.actionSheetSession?.status}
- visible={actions.actionSheetSession !== null}
- />
- <RenameSessionModal
- draft={actions.renameSessionDraft}
- onCancel={actions.closeRenameSession}
- onChangeDraft={actions.setRenameSessionDraft}
- onConfirm={actions.confirmRenameSession}
- saving={false}
- visible={actions.renameSessionTarget !== null}
- />
- </View>
- );
+ </GestureDetector>
+ </View>;
}
-const DrawerSessionRow = memo(function DrawerSessionRow({
- active,
- item,
- onSelect,
- onShowOptions,
- searchResult,
-}: {
- active: boolean;
- item: RemoteSessionListItem;
- onSelect(item: RemoteSessionListItem): void;
- onShowOptions(session: RemoteSession): void;
- searchResult: boolean;
-}) {
- const styles = useThemedStyles(makeStyles);
- const { colors } = useTheme();
- const { t } = useTranslation();
- // 运行态走订阅(行 memo 化后命令式读取会 stale,与首页行同一取舍)。
- const latestItem = latestMobileSessionRow(item);
- const sessionIsRunning = useSessionRunning(latestItem.session.id);
- const running = sessionIsRunning || !!latestItem.scheduleInfo?.running;
- const { status: rightStatus, target: statusTarget } = resolveMobileSessionRowStatus(item, sessionIsRunning);
- // 索引搜索展示命中摘要;普通行(含自动化代表行)才使用自己的最新消息预览。
- const previewItem = item.automationGroup ? statusTarget : item;
- const loadedMessagePreview = useRemoteSessionMessagePreview(previewItem.session.id);
- const preview = buildRemoteSessionCardPreview(
- searchResult || loadedMessagePreview === undefined || loadedMessagePreview === previewItem.messagePreview
- ? previewItem
- : { ...previewItem, messagePreview: loadedMessagePreview },
- { running },
- );
- return (
- <Pressable
- accessibilityLabel={t('devices.list.a11y.openConversation', { title: item.title })}
- accessibilityRole="button"
- accessibilityState={{ selected: active }}
- onPress={() => onSelect(item)}
- delayLongPress={400}
- onLongPress={
- !item.automationGroup && conversationSearchAllowsLocalWrites(item)
- ? () => onShowOptions(latestItem.session as RemoteSession)
- : undefined
- }
- style={({ pressed }) => [styles.row, active && styles.rowActive, pressed && styles.pressed]}
- testID={`sessionDrawer.row.${item.session.id}`}
- >
- <View style={styles.rowTitleLine}>
- <Text numberOfLines={1} style={styles.rowTitle}>
- {item.title}
- </Text>
- <TaskTagDots
- tags={item.session.tags}
- surfaceColor={active ? colors.surfaceChip : colors.surface}
- />
- {rightStatus === 'time' ? (
- <DrawerRelativeTime lastActivityAt={item.lastActivityAt} />
- ) : (
- <View style={styles.rowStatusCell}>
- {rightStatus === 'running' ? (
- <DrawerRowSpinner sessionId={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.rowStatusDot,
- {
- backgroundColor:
- rightStatus === 'error'
- ? colors.statusError
- : rightStatus === 'awaiting'
- ? colors.statusAwaiting
- : colors.statusDone,
- },
- ]}
- testID={`sessionDrawer.rowStatus.${rightStatus}.${item.session.id}`}
- />
- )}
- </View>
- )}
- </View>
- {preview?.trim() ? (
- <Text numberOfLines={1} style={styles.rowPreview}>
- {preview}
- </Text>
- ) : null}
- </Pressable>
- );
+const makeStyles = (colors: ThemeColors) => StyleSheet.create({
+ overlay: { ...StyleSheet.absoluteFill, zIndex: 40 },
+ scrim: { ...StyleSheet.absoluteFill, backgroundColor: colors.overlay },
+ scrimPressable: { flex: 1 },
+ panel: { backgroundColor: colors.surface, borderRightColor: colors.border, borderRightWidth: StyleSheet.hairlineWidth,
+ position: 'absolute', top: 0, bottom: 0, left: 0 },
+ content: { flex: 1, minHeight: 0 },
});
-
-function DrawerRelativeTime({ lastActivityAt }: { lastActivityAt: string }) {
- const styles = useThemedStyles(makeStyles);
- useMinuteNow();
- return (
- <Text numberOfLines={1} style={styles.rowTime}>
- {formatRemoteSessionSidebarTime(lastActivityAt)}
- </Text>
- );
-}
-
-/** 与首页右槽同款:LoaderCircle 圆弧 1s 匀速旋转,中性色。 */
-function DrawerRowSpinner({ sessionId }: { sessionId: string }) {
- const { colors } = useTheme();
- const { t } = useTranslation();
- const reduceMotion = useReduceMotionEnabled();
- const turn = useSharedValue(0);
- const animate = reduceMotion === false;
- useEffect(() => {
- if (!animate) return;
- turn.value = 0;
- turn.value = withRepeat(
- // spinnerCycle 是功能性 loading 的语义循环档(§14.4 窄例外),匀速不走缓动曲线。
- withTiming(1, { duration: motionDuration.spinnerCycle, easing: Easing.linear }),
- -1,
- false,
- );
- return () => {
- cancelAnimation(turn);
- turn.value = 0;
- };
- }, [animate, turn]);
- const spinStyle = useAnimatedStyle(() => ({
- transform: [{ rotate: `${turn.value * 360}deg` }],
- }));
- return (
- <Animated.View
- accessibilityLabel={t('devices.list.a11y.running')}
- style={spinStyle}
- testID={`sessionDrawer.rowStatus.running.${sessionId}`}
- >
- <LoaderCircle
- color={colors.textTertiary}
- size={iconSize.md}
- strokeWidth={iconStroke.regular}
- />
- </Animated.View>
- );
-}
-
-const makeStyles = (colors: ThemeColors) =>
- StyleSheet.create({
- overlay: {
- ...StyleSheet.absoluteFill,
- zIndex: 40,
- },
- scrim: {
- ...StyleSheet.absoluteFill,
- backgroundColor: colors.overlay,
- },
- scrimPressable: {
- flex: 1,
- },
- panel: {
- backgroundColor: colors.surface,
- borderRightColor: colors.border,
- borderRightWidth: StyleSheet.hairlineWidth,
- bottom: 0,
- left: 0,
- position: 'absolute',
- top: 0,
- },
- panelHeader: {
- alignItems: 'center',
- flexDirection: 'row',
- gap: spacing.sm,
- justifyContent: 'space-between',
- paddingHorizontal: spacing.lg,
- paddingVertical: spacing.sm,
- },
- drawerSearchRow: {
- alignItems: 'center',
- borderBottomColor: colors.border,
- borderBottomWidth: StyleSheet.hairlineWidth,
- flexDirection: 'row',
- gap: spacing.sm,
- minHeight: 44,
- paddingHorizontal: spacing.lg,
- paddingVertical: spacing.xs,
- },
- drawerSearchInput: {
- color: colors.textPrimary,
- flex: 1,
- fontSize: typeScale.body,
- minWidth: 0,
- paddingVertical: spacing.xs,
- },
- panelTitle: {
- color: colors.textPrimary,
- flexShrink: 1,
- fontSize: typeScale.title,
- fontWeight: fontWeight.medium,
- lineHeight: lineHeight.subtitle,
- },
- // 38×38 与会话头图标钮同规格,热区经 hitSlop 补到 44。
- panelIconButton: {
- alignItems: 'center',
- borderRadius: radius.pill,
- height: 38,
- justifyContent: 'center',
- width: 38,
- },
- list: {
- flex: 1,
- },
- listContent: {
- paddingBottom: spacing.lg,
- paddingHorizontal: spacing.sm,
- },
- sectionTitle: {
- color: colors.textTertiary,
- fontSize: typeScale.caption,
- fontWeight: fontWeight.medium,
- lineHeight: lineHeight.caption,
- paddingHorizontal: spacing.sm,
- paddingBottom: spacing.xs,
- paddingTop: spacing.md,
- },
- row: {
- borderRadius: radius.container,
- // 标题与预览行距 2pt 微调:xs(4) 会把双行行高撑过 56,列表密度掉档。
- gap: 2,
- // 无预览的单行任务行只有 42(22+20),minHeight 补足 44 触控底线;居中让单行不顶格。
- justifyContent: 'center',
- minHeight: 44,
- paddingHorizontal: spacing.sm,
- // sm+2 微调:凑出双行行高 ≈56 的触控行,md(12) 会松成 60+。
- paddingVertical: spacing.sm + 2,
- },
- rowActive: {
- backgroundColor: colors.surfaceChip,
- },
- rowTitleLine: {
- alignItems: 'center',
- flexDirection: 'row',
- gap: spacing.sm,
- minWidth: 0,
- },
- rowTitle: {
- color: colors.textPrimary,
- flex: 1,
- fontSize: typeScale.body,
- fontWeight: fontWeight.medium,
- lineHeight: lineHeight.body,
- minWidth: 0,
- },
- rowTime: {
- color: colors.textTertiary,
- flexShrink: 0,
- fontSize: typeScale.caption,
- lineHeight: lineHeight.caption,
- },
- // 18×18 定位槽 + 10pt 状态点:与首页会话行右槽同规格(点/spinner 先居中同一槽再对齐)。
- rowStatusCell: {
- alignItems: 'center',
- flexShrink: 0,
- height: 18,
- justifyContent: 'center',
- width: 18,
- },
- rowStatusDot: {
- borderRadius: radius.pill,
- height: 10,
- width: 10,
- },
- rowPreview: {
- color: colors.textTertiary,
- fontSize: typeScale.caption,
- lineHeight: lineHeight.caption,
- },
- emptyState: {
- alignItems: 'center',
- flex: 1,
- justifyContent: 'center',
- padding: spacing.xl,
- },
- emptyStateText: {
- color: colors.textTertiary,
- fontSize: typeScale.body,
- lineHeight: lineHeight.body,
- textAlign: 'center',
- },
- footer: {
- borderTopColor: colors.border,
- borderTopWidth: StyleSheet.hairlineWidth,
- paddingHorizontal: spacing.sm,
- paddingTop: spacing.sm,
- },
- footerRow: {
- alignItems: 'center',
- borderRadius: radius.container,
- flexDirection: 'row',
- gap: spacing.sm,
- // 主操作行触控目标 >=44(iOS HIG):内容 22 + padV 16 只有 38,minHeight 补足。
- minHeight: 44,
- paddingHorizontal: spacing.sm,
- paddingVertical: spacing.sm,
- },
- footerLabel: {
- color: colors.textSecondary,
- fontSize: typeScale.body,
- fontWeight: fontWeight.medium,
- lineHeight: lineHeight.body,
- },
- pressed: {
- opacity: 0.72,
- },
- });
diff --git a/apps/mobile/src/session/SessionSearchNative.ios.tsx b/apps/mobile/src/session/SessionSearchNative.ios.tsx
index 253da3ed8b..24e8432d19 100644
--- a/apps/mobile/src/session/SessionSearchNative.ios.tsx
+++ b/apps/mobile/src/session/SessionSearchNative.ios.tsx
@@ -1,3 +1,4 @@
+import { useNativeGlassButtonStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";
import { Host } from "@expo/ui";
import {
BottomSheet,
@@ -66,6 +67,7 @@ function SearchContent({
}: SessionSearchNativeProps) {
const { t } = useTranslation();
const { colors } = useTheme();
+ const glassStyle = useNativeGlassButtonStyle({ shape: "circle" });
const text = useNativeState(query);
useEffect(() => {
if (text.get() !== query) text.set(query);
@@ -145,7 +147,7 @@ function SearchContent({
testID="session.searchPreviousButton"
modifiers={[
labelStyle("iconOnly"),
- buttonStyle("glass"),
+ ...glassStyle,
disabled(!hasHits),
frame({ width: 44, height: 44 }),
]}
@@ -157,7 +159,7 @@ function SearchContent({
testID="session.searchNextButton"
modifiers={[
labelStyle("iconOnly"),
- buttonStyle("glass"),
+ ...glassStyle,
disabled(!hasHits),
frame({ width: 44, height: 44 }),
]}
diff --git a/apps/mobile/src/session/ShareImageNativeButton.ios.tsx b/apps/mobile/src/session/ShareImageNativeButton.ios.tsx
index 7e0afc04a5..b15d4ab341 100644
--- a/apps/mobile/src/session/ShareImageNativeButton.ios.tsx
+++ b/apps/mobile/src/session/ShareImageNativeButton.ios.tsx
@@ -1,19 +1,16 @@
import { Host } from "@expo/ui";
import { Button } from "@expo/ui/swift-ui";
import {
- buttonBorderShape,
- buttonStyle,
- controlSize,
disabled,
frame,
} from "@expo/ui/swift-ui/modifiers";
import { useTheme } from "@/theme";
-import { useLiquidGlassAvailable } from "@/session/useLiquidGlassAvailable";
+import { useNativeGlassButtonStyle } from "@/platform/chrome/nativeGlassButtonStyle.ios";
import type { ShareImageNativeButtonProps } from "./ShareImageNativeButton";
export function ShareImageNativeButton(props: ShareImageNativeButtonProps) {
const { colors, mode } = useTheme();
- const glass = useLiquidGlassAvailable();
+ const glassStyle = useNativeGlassButtonStyle({ prominent: true });
return (
<Host
@@ -31,9 +28,7 @@ export function ShareImageNativeButton(props: ShareImageNativeButtonProps) {
if (!props.disabled) props.onPress();
}}
modifiers={[
- buttonStyle(glass ? "glassProminent" : "borderedProminent"),
- buttonBorderShape("capsule"),
- controlSize("large"),
+ ...glassStyle,
frame({ minWidth: 112, minHeight: 44 }),
disabled(props.disabled),
]}
diff --git a/apps/mobile/src/session/ShareSelectionBar.tsx b/apps/mobile/src/session/ShareSelectionBar.tsx
index 70618be6d3..e343d4c9ce 100644
--- a/apps/mobile/src/session/ShareSelectionBar.tsx
+++ b/apps/mobile/src/session/ShareSelectionBar.tsx
@@ -1,10 +1,9 @@
-import { GlassView } from "expo-glass-effect";
+import { HomeHeaderGlassButton } from "./HomeHeaderGlassButton";
import { Share as ShareIcon, X } from "lucide-react-native";
import { Pressable, StyleSheet, View } from "react-native";
import { useTranslation } from "react-i18next";
import { Text } from "@/components/AppText";
import { ShareImageNativeButton } from "@/session/ShareImageNativeButton";
-import { useLiquidGlassAvailable } from "@/session/useLiquidGlassAvailable";
import { useTheme, useThemedStyles, type ThemeColors } from "@/theme";
import {
fontWeight,
@@ -31,42 +30,24 @@ export function ShareSelectionBar({
onShare(): void;
}) {
const { t } = useTranslation();
- const { colors, mode } = useTheme();
+ const { colors } = useTheme();
const styles = useThemedStyles(makeStyles);
- const liquidGlass = useLiquidGlassAvailable();
const cancelIcon = (
<X
- color={colors.textSecondary}
- size={iconSize.md}
+ color={colors.textPrimary}
+ size={iconSize.action}
strokeWidth={iconStroke.regular}
/>
);
const cancelButton = (
- <Pressable
+ <HomeHeaderGlassButton
accessibilityLabel={t("session.shareImage.cancel")}
- accessibilityRole="button"
- hitSlop={spacing.sm}
onPress={onCancel}
- style={({ pressed }) => [styles.iconButton, pressed && styles.pressed]}
testID="session.shareImage.cancel"
>
- {liquidGlass ? (
- <GlassView
- colorScheme={mode}
- glassEffectStyle="regular"
- isInteractive
- style={styles.cancelGlass}
- tintColor={colors.surface}
- >
- <View pointerEvents="none" style={styles.iconButton}>
- {cancelIcon}
- </View>
- </GlassView>
- ) : (
- cancelIcon
- )}
- </Pressable>
+ {cancelIcon}
+ </HomeHeaderGlassButton>
);
const countLabel = (
<View
@@ -139,17 +120,6 @@ const makeStyles = (colors: ThemeColors) =>
paddingHorizontal: spacing.md,
paddingVertical: spacing.sm,
},
- iconButton: {
- alignItems: "center",
- flexShrink: 0,
- height: 44,
- justifyContent: "center",
- width: 44,
- },
- cancelGlass: {
- borderRadius: radius.pill,
- overflow: "hidden",
- },
count: { flex: 1, minWidth: 0 },
titleText: {
color: colors.textPrimary,
diff --git a/apps/mobile/src/session/SheetModal.tsx b/apps/mobile/src/session/SheetModal.tsx
index e995c56ff9..929fb23e87 100644
--- a/apps/mobile/src/session/SheetModal.tsx
+++ b/apps/mobile/src/session/SheetModal.tsx
@@ -1,3 +1,5 @@
+import { useAdaptiveWindow, PaneViewportProvider, FloatingSheetContext } from '@/platform/AdaptiveWindowContext';
+import { modalLayout } from '@/platform/modalLayout';
/**
* SheetModal —— 底部 sheet 共用的 Modal 外壳(背板淡入淡出 + 面板自底部滑入滑出)。
*
@@ -21,11 +23,13 @@ import {
Platform,
Pressable,
StyleSheet,
+ View,
useWindowDimensions,
} from 'react-native';
import { useTranslation } from 'react-i18next';
import { BlurBackdrop } from '@/session/BlurBackdrop';
import { GestureHandlerRootView } from '@/platform/gestureHandler';
+import { useMobileKeyboardState } from '@/session/useMobileKeyboardState';
import { useModalFadeLifecycle } from '@/session/useModalFadeLifecycle';
import { useThemedStyles, type ThemeColors } from '@/theme';
@@ -58,6 +62,12 @@ export function SheetModal({
const styles = useThemedStyles(makeStyles);
const { t } = useTranslation();
const { height: windowHeight } = useWindowDimensions();
+ const geometry = useAdaptiveWindow();
+ const keyboard = useMobileKeyboardState();
+ const { region, floating } = modalLayout(geometry, keyboardAvoiding && Platform.OS !== 'android' ? keyboard.height : 0);
+ const displaced = floating || geometry.regions.length > 0 || geometry.barEdge !== 'none'
+ || geometry.insets.left > 0 || geometry.insets.right > 0;
+ const [contentHeight, setContentHeight] = useState(geometry.height);
// 背板淡入 + 面板滑入共用一条 progress;关闭淡出/滑出播完后再卸载 Modal。
const { mounted, progress, onShowStartIn } = useModalFadeLifecycle(visible, {
inMs: 150,
@@ -95,8 +105,8 @@ export function SheetModal({
[progress, windowHeight],
);
const contentLayerStyle = useMemo(
- () => [styles.contentLayer, { transform: [{ translateY }] }],
- [styles, translateY],
+ () => [styles.contentLayer, { justifyContent: floating ? 'center' as const : 'flex-end' as const, transform: [{ translateY }] }],
+ [styles, translateY, floating],
);
const backdropStyle = useMemo(
() => [styles.backdrop, { opacity: progress }],
@@ -105,13 +115,17 @@ export function SheetModal({
// 内容层 box-none:空白区域的点击穿透到下层背板 Pressable,面板本体照常接收触摸。
const content = (
- <Animated.View key={contentEpoch} pointerEvents="box-none" style={contentLayerStyle}>
- {children}
+ <Animated.View key={contentEpoch} pointerEvents="box-none" style={contentLayerStyle}
+ onLayout={event => setContentHeight(event.nativeEvent.layout.height)}>
+ <PaneViewportProvider value={{ width: displaced ? region.width : geometry.width, height: contentHeight }}>
+ <FloatingSheetContext.Provider value={floating}>{children}</FloatingSheetContext.Provider>
+ </PaneViewportProvider>
</Animated.View>
);
return (
<Modal
+ supportedOrientations={["portrait", "portrait-upside-down", "landscape-left", "landscape-right"]}
animationType="none"
onRequestClose={onRequestClose}
onShow={onShowStartIn}
@@ -135,18 +149,19 @@ export function SheetModal({
触发每帧 relayout 的布局回环 → 整窗持续重绘闪烁(用户 2026-07 报「+」/模型选择弹层
键盘开着时一直闪;logcat 实测键盘不开合、但 MainActivity 每帧重绘)。故 Android 直接
用 content、不套 KAV;iOS(adjustResize 不适用)仍需 KAV 走 padding 避让。 */}
- {keyboardAvoiding && Platform.OS !== 'android' ? (
+ <View pointerEvents="box-none" style={displaced ? {
+ position: 'absolute', left: region.x, top: region.y, width: region.width, height: region.height,
+ } : styles.keyboardLayer}>
<KeyboardAvoidingView
+ enabled={keyboardAvoiding && !displaced && Platform.OS !== 'android'}
behavior={keyboardAvoidingBehavior}
- keyboardVerticalOffset={0}
+ keyboardVerticalOffset={displaced ? region.y : 0}
pointerEvents="box-none"
style={styles.keyboardLayer}
>
{content}
</KeyboardAvoidingView>
- ) : (
- content
- )}
+ </View>
</GestureHandlerRootView>
</Modal>
);
diff --git a/apps/mobile/src/session/SheetSurface.tsx b/apps/mobile/src/session/SheetSurface.tsx
index 7b8790f6e1..3fa68e8774 100644
--- a/apps/mobile/src/session/SheetSurface.tsx
+++ b/apps/mobile/src/session/SheetSurface.tsx
@@ -1,3 +1,5 @@
+import { useContext, useMemo } from 'react';
+import { FloatingSheetContext, usePaneViewport } from '@/platform/AdaptiveWindowContext';
/**
* SheetSurface —— 可拖动底部浮窗的「面板表面」(从 ContextSheet 抽出,非 Modal)。
*
@@ -75,8 +77,11 @@ export function SheetSurface({
const styles = useThemedStyles(makeSheetSurfaceStyles);
const { colors } = useTheme();
const { t } = useTranslation();
+ const viewport = usePaneViewport();
+ const floating = useContext(FloatingSheetContext);
+ const boundedHeights = useMemo(() => ({ half: Math.min(heights.half, viewport.height), full: Math.min(heights.full, viewport.height) }), [heights, viewport.height]);
const drag = useContextSheetDrag({
- heights,
+ heights: boundedHeights,
onDismiss: onClose,
onSnapChange,
snap,
@@ -87,8 +92,10 @@ export function SheetSurface({
style={[
styles.sheet,
variant === 'tasksheet' && styles.sheetTasksheet,
- { paddingBottom: bottomInset },
+ { paddingBottom: floating ? spacing.md : bottomInset },
+ floating && { borderRadius: radius.container },
drag.animatedStyle,
+ { maxHeight: "100%" },
]}
testID={testID}
>
diff --git a/apps/mobile/src/session/conversationSearch.ts b/apps/mobile/src/session/conversationSearch.ts
index 7455e840a3..aaef4b2b51 100644
--- a/apps/mobile/src/session/conversationSearch.ts
+++ b/apps/mobile/src/session/conversationSearch.ts
@@ -399,6 +399,8 @@ export function reconcileConversationSearchProjectSelection(
if (selection === 'all') return 'all';
const visible = new Set(visibleKeys);
const next = selection.filter((key) => visible.has(key));
+ // Preserve identity when hydration or a host change leaves the selection intact.
+ if (next.length === selection.length && next.length > 0) return selection;
return next.length > 0 ? next : 'all';
}
diff --git a/apps/mobile/src/session/historyDiskStoreExpo.ts b/apps/mobile/src/session/historyDiskStoreExpo.ts
index aefeb96189..1a75c2031f 100644
--- a/apps/mobile/src/session/historyDiskStoreExpo.ts
+++ b/apps/mobile/src/session/historyDiskStoreExpo.ts
@@ -16,12 +16,18 @@ export function createHistoryDiskIO(): HistoryDiskIO {
async write(name, text) {
directory.create({ intermediates: true, idempotent: true });
const temporary = new File(directory, `${name}.tmp`);
+ const temporaryUri = temporary.uri;
try {
// Native asynchronous write avoids a synchronous filesystem write on the UI thread.
const fs = await import('expo-file-system/legacy');
await fs.writeAsStringAsync(temporary.uri, text);
temporary.moveSync(new File(directory, name), { overwrite: true });
- } finally { if (temporary.exists) temporary.delete(); }
+ } finally {
+ // moveSync changes temporary.uri to the destination. Only clean the original
+ // staging path; deleting temporary here would delete the committed snapshot.
+ const leftover = new File(temporaryUri);
+ if (leftover.exists) leftover.delete();
+ }
},
async remove(name) { const file = new File(directory, name); if (file.exists) file.delete(); },
};
diff --git a/apps/mobile/src/session/homeRowPropsEqual.ts b/apps/mobile/src/session/homeRowPropsEqual.ts
new file mode 100644
index 0000000000..e26ba33790
--- /dev/null
+++ b/apps/mobile/src/session/homeRowPropsEqual.ts
@@ -0,0 +1,17 @@
+import { dataPropsEqual } from '@/utils/valueEquality';
+
+/** Resident rows can move between home controllers without unmounting. Data
+ * equality must not retain callbacks or mutable state from the previous owner. */
+export function homeRowPropsEqual(
+ previous: Readonly<Record<string, unknown>>,
+ next: Readonly<Record<string, unknown>>,
+): boolean {
+ for (const key of new Set([...Object.keys(previous), ...Object.keys(next)])) {
+ const a = previous[key];
+ const b = next[key];
+ if ((typeof a === 'function' || typeof b === 'function'
+ || key === 'swipe' || key === 'registry' || key === 'projectHeaderRefs' || key === 'homeScrollY')
+ && !Object.is(a, b)) return false;
+ }
+ return dataPropsEqual(previous, next);
+}
diff --git a/apps/mobile/src/session/homeViewSession.ts b/apps/mobile/src/session/homeViewSession.ts
new file mode 100644
index 0000000000..3e38319521
--- /dev/null
+++ b/apps/mobile/src/session/homeViewSession.ts
@@ -0,0 +1,59 @@
+import { useCallback, useRef, useState, useSyncExternalStore, type Dispatch, type SetStateAction } from 'react';
+import { getMobileAuthOwner } from '@/auth/authOwnerGeneration';
+
+/** Ephemeral Home state shared by its full-width and sidebar presentations.
+ * No task data or disk writes; changing account ownership drops the entire view. */
+export class HomeViewSession {
+ private values = new Map<string, unknown>();
+ private listeners = new Map<string, Set<() => void>>();
+ has(key: string): boolean { return this.values.has(key); }
+ read<T>(key: string, fallback: T | (() => T)): T {
+ if (!this.values.has(key)) {
+ this.values.set(key, typeof fallback === 'function' ? (fallback as () => T)() : fallback);
+ }
+ return this.values.get(key) as T;
+ }
+ write<T>(key: string, value: T): void {
+ if (Object.is(this.values.get(key), value) && this.values.has(key)) return;
+ this.values.set(key, value);
+ this.listeners.get(key)?.forEach((listener) => listener());
+ }
+ subscribe(key: string, listener: () => void): () => void {
+ let listeners = this.listeners.get(key);
+ if (!listeners) { listeners = new Set(); this.listeners.set(key, listeners); }
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ if (!listeners.size) this.listeners.delete(key);
+ };
+ }
+}
+let owner = getMobileAuthOwner();
+let current = new HomeViewSession();
+export function getHomeViewSession(): HomeViewSession {
+ const next = getMobileAuthOwner();
+ if (next !== owner) { owner = next; current = new HomeViewSession(); }
+ return current;
+}
+
+/** Retain committed interactions synchronously, before navigation can mount Home elsewhere. */
+export function useRetainedHomeState<T>(session: HomeViewSession | undefined, key: string, initial: T | (() => T)):
+ [T, Dispatch<SetStateAction<T>>] {
+ const [localValue, setValue] = useState<T>(() => session
+ ? session.read(key, initial)
+ : typeof initial === 'function' ? (initial as () => T)() : initial);
+ // Home remains mounted behind the task. Sidebar edits must update that same
+ // state before it is uncovered; remounting is no longer the synchronization mechanism.
+ const subscribe = useCallback((listener: () => void) => session?.subscribe(key, listener) ?? (() => {}), [session, key]);
+ const getSnapshot = useCallback(() => session ? session.read(key, localValue) : localValue, [session, key, localValue]);
+ const value = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+ const latest = useRef(value);
+ latest.current = value;
+ const update = useCallback<Dispatch<SetStateAction<T>>>((action) => {
+ const next = typeof action === 'function' ? (action as (previous: T) => T)(latest.current) : action;
+ latest.current = next;
+ session?.write(key, next);
+ setValue(next);
+ }, [session, key]);
+ return [value, update];
+}
diff --git a/apps/mobile/src/session/messageHistoryActivity.ts b/apps/mobile/src/session/messageHistoryActivity.ts
new file mode 100644
index 0000000000..e55cdefd4c
--- /dev/null
+++ b/apps/mobile/src/session/messageHistoryActivity.ts
@@ -0,0 +1,6 @@
+import { createContext, useContext } from 'react';
+
+export const MessageHistoryActive = createContext(true);
+export const MessageHistoryPositioning = createContext(true);
+export const useMessageHistoryPositioning = () => useContext(MessageHistoryPositioning);
+export const useMessageHistoryActive = () => useContext(MessageHistoryActive);
diff --git a/apps/mobile/src/session/messageHistoryAnchor.ts b/apps/mobile/src/session/messageHistoryAnchor.ts
index d0f0c9433c..c6c9168b18 100644
--- a/apps/mobile/src/session/messageHistoryAnchor.ts
+++ b/apps/mobile/src/session/messageHistoryAnchor.ts
@@ -145,22 +145,24 @@ function findClosestMobileHistoryAnchorIndex<ItemT>(
// viewport with O(log n) position reads instead of scanning the whole retained history.
let lower = 0;
let upper = state.data.length - 1;
- let closestIndex: number | null = null;
- let closestDistance = Number.POSITIVE_INFINITY;
+ let containingIndex: number | null = null;
+ let firstFollowingIndex: number | null = null;
+ const dataScroll = state.scroll - (state.topOffsetAdjustment ?? 0);
while (lower <= upper) {
const index = Math.floor((lower + upper) / 2);
const position = state.positionAtIndex(index);
if (!Number.isFinite(position)) break;
- const dataScroll = state.scroll - (state.topOffsetAdjustment ?? 0);
- const distance = Math.abs((position as number) - dataScroll);
- if (distance < closestDistance) {
- closestDistance = distance;
- closestIndex = index;
+ // Anchor the row containing the viewport top, not the next row whose top
+ // happens to be closer. That next row can be offscreen and still estimated.
+ if ((position as number) <= dataScroll) {
+ containingIndex = index;
+ lower = index + 1;
+ } else {
+ firstFollowingIndex = index;
+ upper = index - 1;
}
- if ((position as number) < dataScroll) lower = index + 1;
- else upper = index - 1;
}
- return closestIndex;
+ return containingIndex ?? firstFollowingIndex;
}
/**
diff --git a/apps/mobile/src/session/messageReadingPosition.ts b/apps/mobile/src/session/messageReadingPosition.ts
new file mode 100644
index 0000000000..3ec3a3b0f4
--- /dev/null
+++ b/apps/mobile/src/session/messageReadingPosition.ts
@@ -0,0 +1,30 @@
+import { getMobileAuthOwner } from '@/auth/authOwnerGeneration';
+import type { MobileHistoryAnchor } from './messageHistoryAnchor';
+
+export type MessageReadingPosition = { anchor: MobileHistoryAnchor | null; atEnd: boolean };
+let owner = getMobileAuthOwner();
+const positions = new Map<string, { device: string; session: string; value?: MessageReadingPosition }>();
+
+/** Small, account-scoped bookmarks only; message content stays in the existing history cache. */
+export function messageReadingPosition(device: string, session: string) {
+ const capturedOwner = getMobileAuthOwner();
+ if (owner !== capturedOwner) { positions.clear(); owner = capturedOwner; }
+ const key = JSON.stringify([device, session]);
+ const entry = positions.get(key) ?? { device, session };
+ positions.delete(key);
+ positions.set(key, entry);
+ while (positions.size > 8) positions.delete(positions.keys().next().value!);
+ const current = () => capturedOwner === getMobileAuthOwner() && positions.get(key) === entry;
+ return {
+ read: () => current() ? entry.value : undefined,
+ write: (value: MessageReadingPosition) => { if (current()) entry.value = value; },
+ };
+}
+
+export function clearMessageReadingPositions(device?: string, session?: string) {
+ for (const [key, entry] of positions) {
+ if ((device === undefined || device === entry.device) && (session === undefined || session === entry.session)) {
+ positions.delete(key);
+ }
+ }
+}
diff --git a/apps/mobile/src/session/recentTasks.ts b/apps/mobile/src/session/recentTasks.ts
new file mode 100644
index 0000000000..2b5c434947
--- /dev/null
+++ b/apps/mobile/src/session/recentTasks.ts
@@ -0,0 +1,31 @@
+import { subscribeMobileAuthOwner } from '@/auth/authOwnerGeneration';
+
+export const MAX_RECENT_TASKS = 5;
+export type RecentTaskRoute = {
+ pathname: '/sessions/[sessionId]';
+ params: { deviceId: string; deviceName: string; sessionId: string };
+};
+export const recentTaskKey = (params: { deviceId?: unknown; sessionId?: unknown }) =>
+ JSON.stringify([params.deviceId ?? '', params.sessionId ?? '']);
+
+let recent: RecentTaskRoute[] = [];
+const listeners = new Set<() => void>();
+const emit = () => listeners.forEach(listener => listener());
+export const subscribeRecentTasks = (listener: () => void) => {
+ listeners.add(listener); return () => { listeners.delete(listener); };
+};
+export const getRecentTasks = () => recent;
+export function rememberRecentTask(href: RecentTaskRoute) {
+ const { deviceId, deviceName, sessionId } = href.params;
+ if (!deviceId || !sessionId) return;
+ const key = recentTaskKey(href.params);
+ if (recentTaskKey(recent.at(-1)?.params ?? {}) === key && recent.at(-1)?.params.deviceName === deviceName) return;
+ recent = [...recent.filter(item => recentTaskKey(item.params) !== key), {
+ pathname: '/sessions/[sessionId]' as const, params: { deviceId, deviceName, sessionId },
+ }].slice(-MAX_RECENT_TASKS);
+ emit();
+}
+
+subscribeMobileAuthOwner(() => {
+ recent = []; emit();
+});
diff --git a/apps/mobile/src/session/remoteHistoryViews.ts b/apps/mobile/src/session/remoteHistoryViews.ts
index c82f02e048..5fe05de86f 100644
--- a/apps/mobile/src/session/remoteHistoryViews.ts
+++ b/apps/mobile/src/session/remoteHistoryViews.ts
@@ -2,18 +2,26 @@ import { HistoryViewController, isHistoryViewUnavailable } from '@cindy/maker-sh
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
import type { RemoteMessage } from './types';
import { clearHistoryDisk, historyDiskAuthority, readHistoryDisk, writeHistoryDisk } from './remoteHistoryDiskCache';
-import { historyValueBytes } from './historyDiskStore';
+import { getRecentTasks, recentTaskKey, subscribeRecentTasks } from './recentTasks';
+import { clearMessageReadingPositions } from './messageReadingPosition';
-// Retain only recently visited views in memory. The existing account/device and
-// session reclamation boundaries own invalidation. Older views remain in the disk LRU.
-export const MAX_INACTIVE_HISTORY_VIEWS = 8;
-const MAX_INACTIVE_HISTORY_BYTES = 4 * 1024 * 1024;
+// Data and resident message lists share the same five-task retention policy.
type Reader = Pick<MobileMakerTransport, 'readHistoryView' | 'readWorkDetails' | 'setHistoryExpanded'>;
type Entry = { deviceId: string; sessionId: string; reader: Reader;
- view: HistoryViewController<RemoteMessage>; consumers: number; bytes: number };
+ view: HistoryViewController<RemoteMessage>; consumers: number };
const views = new Map<string, Entry>();
const keyFor = (deviceId: string, sessionId: string) => JSON.stringify([deviceId, sessionId]);
+function pruneDetachedViews() {
+ const retained = new Set(getRecentTasks().map(task => recentTaskKey(task.params)));
+ for (const [key, entry] of views) {
+ // A live route still owns its controller. Release it when that route unmounts;
+ // never create a second controller for an existing consumer.
+ if (!entry.consumers && !retained.has(key)) views.delete(key);
+ }
+}
+subscribeRecentTasks(pruneDetachedViews);
+
export function findRemoteHistoryView(deviceId: string, sessionId: string) {
return views.get(keyFor(deviceId, sessionId))?.view;
}
@@ -22,7 +30,7 @@ export function getRemoteHistoryView(deviceId: string, sessionId: string, reader
const key = keyFor(deviceId, sessionId);
const existing = views.get(key);
if (existing) return existing;
- const entry: Entry = { deviceId, sessionId, reader, consumers: 0, bytes: 0,
+ const entry: Entry = { deviceId, sessionId, reader, consumers: 0,
view: new HistoryViewController<RemoteMessage>({
page: (before) => entry.reader.readHistoryView(sessionId, before),
details: (ref, after) => entry.reader.readWorkDetails(sessionId, ref, after),
@@ -75,34 +83,20 @@ export function mountRemoteHistoryView(entry: Entry, reader: Reader, active: boo
entry.view.setActive(false);
const key = keyFor(entry.deviceId, entry.sessionId);
if (views.get(key) !== entry) return;
- const snapshot = entry.view.getSnapshot();
- // Bound accounting work before allocating a serialization of large details.
- entry.bytes = Math.min(MAX_INACTIVE_HISTORY_BYTES + 1,
- 2 * historyValueBytes([snapshot.items, snapshot.details, snapshot.expanded], MAX_INACTIVE_HISTORY_BYTES));
- views.delete(key);
- views.set(key, entry);
- let count = 0;
- let bytes = 0;
- for (const candidate of views.values()) {
- if (!candidate.consumers) { count++; bytes += candidate.bytes; }
- }
- for (const [candidateKey, candidate] of views) {
- if (count <= MAX_INACTIVE_HISTORY_VIEWS && bytes <= MAX_INACTIVE_HISTORY_BYTES) break;
- if (candidate.consumers) continue;
- views.delete(candidateKey);
- count--; bytes -= candidate.bytes;
- }
+ pruneDetachedViews();
};
}
/** Hard boundaries also invalidate reads already held by mounted consumers. */
export function resetRemoteHistoryViews(deviceId: string | undefined, sessionId: string): void {
+ clearMessageReadingPositions(deviceId, sessionId);
for (const entry of views.values()) {
if (entry.sessionId === sessionId && (deviceId === undefined || entry.deviceId === deviceId)) entry.view.reset();
}
}
export function clearRemoteHistoryViews(deviceId?: string, sessionId?: string): void {
+ clearMessageReadingPositions(deviceId, sessionId);
for (const [key, entry] of views) {
if (deviceId !== undefined && entry.deviceId !== deviceId) continue;
if (sessionId !== undefined && entry.sessionId !== sessionId) continue;
diff --git a/apps/mobile/src/session/sessionPaneLayout.ts b/apps/mobile/src/session/sessionPaneLayout.ts
new file mode 100644
index 0000000000..cccb758226
--- /dev/null
+++ b/apps/mobile/src/session/sessionPaneLayout.ts
@@ -0,0 +1,13 @@
+import { safeWindowRect, windowDivision, type WindowGeometry } from '@/platform/windowGeometry';
+
+/** Navigation consumes space only when the remaining conversation is comfortably usable. */
+export function sessionPaneLayout(g: WindowGeometry) {
+ const safe = safeWindowRect(g);
+ const division = windowDivision(g);
+ const splitAtFold = division?.axis === 'vertical' && division.first.width >= 240 && division.second.width >= 320;
+ const persistent = !!splitAtFold || (!division && g.regularWidth && safe.width >= 760 && safe.height >= 480);
+ const sidebarWidth = persistent ? (splitAtFold ? division!.first.width : Math.min(320, Math.round(safe.width * 0.34))) : 0;
+ const sidebarGap = splitAtFold ? division!.second.x - safe.x - sidebarWidth : 0;
+ const pane = { ...safe, x: safe.x + sidebarWidth + sidebarGap, width: safe.width - sidebarWidth - sidebarGap };
+ return { persistent, sidebarWidth, sidebarGap, detail: pane };
+}
diff --git a/apps/mobile/src/session/useConversationSearch.ts b/apps/mobile/src/session/useConversationSearch.ts
index 43e26763ec..73994a0b75 100644
--- a/apps/mobile/src/session/useConversationSearch.ts
+++ b/apps/mobile/src/session/useConversationSearch.ts
@@ -1,3 +1,4 @@
+import { useRetainedHomeState, type HomeViewSession } from './homeViewSession';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
@@ -33,11 +34,13 @@ export type ConversationSearchStatus = 'idle' | 'searching' | 'ready';
export function useConversationSearch({
origins,
enabled,
+ retainedState,
lockedWorkingDirs,
projects,
}: {
origins: readonly ConversationSearchDeviceOrigin[];
enabled: boolean;
+ retainedState?: HomeViewSession;
lockedWorkingDirs?: string[] | null;
projects?: readonly ConversationSearchProjectOption[];
}): {
@@ -61,15 +64,15 @@ export function useConversationSearch({
} {
const { invoke } = useDeviceLink();
const { t } = useTranslation();
- const [query, setQuery] = useState('');
+ const [query, setQuery] = useRetainedHomeState(retainedState, 'search.query', '');
const [status, setStatus] = useState<ConversationSearchStatus>('idle');
const [results, setResults] = useState<ConversationSearchListItem[]>([]);
- const [sortBy, setSortBy] = useState<ConversationSearchSortBy>('relevance');
- const [statusFilter, setStatusFilter] = useState<ConversationSearchStatusFilter>('all');
- const [agentFilter, setAgentFilter] = useState<ConversationSearchAgentFilter>('all');
+ const [sortBy, setSortBy] = useRetainedHomeState<ConversationSearchSortBy>(retainedState, 'search.sortBy', 'relevance');
+ const [statusFilter, setStatusFilter] = useRetainedHomeState<ConversationSearchStatusFilter>(retainedState, 'search.statusFilter', 'all');
+ const [agentFilter, setAgentFilter] = useRetainedHomeState<ConversationSearchAgentFilter>(retainedState, 'search.agentFilter', 'all');
const [lastActivityFilter, setLastActivityFilter] =
- useState<ConversationSearchLastActivityFilter>('all');
- const [projectSelection, setProjectSelection] = useState<ConversationSearchProjectSelection>('all');
+ useRetainedHomeState<ConversationSearchLastActivityFilter>(retainedState, 'search.lastActivityFilter', 'all');
+ const [projectSelection, setProjectSelection] = useRetainedHomeState<ConversationSearchProjectSelection>(retainedState, 'search.projectSelection', 'all');
const requestSeq = useRef(0);
const unnamedLabel = t('session.menu.unnamedTitle');
const visibleProjectKeys = useMemo(
diff --git a/apps/mobile/src/session/useSessionHeaderHeight.ts b/apps/mobile/src/session/useSessionHeaderHeight.ts
new file mode 100644
index 0000000000..b7f06ef9cd
--- /dev/null
+++ b/apps/mobile/src/session/useSessionHeaderHeight.ts
@@ -0,0 +1,30 @@
+import { useLayoutEffect, useState, useCallback } from 'react';
+import { useFocusEffect, useNavigation } from 'expo-router';
+import { useHeaderHeight } from 'expo-router/react-navigation';
+
+// Native Stack starts offscreen routes with an estimated header height. Reuse the
+// last measured task header for this geometry until the push has completed.
+// Geometry only: no account or task data, and no persisted state.
+const measuredHeights = new Map<string, number>();
+type HeaderNavigation = {
+ addListener(event: 'transitionEnd', callback: (event: { data: { closing: boolean } }) => void): () => void;
+};
+
+export function useSessionHeaderHeight(geometryKey: string): number {
+ const nativeHeight = useHeaderHeight();
+ const navigation = useNavigation<HeaderNavigation>();
+ const [settled, setSettled] = useState(false);
+ useFocusEffect(useCallback(() => {
+ const unsubscribe = navigation.addListener('transitionEnd', ({ data }) => {
+ if (!data.closing) setSettled(true);
+ });
+ return () => { unsubscribe(); setSettled(false); };
+ }, [navigation]));
+ useLayoutEffect(() => {
+ if (!settled || nativeHeight <= 0 || !Number.isFinite(nativeHeight)) return;
+ measuredHeights.delete(geometryKey);
+ measuredHeights.set(geometryKey, nativeHeight);
+ while (measuredHeights.size > 8) measuredHeights.delete(measuredHeights.keys().next().value!);
+ }, [settled, geometryKey, nativeHeight]);
+ return !settled ? measuredHeights.get(geometryKey) ?? nativeHeight : nativeHeight;
+}
diff --git a/apps/mobile/src/session/wideSessionNav.ts b/apps/mobile/src/session/wideSessionNav.ts
index 9202f3ca1d..7ede2ad770 100644
--- a/apps/mobile/src/session/wideSessionNav.ts
+++ b/apps/mobile/src/session/wideSessionNav.ts
@@ -1,27 +1,4 @@
-/**
- * wideSessionNav —— 会话页宽屏导航模式的断点判定(纯函数,便于单测)。
- *
- * 宽屏(iPad 双向 / 折叠屏展开内屏 / 横屏手机)下会话页左上角不再是「返回」,
- * 而是三条杠(Menu):点击拉出任务列表抽屉,原地切换任务,不来回压导航栈。
- *
- * 断点口径与仓内另外两套是三种不同语义,不合并:
- * - `responsiveViewportLayout.wideViewport`(>=700 或 landscape)管的是**内容可读宽度**,
- * 小手机横屏也要限宽,所以 landscape 一律算宽;
- * - `loginSkinLayout`(1000×690 / 700)管的是登录页立绘皮肤的三态;
- * - 本文件管的是**导航形态**:600dp 取 Material 3 的 medium 窗口档,恰好覆盖
- * iPad 竖屏(768+)、主流折叠屏展开内屏(约 600-680dp,竖持也 >=600)与横屏手机
- * (>=640),同时排除所有竖屏直板手机(<=约 440)与 iPad 窄分屏(~320,此时回退
- * 返回键模式是正确行为)。不额外要求 landscape:折叠屏内屏竖持宽度已达标,
- * 要求横向反而把它漏掉。
- *
- * 发布策略按平台分闸(2026-08-02 用户定稿):
- * - Android:纯宽度闸——折叠屏展开 / 平板 / 横屏大屏机都启用;
- * - iOS:仅 iPad(iosPad)启用;iPhone 即使横屏达宽也**不发**,保持返回键
- * (评审风险面最小,后续要放开 iPhone 横屏只改这一处)。
- */
-
-export const WIDE_SESSION_NAV_MIN_WIDTH = 600;
-
+/** Quick-switch panel sizing. Back navigation remains available at every width. */
const DRAWER_MIN_WIDTH = 300;
const DRAWER_MAX_WIDTH = 360;
const DRAWER_WIDTH_RATIO = 0.4;
@@ -29,14 +6,14 @@ const DRAWER_WIDTH_RATIO = 0.4;
export interface WideSessionNavLayoutInput {
windowWidth?: number;
windowHeight?: number;
- /** Platform.OS。iOS 有 iPad 专属闸;其余平台(android/web)纯宽度闸。 */
+ /** Retained for existing callers; sizing is platform-independent. */
platform?: string;
- /** iOS 下是否 iPad(Platform.isPad)。iPhone 恒 false → 宽屏形态不启用。 */
+ /** Retained for existing callers; phone and tablet share this behavior. */
iosPad?: boolean;
}
export interface WideSessionNavLayout {
- /** true = 会话页用三条杠 + 任务列表抽屉;false = 传统返回键。 */
+ /** Whether a measured window can host quick switching. */
enabled: boolean;
/** 抽屉面板宽度(enabled 为 false 时给 0,调用方不消费)。 */
drawerWidth: number;
@@ -46,14 +23,11 @@ export function buildWideSessionNavLayout(
input: WideSessionNavLayoutInput,
): WideSessionNavLayout {
const windowWidth = normalizeDimension(input.windowWidth);
- // iOS 只对 iPad 发宽屏形态;iPhone(含横屏)按发布策略回退返回键。
- const platformAllowed = input.platform !== 'ios' || input.iosPad === true;
- const enabled = platformAllowed && windowWidth >= WIDE_SESSION_NAV_MIN_WIDTH;
+ const enabled = windowWidth >= 600;
if (!enabled) return { drawerWidth: 0, enabled };
- const drawerWidth = clamp(
- Math.round(windowWidth * DRAWER_WIDTH_RATIO),
- DRAWER_MIN_WIDTH,
- DRAWER_MAX_WIDTH,
+ const drawerWidth = Math.min(
+ Math.max(0, windowWidth - 24),
+ clamp(Math.round(windowWidth * DRAWER_WIDTH_RATIO), DRAWER_MIN_WIDTH, DRAWER_MAX_WIDTH),
);
return { drawerWidth, enabled };
}
diff --git a/apps/mobile/src/theme/index.ts b/apps/mobile/src/theme/index.ts
index 45284a41c2..1ee6b2cb50 100644
--- a/apps/mobile/src/theme/index.ts
+++ b/apps/mobile/src/theme/index.ts
@@ -9,6 +9,7 @@ export {
iconStroke,
lightColors,
lineHeight,
+ navigationChrome,
motionDuration,
motionEasing,
palettes,
diff --git a/apps/mobile/src/theme/tokens.ts b/apps/mobile/src/theme/tokens.ts
index 3ffcb4d4d0..60d6d08b62 100644
--- a/apps/mobile/src/theme/tokens.ts
+++ b/apps/mobile/src/theme/tokens.ts
@@ -781,3 +781,21 @@ export const motionEasing = {
/** 位置 / 尺寸插值 */
move: [0.4, 0, 0.2, 1],
} as const;
+
+/** Shared size for floating iOS navigation/menu controls (points). */
+export const navigationChrome = {
+ target: 44,
+ // Match navigation foreground polarity; backing stays local to the glass shape.
+ clear: {
+ light: {
+ foreground: '#000000',
+ scrim: 'rgba(255, 255, 255, 0.35)',
+ selected: 'rgba(0, 0, 0, 0.10)',
+ },
+ dark: {
+ foreground: '#FFFFFF',
+ scrim: 'rgba(0, 0, 0, 0.35)',
+ selected: 'rgba(255, 255, 255, 0.18)',
+ },
+ },
+} as const;
diff --git a/docs/design-evidence/iphone-duo-adaptation.md b/docs/design-evidence/iphone-duo-adaptation.md
new file mode 100644
index 0000000000..2e6badf68f
--- /dev/null
+++ b/docs/design-evidence/iphone-duo-adaptation.md
@@ -0,0 +1,304 @@
+# iPhone Duo 适配实现与验收
+
+本次按窗口几何适配,不通过设备名称判断 Duo,不将 phone idiom 等同于窄屏。
+
+## 三阶段实现
+
+1. **基础布局**:安全区四边独立处理;旧 iOS 手机旋转残留修正显式限于旧布局。登录新增中等横向窗口构图,折叠分区不足时表单滚动。远程桌面使用窗口而非物理屏幕尺寸。自绘 Modal 声明双向旋转,输入 sheet 根据键盘剩余空间重新选择折叠区域。
+2. **展开导航**:有足够空间时任务列表与详情并列;折叠分界可以偏离中线。详情内消息与交互面板按实际 pane 宽度排版。系统推荐纵向栏时将操作移到对应物理侧边。宽窄转换保持详情、编辑器和消息列表组件身份;抽屉导航仍等待真实退场完成。
+3. **折叠区域**:现有 iOS 本地模块提供窗口 safe area、size class、verticalBarEdge 与 active reserved regions。自绘输入区域避让 division/occlusion;高键盘覆盖下半区时回到上半区。远程桌面在第一分区显示画面,第二分区提供相对触控板和既有鼠标/键盘操作;视频层和 WebView 使用同一矩形,不改变远程控制协议或重建连接。
+
+登录表单、输入 sheet 和远程桌面均复用已有主题颜色;没有引入新的颜色或图标体系。
+
+## 原生桥接与兼容
+
+- 使用 `UIView.reservedRegions(of:)` 对应 Objective-C API,以及 `verticalBarEdge`;同时有编译期头文件检测和 iOS 27.1 运行期检查。
+- 旧 SDK、旧系统及 Android 使用普通窗口几何,不虚构折痕位置。
+- attached、foreground active scene 内至多 10 Hz 采样区域变化;快照去重后才向 JS 发送。CADisplayLink 使用弱引用中间对象,离开窗口/后台时停用。
+- 此原生能力无法由 JS 准确替代,因此需要冷更。未升级原生包的装机不会获得新 runtime 的 OTA;现有包保留旧 runtime 的更新通道。发布需配合新商店包或自建重装,不能作为纯 OTA 发布。合并前须按 mobile-development 冷更规则取得指定把关人的明确确认。
+- 本机相同 `@expo/fingerprint 0.20.13` production 计算:iOS `8b048bf11a9c8a2c24ea80992641aa9545118e37` → `97cb76162f50bfd4387f697018d3c5e801726ded`;Android `ac812fe4744bde795af40e2ad3ef207b6a8c3065` → `98e7d33558ec65b95612f8a303bc3c838b1d13ba`。本地模块目录参与指纹,虽然没有 Android 原生逻辑改动,其指纹也变化。最终发版仍以 release check 为准。
+
+## 验证范围
+
+- 覆盖独立安全边、窄分屏、偏心折痕、摄像头遮挡、键盘覆盖下半区的几何回归。
+- 覆盖触控板相对坐标、无效输入、隐藏鼠标按钮时 tap、拖拽中的 tap 不释放按键,以及折叠前后 viewer/lease 连续性。
+- Xcode 27.1 模拟器原生构建两次成功;新增桥接也通过旧 Xcode SDK 的 Objective-C 语法编译。Mobile TypeScript 检查通过,shared viewer 生成文件一致性检查通过。
+- Mobile 全量复跑:486 个文件、6,219 项测试通过。Desktop 首轮失败的 10 个文件复跑:137 项测试全部通过。复跑清除了宿主 CINDY_AUTH_REGION / VITE_CINDY_AUTH_REGION,且不与原生构建并行,未延长测试超时、跳过测试或弱化断言。
+- 根 pnpm test:unit:related 第一轮退出非零:Desktop 含环境相关断言与超时;Mobile 含本次布局改变需更新的旧断言/mock 与超时。受影响断言/mock 已更新并通过上述复跑。maker-core、maker-shared、lizi-mcps、orca-workflow 在第一轮全部通过。未宣称重新完整执行过第二轮根命令。
+- 上述为早期验证记录;最终模拟器验收与门禁结果见下方「本轮收尾检查」。源码与自动测试不替代设备验收。
+
+## Apple 依据
+
+### 全 App 核对清单(2026-09-19)
+
+| 规则 | Cindy 落点 |
+| --- | --- |
+| 竖栏遵循系统物理边缘,可左可右,不以横屏或 RTL 推断 | 原生 Stack toolbar;不增加自绘侧栏或重复扣除侧栏宽度 |
+| 返回/关闭在竖栏顶部;图标保留辅助功能名称 | 登录流程、任务页、文件浏览/预览和简单页面使用原生 toolbar button;远程桌面保留原有全屏控制 |
+| 自绘控件不会自动参与 UIKit 竖栏;不能把横排多个按钮视为一个可自适应项 | 首页沿用原生导航容器内的自定义横向项;任务动作组维持横向,不再额外造栏 |
+| 内屏竖屏恢复水平栏;居中 sheet 不强行继承主页面竖栏 | `barEdge: none` 保留普通布局,`SheetSurface` 保留局部导航 |
+| 四边 safe area 独立;控件整体避让 division / occlusion | 登录表单、`SheetModal`、重命名弹窗、首页下拉菜单 |
+| 外屏横屏及键盘状态下操作可滚动到达 | 登录表单、新建页、重命名弹窗;Android 不重复扣系统缩窗后的键盘高度 |
+| resize 保留输入与页面状态,分页基于实际内容宽度 | `SheetModal` 固定组件层级;文件预览测量 pager 宽并重锚当前页 |
+| 键盘附件栏保持贴键盘,不搬到页面侧栏 | 任务编辑器及远程桌面键盘维持原归属 |
+
+以上为实现核对,不等同于全部运行验收。需分别验证内外屏、两种横屏方向、
+左右 Split View、键盘、Light/Dark、读屏,以及真实设备连接下的文件/远程桌面操作。
+
+### 本轮收尾检查(2026-09-19)
+
+- 移除登录布局与启动遮罩的临时调试日志;启动遮罩及首页恢复逻辑未改变。
+- 早期自绘侧栏方案已于 2026-09-20 撤除;下面旧截图不能作为最终导航验收。
+- Mobile TypeScript、9 个文件的 147 项定向回归、scope guard、2 项远程流程 smoke 均通过。
+- 全仓单测首轮被设计台账快照过期拦下;已通过正式生成器更新机器区块,保留人工标注。
+- 更新台账后,根 `pnpm test:unit` 的脚本检查、Desktop 与其它包全部通过;Mobile 为 487 个文件、6,230 项通过,1 项 Android splash introspect 超时,因此该次根命令仍退出 1。
+- 超时项单独复跑仍耗时 54 秒。`EXPO_DEBUG=1` 显示配置解析不足一秒,退出前等待落在 CLI 遥测链路;仅本次命令设 `EXPO_NO_TELEMETRY=1` 后,同文件 5 项全部通过,introspect 用时 594ms。未改断言、超时阈值、原生配置或永久遥测偏好;不将组合验证写成整轮根门禁通过。
+- 关闭本次命令的 Expo CLI 遥测后,完整重跑根单测门禁退出 0(`cindy-duo-complete-gate.log`)。随后修正连接提示层按所在内容区测量横向范围,避免覆盖侧栏;相关 4 个文件、53 项回归通过,Mobile TypeScript 再次通过。
+- 移除登录表单测量容器的临时背景并恢复入场透明度;保留原有登录状态与启动逻辑。
+- 当前 Duo 模拟器原生包与 worktree 开发指纹匹配(`3faa006daa206d295c834418966c63c02a8ca1aa`)。已启动本 worktree Metro 并加载新 JS bundle。
+
+### 模拟器画面验收
+
+| 场景 | 结果 |
+| --- | --- |
+| 内屏横向、浅色首页与任务双栏 | 已目检,列表与详情分区、侧栏可见 |
+| 内屏纵向、深色任务页 | 已目检,水平导航和底部输入区域可见 |
+| 外屏横向、深色任务页与软件键盘 | 已目检,输入区域位于键盘上方,侧栏保留 |
+| 外屏两种横向、深色设置页 | 已目检,原生返回键随系统切换到右/左侧栏 |
+| Book 姿态、深色设置页 | 已目检,返回键与内容可见 |
+| 连接提示 | 已修复并目检,提示宽度限制在内容区,不覆盖侧栏 |
+
+本地截图在 `/tmp/cindy-duo-*.png`,含个人账户与任务信息,不作为公开附件上传。
+当前电脑连接停留在握手重试,因此文件内容、远程桌面控制和折叠触控板的端到端操作未验收;
+保留已登录账户,没有为重测登录而退出账户。最终登录态页面、左右 Split View、VoiceOver、
+Android 实机以及所有页面的浅/深色全矩阵仍未逐项目检,不把上述局部验收写成全设备验收。
+
+详细 Apple 说明:
+[导航和工具栏](https://developer.apple.com/videos/play/tech-talks/111462/)、
+[窗口和安全区域](https://developer.apple.com/videos/play/tech-talks/111461/)、
+[折叠姿态与保留区域](https://developer.apple.com/videos/play/tech-talks/111463/)。
+
+- [Designing for iPhone Duo](https://developer.apple.com/design/human-interface-guidelines/designing-for-iphone-duo)
+- [Preparing your app for iPhone Duo](https://developer.apple.com/documentation/technologyoverviews/preparing-your-app-for-iphone-duo)
+
+按实际窗口和系统保留区域布局;纵向操作栏遵循硬件相对边缘,不随内容语言镜像。UIKit 原生展示和 React Native 自绘层的适配分别验证。
+
+## 用户截图复查:弹层(2026-09-19)
+
+用户指出账号面板在内屏横向偏左、过宽且底部悬空。这说明前轮“全部落地”的结论过早:
+主页面导航通过不代表共用弹层已验收。
+
+- iOS 账号切换改用现有 `ComposerSheet` 系统容器,系统负责呈现位置、圆角、档位和关闭完成通知;账号切换与新增账号的业务逻辑不变。
+- 存量 `SheetModal` 在宽窗/横窗内使用有限宽度、四边留白和垂直居中;`SheetSurface` 浮动时四角圆角,不重复添加主页面底部安全区。窄屏竖向保留原贴底呈现。
+- 重命名等 `ModalContentArea` 消费同一弹层区域计算。文件浏览的路径菜单与长按菜单补齐双向横屏、区域内滚动,去掉固定顶部 96 点定位。
+- 模型、上下文、任务菜单已有 iOS 原生分支;Android 和仍使用自绘容器的分支统一受上述边界约束。图片查看/全文预览为全屏内容,不改成小弹窗;锚定引用预览不改成居中 sheet。
+- 新增宽窗、短窗键盘、折痕区域与窄屏竖向回归;Mobile 全量 489 个文件、6,235 项通过,TypeScript 通过。画面验收另行记录,不以测试代替。
+- 本轮最终弹层画面尚未验收:Device Hub 的窗口存在,但桌面工具返回 `ax_window_unresolved`;改用 Maestro 后,其截图读取到未激活的外屏黑画面,未找到首页菜单。两者均不计为产品验证通过;没有执行账号切换或清除账户数据。
+
+## 新 Worktree 本机启动
+
+Metro 会静态解析所有 region 分支,即使运行 Global,也需要本地存在 `config/endpoint.dev.json`。首次启动前从仓库 `config/endpoint.dev.json.example` 复制生成这个 gitignored 文件;它不改变 Global 的生效端点。若 Metro 已缓存缺失文件错误,补齐后重新启动 Metro。
+
+## 导航纠正(2026-09-20)
+
+移除首页、任务、文件、预览和登录中的自绘侧栏及其额外 56 点占位。
+返回/关闭通过原生 Stack 工具栏注册,由系统安置到共享栏;标题与页面操作组保留原布局。
+登录的嵌入式新增账号流程保留所在弹层导航,不修改底层页面导航。
+安全区、双栏、折叠触控板、弹层与预览分页修复保留。
+最终 Mobile 全量 488 个文件、6,230 项通过,TypeScript 与 diff whitespace 检查通过。
+已加载新 bundle 并目检内屏横向浅色首页:菜单与动作组恢复横向,右侧无第二列自绘栏,
+截图 `/tmp/cindy-systembar-current.png`。其它页面、旋转后的返回操作与深色模式尚未完成本轮目检。
+
+## 双栏设计收敛(2026-09-20)
+
+- 常驻左栏沿用主页的设备范围、分组与排序偏好;项目头和任务行共用 `HomeListVisuals` 的样式与 Agent 状态图标,子任务保持列表虚拟化。临时抽屉仍保留原导航操作。
+- 移除常驻栏底部“主页”。Duo 竖向系统栏承担返回和新建任务,不增加自绘栏;页面标题与文件/远程桌面等动作组仍为横向布局。
+- 两栏顶部增加同档留白,任务页顶部使用主题背景,避免滚动文字透入留白。输入框区域扣除已经由内容内边距承担的底部安全区,消除重复留白。
+- 回归:Mobile 全量 488 文件、6,231 项通过;Mobile TypeScript 与 `git diff --check` 通过。新增常驻栏分组折叠、选中任务、任务切换与移除重复导航入口的交互测试。
+- 实际目检:Duo 内屏横向,Global `com.xd.cindy`,当前适配 worktree 的 Metro;原生 fingerprint 匹配。通过现有任务深链进入截图所示任务,浅色 `/tmp/cindy-pane-task-final.png`、深色 `/tmp/cindy-pane-task-dark.png` 均确认单列系统导航、顶部留白、侧栏选中态及输入框底部间距。目检后恢复浅色。
+- 限制:Device Hub 的 AX 窗口不可解析,本轮未完成系统按钮实点、软件键盘、旋转/外屏的新增目检;未修改任务内容或账号数据。
+
+## 主页主体复用(2026-09-20)
+
+此前 `HomeListVisuals` 只共用行样式,侧栏仍维护自己的列表与数据控制器,没有满足“主页收窄到左侧”。本轮以完整主体替代该实现:
+
+- `HomeSurface.tsx` 的 `MobileHome` 承接原主页全部列表、项目/自动化展开、设备范围、搜索、菜单、滑动操作和数据同步。主页路由只渲染该组件;任务抽屉只提供宽度、当前选中任务和导航回调,不再包含第二套 `SectionList` 或任务行。
+- 当前账号的内存视图状态在两种容器之间保留搜索条件、设备范围、分组展开和滚动偏移;账号/realm 换代清空,旧回调不能写入新账号状态。失焦页面卸载控制器,避免后台主页与前台侧栏重复订阅。
+- 系统栏的新建入口调用同一主页操作,遵循主页选择的设备。临时抽屉导航仍等关闭完成后执行,常驻侧栏原地切任务,不重挂主页。
+- Mobile 全量 489 文件、6,225 项通过;TypeScript 通过。新增实际状态 hook 的容器交接、批量展开更新、账号隔离与搜索条件保留测试;抽屉测试改为验证共用主体的挂载和导航生命周期。路由包装调整后补跑对应定向测试及 TypeScript。设计台账已重生成。
+- Duo 内屏横向目检:完整主页 `/tmp/cindy-shared-home-full.png`、窄栏浅色 `/tmp/cindy-shared-home-light.png`、窄栏深色 `/tmp/cindy-shared-home-dark.png`。同一组项目和任务在两个宽度下呈现,窄栏选中态清晰,系统返回/新建只有一列,常驻栏没有“主页”底栏。目检后恢复浅色。
+- 交互限制仍在:Device Hub 无可用 AX 窗口,未实点菜单、拖动列表或执行键盘/旋转操作;滚动偏移的原生恢复效果未手动验收,不能用状态测试替代。没有清除登录态或发送任务消息。
+
+## 窄窗口返回与快速切换(2026-09-20)
+
+- 窄窗口保留独立返回键,快速切换使用顶部右侧侧栏图标;普通手机与平板共用入口,不再用宽屏门槛替换返回。宽窗口继续常驻主页列。
+- 临时面板仍使用 `MobileHome`,左上角提供关闭操作,删除底部“主页”;选中任务继续在关闭完成后原地替换参数,不增加路由层级。
+- 面板存续期间页面返回操作先关闭面板,iOS 页面侧滑返回暂停,Android 返回及退场期拦截沿用既有逻辑。面板关闭后恢复页面返回。
+- 窄窗口顶部也采用主题背景,正文不再透进顶部留白和导航区域。
+- Mobile 全量 489 文件、6,229 项通过,TypeScript 通过;最后的顶部背景调整补跑 header 定向测试和 TypeScript,通过。设计台账重生成、diff whitespace 检查通过。
+- Duo 竖向内屏已目检左右独立导航入口,深色截图 `/tmp/cindy-quick-switch-dark.png`;已匹配当前 worktree Metro 和原生 fingerprint。面板点击、连续任务切换和返回手势仍未完成自动化实机操作验证,不能以源码及单测替代。
+
+## 快速切换关闭后点击被拦截(2026-09-20)
+
+- 用户报告所有按钮无响应后,保留进程现场检查原生 hit-test:返回、快速切换、输入框均命中 `sessionDrawer.overlay`。面板已移出屏幕、遮罩透明,但全屏容器仍挂载;此前仅做视觉目检遗漏了这一交互故障。
+- 关闭收尾改由可清理的 JS 生命周期定时器负责,不再依赖 Reanimated 完成回调;动画只控制视觉。重新打开或布局变化会取消旧收尾,导航仍等原生子树卸载后的 effect 才执行。
+- 新增动画回调不执行、关闭中重新打开两项行为回归;抽屉相关 13 项测试、Mobile TypeScript 和 diff whitespace 检查通过。
+- 当前 Global Duo 竖向内屏通过热更新验证,未重启 App 或清除登录态:辅助功能按钮操作关闭面板、重新打开、再次关闭、返回主页均得到实际界面变化。关闭后的原生 hit-test 分别命中返回的 SwiftUI 控件和快速切换图标,不再命中透明容器。截图 `/tmp/cindy-drawer-after-close.png`、`/tmp/cindy-drawer-back-home.png`,hit-test 记录 `/tmp/cindy-drawer-hit-fixed.txt`。
+- 本轮未验证物理触屏、Android 或关闭中的旋转操作;不能将辅助功能操作等同于完整手势验收。
+
+## 窄窗口导航最终收敛(2026-09-20)
+
+- 按用户最新决定,移除窄窗口快速切换按钮及其打开、焦点归还逻辑,只保留返回主页。此前关于窄窗口快速切换入口的设计记录被本条替代。
+- 宽窗口继续常驻同一个 `MobileHome` 侧栏,Duo 系统返回位置不变;保留共用面板已有的关闭卸载修复。
+- 相关 14 项测试与 Mobile TypeScript 通过;本轮未做新增模拟器目检。
+
+## 竖向任务顶栏与系统状态区对齐(2026-09-20)
+
+- iOS 无常驻侧栏且系统栏为横向时,任务页改用 Stack 原生标题和工具栏;返回居左,任务操作居右,由 UINavigationBar 负责与状态区对齐及避让。不再在顶部安全区下面叠加自绘导航行。
+- 正文顶部占位使用系统实际 headerHeight,分享选择模式仍使用原全选行;常驻双栏与系统竖栏保持既有布局。颜色沿用主题语义色。
+- 当前 Global Duo 竖向内屏浅色目检确认按钮与时间、信号同一行,截图 `/tmp/cindy-native-top-app.png`。7 项顶栏测试、Mobile TypeScript、diff whitespace 检查通过。深色、普通 iPhone 和旋转切换未做本轮目检。
+
+## 再次进入任务的阅读位置(2026-09-20)
+
+- 复用现有历史缓存,首屏不等待网络校验;补充最近 8 个任务的内存阅读位置,按账号、设备和任务隔离。记录消息标识及其相对视口偏移,而非单独保存整页像素位置。
+- 再进入时一次无动画定位到原消息,原来处于底部则保持跟随最新;搜索/消息链接优先,原消息已不在缓存时回到最新。定位得到原生滚动确认后立即揭示内容,保留原有 300ms 显示上限以避免长期空白,不启用曾引发滚动风暴的 initialScrollIndex 属性。
+- 不增加消息落盘或后台页面常驻;账号切换、历史删除/重置同步清理位置。位置仅在本次 App 运行期间保留。
+- Mobile 全量 491 文件、6,238 项通过,TypeScript 和 diff whitespace 检查通过。新增账号隔离、失效与旧回调、容量限制、实际初始定位回调测试。本轮未做模拟器往返滚动位置和不同宽度重排的目检。
+
+### 往返首屏实测:尚未通过(2026-09-20)
+
+- 已核对 Global Duo 内屏竖向、当前 worktree Metro 与原生指纹,并实际打开「本地构建」、返回主页、再次打开同一任务。录屏 `/tmp/cindy-reentry-warm-before.mov` 捕获到数百毫秒的空白,再出现原内容;不能以历史缓存命中或单测通过宣称无空白重入。
+- 临时诊断确认重入 MessageRenderer 时已有 2 个渲染项;将这类首屏的 opacity 直接设为 1 后,录屏 `/tmp/cindy-reentry-warm-after.mov` 仍捕获到空白。数据缓存没有避免列表重新挂载、测量与定位;单改透明遮罩不足以解决。
+- 已撤去这次无效透明度实验、对应实验测试和临时诊断日志,保留原有实现。无空白重入仍未完成,非底部阅读位置、横屏和深色模式未在本轮验收。
+
+### 原生路由常驻实验:交互不合格,已撤下(2026-09-20)
+
+- 尝试将最近 3 个退出的任务路由保留在 Home 之前,再进入时复用 route key。录屏及前后截图证明非底部内容位置能够保留,但重新进入后正文滚动及输入区按钮失去响应;不能将保留画面当成可用的页面缓存。
+- 关闭冻结、完整重启 App、关闭动画、对非焦点页面禁用触摸均未解决。原生 hit-test 命中 `_UIReplicantView`(`Snapshot of <RNSScreenView>`)。当前 `react-native-screens` 在 Fabric 子视图移位触发的 unmount 中调用 `setViewToSnapshot`,再次挂回相同屏幕时仍显示快照。证据:`/tmp/cindy-retain-hit3.txt`、`/tmp/cindy-retained-verified.mov`、`/tmp/cindy-reading-retain-before.png`、`/tmp/cindy-reading-retain-after.png`。
+- 已移除本次自定义路由、原型测试、诊断日志和关闭动画实验,恢复原有 Stack;未改依赖或原生代码。先前的数据缓存与阅读位置实现保留。真正的列表常驻仍未完成,需要稳定的列表承载位置,不能继续通过重排原生页面冒充保活。
+
+### 标准 Stack + 最近任务预加载(2026-09-20)
+
+- 保留系统 push/pop,通过 Expo Router `router.prefetch` 在返回首页后的空闲时间挂载最近打开的一个任务,提前用缓存消息完成列表布局。默认非 singular Stack 只保留同路由名的一个预加载项;未修改原生 route 排序,也不承诺多个已退出页面仍是同一实例。未访问的任务、预加载尚未完成即点击的情况仍按普通进入路径加载。
+- 首页取消失焦即卸载内容的条件,保留原列表实例。覆盖期间暂停列表订阅和设备同步;全页与侧栏各自持有订阅 owner,共享筛选状态通过订阅同步。账号代际变化重建 Stack,释放旧账号的预加载页面。
+- 修复阅读位置的实测偏移:首次 seek 使用估算行高后,随实际布局变化进行有界定位校正,不从 scroll 回调循环重试;用户触摸、拖动、跳到最新和显式消息定位立即接管。离屏预加载及退出中的滚动事件不能覆盖用户书签。
+- Global iPhone Duo 内屏竖向实测:`/tmp/cindy-official-preload.mov` 中约 32.5 秒处,重新进入「本地构建」时正文随页面滑入;逐帧未见先空白后补正文。重新进入后输入区加号可打开面板,正文可滚动。切换另一任务显示对应正文。历史长表格停留位置前后截图 `/tmp/cindy-preload-reading5-before.png` 与 `/tmp/cindy-preload-reading5-after.png` 在正文裁剪区域 `(0,250)-(1300,1600)` 逐像素一致。
+- Mobile 全量 492 文件、6,245 项通过,TypeScript、scope、smoke 通过。预加载焦点/账号/后台取消、共享首页状态、行高测量后的校正及用户接管有定向覆盖。当前轮未验证普通 iPhone、Android、深色模式、旋转后位置恢复及返回手势取消;自动手势操作未取得可靠触发证据,不计作通过。
+- 此次导航修复没有新增依赖、修改原生配置或原生代码;以上不覆盖同分支先前已有的 Duo 原生改动。
+
+### 重新进入时的顶部高度跳变(2026-09-20)
+
+- 实测普通任务往返:预加载 Native Stack 的 `useHeaderHeight()` 为 120.67pt,进入后原生报告 82pt;顶部 padding 从 129pt 降至 90pt,随后触发 contentSize/贴底校正。没有连接横幅,不能把这次变化归因于网络加载消息。
+- 新增 `useSessionHeaderHeight`:按窗口尺寸、字体缩放、安全区和栏位置保存最多 8 个已完成转场的实测高度,预加载及推进转场期间复用。转场结束继续跟随原生高度。只存几何值,无持久化、账号或任务内容;不改图标和正文滚动算法。
+- 验证:67 项相关测试通过,mobile typecheck、diff whitespace 检查通过。模拟器 com.xd.cindy / Duo iOS 27.1,当前 worktree 源 `7c1c004a5+78a5aa11fa`,原生 fingerprint 匹配。
+- 修前录屏 `/tmp/cindy-jump-before.mov`;修后 `/tmp/cindy-jump-fixed.mov`。竖屏往返复查的 `/tmp/cindy-jump-fixed-before.png` 与 `after.png` 正文裁剪 `(0,300,2000,2500)` 逐像素一致。修后转场片段未见滑入结束后的额外纵向跳动。
+- 此验证只覆盖已捕获的顶部几何变化;不能据此排除异步图片、长表格测量或其他姿态下的独立跳动。普通 iPhone、深色、旋转后的修复效果本轮未目检。临时数值诊断日志已移除。未提交或推送。
+
+### 横屏侧栏切换保留最近消息列表(2026-09-20)
+
+- `RecentMessageHistories` 在常驻双栏下保留最近三个消息列表实例,按账号代际隔离、按设备和任务组合定位;切回窄屏释放隐藏列表。保持相同视口布局,不重排 Native Stack 路由。
+- 隐藏列表退出触摸和无障碍树,暂停自动补页、贴底跟随、书签修正及可见消息读取回调;图片、正文查看器和消息操作弹层关闭。再次激活不重放其它任务期间的跳底请求。
+- Global iPhone Duo 横屏,Metro 8081 当前工作区,源码 `7c1c004a5+57ce8841e0`,原生 fingerprint 匹配、whoami healthy,重新加载日志有 `iOS Bundled 4988ms apps/mobile/index.js`。随后仅更改测试夹具和本证据文档,产品源码不变。
+- 在「远程连接安全风险防范」与「本地构建」之间来回切换,截图 `/tmp/cindy-wide-a-before.png` / `a-after.png` 和 `/tmp/cindy-wide-b-before.png` / `b-after.png` 的正文区域 `(950,250)-(2550,1680)` 分别逐像素一致。自动拖动未取得内容移动证据,本轮不声称已验证非底部手势阅读位置或无瞬时空白。
+- 84 项定向测试、mobile typecheck、scope、2 项 smoke 通过。Mobile 全量先跑 494 文件(6248 通过、5 个旧夹具失败),补齐可见状态及更新图片查看器断言后,两个失败文件共 20 项全部通过(含新增隐藏列表不补页测试);未重复整包执行。
+- Light 模式已目检;Dark、Android、普通 iPhone、横竖屏旋转期间的列表位置本轮未实测。没有新增颜色、依赖或原生配置。未提交或推送。
+
+### Duo 导航与悬浮控件统一(2026-09-20)
+
+- 查阅 Apple `Designing for iPhone Duo`、`Raise the bar with iPhone Duo`(111462)、`Design for iPhone Duo`(111466)。规则已写入 DESIGN §5:原生容器优先,分栏仅详情竖排,侧栏菜单留在侧栏;全屏自定义远程桌面两种横屏都在右侧。44pt 是 Cindy 悬浮控件规格,不冒充 Apple 状态图标的规范尺寸。
+- 首页原来的 `Stack.Toolbar.View` 横排包裹改为系统 Button/Menu;已实测进入右侧竖排,显示菜单保留分组、选中态。任务页与远程桌面共用 NativeChromeBackButton;侧栏菜单、任务动作和远程工具栏共用 navigationChrome.target,移除远程工具栏额外 padding。中性玻璃不再使用不透明 surface tint。
+- 远程桌面返回使用单一横坐标及固定宽度,修复旋转中左右约束切换后返回残留在左边的实机问题;工具栏与弹出菜单锚点共用右侧几何,优先读取顶部 occlusion 保留区。按当前模拟器系统栏的中心线校准 6pt 内移;未把该校准说成 Apple API 合同。
+- Duo iOS 27.1 / Global com.xd.cindy:Light 两个横屏截图 `/tmp/cindy-chrome-a-light-final.png`、`/tmp/cindy-chrome-b-light-final.png`;Dark `/tmp/cindy-chrome-a-dark-final.png`。实际远程画面下返回、工具栏与信号中心线一致;连接实例保留由单测覆盖。恢复 Light。首页菜单展开已目检。
+- 193 项定向测试通过;后续定位修正后再跑远程 140 项通过,mobile typecheck 通过。整包先跑 6249 项通过、1 个文件因新增 token 缺少 mock 未加载;补齐 mock 后该文件 5 项通过。不宣称整包最终重跑全绿。
+- 普通 iPhone、Android、系统多任务左右分屏及全应用每个页面的视觉回归未覆盖。原生系统导航继续由系统决定位置;自定义悬浮控件此次统一。无新增依赖或原生配置改动,未提交、推送。
+- 最终运行身份:`7c1c004a5+6014a8f831`,Metro 8081 PID 35363,whoami target-fresh/native-matched;重启 com.xd.cindy 后日志 `iOS Bundled 921ms apps/mobile/index.js`,前台首页右侧原生导航已截图复核。此后仅补证据文字。
+
+### 保留图标并减轻玻璃蒙层(2026-09-20)
+
+- 按用户要求保留原有图标。首页远程桌面入口恢复 Lucide Monitor 的原始轮廓,22pt、stroke 2;直接栅格化同一 SVG 为 Metro 引用的 1x/2x/3x template 图片,保留系统工具栏竖排能力,不改原生资源目录。远程桌面四个操作图标未更换。首页恢复后已目检,41 项相关测试及类型检查通过。
+- 远程桌面的圆形返回与胶囊工具栏改用系统 Clear Liquid Glass,减少 regular 材质的白灰蒙层。保留尺寸、位置、图案及非玻璃回退;其它常规导航保持系统 regular 材质。
+- Global Duo iOS 27.1 / com.xd.cindy,源码 `7c1c004a5+8e77d0e27b`,whoami 原生及 Metro 身份通过;启动日志 `iOS Bundled 936ms apps/mobile/index.js`,前台远程画面已检查。截图 `/tmp/cindy-clear-glass-light.png` 与 `/tmp/cindy-clear-glass-dark.png`;检查后恢复 Light。5 项 nativeChrome 测试、mobile typecheck 和 diff whitespace 检查通过。本次材质修改未重复其它设备或方向验证,未提交或推送。
+
+### Clear 玻璃上的白色图标与局部暗衬(2026-09-20)
+
+- 用户确认按 Clear 材质规范处理:远程返回与四个工具图标固定白色,按钮轮廓内叠 35% 黑色暗衬;选中态使用 18% 白色薄层,避免浅色主题白底白图标。共用 navigationChrome 语义值,不更换图案、不压暗整个桌面;非玻璃回退维持原主题配色。
+- 重新打开原 Duo(用户关闭后为 Shutdown)、启动 Device Hub 和 Global com.xd.cindy。源码 `7c1c004a5+5ca8683e23`,Metro 8081 PID 8426,whoami `healthy:true`、native-matched,日志 `iOS Bundled 7558ms apps/mobile/index.js`;前台远程桌面已验证。
+- Light/Dark 均通过 Device Hub 窗口目检:返回及工具图标保持白色,暗衬局限在圆/胶囊轮廓内。Dark 窗口证据 `/tmp/cindy-glass-contrast-dark-window.png`。simctl 默认抓取外屏会得到黑图,不能当本轮内屏证据。检查后恢复 Light,保留远程桌面供用户测试。
+- mobile typecheck、5 项 nativeChrome 测试及 diff whitespace 检查通过;此轮不重复声明其它姿态或设备的验证。无原生指纹改动,未提交或推送。
+
+### Clear 玻璃双模式配色(2026-09-20,取代上一节固定白色方案)
+
+- 用户确认浅色用深图标、深色用浅图标。返回与工具栏共用 `navigationChrome.clear[mode]`:Light 黑色前景、局部白色 35% 底衬、黑色 10% 选中层;Dark 白色前景、局部黑色 35% 底衬、白色 18% 选中层。保留 Clear 材质及原图案,没有整屏蒙层。
+- Duo 当前横屏、实际远程锁屏背景下目检 Light/Dark:信号和操作图标颜色极性一致;恢复 Light。此轮未重复另一横屏、其它设备或任意远程背景的对比度验收。
+- mobile typecheck、5 项 nativeChrome 测试、git diff --check 通过。Metro 仍为当前 worktree,源码指纹更新为 `7c1c004a5+d49cee641d`;无原生配置改动,未提交、推送。
+
+### 远程菜单顶部文字裁切修复(2026-09-20)
+
+- 横屏 Popover 内容原先按窗口计算固定高度;系统给出的弹窗空间更小时,固定 SwiftUI frame 会让过高内容居中溢出,顶部标题被裁掉。改为独立宽度约束和可收缩的 min/max 高度,让 RNHostView 按实际布局提案获得尺寸。
+- 标题区域明确不收缩,正文 ScrollView 可缩至剩余空间;保留单一 RN surface、子页滚动重置与原有菜单交互。未改图标、配色或原生配置。
+- mobile typecheck、5 项 nativeChrome 测试及 git diff --check 通过。按用户要求仅代码检查;本次修复未做模拟器视觉验收,未提交或推送。
+
+### 菜单高度收缩回归修正(2026-09-20)
+
+- 用户截图确认上一版 min/max 高度方案使菜单仅剩标题,不能视为视觉修复完成。原因是弹窗首次查询理想尺寸时,RN flex ScrollView 没有内在期望高度;仅给最大高度不能建立正文空间。
+- 在可收缩 frame 中补齐 idealHeight,使用窗口安全高度作为期望及上限,保留固定宽度与弹性高度的独立 modifier(Expo 的固定 width/height 分支会忽略同一 modifier 中的 ideal/min/max)。标题不收缩、正文滚动的约束保持。
+- 新增配置回归测试,防止理想高度缺失或重新引入固定正文高度。6 项 nativeChrome 测试、mobile typecheck、diff whitespace 检查通过;这些不模拟 UIKit/SwiftUI 排版,按用户要求未使用 computer use,仍需实际视觉验证。
+
+### 首页与返回共用 SwiftUI 原生玻璃按钮(2026-09-20)
+
+- 用户要求统一画法。新增 iOS NativeChromeButton,由原返回按钮实现抽出;首页/侧栏 HomeHeaderGlassButton 的 iOS 分支及 NativeChromeBackButton 共用该组件。SwiftUI Button 负责圆形玻璃和点击反馈;自定义图标经 RNHostView 放入原生 label,保留 Lucide 原图,不更换远程桌面图标。44pt 目标、浅深色、Clear 分支保持。
+- 首页左上位置不变。非 iOS 继续使用原平台回退,不引入 SwiftUI 依赖到 Android。原生工具栏项目与已使用 SwiftUI 的胶囊动作组保持各自原生容器。
+- 47 项定向测试、mobile typecheck、git diff --check 通过。按用户要求未使用 computer use;原生视觉及点击、菜单触发需实际验证,不将源码测试当作视觉证明。无原生配置或依赖改动,未提交、推送。
+
+### 分栏系统栏按钮统一(2026-09-20)
+
+- 补齐此前漏掉的 SystemNavigationBack 路径:iOS 的返回/关闭、新建按钮使用与首页侧栏相同的 NativeChromeButton。保留系统工具栏定位,用 Toolbar.View hidesSharedBackground 承载,避免容器另加一层玻璃。disabled 继续传入 SwiftUI modifier,原系统图案保持。
+- 从当前 8081 Metro 请求 iOS index source map,确认 HomeHeaderGlassButton.ios、SystemNavigationBack.ios、NativeChromeButton.ios 均进入 bundle,两个入口确实引用共同按钮。这证明打包解析正确,不证明设备已加载该 bundle 或视觉完全相同。
+- 47 项相关测试、mobile typecheck、git diff --check 通过。按用户要求未使用 computer use,分栏原生工具栏的实际布局/交互和浅深色视觉仍待目检。未提交、推送。
+
+### 撤回破坏 Duo 原生竖排的自定义工具栏替换(2026-09-20)
+
+- 用户在重新加载后的截图确认:返回覆盖左侧菜单,新建挤入顶部操作栏。上一节把 Toolbar.Button 换成 Toolbar.View 的方案破坏 Duo 自适应,不能保留。
+- 删除本轮新增的 SystemNavigationBack.ios.tsx,让入口恢复既有 SystemNavigationBack.tsx 原生 Toolbar.Button;保留首页/侧栏 SwiftUI 原生按钮。统一视觉不能以破坏系统导航定位为代价,此时两处仍分别为 SwiftUI 按钮和系统 toolbar item,不能宣称底层全部相同。
+- 41 项相关测试、mobile typecheck 通过;更新结构回归断言禁止系统导航路径再次使用 Toolbar.View。按要求未使用 computer use,待用户核对实际布局。
+
+### 独立圆形按钮尺寸规范(2026-09-20)
+
+- 自定义导航按钮明确三层:44pt 可见玻璃圆形、44pt 点击区域、20pt 图标。NativeChromeButton 使用 borderless SwiftUI Button,先设 frame 再施加系统 interactive glassEffect,取消 large/buttonStyle glass 的隐式尺寸。首页及侧栏对应 Menu/X/Monitor/Ellipsis 使用 iconSize.action,保留原图形和笔画。
+- Light/Dark 配色及 Clear 材质选择不变。系统 Toolbar.Button 保留原生定位与尺寸,不再用 Toolbar.View 替换。规范记入 DESIGN §5。
+- mobile typecheck、47 项相关测试、git diff --check 通过。按用户要求未用 computer use,不宣称实际玻璃视觉完全一致或目检通过。
+
+### 历史恢复期间顶部留白重复补偿(2026-09-21)
+
+- Duo 内屏竖屏运行期诊断捕获:预加载列表开始按书签 scrollToIndex,随后 topPadding 从 0 变成 90;此时 native offset 仍为 0,旧补偿 effect 另发 scrollToOffset(90),与正在进行的书签定位冲突。
+- 修复只在恢复期间让书签 resolver 负责定位;尚未收到原生滚动坐标时不做相对补偿。正常历史阅读期间顶部高度变化仍补偿。没有修改缓存数量或原生路由顺序。
+- 新增 4 项生产 effect 回归测试,相关三文件 74 项测试通过。Duo 内屏竖屏同一任务两个历史位置往返截图位置一致,修复后日志未再出现上述 offset=90 指令。此检查覆盖预加载完成后重进;未证明极快连续点击、其他设备和所有消息类型均无跳动。临时诊断日志已移除。
+### 五个消息列表的公共承载层(2026-09-21,设备验收待完成)
+
+- `RecentMessageHistoriesProvider` 放在账号隔离边界内、Native Stack 外。按设备和任务 ID 保留最近五个消息列表;页面退出仅释放显示槽,第六个任务才淘汰最久未使用的列表,账号切换清空。不再并行预加载五个原生路由。
+- 路由发布最新消息属性、导航上下文和显示尺寸。新路由的历史数据/顶部高度未就绪时保留旧内容与布局,不把初始零高度和载入占位覆盖到已有实例上。隐藏列表暂停自动定位与历史补拉。
+- 初版 JS 根层浮层实测挡住了 iOS 边缘返回,不能作为 iOS 交付实现。改为 Expo 原生 host/slot:React 一直持有 host,原生只移动普通 UIView 内容容器到路由内的 slot。Fabric 管理的 host 及其子组件不重新挂载;原生页面层级继续承载返回手势、转场、标题栏、输入框和抽屉。非 iOS 使用公共容器浮层;缺少新原生能力的旧 iOS 包退回页面内渲染,避免阻塞返回手势。
+- 本次新增原生模块视图,改变 iOS runtime fingerprint,需重新出原生包;旧安装包不能通过 OTA 获得完整保活。Android 虽未新增原生逻辑,但本地 `modules/` 目录也参与其指纹计算,指纹同样变化,需要匹配的新 Android 原生包,不能向旧 runtime 仅发 OTA。两端指纹记录见上文「原生桥接与兼容」,最终发版以 release check 为准。建议随下一次原生版本发出;合并前仍须完成冷更确认。
+- 自动验证:Mobile 497 文件、6,278 项测试通过,包含列表实例跨路由销毁、旋转、五项淘汰、账号隔离、未就绪布局保护和原生槽重接测试;Mobile TypeScript 与 scope guard 通过。
+- 设备验收尚未完成:最初 JS 浮层版的实例保留与阅读位置检查不能代替最终原生承载层验证。Mac 锁屏导致 Device Hub 无法采集有效画面或触摸,需解锁后补测 Duo 的边缘返回、历史位置往返、横竖屏、侧栏切换、输入框和抽屉。未验证 Android、普通 iPhone 和最终版本的浅/深色实机表现。
+
+### 缓存命中仍白屏的显示条件修复(2026-09-21)
+
+- Duo 安装包指纹与 Metro 均匹配上述公共承载层版本。运行日志确认两项已打开任务来回切换没有列表卸载/重建;白屏源自原生 slot 的 `selected={focused && ready}`,新页面初始顶部高度尚未测量时会关闭显示槽。
+- 改为聚焦就接回已有原生内容,`ready` 只控制新属性、定位和交互。新任务没有 host 时继续正常等待初始化,不显示其他任务;缓存命中不再等待新路由测量才能显示。
+- Duo 内屏竖屏实测:历史长表格拖到中间→原生边缘返回→打开另一任务→返回→重进长表格,正文区域逐像素一致,期间实例挂载/卸载计数不变。过渡录屏 `/tmp/cindy-resident-switch-fix.mov` 末次进入时正文随页面进入,没有先出现整页空白;边缘返回可用。
+- 新增“新路由未就绪仍接回缓存”的回归测试,相关 69 项通过。临时诊断日志已移除。此轮未追加其他设备和横屏验收。
+
+### 登录按钮原生化(2026-09-21)
+
+- 登录主操作、第三方入口、返回、登录方式、组织历史、重发、协议弹窗动作、人机验证重试/取消、注销状态提示、账号切换/添加接入 SwiftUI Button;添加账号关闭复用 HomeHeaderGlassButton。原有品牌图标保留,原生 ProgressView 表达提交中状态。
+- 通过 LoginNativeButton 复用 nativeGlassButtonStyle;使用语义色和有效主题,原有设计坐标及缩放保留。iOS 禁用与忙碌时同时阻断 native Button 和回调;其他系统继续原 RN 分支。没有改动原生依赖、配置、认证协议或凭证处理。
+- 输入框、协议勾选、内联法律链接和弹窗布局不在这次按钮迁移范围。
+- 登录及相关原生控件 290 项测试通过,Mobile 类型检查通过。iPad Pro 13 英寸 iPadOS 27.0 浅色横屏登录页已检查;深色、VoiceOver、其他设备、账号切换弹层和完整真实认证尚未实机验收,不将组件测试等同于系统交互验收。
+
+### 五项统一保留与磁盘恢复验收(2026-09-21)
+
+- 历史控制器跟随最近五个任务列表保留,移除独立的八项/4 MiB 未使用历史视图池。仍有消费者的控制器在释放后清理,避免同一任务产生两个控制器。磁盘快照格式和配额不变。
+- Duo 外屏竖屏实测六个不同任务,第六个打开后捕获历史控制器淘汰;重进最早任务捕获有效磁盘快照命中(20 项),正文正常显示。重进最近任务、展开横屏侧栏往返没有新增磁盘命中。此轮未做逐帧动画分析、断网实机测试或其他设备验收。
+- 实测发现并修复磁盘 IO 清理错误:Expo File.moveSync 会更新源对象 URI,finally 删除源对象实际删除了正式快照。现在只清理原始临时 URI。模拟器确认快照和索引真实保留;新增回归覆盖移动成功、写入失败、移动失败。
+- 63 项相关测试、Mobile 类型检查通过。测试覆盖淘汰后的离线磁盘恢复;不等同于模拟器断网验收。临时诊断日志已移除。
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 657a5f31c4..2e4fdf09ec 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -398,6 +398,23 @@ Chat prose and compact code use the existing `chatChrome.ts` presentation entry;
- Centered-card layouts (login, empty states) follow the Surface + Card two-layer rule in §2.
- Reading-width content (settings forms, document previews) is centered with a comfortable max width; full-bleed content (chat stream, file tree) fills its region.
+### Mobile iOS navigation chrome / iPhone Duo
+
+- Wide Home and task-sidebar presentations share one native list instance in `ResidentHomeListProvider`, outside route lifetimes. Route slots supply layout and callbacks; do not key the host by task/route or restore a cached offset over its live scroll position. Collapse/expand its bounds, keep native headers outside its touch area, and pause hidden row subscriptions. Narrow screens retain their route-local list.
+
+- Home's main menu is a top-left affordance, including when Duo moves native toolbar actions into the right rail. Host this home-only exception in the native header's left custom view with its shared background hidden, never in an absolute screen-content overlay under the transparent navigation bar; remote-desktop and display actions remain native toolbar items.
+- Custom iOS home/sidebar icon buttons and standalone back buttons share `NativeChromeButton` (SwiftUI Button with native glass style). Preserve existing icon artwork inside the native label; do not substitute a React Native Pressable with a separate GlassView for this button family.
+- Mobile glass button styles are configured in `platform/chrome/nativeGlassButtonStyle.ios.ts`: neutral circles, text/primary actions and grouped toolbar material share that entry. Home floating new-task and share-cancel actions use the same native button path; text buttons retain intrinsic label sizing. Keep light/dark semantic colors and native disabled/activation behavior. Non-iOS retains the React Native fallback.
+- Login actions use `LoginNativeButton.ios.tsx` with the same shared glass styling. SwiftUI owns activation, disabled state and loading indicators; existing brand artwork can remain inside RNHostView labels. The login stage retains its design-coordinate frames and scaling, while text actions use native borderless buttons. This supersedes the hand-painted button feedback in the login skin on iOS only; inputs, consent checkbox, inline legal links and non-iOS controls retain their existing implementations.
+- The home main menu remains a left-edge drawer on every platform and window shape, using `HomeChromeDrawer.tsx` (iOS uses FullWindowOverlay above the native header). Preserve backdrop dismissal, swipe-left dismissal and the drawer's close lifecycle. Native glass button unification must not replace this navigation drawer with a bottom sheet. Device-scope/display pull-downs keep their existing system UIMenu path and native toolbar menus; their custom panels are fallback code, not a reason to replace working native menus. System navigation/toolbars remain native container-owned.
+- Standalone custom navigation controls use a 44pt visible circle and 44pt hit frame (`navigationChrome.target`), with 20pt artwork (`iconSize.action`) centered inside. Apply the native interactive glass effect after the explicit frame on a borderless SwiftUI Button; do not add `controlSize(large)` or another glass/padding layer. System toolbar items retain native sizing and positioning: never replace them with `Toolbar.View` to enforce this custom-control rule, because that breaks Duo's vertical adaptation.
+- Prefer the native navigation container for page back/close and toolbar actions. On Duo, let the system adapt navigation to the shared status/toolbar region; only the detail column gets the vertical bar in a split view. Sidebar-local menus stay in the sidebar.
+- Full-screen custom overlays (remote desktop) keep back and tools on the right in both Duo landscape rotations, centered on one rail below the system status area. Back comes before tools. Respect safe areas and reserved folds; do not mirror the rail from a video orientation event.
+- Floating back/menu controls use the shared `navigationChrome.target` size; grouped actions use the same target breadth, without an extra outer padding ring. Use native Liquid Glass (regular for app navigation; clear over immersive remote desktop imagery), circle for a single icon and capsule for a group; do not tint neutral glass with opaque surface colors. Use semantic foregrounds and the existing non-glass fallback in both themes.
+- Clear glass over remote imagery follows the navigation theme: dark icons in Light and light icons in Dark. A localized light/dark backing inside the control outline protects contrast, with a matching translucent selected-state fill. Keep the material clear and the desktop outside the controls unchanged. This explicit two-mode palette is Cindy’s design choice; Clear material does not provide automatic foreground adaptation.
+- These are Cindy's shared component rules, not a claim that Apple's status glyph is an app button or that Apple mandates our precise size. Content actions and keyboard accessories retain their own hierarchy.
+- References: [Designing for iPhone Duo](https://developer.apple.com/design/human-interface-guidelines/designing-for-iphone-duo), [Raise the bar with iPhone Duo](https://developer.apple.com/videos/play/tech-talks/111462/), [Design for iPhone Duo](https://developer.apple.com/videos/play/tech-talks/111466/).
+
### Whitespace Philosophy
- **Emptiness as luxury**: no surface overstays its welcome — each concept gets minimal but sufficient space.
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 97b84f07bb..07d8f3842b 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -51,20 +51,20 @@
| `desktop.window.sidebar` | desktop | 右侧栏独立窗口 | `?sidebarWindow=1` → renderer/sidebar-window-entry.tsx;hash `/sidebar-window` | RightSidebar, RightSidebarShell, SidebarWindowLayout | apps/desktop/src/main/right-sidebar-window/controller.ts, apps/desktop/src/main/right-sidebar-window/ipc.ts, apps/desktop/src/main/right-sidebar-window/registry.ts, apps/desktop/src/main/right-sidebar-window/resolveHostContext.ts, apps/desktop/src/main/right-sidebar-window/settings-store.ts, apps/desktop/src/main/right-sidebar-window/window.ts, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/sidebar-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 104 | 45 | 196 |
| `desktop.window.voice-dictionary-toast` | desktop | 语音词典 Toast 窗 | `?view=voice-input-dictionary-toast` → main-entry.tsx → VoiceInputDictionaryToast | VoiceInputDictionaryToast | apps/desktop/src/renderer/voice-input/VoiceInputDictionaryToast.tsx | 6 | 0 | 2 |
| `desktop.window.voice-overlay` | desktop | 语音输入浮窗 | `?view=voice-input-overlay` → main-entry.tsx → VoiceInputOverlay | VoiceInputOverlay, VoiceInputStatusNotice | apps/desktop/src/main/voice-input/global.ts, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css, apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx, apps/desktop/src/renderer/voice-input/VoiceInputStatusNotice.tsx | 71 | 38 | 25 |
-| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 55 |
-| `mobile.auth` | mobile | 登录与添加账号 | app/(auth)/login.tsx / app/add-account.tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, LoginCaptchaWebView, LoginSkinControls, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, add-account, gestureHandler, login, peerFileTransport, useLocale | apps/mobile/app/(auth)/login.tsx, apps/mobile/app/_layout.tsx, apps/mobile/app/add-account.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/LoginCaptchaWebView.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginSkinControls.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 203 | 76 |
-| `mobile.automations` | mobile | 自动化 | app/automations/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/automations/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 71 |
-| `mobile.chat.new` | mobile | 新建任务 | app/sessions/new.tsx | AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerAttachmentTray, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, ImageLightbox, IncomingShareBridge, MobileAgentMark, MobileAgentSwitcher, MobileChoicePickerList, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, NewTaskSelectionSheet, NewTaskSelectionSheet.ios, PaperPlaneIcon, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, _layout, gestureHandler, new, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/new.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 228 | 110 |
-| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, CompanionMessageCard, ComposerAttachmentTray, ComposerExpandButton, ComposerExpandButton.ios, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeInput, ComposerNativeInput.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerRichInput, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, HomeEntryProvider, HomeGlassMenuPanel, HomeNativeStackHeader, HomeSearchBar, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InteractionPanel, MarkdownBlockContent, MessageActionSheet, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PluginInvocationHeader, PromptRecommendation, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RenameSessionModal, RewindPreviewPanel, SentInlineAtomBody, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionOptionsExpoSheet, SessionResourceCards, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionUsageSummary, ShareImageNativeButton, ShareImageNativeButton.ios, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, StreamingStatusText, TaskTags, TaskTagsSheet, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, [sessionId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerExpandButton.ios.tsx, apps/mobile/src/session/ComposerExpandButton.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeInput.ios.tsx, apps/mobile/src/session/ComposerNativeInput.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerRichInput.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/PromptRecommendation.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/RewindPreviewPanel.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionResourceCards.tsx, apps/mobile/src/session/SessionSearchNative.ios.tsx, apps/mobile/src/session/SessionSearchNative.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareImageNativeButton.ios.tsx, apps/mobile/src/session/ShareImageNativeButton.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/StreamingStatusText.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/TaskTagsSheet.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 7 | 229 | 252 |
-| `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/direct/[threadId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 50 |
-| `mobile.device-management` | mobile | 设备管理 | app/devices/manage.tsx / app/devices/manage/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceInformationFields, DeviceInformationFields.ios, DeviceLinkContext, DeviceManagementDialogs, DeviceManagementList, DeviceManagementList.ios, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RenameDeviceModal, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, manage, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/manage.tsx, apps/mobile/app/devices/manage/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceInformationFields.ios.tsx, apps/mobile/src/device-link/DeviceInformationFields.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/DeviceManagementDialogs.tsx, apps/mobile/src/device-link/DeviceManagementList.ios.tsx, apps/mobile/src/device-link/DeviceManagementList.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RenameDeviceModal.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 53 |
-| `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, [deviceId], _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/[deviceId].tsx, apps/mobile/app/devices/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 112 |
-| `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HtmlBrowserChrome, HtmlBrowserChrome.ios, HtmlFileReader, HtmlWebsiteBrowser, ImageLightbox, IncomingShareBridge, MarkdownFileReader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HtmlBrowserChrome.ios.tsx, apps/mobile/src/session/HtmlBrowserChrome.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/HtmlWebsiteBrowser.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MarkdownFileReader.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 228 | 77 |
-| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 108 |
-| `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 48 |
-| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 48 |
-| `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [collectionId], [resourceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/resources/[collectionId].tsx, apps/mobile/app/resources/[collectionId]/[resourceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 54 |
-| `mobile.settings` | mobile | 设置(含调试与日志上传可见入口) | app/settings.tsx | AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, HomeEntryProvider, HomeNativeStackHeader, IncomingShareBridge, MobileChoicePickerList, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeRemoteDesktopView, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, settings, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/settings.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 196 | 56 |
+| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AdaptiveWindow, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 198 | 58 |
+| `mobile.auth` | mobile | 登录与添加账号 | app/(auth)/login.tsx / app/add-account.tsx | AccountSwitcherSheet, AdaptiveWindow, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, IncomingShareBridge, LoginCaptchaWebView, LoginNativeButton, LoginNativeButton.ios, LoginSkinControls, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, StartupSplashOverlay, SystemNavigationBack, ThemeProvider, _layout, add-account, gestureHandler, login, peerFileTransport, useLocale | apps/mobile/app/(auth)/login.tsx, apps/mobile/app/_layout.tsx, apps/mobile/app/add-account.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/LoginCaptchaWebView.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginNativeButton.ios.tsx, apps/mobile/src/components/LoginNativeButton.tsx, apps/mobile/src/components/LoginSkinControls.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SystemNavigationBack.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 205 | 80 |
+| `mobile.automations` | mobile | 自动化 | app/automations/[deviceId].tsx | AdaptiveWindow, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/automations/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 198 | 74 |
+| `mobile.chat.new` | mobile | 新建任务 | app/sessions/new.tsx | AdaptiveWindow, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerAttachmentTray, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, ImageLightbox, IncomingShareBridge, MobileAgentMark, MobileAgentSwitcher, MobileChoicePickerList, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, NewTaskSelectionSheet, NewTaskSelectionSheet.ios, PaperPlaneIcon, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, _layout, gestureHandler, new, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/new.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/NewTaskSelectionSheet.ios.tsx, apps/mobile/src/session/NewTaskSelectionSheet.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 230 | 113 |
+| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AccountSwitcherSheet, AdaptiveWindow, AndroidUpdateSheet, AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, CompanionMessageCard, ComposerAttachmentTray, ComposerExpandButton, ComposerExpandButton.ios, ComposerFrame, ComposerFrame.ios, ComposerKeyboardAvoidingView, ComposerNativeInput, ComposerNativeInput.ios, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerRichInput, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ContextSheetGoalView, ContextSheetGoalView.ios, ContextSheetMediaViews, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSurface, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InteractionPanel, LoginNativeButton, LoginNativeButton.ios, MarkdownBlockContent, MessageActionSheet, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobileModelPickerList.ios, MobilePermissionPickerList, MobilePermissionPickerList.ios, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModalContentArea, ModelOptionsSheetView, ModelOptionsSheetView.ios, ModelPickerNativeHeader, ModelPickerNativeHeader.ios, ModelPickerSheet, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePermissionSheet, NativePermissionSheet.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PaperPlaneIcon, PendingSendBubble, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PlanModeChip, PluginInvocationHeader, PromptRecommendation, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, RecentMessageHistories, RemoteAccessGuide, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, RewindPreviewPanel, SentInlineAtomBody, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionListDrawer, SessionMenuSheet, SessionOptionsExpoSheet, SessionResourceCards, SessionSearchNative, SessionSearchNative.ios, SessionTailBanner, SessionUsageSummary, ShareImageNativeButton, ShareImageNativeButton.ios, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, StreamingStatusText, SwipeableSessionRow, SwipeableSessionRow.ios, SystemNavigationBack, TaskTags, TaskTagsSheet, ThemeProvider, UnifiedModelPickerSheet, UnifiedModelPickerView, UnifiedModelPickerView.ios, VoiceRecordingPill, [sessionId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginNativeButton.ios.tsx, apps/mobile/src/components/LoginNativeButton.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/SystemNavigationBack.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerExpandButton.ios.tsx, apps/mobile/src/session/ComposerExpandButton.tsx, apps/mobile/src/session/ComposerFrame.ios.tsx, apps/mobile/src/session/ComposerFrame.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerNativeInput.ios.tsx, apps/mobile/src/session/ComposerNativeInput.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerRichInput.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.ios.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeListVisuals.tsx, apps/mobile/src/session/HomeNewTaskButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/HomeSurface.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.ios.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.ios.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.ios.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerNativeHeader.ios.tsx, apps/mobile/src/session/ModelPickerNativeHeader.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/NativePermissionSheet.ios.tsx, apps/mobile/src/session/NativePermissionSheet.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/PluginInvocationHeader.tsx, apps/mobile/src/session/PromptRecommendation.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/RewindPreviewPanel.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SessionResourceCards.tsx, apps/mobile/src/session/SessionSearchNative.ios.tsx, apps/mobile/src/session/SessionSearchNative.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareImageNativeButton.ios.tsx, apps/mobile/src/session/ShareImageNativeButton.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/StreamingStatusText.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/session/TaskTagsSheet.tsx, apps/mobile/src/session/UnifiedModelPickerSheet.tsx, apps/mobile/src/session/UnifiedModelPickerView.ios.tsx, apps/mobile/src/session/UnifiedModelPickerView.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 7 | 231 | 277 |
+| `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AdaptiveWindow, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/direct/[threadId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 198 | 53 |
+| `mobile.device-management` | mobile | 设备管理 | app/devices/manage.tsx / app/devices/manage/[deviceId].tsx | AdaptiveWindow, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceInformationFields, DeviceInformationFields.ios, DeviceLinkContext, DeviceManagementDialogs, DeviceManagementList, DeviceManagementList.ios, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, ModalContentArea, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RenameDeviceModal, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, manage, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/manage.tsx, apps/mobile/app/devices/manage/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceInformationFields.ios.tsx, apps/mobile/src/device-link/DeviceInformationFields.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/DeviceManagementDialogs.tsx, apps/mobile/src/device-link/DeviceManagementList.ios.tsx, apps/mobile/src/device-link/DeviceManagementList.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RenameDeviceModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 198 | 56 |
+| `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AdaptiveWindow, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSurface, IncomingShareBridge, LoginNativeButton, LoginNativeButton.ios, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, ModalContentArea, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteAccessGuide, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginNativeButton.ios.tsx, apps/mobile/src/components/LoginNativeButton.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeListVisuals.tsx, apps/mobile/src/session/HomeNewTaskButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/HomeSurface.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 198 | 112 |
+| `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AdaptiveWindow, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HtmlBrowserChrome, HtmlBrowserChrome.ios, HtmlFileReader, HtmlWebsiteBrowser, ImageLightbox, IncomingShareBridge, MarkdownFileReader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, ModalContentArea, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, StartupSplashOverlay, SystemNavigationBack, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SystemNavigationBack.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HtmlBrowserChrome.ios.tsx, apps/mobile/src/session/HtmlBrowserChrome.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/HtmlWebsiteBrowser.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MarkdownFileReader.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 230 | 79 |
+| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AdaptiveWindow, AndroidUpdateSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ComposerNativeRow, ComposerNativeRow.ios, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, ConversationSearchFilterSheet, DeviceLinkContext, FoldTouchpad, HomeChromeDrawer, HomeChromeFrost, HomeEntryProvider, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeListVisuals, HomeNativeStackHeader, HomeNewTaskButton, HomeProjectMachineLabel, HomeSearchBar, HomeSurface, IncomingShareBridge, LoginNativeButton, LoginNativeButton.ios, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, ModalContentArea, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteAccessGuide, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteTaskSuggestions, RenameSessionModal, ResidentHomeList, SessionActionSheet, SessionDetailsNative, SessionDetailsNative.ios, SessionHeaderNativeControls, SessionHeaderNativeControls.ios, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, TaskTags, ThemeProvider, _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginNativeButton.ios.tsx, apps/mobile/src/components/LoginNativeButton.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/ModalContentArea.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeRow.ios.tsx, apps/mobile/src/session/ComposerNativeRow.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeListVisuals.tsx, apps/mobile/src/session/HomeNewTaskButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/HomeSurface.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionDetailsNative.ios.tsx, apps/mobile/src/session/SessionDetailsNative.tsx, apps/mobile/src/session/SessionHeaderNativeControls.ios.tsx, apps/mobile/src/session/SessionHeaderNativeControls.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/session/TaskTags.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 198 | 108 |
+| `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AdaptiveWindow, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 198 | 50 |
+| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AdaptiveWindow, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 198 | 50 |
+| `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AdaptiveWindow, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteCompanionAvatar, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [collectionId], [resourceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/resources/[collectionId].tsx, apps/mobile/app/resources/[collectionId]/[resourceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 198 | 57 |
+| `mobile.settings` | mobile | 设置(含调试与日志上传可见入口) | app/settings.tsx | AdaptiveWindow, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerNativeSection, ComposerNativeSection.ios, ComposerSheet, ComposerSheet.ios, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheet.ios, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, IncomingShareBridge, MobileChoicePickerList, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativeChromeBackButton.ios, NativeChromeButton.ios, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, ResidentHomeList, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, settings, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/settings.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerNativeSection.ios.tsx, apps/mobile/src/session/ComposerNativeSection.tsx, apps/mobile/src/session/ComposerSheet.ios.tsx, apps/mobile/src/session/ComposerSheet.tsx, apps/mobile/src/session/ContextSheet.ios.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 198 | 59 |
### 生产路由覆盖
@@ -228,3 +228,10 @@ Mobile 已由 DS-7 纳入同一台账(2026-09-10 静态入口发现),保
- All historical model identities share the category palette across table and daily bars; Agent/harness marks reuse `--engine-badge-cc`, `--engine-badge-codex` and `--usage-model-1` for pi teal (owner refinement, 2026-09-09).
- `usageHistoryColors.ts` derives OKLCH hues from existing `--usage-model-*` seeds at runtime (governance §3.4), outside static token migration.
- Geometry, hit testing and filtering retain their existing contracts. Light/Dark evidence and designer acceptance are recorded separately.
+
+### Mobile login native actions (2026-09-21)
+
+- Surface: `mobile.auth`; partial iOS migration, not a whole-screen native conversion.
+- LoginNativeButton.ios shares nativeGlassButtonStyle with navigation chrome. Primary, social, back, method, resend, consent-dialog, captcha, organization-history and saved-account actions use SwiftUI Button; loading uses ProgressView. Brand artwork and login geometry remain owned by their existing components.
+- RN remains for non-iOS controls, inputs, consent checkbox and inline legal links. Login panels themselves remain RN layout. No authentication protocol or native fingerprint inputs changed.
+- Evidence: `docs/design-evidence/iphone-duo-adaptation.md`, login native actions section. Light iPad landscape inspected; dark and complete native interactions remain unverified.
diff --git a/packages/maker-shared/src/remote-desktop/viewerRuntime.js b/packages/maker-shared/src/remote-desktop/viewerRuntime.js
index e7d05a957f..1a24f3b111 100644
--- a/packages/maker-shared/src/remote-desktop/viewerRuntime.js
+++ b/packages/maker-shared/src/remote-desktop/viewerRuntime.js
@@ -238,6 +238,8 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
const post = (message) => postMessage({ ...message, epoch });
const clamp = (v) => Math.max(0, Math.min(1, v));
let fillHeight = false;
+ let fitToInsets = false;
+ const usesViewportInsets = () => viewerSized || fitToInsets;
let panAnimation = null,
viewportRightInset = 0,
viewportLeftInset = 0,
@@ -246,6 +248,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
keyboardViewportInset = 0,
portraitKeyboardTopInset = 0;
let keyboardViewportOpen = false;
+ let keyboardFitWidth = null;
let cursorNeedsEntry = true,
manualViewMoved = false,
followRest = null;
@@ -255,7 +258,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
const usableHeight = () =>
Math.max(1, stage.clientHeight - viewportTopInset - viewportBottomInset);
const viewportHeight = () =>
- viewerSized ? usableHeight() : Math.max(1, stage.clientHeight);
+ usesViewportInsets() ? usableHeight() : Math.max(1, stage.clientHeight);
const viewportWidth = () =>
Math.max(
1,
@@ -267,13 +270,13 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
// The usable center is (topInset + stageHeight) / 2, so shift by topInset / 2.
// Keep the fitted size and cap the shift when the desktop is too tall to fit.
const verticalOffset = (height) =>
- (viewerSized ? viewportTopInset : 0) +
+ (usesViewportInsets() ? viewportTopInset : 0) +
(fillHeight
? 0
: Math.min(
Math.max(
0,
- portraitKeyboardTopInset - (viewerSized ? viewportTopInset : 0),
+ portraitKeyboardTopInset - (usesViewportInsets() ? viewportTopInset : 0),
) / 2,
Math.max(0, (viewportHeight() - height) / 2),
));
@@ -286,14 +289,16 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
height: dh * desktopScale,
}
: transform(
- viewportWidth(),
+ keyboardFitWidth?.stageWidth === stage.clientWidth
+ ? keyboardFitWidth.width : viewportWidth(),
viewportHeight(),
dw,
dh,
zoom,
fx,
fy,
- fillHeight && !viewerSized,
+ // Mobile fits both axes; retain Desktop scale semantics.
+ config.desktop ? fillHeight && !viewerSized : false,
);
return {
...r,
@@ -350,7 +355,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
picture.y + picture.height >= vh;
const seg = coversStage
? null
- : backgroundSegments(vw, vh, dw, dh, fillHeight, config.desktop);
+ : backgroundSegments(vw, vh, dw, dh, config.desktop ? fillHeight : false, config.desktop);
if (!seg) {
bg.style.display = "none";
bgRects = null;
@@ -571,7 +576,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
const minX = Math.min(right - 1, left + 8 + hotX),
minY = Math.min(
bottom - 1,
- (viewerSized ? viewportTopInset : 0) + 8 + hotY,
+ (usesViewportInsets() ? viewportTopInset : 0) + 8 + hotY,
);
return {
minX,
@@ -642,7 +647,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
if (config.nativeMedia && epoch)
post({
type: "nativeViewport",
- fillHeight,
+ fillHeight: false,
x: r.x,
y: r.y,
width: r.width,
@@ -2047,6 +2052,20 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
status.style.color = message.color;
break;
}
+ case "nativeTouchpad": {
+ if (!nativeMouseControls || !control) break;
+ if (message.tap === true) {
+ if (!heldMouse.size) { click(); flush(); }
+ break;
+ }
+ if (!Number.isFinite(message.dx) || !Number.isFinite(message.dy)) break;
+ moveTouchpad(message.dx, message.dy);
+ queue({ kind: "move", x: cx, y: cy });
+ touchCursor = { x: cx, y: cy };
+ touchCursorVisible = true;
+ render();
+ break;
+ }
case "nativeMouse": {
if (
!nativeMouseControls ||
@@ -2083,8 +2102,15 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
keyboardOpen = fillHeight && message.keyboardOpen === true;
const keepHorizontal =
fillHeight && (keyboardOpen || keyboardViewportOpen);
+ // Hiding the rail for the keyboard must not enlarge a width-fitted desktop.
+ if (keyboardOpen && (!keyboardViewportOpen || !keyboardFitWidth)) {
+ keyboardFitWidth = { stageWidth: stage.clientWidth, width: viewportWidth() };
+ }
+ if (!keyboardOpen) keyboardFitWidth = null;
// Opening is observable before the native keyboard has a measured height.
keyboardViewportOpen = keyboardOpen;
+ const fitChanged = fitToInsets !== (message.fitToInsets === true);
+ fitToInsets = message.fitToInsets === true;
const previousOffset = portraitKeyboardTopInset;
if (Number.isFinite(message.portraitKeyboardTopInset))
portraitKeyboardTopInset = Math.max(
@@ -2149,10 +2175,11 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
followRest = { fx, fy, zoom };
render();
} else if (
+ fitChanged ||
sideInsetsChanged ||
offsetChanged ||
- (viewerSized && previousTopInset !== viewportTopInset) ||
- (viewerSized && previousBottomInset !== viewportBottomInset)
+ (usesViewportInsets() && previousTopInset !== viewportTopInset) ||
+ (usesViewportInsets() && previousBottomInset !== viewportBottomInset)
) {
settlePan();
render();
@@ -2226,6 +2253,7 @@ export function mountRemoteDesktopViewer(root, postMessage, config) {
receiveCursor(message.cursor);
break;
case "viewport":
+ if (fillHeight !== (message.fillHeight === true)) keyboardFitWidth = null;
fillHeight = message.fillHeight === true;
release();
render();
diff --git a/packages/maker-shared/src/remote-desktop/viewerSource.ts b/packages/maker-shared/src/remote-desktop/viewerSource.ts
index f44e64d716..ca25de51e2 100644
--- a/packages/maker-shared/src/remote-desktop/viewerSource.ts
+++ b/packages/maker-shared/src/remote-desktop/viewerSource.ts
@@ -1,2 +1,2 @@
// Generated by scripts/sync-remote-desktop-viewer.mjs. Do not edit.
-export const DESKTOP_VIEWER_SOURCE = "/** Shared browser viewer. Mobile bundles this exact source; Desktop imports it as a CSP-safe module. */\nfunction mountRemoteDesktopViewer(root, postMessage, config) {\n const cleanups = [];\n const listen = (target, type, fn, options) => {\n target.addEventListener(type, fn, options);\n cleanups.push(() => target.removeEventListener(type, fn, options));\n };\n const find = (id) =>\n root.getElementById\n ? root.getElementById(id)\n : root.querySelector(\"#\" + id);\n const { net, iceServers } = config;\n let nativeVideoActive = false;\n const validKeys = new Set(config.keyCodes);\n const transform =\n /* BEGIN TRANSFORM */\n function desktopTransform(\n vw,\n vh,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight = false,\n ) {\n const scale =\n (fillHeight\n ? vh / Math.max(1, dh)\n : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh))) *\n Math.max(1, Math.min(5, zoom));\n const width = dw * scale;\n const height = dh * scale;\n const x =\n width <= vw\n ? (vw - width) / 2\n : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));\n const y =\n height <= vh\n ? (vh - height) / 2\n : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));\n return { x, y, width, height, scale };\n };\n /* END TRANSFORM */ const networkStats =\n /* BEGIN NETWORK_STATS */\n function networkStats(stats, previous) {\n const rows = [...stats.values()];\n const video = rows.find(\n (s) =>\n s.type === \"inbound-rtp\" &&\n (s.kind === \"video\" || s.mediaType === \"video\"),\n );\n const transport = rows.find(\n (s) => s.type === \"transport\" && s.selectedCandidatePairId,\n );\n const pair = transport\n ? stats.get(transport.selectedCandidatePairId)\n : rows.find(\n (s) =>\n s.type === \"candidate-pair\" &&\n s.state === \"succeeded\" &&\n s.nominated,\n );\n const local = pair && stats.get(pair.localCandidateId),\n remote = pair && stats.get(pair.remoteCandidateId);\n const direct = [\"host\", \"srflx\", \"prflx\"];\n const route =\n local?.candidateType === \"relay\" || remote?.candidateType === \"relay\"\n ? \"relay\"\n : direct.includes(local?.candidateType) &&\n direct.includes(remote?.candidateType)\n ? \"direct\"\n : \"video\";\n const sample =\n video &&\n Number.isFinite(video.bytesReceived) &&\n Number.isFinite(video.timestamp)\n ? {\n id: video.id,\n path: pair?.id,\n bytes: video.bytesReceived,\n time: video.timestamp,\n }\n : null;\n let bytesPerSecond = null;\n if (\n sample &&\n previous &&\n sample.id === previous.id &&\n sample.path === previous.path &&\n sample.time > previous.time &&\n sample.bytes >= previous.bytes\n )\n bytesPerSecond =\n ((sample.bytes - previous.bytes) * 1000) /\n (sample.time - previous.time);\n const latencyMs =\n Number.isFinite(pair?.currentRoundTripTime) &&\n pair.currentRoundTripTime >= 0\n ? pair.currentRoundTripTime * 1000\n : null;\n return { transport: route, bytesPerSecond, latencyMs, sample };\n };\n\n /* END NETWORK_STATS */ const stage = find(\"stage\"),\n image = find(\"image\"),\n video = find(\"video\"),\n cursor = find(\"cursor\");\n // Shared ambient backdrop. Minimal viewer embeds may omit its subtree.\n const bg = find(\"bg\") || null,\n bgCanvas = find(\"bg-canvas\") || null,\n bgContext = bgCanvas ? bgCanvas.getContext(\"2d\") : null;\n let dw = 1920,\n dh = 1080,\n viewerSized = false,\n zoom = 1,\n desktopScale = null,\n reportedScaleMode = null,\n desktopPan = null,\n edgePointer = null,\n edgeFrame = null,\n edgeTime = 0,\n fx = 0.5,\n fy = 0.5,\n mode = \"pointer\",\n control = false,\n clipboardShortcuts = false,\n clipboardModifier = \"control\",\n deferredClipboardModifier = null,\n pc = null,\n dc = null,\n seq = 0,\n generation = 0,\n epoch = null,\n gestureFrame = null;\n let remoteCursor = null,\n lastLocalMove = 0,\n localCursorAwake = false;\n let touchCursor = null,\n touchCursorTimer = null,\n touchCursorVisible = false;\n const reducedMotion = matchMedia(\"(prefers-reduced-motion: reduce)\");\n const cursorImage = find(\"cursor-image\");\n let pending = [],\n sending = false,\n cx = 0.5,\n cy = 0.5,\n drag = false,\n start = null,\n last = null,\n multi = null,\n hold = null,\n moved = false;\n const pointers = new Map();\n const mouseButtons = find(\"mouse-buttons\"),\n wheel = find(\"mouse-wheel\"),\n wheelGrip = find(\"mouse-wheel-grip\");\n let nativeMouseControls = false;\n const mouseControlHandlers = new Map();\n function listenMouse(el, type, handler) {\n listen(el, type, handler);\n mouseControlHandlers.set(el.id + \":\" + type, handler);\n }\n const keyboardInput = find(\"keyboard-input\");\n let keyboardEnabled = false,\n composing = false;\n const keyboardSentinel = \"\\u200b\";\n function resetKeyboard() {\n keyboardInput.value = keyboardSentinel;\n keyboardInput.setSelectionRange(1, 1);\n }\n function showKeyboard(enabled) {\n keyboardEnabled = enabled && control;\n if (!keyboardEnabled) {\n composing = false;\n resetKeyboard();\n keyboardInput.blur();\n return;\n }\n if (composing) return;\n if (config.desktop && document.activeElement === keyboardInput) return;\n // Keep focus inside the native evaluateJavaScript call; WebKit can reject\n // keyboard presentation after requestAnimationFrame loses user activation.\n keyboardInput.blur();\n resetKeyboard();\n keyboardInput.focus({ preventScroll: true });\n }\n function keyboardKey(code) {\n if (!keyboardEnabled || !control) return;\n queue({ kind: \"key\", code, down: true });\n queue({ kind: \"key\", code, down: false });\n flush();\n }\n function commitKeyboard() {\n if (!keyboardEnabled || !control || composing) return;\n const text = keyboardInput.value.replace(keyboardSentinel, \"\");\n if (text) {\n for (let i = 0; i < text.length; i += 4096)\n queue({ kind: \"text\", text: text.slice(i, i + 4096) });\n flush();\n }\n resetKeyboard();\n }\n listen(keyboardInput, \"compositionstart\", () => {\n composing = true;\n });\n listen(keyboardInput, \"compositionend\", () => {\n composing = false;\n commitKeyboard();\n });\n listen(keyboardInput, \"input\", (e) => {\n if (!e.isComposing) commitKeyboard();\n });\n listen(keyboardInput, \"beforeinput\", (e) => {\n if (composing || e.isComposing) return;\n if (e.inputType === \"deleteContentBackward\") {\n e.preventDefault();\n keyboardKey(\"Backspace\");\n resetKeyboard();\n } else if (\n e.inputType === \"insertLineBreak\" ||\n e.inputType === \"insertParagraph\"\n ) {\n e.preventDefault();\n keyboardKey(\"Enter\");\n resetKeyboard();\n }\n });\n const heldMouse = new Map();\n let showMouseButtons = false,\n wheelY = null;\n function resetWheel() {\n wheelY = null;\n wheelGrip.style.transform = \"translateY(0px)\";\n }\n let statsTimer = null,\n statsSample = null;\n const post = (message) => postMessage({ ...message, epoch });\n const clamp = (v) => Math.max(0, Math.min(1, v));\n let fillHeight = false;\n let panAnimation = null,\n viewportRightInset = 0,\n viewportLeftInset = 0,\n viewportBottomInset = 0,\n viewportTopInset = 0,\n keyboardViewportInset = 0,\n portraitKeyboardTopInset = 0;\n let keyboardViewportOpen = false;\n let cursorNeedsEntry = true,\n manualViewMoved = false,\n followRest = null;\n // Insets guide centering and pan limits without clipping the full-screen\n // video surface or adding an opaque strip beside the Dynamic Island.\n const viewportLeft = () => (fillHeight ? viewportLeftInset : 0);\n const usableHeight = () =>\n Math.max(1, stage.clientHeight - viewportTopInset - viewportBottomInset);\n const viewportHeight = () =>\n viewerSized ? usableHeight() : Math.max(1, stage.clientHeight);\n const viewportWidth = () =>\n Math.max(\n 1,\n stage.clientWidth -\n viewportLeft() -\n (fillHeight ? viewportRightInset : 0),\n );\n // Center between the measured top controls and the keyboard edge (stage bottom).\n // The usable center is (topInset + stageHeight) / 2, so shift by topInset / 2.\n // Keep the fitted size and cap the shift when the desktop is too tall to fit.\n const verticalOffset = (height) =>\n (viewerSized ? viewportTopInset : 0) +\n (fillHeight\n ? 0\n : Math.min(\n Math.max(\n 0,\n portraitKeyboardTopInset - (viewerSized ? viewportTopInset : 0),\n ) / 2,\n Math.max(0, (viewportHeight() - height) / 2),\n ));\n const layout = () => {\n const r =\n config.desktop && desktopScale !== null\n ? {\n scale: desktopScale,\n width: dw * desktopScale,\n height: dh * desktopScale,\n }\n : transform(\n viewportWidth(),\n viewportHeight(),\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight && !viewerSized,\n );\n return {\n ...r,\n x: viewportLeft() + viewportWidth() / 2 - fx * r.width,\n y: viewportHeight() / 2 + verticalOffset(r.height) - fy * r.height,\n };\n };\n // The backdrop uses 5% / 90% / 5% source segments. The middle 90%\n // keeps the fitted picture's scale; each outer 5% stretches uniformly\n // to fill the remaining space, horizontally or vertically as needed.\n // Zoom and pan never move the backdrop: where the picture covers it, the\n // opaque picture simply occludes it, so input mapping stays uniform. Returns\n // null when the fitted picture already covers the stage, unless a Desktop\n // viewer has shrunk its foreground below fit and still needs the backdrop.\n const bgEdgeFraction = 0.05;\n const bgCenterFraction = 1 - 2 * bgEdgeFraction;\n function backgroundSegments(vw, vh, dw, dh, fill, includeFitted = false) {\n if (!(vw > 0 && vh > 0 && dw > 0 && dh > 0)) return null;\n const s = fill\n ? vh / Math.max(1, dh)\n : Math.min(vw / dw, vh / Math.max(1, dh));\n const w = dw * s,\n h = dh * s;\n if (w < vw || (includeFitted && w === vw && h === vh)) {\n const centerW = w * bgCenterFraction,\n centerX = vw / 2 - centerW / 2,\n sideW = centerX,\n top = (vh - h) / 2;\n return { axis: \"x\", s, w, h, top, centerW, centerX, sideW };\n }\n if (h < vh) {\n const centerH = h * bgCenterFraction,\n centerY = vh / 2 - centerH / 2,\n sideH = centerY,\n left = (vw - w) / 2;\n return { axis: \"y\", s, w, h, left, centerH, centerY, sideH };\n }\n return null;\n }\n function paintBackground() {\n if (nativeVideoActive) {\n if (bg) bg.style.display = \"none\";\n return;\n }\n if (!bg || !bgCanvas || !bgContext) return;\n const vw = stage.clientWidth,\n vh = stage.clientHeight;\n const picture = config.desktop ? layout() : null;\n const coversStage =\n picture &&\n picture.x <= 0 &&\n picture.y <= 0 &&\n picture.x + picture.width >= vw &&\n picture.y + picture.height >= vh;\n const seg = coversStage\n ? null\n : backgroundSegments(vw, vh, dw, dh, fillHeight, config.desktop);\n if (!seg) {\n bg.style.display = \"none\";\n bgRects = null;\n stopBackgroundLoop();\n return;\n }\n bg.style.display = \"block\";\n bgAxis = seg.axis;\n // The ambient layer also fills the notch and the area beneath native\n // controls. Only the interactive picture respects viewport insets.\n const originX = 0;\n // Source segments are resolved at draw time from the live source dimensions;\n // these dest rects only encode where each segment lands on the stage.\n bgRects =\n seg.axis === \"x\"\n ? [\n {\n x: originX,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX,\n y: seg.top,\n w: seg.centerW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX + seg.centerW,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n ]\n : [\n {\n x: seg.left,\n y: 0,\n w: seg.w,\n h: seg.sideH,\n },\n {\n x: seg.left,\n y: seg.centerY,\n w: seg.w,\n h: seg.centerH,\n },\n {\n x: seg.left,\n y: seg.centerY + seg.centerH,\n w: seg.w,\n h: seg.sideH,\n },\n ];\n // Keep the backing store at stage resolution (capped) so the stretched\n // edges stay crisp without oversized allocations.\n bgDpr = Math.min(2, window.devicePixelRatio || 1);\n const bw = Math.round(stage.clientWidth * bgDpr),\n bh = Math.round(vh * bgDpr);\n if (bgCanvas.width !== bw || bgCanvas.height !== bh) {\n bgCanvas.width = bw;\n bgCanvas.height = bh;\n }\n scheduleBackgroundDraw();\n startBackgroundLoop();\n }\n // One canvas, three draws: each source segment stretches into whatever bar\n // the picture leaves open. The live video feeds it once presented; until\n // then the decoded JPEG frame does, so the backdrop always matches the\n // picture's own pixels and scale in the center segment.\n let bgRects = null,\n bgAxis = \"x\",\n bgDpr = 1,\n bgDrawFrame = null,\n bgLoopFrame = null;\n function drawBackground() {\n if (!bgContext || !bgRects) return;\n const useVideo =\n videoPresented && video.videoWidth > 0 && video.videoHeight > 0;\n const src = useVideo ? video : image;\n // drawImage source rects live in the source's own pixel space, which can\n // differ from dw/dh; fractions of the real bitmap keep every segment lined\n // up with what the picture element actually shows.\n const sw = useVideo ? video.videoWidth : image.naturalWidth;\n const sh = useVideo ? video.videoHeight : image.naturalHeight;\n // Cursor updates can schedule a repaint while the next JPEG is loading.\n // Keep the last backdrop until the replacement has drawable pixels.\n if ((!useVideo && !image.complete) || !(sw > 0 && sh > 0)) return;\n bgContext.setTransform(bgDpr, 0, 0, bgDpr, 0, 0);\n bgContext.clearRect(0, 0, stage.clientWidth, stage.clientHeight);\n const horizontal = bgAxis === \"x\";\n const sourceLength = horizontal ? sw : sh;\n const cuts = [0, bgEdgeFraction, 1 - bgEdgeFraction, 1];\n for (let i = 0; i < bgRects.length; i++) {\n const rect = bgRects[i];\n const origin = cuts[i] * sourceLength;\n const length = (cuts[i + 1] - cuts[i]) * sourceLength;\n bgContext.drawImage(\n src,\n horizontal ? origin : 0,\n horizontal ? 0 : origin,\n horizontal ? length : sw,\n horizontal ? sh : length,\n rect.x,\n rect.y,\n rect.w,\n rect.h,\n );\n }\n }\n function scheduleBackgroundDraw() {\n if (bgDrawFrame !== null || !bgRects || !bgContext) return;\n bgDrawFrame = requestAnimationFrame(() => {\n bgDrawFrame = null;\n drawBackground();\n });\n }\n function startBackgroundLoop() {\n if (\n bgLoopFrame !== null ||\n !bgContext ||\n !bgRects ||\n !videoPresented ||\n typeof video.requestVideoFrameCallback !== \"function\"\n )\n return;\n const frame = video.requestVideoFrameCallback(() => {\n if (bgLoopFrame !== frame) return;\n bgLoopFrame = null;\n drawBackground();\n startBackgroundLoop();\n });\n bgLoopFrame = frame;\n }\n // Only the streaming loop stops here; a pending one-shot draw is harmless\n // (it re-paints the preserved frame) and must survive reconnects.\n function stopBackgroundLoop() {\n if (bgLoopFrame !== null) video.cancelVideoFrameCallback?.(bgLoopFrame);\n bgLoopFrame = null;\n }\n function clearBackground() {\n stopBackgroundLoop();\n bgRects = null;\n // Resizing a canvas resets its bitmap; same-value assignment still clears.\n if (bgCanvas) bgCanvas.width = bgCanvas.width;\n }\n listen(image, \"load\", () => scheduleBackgroundDraw());\n // Older WebViews update the ambient layer on media progress, never with an\n // idle display-refresh loop. Geometry changes still get a one-shot repaint.\n listen(video, \"timeupdate\", () => {\n if (videoPresented && typeof video.requestVideoFrameCallback !== \"function\")\n scheduleBackgroundDraw();\n });\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = viewportHeight();\n // Grow extra resting travel continuously from zero at fit to 180 screen\n // points at maximum zoom. Never count the unused space of a fitting axis.\n const clearance = (180 * (Math.max(1, Math.min(5, zoom)) - 1)) / 4;\n const axis = (viewport, content) =>\n content <= viewport\n ? {\n min: (viewport - content) / 2 - clearance,\n max: (viewport - content) / 2 + clearance,\n }\n : { min: viewport - content - clearance, max: clearance };\n const x = axis(vw, r.width),\n y = axis(vh, r.height);\n const bounds = {\n minX: viewportLeft() + x.min,\n maxX: viewportLeft() + x.max,\n minY: y.min + verticalOffset(r.height),\n maxY: y.max + verticalOffset(r.height),\n };\n // A camera position required to expose the cursor is a valid resting point,\n // not elastic overshoot. Preserve it across the next pan/pinch handoff.\n if (followRest) {\n const restX = viewportLeft() + vw / 2 - followRest.fx * r.width,\n restY = vh / 2 + verticalOffset(r.height) - followRest.fy * r.height;\n const weight =\n followRest.zoom > 1 ? clamp((zoom - 1) / (followRest.zoom - 1)) : 1;\n bounds.minX += Math.min(0, restX - bounds.minX) * weight;\n bounds.maxX += Math.max(0, restX - bounds.maxX) * weight;\n bounds.minY += Math.min(0, restY - bounds.minY) * weight;\n bounds.maxY += Math.max(0, restY - bounds.maxY) * weight;\n }\n return bounds;\n }\n const bounded = (v, min, max) => Math.max(min, Math.min(max, v));\n // Convert displayed overshoot back to finger travel before the next delta,\n // so reversing direction unwinds smoothly without an edge jump.\n function rubber(v, min, max, inverse = false) {\n const edge = bounded(v, min, max),\n d = v - edge;\n const reach = 40 + 10 * (Math.max(1, Math.min(5, zoom)) - 1);\n return (\n edge +\n Math.sign(d) *\n (inverse\n ? (reach * Math.abs(d)) / Math.max(1, reach - Math.abs(d))\n : (reach * Math.abs(d)) / (reach + Math.abs(d)))\n );\n }\n function place(x, y, r) {\n fx = (viewportLeft() + viewportWidth() / 2 - x) / r.width;\n fy = (viewportHeight() / 2 + verticalOffset(r.height) - y) / r.height;\n }\n function cursorViewport() {\n const hotX = remoteCursor?.hotX ?? 9,\n hotY = remoteCursor?.hotY ?? 9;\n const w = remoteCursor?.width ?? 18,\n h = remoteCursor?.height ?? 18;\n const left = viewportLeft(),\n right = left + viewportWidth(),\n bottom = Math.max(1, stage.clientHeight - viewportBottomInset);\n // Keep the entire cursor, including its hotspot offset, clear of chrome.\n const minX = Math.min(right - 1, left + 8 + hotX),\n minY = Math.min(\n bottom - 1,\n (viewerSized ? viewportTopInset : 0) + 8 + hotY,\n );\n return {\n minX,\n maxX: Math.max(minX, right - 8 - (w - hotX)),\n minY,\n maxY: Math.max(minY, bottom - 8 - (h - hotY)),\n };\n }\n function moveTouchpad(dx, dy) {\n stopPanAnimation();\n const r = layout(),\n v = cursorViewport();\n if (cursorNeedsEntry) {\n // Re-enter at the nearest visible edge; do not pull a manually positioned\n // desktop back to the old off-screen cursor before applying this movement.\n cx = clamp((bounded(r.x + cx * r.width, v.minX, v.maxX) - r.x) / r.width);\n cy = clamp(\n (bounded(r.y + cy * r.height, v.minY, v.maxY) - r.y) / r.height,\n );\n cursorNeedsEntry = false;\n }\n cx = clamp(cx + dx / r.width);\n cy = clamp(cy + dy / r.height);\n const x = r.x + cx * r.width,\n y = r.y + cy * r.height;\n if (\n zoom > 1 ||\n r.width > viewportWidth() ||\n r.height > stage.clientHeight - viewportBottomInset\n ) {\n place(\n r.x + bounded(x, v.minX, v.maxX) - x,\n r.y + bounded(y, v.minY, v.maxY) - y,\n r,\n );\n followRest = { fx, fy, zoom };\n }\n manualViewMoved = false;\n }\n function stopPanAnimation() {\n if (panAnimation !== null) cancelAnimationFrame(panAnimation);\n panAnimation = null;\n }\n function settlePan() {\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r),\n x = bounded(r.x, b.minX, b.maxX),\n y = bounded(r.y, b.minY, b.maxY);\n if (x === r.x && y === r.y) return;\n if (reducedMotion.matches) {\n place(x, y, r);\n render();\n return;\n }\n const started = performance.now();\n const tick = (now) => {\n const t = Math.min(1, (now - started) / 280),\n ease = 1 - Math.pow(1 - t, 3);\n place(r.x + (x - r.x) * ease, r.y + (y - r.y) * ease, r);\n render();\n panAnimation = t < 1 ? requestAnimationFrame(tick) : null;\n };\n panAnimation = requestAnimationFrame(tick);\n }\n function render() {\n const r = layout();\n if (config.nativeMedia && epoch)\n post({\n type: \"nativeViewport\",\n fillHeight,\n x: r.x,\n y: r.y,\n width: r.width,\n height: r.height,\n });\n if (config.desktop && epoch) {\n const scaleMode =\n desktopScale === null\n ? \"fit\"\n : desktopScale === 1\n ? \"actual\"\n : \"custom\";\n if (reportedScaleMode !== scaleMode) {\n reportedScaleMode = scaleMode;\n post({ type: \"scaleMode\", mode: scaleMode });\n }\n }\n const touchFeedback = control && mode === \"touch\" && touchCursorVisible;\n const cursorX = mode === \"touch\" && touchCursor ? touchCursor.x : cx;\n const cursorY = mode === \"touch\" && touchCursor ? touchCursor.y : cy;\n cursor.style.transition =\n mode === \"touch\" && !touchFeedback && !reducedMotion.matches\n ? \"opacity 120ms ease-out\"\n : \"none\";\n for (const el of [image, video]) {\n el.style.width = r.width + \"px\";\n el.style.height = r.height + \"px\";\n el.style.left = r.x + \"px\";\n el.style.top = r.y + \"px\";\n }\n paintBackground();\n if (remoteCursor) {\n cursor.style.width = remoteCursor.width + \"px\";\n cursor.style.height = remoteCursor.height + \"px\";\n cursor.style.border = \"0\";\n cursor.style.borderRadius = \"0\";\n cursor.style.transform = \"none\";\n cursor.style.left = r.x + cursorX * r.width - remoteCursor.hotX + \"px\";\n cursor.style.top = r.y + cursorY * r.height - remoteCursor.hotY + \"px\";\n cursor.style.display = \"block\";\n cursor.style.opacity = (\n mode === \"touch\"\n ? touchFeedback\n : remoteCursor.visible ||\n (control && mode === \"pointer\" && localCursorAwake)\n )\n ? \"1\"\n : \"0\";\n } else {\n cursor.style.opacity = (mode === \"touch\" ? !touchFeedback : false)\n ? \"0\"\n : \"1\";\n cursor.style.width = \"18px\";\n cursor.style.height = \"18px\";\n cursor.style.border = \"2px solid var(--foreground)\";\n cursor.style.borderRadius = \"50%\";\n cursor.style.transform = \"translate(-50%,-50%)\";\n cursor.style.left = r.x + cursorX * r.width + \"px\";\n cursor.style.top = r.y + cursorY * r.height + \"px\";\n cursor.style.display =\n !config.desktop && control && (mode === \"pointer\" || mode === \"touch\")\n ? \"block\"\n : \"none\";\n }\n if (config.desktop) {\n // Let the local OS own pointer size, DPI and accessibility preferences.\n // Never use a remote URL or bitmap as the desktop's native cursor.\n cursor.style.display = \"none\";\n const shape = remoteCursor?.shape;\n stage.style.cursor =\n control &&\n [\n \"default\",\n \"text\",\n \"vertical-text\",\n \"pointer\",\n \"crosshair\",\n \"grab\",\n \"grabbing\",\n \"ew-resize\",\n \"ns-resize\",\n \"nwse-resize\",\n \"nesw-resize\",\n \"move\",\n \"not-allowed\",\n \"copy\",\n \"alias\",\n \"wait\",\n \"progress\",\n \"help\",\n ].includes(shape)\n ? shape\n : \"default\";\n }\n }\n // Literal source is required: Hermes function.toString() yields bytecode.\n function validCursor(v) {\n return (\n !!v &&\n typeof v === \"object\" &&\n typeof v.visible === \"boolean\" &&\n [v.x, v.y, v.width, v.height, v.hotX, v.hotY].every(Number.isFinite) &&\n v.x >= 0 &&\n v.x <= 1 &&\n v.y >= 0 &&\n v.y <= 1 &&\n v.width > 0 &&\n v.width <= 256 &&\n v.height > 0 &&\n v.height <= 256 &&\n v.hotX >= 0 &&\n v.hotX <= v.width &&\n v.hotY >= 0 &&\n v.hotY <= v.height &&\n typeof v.png === \"string\" &&\n v.png.length <= 65536 &&\n /^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(v.png)\n );\n }\n function receiveCursor(value) {\n if (value === null) {\n if (remoteCursor) {\n remoteCursor = { ...remoteCursor, visible: false };\n render();\n }\n return;\n }\n if (!validCursor(value)) return;\n if (!remoteCursor || remoteCursor.png !== value.png)\n cursorImage.src = \"data:image/png;base64,\" + value.png;\n // Keep delayed host coordinates from pulling the local touchpad backwards.\n if (\n !remoteCursor ||\n !control ||\n mode !== \"pointer\" ||\n (!pointers.size && performance.now() - lastLocalMove > 200)\n ) {\n cx = value.x;\n cy = value.y;\n }\n if (value.visible) localCursorAwake = false;\n remoteCursor = value;\n render();\n }\n function resetCursor() {\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n touchCursor = null;\n localCursorAwake = false;\n remoteCursor = null;\n cursorImage.removeAttribute(\"src\");\n render();\n }\n function queue(event) {\n if (!control) return;\n if (config.desktop && (event.kind === \"button\" || event.kind === \"scroll\"))\n flushClipboardModifier();\n // Remote visibility can remain hidden after synthetic mouse movement. Wake\n // the local touchpad cursor until the host reports a visible cursor again.\n if (event.kind === \"move\" && mode === \"pointer\") localCursorAwake = true;\n if (event.kind === \"key\" || event.kind === \"text\") {\n localCursorAwake = false;\n render();\n }\n if (event.kind === \"move\" || event.kind === \"button\")\n lastLocalMove = performance.now();\n const tail = pending[pending.length - 1];\n if (event.kind === \"move\" && tail?.kind === \"move\")\n pending[pending.length - 1] = event;\n // Coalesce only adjacent scrolls, preserving button/key ordering. Bound the\n // accumulated distance so a delayed ACK cannot replay a large scroll backlog.\n else if (event.kind === \"scroll\" && tail?.kind === \"scroll\") {\n tail.dx = Math.max(-2000, Math.min(2000, tail.dx + event.dx));\n tail.dy = Math.max(-2000, Math.min(2000, tail.dy + event.dy));\n } else pending.push(event);\n if (pending.length > 64) {\n pending = [{ kind: \"release\" }];\n control = false;\n post({ type: \"inputOverflow\" });\n }\n }\n function flush() {\n if (!pending.length || sending) return;\n const events = pending.splice(0, 64),\n sequence = ++seq;\n if (\n pc?.connectionState === \"connected\" &&\n dc &&\n dc.readyState === \"open\" &&\n dc.bufferedAmount < 16384\n ) {\n dc.send(JSON.stringify({ sequence, events }));\n } else {\n sending = true;\n post({ type: \"input\", sequence, events });\n }\n }\n const inputTimer = setInterval(() => {\n // Hold displacement controls speed, even without further pointer moves.\n // Skip missed ticks while awaiting ACK instead of building a scroll backlog.\n if (wheelY?.moved && !sending) {\n const offset = Math.max(-24, Math.min(24, wheelY.y - wheelY.start));\n if (Math.abs(offset) > 4)\n scrollMouse(Math.sign(offset) * (Math.abs(offset) - 4) * 1.5);\n }\n flush();\n }, 33);\n cleanups.push(() => clearInterval(inputTimer));\n function release() {\n stopEdgePan();\n desktopPan = null;\n deferredClipboardModifier = null;\n clearTimeout(hold);\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n if (control) {\n queue({ kind: \"release\" });\n flush();\n }\n heldMouse.clear();\n resetWheel();\n updateMouseButtons();\n drag = false;\n pointers.clear();\n start = null;\n last = null;\n multi = null;\n }\n function updateMouseButtons() {\n mouseButtons.style.display =\n showMouseButtons && control && !nativeMouseControls ? \"block\" : \"none\";\n for (const [name, button] of [\n [\"left\", 0],\n [\"right\", 2],\n ])\n find(\"mouse-\" + name).setAttribute(\n \"aria-pressed\",\n String(heldMouse.has(button)),\n );\n }\n for (const [name, button] of [\n [\"left\", 0],\n [\"right\", 2],\n ]) {\n const el = find(\"mouse-\" + name);\n listenMouse(el, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || heldMouse.has(button)) return;\n clearTimeout(hold);\n if (!e.nativeInput) el.setPointerCapture(e.pointerId);\n heldMouse.set(button, e.pointerId);\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n flush();\n updateMouseButtons();\n });\n const up = (e) => {\n e.preventDefault();\n if (heldMouse.get(button) !== e.pointerId) return;\n heldMouse.delete(button);\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n flush();\n updateMouseButtons();\n };\n listenMouse(el, \"pointerup\", up);\n listenMouse(el, \"pointercancel\", up);\n listenMouse(el, \"lostpointercapture\", up);\n listenMouse(el, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(button);\n flush();\n }\n });\n }\n const scrollMouse = (dy) => {\n if (control && showMouseButtons && Number.isFinite(dy)) {\n queue({ kind: \"scroll\", dx: 0, dy: Math.max(-2000, Math.min(2000, dy)) });\n }\n };\n listenMouse(wheel, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || wheelY) return;\n if (!e.nativeInput) wheel.setPointerCapture(e.pointerId);\n wheelY = { id: e.pointerId, y: e.clientY, start: e.clientY, moved: false };\n });\n // A small dead zone preserves middle clicks; displacement drives the timer.\n listenMouse(wheel, \"pointermove\", (e) => {\n if (!wheelY || wheelY.id !== e.pointerId) return;\n e.preventDefault();\n wheelGrip.style.transform =\n \"translateY(\" +\n Math.max(-24, Math.min(24, e.clientY - wheelY.start)) +\n \"px)\";\n wheelY.y = e.clientY;\n if (Math.abs(e.clientY - wheelY.start) > 4) wheelY.moved = true;\n });\n listenMouse(wheel, \"pointerup\", (e) => {\n if (!wheelY || wheelY.id !== e.pointerId) return;\n e.preventDefault();\n if (!wheelY.moved && control && showMouseButtons) {\n click(1);\n flush();\n }\n resetWheel();\n });\n const cancelWheel = (e) => {\n if (wheelY?.id === e.pointerId) resetWheel();\n };\n listenMouse(wheel, \"pointercancel\", cancelWheel);\n listenMouse(wheel, \"lostpointercapture\", cancelWheel);\n listenMouse(wheel, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(1);\n flush();\n }\n });\n listenMouse(wheel, \"keydown\", (e) => {\n if (e.key === \"ArrowUp\" || e.key === \"ArrowDown\") {\n e.preventDefault();\n scrollMouse(e.key === \"ArrowUp\" ? -120 : 120);\n }\n });\n function insideDesktop(p) {\n const r = layout();\n return (\n p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.height\n );\n }\n function point(p) {\n const r = layout();\n return {\n x: clamp((p.x - r.x) / r.width),\n y: clamp((p.y - r.y) / r.height),\n };\n }\n const desktopPoint = (e) => {\n const bounds = stage.getBoundingClientRect();\n return { x: e.clientX - bounds.left, y: e.clientY - bounds.top };\n };\n function stopEdgePan() {\n if (edgeFrame !== null) cancelAnimationFrame(edgeFrame);\n edgeFrame = null;\n edgePointer = null;\n }\n function edgePanTick(now) {\n edgeFrame = null;\n if (!edgePointer || desktopPan || !epoch) return;\n const r = layout(),\n vw = viewportWidth(),\n vh = viewportHeight();\n const p = edgePointer;\n const dt = Math.min(32, Math.max(0, now - edgeTime)) / 1000;\n edgeTime = now;\n // rAF timestamps describe the frame start and can precede the pointer\n // handler's performance.now(). A zero-time first frame is not a boundary.\n if (dt === 0) {\n edgeFrame = requestAnimationFrame(edgePanTick);\n return;\n }\n // A narrow edge band accelerates smoothly to 720 local pixels per second.\n const velocity = (position, extent) => {\n const band = Math.min(28, extent / 4);\n return position < band\n ? -(1 - position / band)\n : position > extent - band\n ? (position - extent + band) / band\n : 0;\n };\n const x =\n r.width > vw\n ? bounded(\n r.x - velocity(p.x - viewportLeft(), vw) * 720 * dt,\n viewportLeft() + vw - r.width,\n viewportLeft(),\n )\n : r.x;\n const y =\n r.height > vh\n ? bounded(r.y - velocity(p.y, vh) * 720 * dt, vh - r.height, 0)\n : r.y;\n if (Math.abs(x - r.x) < 0.001 && Math.abs(y - r.y) < 0.001) return;\n stopPanAnimation();\n manualViewMoved = true;\n place(x, y, r);\n // Keep remote hover/drag attached to the local pointer as the picture moves.\n if (control) {\n const next = point(p);\n cx = next.x;\n cy = next.y;\n queue({ kind: \"move\", x: cx, y: cy });\n }\n render();\n edgeFrame = requestAnimationFrame(edgePanTick);\n }\n function trackEdgePointer(e) {\n const p = desktopPoint(e);\n if (\n !epoch ||\n desktopPan ||\n p.x < viewportLeft() ||\n p.x > viewportLeft() + viewportWidth() ||\n p.y < 0 ||\n p.y > viewportHeight() ||\n !insideDesktop(p)\n ) {\n stopEdgePan();\n return;\n }\n edgePointer = p;\n if (edgeFrame === null) {\n edgeTime = performance.now();\n edgeFrame = requestAnimationFrame(edgePanTick);\n }\n }\n listen(stage, \"pointerleave\", stopEdgePan);\n function mouse(e, down) {\n if (!control || ![0, 1, 2].includes(e.button)) return;\n const local = desktopPoint(e);\n if (down && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n if (down) {\n showKeyboard(true);\n stage.setPointerCapture(e.pointerId);\n heldMouse.set(e.button, e.pointerId);\n } else if (!heldMouse.delete(e.button)) return;\n queue({ kind: \"button\", button: e.button, down, x: cx, y: cy });\n flush();\n render();\n }\n function click(button = 0) {\n if (control && mode === \"touch\") {\n clearTimeout(touchCursorTimer);\n touchCursor = { x: cx, y: cy };\n touchCursorVisible = true;\n render();\n touchCursorTimer = setTimeout(() => {\n touchCursorVisible = false;\n render();\n }, 450);\n }\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n }\n function pan(dx, dy) {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r);\n place(\n rubber(rubber(r.x, b.minX, b.maxX, true) + dx, b.minX, b.maxX),\n rubber(rubber(r.y, b.minY, b.maxY, true) + dy, b.minY, b.maxY),\n r,\n );\n render();\n }\n function pair() {\n const [a, b] = [...pointers.values()];\n return {\n x: (a.x + b.x) / 2,\n y: (a.y + b.y) / 2,\n d: Math.hypot(a.x - b.x, a.y - b.y),\n };\n }\n function movePair() {\n gestureFrame = null;\n if (pointers.size < 2 || !multi) return;\n const next = pair(),\n span = Math.abs(next.d - multi.d),\n travel = Math.hypot(next.x - multi.x, next.y - multi.y);\n if (multi.kind !== \"pinch\") {\n const pinchSlop = Math.max(6, Math.min(12, multi.d * 0.04));\n if (span >= pinchSlop && span > travel * 0.65) {\n // A parallel scroll may deliver its two pointer updates in different\n // frames. Confirm separation briefly before taking over as a pinch.\n if (!multi.candidate)\n multi.candidate = {\n at: Date.now(),\n d: next.d,\n zoom,\n anchor: point(next),\n };\n if (Date.now() - multi.candidate.at >= 40) {\n if (multi.kind === \"scroll\") {\n multi.d = multi.candidate.d;\n multi.zoom = multi.candidate.zoom;\n multi.anchor = multi.candidate.anchor;\n }\n multi.kind = \"pinch\";\n multi.candidate = null;\n } else {\n gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n } else {\n multi.candidate = null;\n if (!multi.kind && travel > 8 && travel > span) multi.kind = \"scroll\";\n }\n }\n if (multi.kind === \"pinch\") {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n zoom = Math.max(\n 1,\n Math.min(5, (multi.zoom * next.d) / Math.max(1, multi.d)),\n );\n const r = layout();\n fx =\n multi.anchor.x +\n (viewportLeft() + viewportWidth() / 2 - next.x) / r.width;\n fy =\n multi.anchor.y +\n (viewportHeight() / 2 + verticalOffset(r.height) - next.y) / r.height;\n const moved = layout(),\n b = panBounds(moved);\n place(\n rubber(moved.x, b.minX, b.maxX),\n rubber(moved.y, b.minY, b.maxY),\n moved,\n );\n } else if (multi.kind === \"scroll\") {\n const dx = next.x - multi.lastX,\n dy = next.y - multi.lastY;\n if (control && mode !== \"pan\")\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, -dx)),\n dy: Math.max(-2000, Math.min(2000, -dy)),\n });\n else pan(dx, dy);\n }\n if (multi.kind) {\n multi.lastX = next.x;\n multi.lastY = next.y;\n }\n render();\n }\n listen(stage, \"pointerdown\", (e) => {\n if (config.desktop) {\n e.preventDefault();\n if (\n e.button === 1 &&\n (layout().width > viewportWidth() || layout().height > viewportHeight())\n ) {\n stopEdgePan();\n stopPanAnimation();\n desktopPan = {\n id: e.pointerId,\n x: e.clientX,\n y: e.clientY,\n start: e,\n moved: false,\n };\n stage.setPointerCapture(e.pointerId);\n return;\n }\n mouse(e, true);\n return;\n }\n e.preventDefault();\n stopPanAnimation();\n stage.setPointerCapture(e.pointerId);\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size === 1) {\n cursorNeedsEntry = true;\n start = { x: e.clientX, y: e.clientY };\n last = start;\n moved = false;\n hold = setTimeout(() => {\n if (\n control &&\n mode !== \"pan\" &&\n !moved &&\n pointers.size === 1 &&\n !heldMouse.size &&\n (mode !== \"touch\" || insideDesktop(start))\n ) {\n if (mode === \"touch\") {\n const p = point(start);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"button\", button: 0, down: true, x: cx, y: cy });\n drag = true;\n }\n }, 400);\n } else {\n clearTimeout(hold);\n if (drag) queue({ kind: \"release\" });\n drag = false;\n start = null;\n const p = pair();\n multi = {\n ...p,\n lastX: p.x,\n lastY: p.y,\n zoom,\n anchor: point(p),\n kind: null,\n };\n }\n });\n listen(stage, \"pointermove\", (e) => {\n if (config.desktop) {\n if (desktopPan?.id === e.pointerId) {\n const dx = e.clientX - desktopPan.x,\n dy = e.clientY - desktopPan.y;\n if (!desktopPan.moved && Math.hypot(dx, dy) < 3) return;\n desktopPan.moved = true;\n desktopPan.x = e.clientX;\n desktopPan.y = e.clientY;\n pan(dx, dy);\n return;\n }\n trackEdgePointer(e);\n if (!control) return;\n const local = desktopPoint(e);\n if (!heldMouse.size && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n e.preventDefault();\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size >= 2) {\n if (gestureFrame === null) gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n if (!start || !last) return;\n const now = { x: e.clientX, y: e.clientY },\n dx = now.x - last.x,\n dy = now.y - last.y;\n last = now;\n if (Math.hypot(now.x - start.x, now.y - start.y) > 6) {\n moved = true;\n clearTimeout(hold);\n }\n if (\n !control ||\n mode === \"pan\" ||\n (mode === \"touch\" && !drag && !heldMouse.size)\n ) {\n pan(dx, dy);\n return;\n }\n if (mode === \"pointer\") {\n moveTouchpad(dx, dy);\n } else {\n const p = point(now);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n });\n function up(e) {\n if (config.desktop) {\n if (desktopPan?.id === e.pointerId) {\n const gesture = desktopPan;\n desktopPan = null;\n if (gesture.moved) settlePan();\n else {\n mouse(gesture.start, true);\n mouse(e, false);\n }\n return;\n }\n mouse(e, false);\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n clearTimeout(hold);\n if (pointers.size >= 2 && multi) {\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n movePair();\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n }\n pointers.delete(e.pointerId);\n if (drag) {\n queue({ kind: \"button\", button: 0, down: false, x: cx, y: cy });\n drag = false;\n } else if (\n start &&\n !moved &&\n control &&\n mode !== \"pan\" &&\n !heldMouse.size &&\n e.type === \"pointerup\" &&\n (mode !== \"touch\" || insideDesktop({ x: e.clientX, y: e.clientY }))\n ) {\n if (mode === \"touch\") {\n const p = point({ x: e.clientX, y: e.clientY });\n cx = p.x;\n cy = p.y;\n }\n click();\n }\n start = null;\n last = null;\n multi = null;\n render();\n if (!pointers.size && manualViewMoved) settlePan();\n }\n listen(stage, \"pointerup\", up);\n listen(stage, \"pointercancel\", () => {\n release();\n settlePan();\n });\n listen(stage, \"lostpointercapture\", () => {\n desktopPan = null;\n if (config.desktop && heldMouse.size) release();\n });\n if (config.desktop)\n listen(\n stage,\n \"wheel\",\n (e) => {\n e.preventDefault();\n if (!control) return;\n const factor =\n e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? stage.clientHeight : 1;\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, e.deltaX * factor)),\n dy: Math.max(-2000, Math.min(2000, e.deltaY * factor)),\n });\n flush();\n },\n { passive: false },\n );\n listen(config.desktop ? stage : document, \"contextmenu\", (e) =>\n e.preventDefault(),\n );\n // Scope selection suppression to the desktop surface, preserving the hidden\n // textarea's native keyboard/IME editing and programmatic selection.\n listen(stage, \"selectstart\", (e) => e.preventDefault());\n listen(stage, \"dragstart\", (e) => e.preventDefault());\n const normalizedKey = (code) =>\n /^(Shift|Control|Alt|Meta)Right$/.test(code)\n ? code.replace(/Right$/, \"Left\")\n : code;\n const hardwareKeys = new Set();\n function flushClipboardModifier() {\n if (!deferredClipboardModifier) return;\n const code = deferredClipboardModifier;\n deferredClipboardModifier = null;\n hardwareKeys.add(code);\n queue({ kind: \"key\", code, down: true });\n }\n listen(document, \"keydown\", (e) => {\n if (config.desktop) {\n if (e.ctrlKey && e.altKey && e.code === \"Escape\") {\n e.preventDefault();\n release();\n showKeyboard(false);\n post({ type: \"releaseFocus\" });\n return;\n }\n if (\n document.activeElement !== keyboardInput ||\n e.isComposing ||\n composing\n )\n return;\n if ((e.metaKey || e.ctrlKey) && e.code === \"KeyW\") return; // always retain a local close shortcut\n if (\n control &&\n clipboardShortcuts &&\n normalizedKey(e.code) ===\n (clipboardModifier === \"meta\" ? \"MetaLeft\" : \"ControlLeft\")\n ) {\n e.preventDefault();\n if (!hardwareKeys.has(normalizedKey(e.code)))\n deferredClipboardModifier = normalizedKey(e.code);\n return;\n }\n if (\n control &&\n clipboardShortcuts &&\n (clipboardModifier === \"meta\"\n ? e.metaKey && !e.ctrlKey\n : e.ctrlKey && !e.metaKey) &&\n !e.altKey &&\n !e.shiftKey &&\n (e.code === \"KeyC\" || e.code === \"KeyV\")\n ) {\n e.preventDefault();\n if (!e.repeat) {\n release();\n hardwareKeys.clear();\n post({\n type: \"clipboard\",\n action: e.code === \"KeyC\" ? \"copy\" : \"paste\",\n });\n }\n return;\n }\n if (\n !e.ctrlKey &&\n !e.metaKey &&\n !e.altKey &&\n (e.key?.length === 1 || e.key === \"Process\" || e.key === \"Dead\")\n )\n return;\n }\n if (control && validKeys.has(normalizedKey(e.code))) {\n e.preventDefault();\n flushClipboardModifier();\n hardwareKeys.add(normalizedKey(e.code));\n queue({ kind: \"key\", code: normalizedKey(e.code), down: true });\n }\n });\n listen(document, \"keyup\", (e) => {\n const code = normalizedKey(e.code);\n if (config.desktop && control && deferredClipboardModifier === code) {\n flushClipboardModifier();\n }\n if (config.desktop && !hardwareKeys.delete(code)) return;\n if (control && validKeys.has(code)) {\n e.preventDefault();\n queue({ kind: \"key\", code, down: false });\n }\n });\n if (config.desktop)\n listen(keyboardInput, \"blur\", () => {\n hardwareKeys.clear();\n release();\n });\n listen(window, \"blur\", () => {\n release();\n settlePan();\n });\n function reportViewport() {\n post({\n type: \"viewportChanged\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n }\n const observer = new ResizeObserver(() => {\n reportViewport();\n release();\n settlePan();\n render();\n });\n observer.observe(stage);\n cleanups.push(\n () => observer.disconnect(),\n () => stopPanAnimation(),\n () => stopBackgroundLoop(),\n () => clearTimeout(touchCursorTimer),\n );\n // Keep one bounded frame in this document only; never persist desktop pixels.\n // Snapshot before detaching the track. A JPEG fallback already lives in image.\n function retainFrame() {\n if (\n !videoPresented ||\n video.style.display !== \"block\" ||\n video.readyState < 2 ||\n !video.videoWidth ||\n !video.videoHeight\n )\n return;\n const canvas = document.createElement(\"canvas\");\n try {\n const scale = Math.min(\n 1,\n 1280 / Math.max(video.videoWidth, video.videoHeight),\n );\n canvas.width = Math.max(1, Math.round(video.videoWidth * scale));\n canvas.height = Math.max(1, Math.round(video.videoHeight * scale));\n const context = canvas.getContext(\"2d\");\n if (context) {\n context.drawImage(video, 0, 0, canvas.width, canvas.height);\n image.src = canvas.toDataURL(\"image/jpeg\", 0.7);\n }\n } catch {\n /* Keep the previous compatibility frame if WebKit cannot read video. */\n } finally {\n canvas.width = 0;\n canvas.height = 0;\n }\n }\n /* BEGIN RTC */\n\n let trickleIce = false,\n attemptId = null,\n retries = 0,\n exchangeId = 0;\n let configPending = false;\n let videoPresented = false,\n videoFrameCallback = null,\n videoPaintCallback = null;\n function cancelVideoHandoff() {\n if (videoFrameCallback !== null)\n video.cancelVideoFrameCallback?.(videoFrameCallback);\n if (videoPaintCallback !== null) cancelAnimationFrame(videoPaintCallback);\n videoFrameCallback = videoPaintCallback = null;\n }\n function revealVideo(g) {\n post({ type: \"videoFrameReady\", attemptId });\n // Keep the JPEG decoded and painted as a backing layer. Promote the video\n // only after its first frame; removing the image exposes WebKit repaint gaps.\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = null;\n videoPresented = true;\n video.style.zIndex = \"2\";\n if (typeof startBackgroundLoop === \"function\") startBackgroundLoop();\n post({ type: \"streaming\", attemptId });\n post({\n type: \"pipCapability\",\n supported: !!(\n video.webkitSupportsPresentationMode?.(\"picture-in-picture\") ||\n document.pictureInPictureEnabled\n ),\n });\n });\n });\n }\n function waitForVideoFrame(g) {\n if (g !== generation) return;\n if (\n video.readyState >= 2 &&\n video.videoWidth > 0 &&\n video.videoHeight > 0\n ) {\n revealVideo(g);\n return;\n }\n videoPaintCallback = requestAnimationFrame(() => waitForVideoFrame(g));\n }\n let retryTimer = null,\n deadlineTimer = null,\n disconnectTimer = null,\n stableTimer = null,\n iceTimer = null,\n gatherTimer = null,\n gatherDone = null;\n let localCandidates = [],\n localAck = 0,\n remoteAfter = 0,\n icePending = null,\n remoteSeen = new Set(),\n exchangeUntil = 0,\n remoteComplete = false;\n function clearRtcTimers() {\n for (const timer of [\n retryTimer,\n deadlineTimer,\n disconnectTimer,\n stableTimer,\n iceTimer,\n gatherTimer,\n ])\n clearTimeout(timer);\n retryTimer =\n deadlineTimer =\n disconnectTimer =\n stableTimer =\n iceTimer =\n gatherTimer =\n null;\n if (gatherDone) {\n gatherDone();\n gatherDone = null;\n }\n }\n function closeRtc(preserveFrame = true) {\n configPending = false;\n if (preserveFrame) retainFrame();\n generation++;\n clearRtcTimers();\n cancelVideoHandoff();\n videoPresented = false;\n localCandidates = [];\n localAck = remoteAfter = 0;\n icePending = null;\n remoteSeen = new Set();\n attemptId = null;\n clearInterval(statsTimer);\n statsTimer = null;\n statsSample = null;\n if (dc) dc.close();\n if (pc) pc.close();\n pc = null;\n dc = null;\n video.onplaying = null;\n video.srcObject = null;\n video.style.display = \"none\";\n video.style.zIndex = \"0\";\n image.style.display = \"block\";\n if (typeof stopBackgroundLoop === \"function\") stopBackgroundLoop();\n if (!preserveFrame) {\n image.removeAttribute(\"src\");\n if (typeof clearBackground === \"function\") clearBackground();\n }\n }\n function failRtc(reason, canRetry = true) {\n const failedAttempt = attemptId;\n release();\n closeRtc();\n post({ type: \"fallback\", attemptId: failedAttempt, reason });\n // Local consent is bounded by the host's picker lifetime. Reuse this retry\n // timer without consuming the finite network-recovery attempts.\n const capturePending = reason === \"capture-pending\";\n if (canRetry && epoch && (capturePending || retries < net.retryMs.length)) {\n const delay = capturePending\n ? net.retryMs[net.retryMs.length - 1]\n : net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(\n () => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n },\n (net.iceConfigMs ?? 8000) + (net.iceConfigBridgeMs ?? 500),\n );\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n (video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video) &&\n message.type === \"viewPing\" &&\n typeof message.challenge === \"string\" &&\n message.challenge.length <= 64 &&\n dc?.readyState === \"open\"\n )\n dc.send(message.challenge);\n } catch {}\n };\n let readingStats = false;\n statsTimer = setInterval(async () => {\n if (readingStats || g !== generation) return;\n readingStats = true;\n try {\n const stats = await rtc.getStats();\n if (g !== generation || pc !== rtc) return;\n const result = networkStats(stats, statsSample);\n statsSample = result.sample;\n post({\n type: \"network\",\n transport: result.transport,\n bytesPerSecond: result.bytesPerSecond,\n latencyMs: result.latencyMs,\n });\n } catch {\n } finally {\n readingStats = false;\n }\n }, 1000);\n rtc.ontrack = (e) => {\n if (g !== generation) return;\n video.srcObject = e.streams[0] || new MediaStream([e.track]);\n video.play().catch(() => {});\n };\n video.onplaying = () => {\n if (\n g !== generation ||\n videoPresented ||\n videoFrameCallback !== null ||\n videoPaintCallback !== null\n )\n return;\n video.style.display = \"block\";\n render();\n if (typeof scheduleBackgroundDraw === \"function\")\n scheduleBackgroundDraw();\n if (typeof video.requestVideoFrameCallback === \"function\") {\n videoFrameCallback = video.requestVideoFrameCallback(() => {\n if (g !== generation) return;\n videoFrameCallback = null;\n revealVideo(g);\n });\n } else waitForVideoFrame(g);\n };\n rtc.onconnectionstatechange = () => {\n if (g !== generation) return;\n if ([\"failed\", \"closed\"].includes(rtc.connectionState)) {\n failRtc(\"transport\");\n return;\n }\n if (rtc.connectionState === \"disconnected\") {\n clearTimeout(stableTimer);\n stableTimer = null;\n if (!disconnectTimer) {\n release();\n post({ type: \"reconnecting\", attemptId });\n disconnectTimer = setTimeout(() => {\n if (g === generation) failRtc(\"disconnected\");\n }, net.disconnectedMs);\n }\n } else if (rtc.connectionState === \"connected\") {\n clearTimeout(disconnectTimer);\n disconnectTimer = null;\n clearTimeout(deadlineTimer);\n if (!stableTimer)\n stableTimer = setTimeout(() => {\n if (g === generation) retries = 0;\n }, net.stableMs);\n if (videoPresented) post({ type: \"streaming\", attemptId });\n }\n };\n await rtc.setLocalDescription(await rtc.createOffer());\n if (!trickleIce)\n await new Promise((resolve) => {\n if (rtc.iceGatheringState === \"complete\") return resolve();\n gatherDone = resolve;\n gatherTimer = setTimeout(resolve, net.legacyGatherMs);\n rtc.onicegatheringstatechange = () => {\n if (rtc.iceGatheringState === \"complete\") {\n clearTimeout(gatherTimer);\n resolve();\n }\n };\n });\n if (g !== generation) return;\n post({ type: \"offer\", attemptId, sdp: rtc.localDescription.sdp });\n deadlineTimer = setTimeout(() => {\n if (g === generation) failRtc(\"answer-timeout\");\n }, net.answerMs);\n } catch {\n if (g === generation) failRtc(\"setup\");\n }\n }\n\n /* END RTC */\n function reportPresentation() {\n post({\n type: \"presentation\",\n active:\n video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video,\n });\n }\n listen(video, \"webkitpresentationmodechanged\", reportPresentation);\n listen(video, \"enterpictureinpicture\", reportPresentation);\n listen(video, \"leavepictureinpicture\", reportPresentation);\n function receive(event) {\n let message;\n try {\n message = JSON.parse(event.data);\n } catch {\n return;\n }\n switch (message.type) {\n case \"measureViewport\":\n post({\n type: \"viewportSize\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n break;\n case \"presentation\":\n if (config.nativeMedia) {\n release();\n showKeyboard(false);\n break;\n }\n try {\n if (message.enabled) {\n release();\n showKeyboard(false);\n if (video.webkitSupportsPresentationMode?.(\"picture-in-picture\"))\n video.webkitSetPresentationMode(\"picture-in-picture\");\n else if (video.requestPictureInPicture)\n video\n .requestPictureInPicture()\n .catch(() => post({ type: \"presentationFailed\" }));\n else post({ type: \"presentationFailed\" });\n } else if (video.webkitSetPresentationMode)\n video.webkitSetPresentationMode(\"inline\");\n else if (document.pictureInPictureElement)\n document.exitPictureInPicture().catch(() => {});\n } catch {\n post({ type: \"presentationFailed\" });\n }\n break;\n case \"videoSettings\":\n if (\n Number.isInteger(message.width) &&\n Number.isInteger(message.height) &&\n message.width >= 320 &&\n message.height >= 320 &&\n (message.restore === true ||\n (message.width <= 2560 && message.height <= 2560))\n ) {\n release();\n stopPanAnimation();\n viewerSized = message.restore !== true;\n zoom = 1;\n desktopScale = null;\n fx = fy = 0.5;\n followRest = null;\n dw = message.width;\n dh = message.height;\n render();\n }\n video.muted = !message.audio;\n retries = 0;\n if (!config.nativeMedia) connect();\n break;\n case \"keyboard\":\n showKeyboard(message.enabled === true);\n break;\n case \"resume\":\n if (video.srcObject) video.play().catch(() => {});\n break;\n case \"releaseInput\":\n release();\n break;\n case \"theme\":\n if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {\n document.body.style.background = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.background = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.setProperty(\n \"--surface\",\n message.surface,\n );\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.foreground)) {\n cursor.style.borderColor = message.foreground;\n document.documentElement.style.setProperty(\n \"--foreground\",\n message.foreground,\n );\n }\n break;\n case \"networkStatus\": {\n const status = document.getElementById(\"network-status\");\n if (!status) break;\n status.textContent =\n typeof message.text === \"string\" ? message.text : \"\";\n status.style.display = status.textContent ? \"block\" : \"none\";\n for (const key of [\"top\", \"right\", \"fontSize\"]) {\n if (Number.isFinite(message[key]) && message[key] >= 0)\n status.style[key] = message[key] + \"px\";\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.color))\n status.style.color = message.color;\n break;\n }\n case \"nativeMouse\": {\n if (\n !nativeMouseControls ||\n ![\"left\", \"right\", \"wheel\"].includes(message.control)\n )\n break;\n if (\n ![\n \"pointerdown\",\n \"pointermove\",\n \"pointerup\",\n \"pointercancel\",\n \"click\",\n ].includes(message.event)\n )\n break;\n if (!Number.isFinite(message.id) || !Number.isFinite(message.y)) break;\n mouseControlHandlers.get(\n \"mouse-\" + message.control + \":\" + message.event,\n )?.({\n pointerId: message.id,\n clientY: message.y,\n detail: 0,\n nativeInput: true,\n preventDefault() {},\n });\n break;\n }\n case \"mouseButtons\": {\n nativeMouseControls = message.native === true;\n const before = layout(),\n previousTopInset = viewportTopInset,\n previousBottomInset = viewportBottomInset,\n keyboardOpen = fillHeight && message.keyboardOpen === true;\n const keepHorizontal =\n fillHeight && (keyboardOpen || keyboardViewportOpen);\n // Opening is observable before the native keyboard has a measured height.\n keyboardViewportOpen = keyboardOpen;\n const previousOffset = portraitKeyboardTopInset;\n if (Number.isFinite(message.portraitKeyboardTopInset))\n portraitKeyboardTopInset = Math.max(\n 0,\n message.portraitKeyboardTopInset,\n );\n const offsetChanged = previousOffset !== portraitKeyboardTopInset;\n let sideInsetsChanged = false;\n if (Number.isFinite(message.topInset))\n viewportTopInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.topInset),\n );\n if (Number.isFinite(message.bottomInset))\n viewportBottomInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.bottomInset),\n );\n if (Number.isFinite(message.leftInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.leftInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportLeftInset;\n viewportLeftInset = inset;\n }\n if (Number.isFinite(message.rightInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.rightInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportRightInset;\n viewportRightInset = inset;\n }\n // Hiding the side toolbar changes the viewport center. Keep the image's\n // actual horizontal position instead of following that center sideways.\n if (keepHorizontal) {\n stopPanAnimation();\n const r = layout();\n place(before.x, r.y, r);\n }\n const keyboardInset = keyboardOpen ? viewportBottomInset : 0;\n if (keyboardInset !== keyboardViewportInset) {\n const wasOpen = keyboardViewportInset > 0;\n keyboardViewportInset = keyboardInset;\n if (fillHeight && (keyboardInset > 0 || wasOpen)) {\n const r = layout(),\n v = cursorViewport();\n place(r.x, (v.minY + v.maxY) / 2 - cy * r.height, r);\n cursorNeedsEntry = false;\n manualViewMoved = false;\n }\n }\n if (keepHorizontal) {\n // Restoring the toolbar can cover the cursor even after a zero-height opening.\n if (!keyboardOpen || keyboardInset > 0) {\n const r = layout(),\n v = cursorViewport(),\n x = r.x + cx * r.width;\n place(r.x + bounded(x, v.minX, v.maxX) - x, r.y, r);\n }\n followRest = { fx, fy, zoom };\n render();\n } else if (\n sideInsetsChanged ||\n offsetChanged ||\n (viewerSized && previousTopInset !== viewportTopInset) ||\n (viewerSized && previousBottomInset !== viewportBottomInset)\n ) {\n settlePan();\n render();\n }\n reportViewport();\n if (!message.enabled) {\n for (const button of heldMouse.keys())\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n heldMouse.clear();\n resetWheel();\n flush();\n }\n for (const [edge, value] of [\n [\"bottom\", message.bottomInset],\n [\"right\", message.rightInset],\n ])\n if (Number.isFinite(value) && value >= 0 && value <= 4096)\n mouseButtons.style[edge] = value + \"px\";\n showMouseButtons = message.enabled === true;\n for (const name of [\"left\", \"right\", \"wheel\"])\n if (typeof message.labels?.[name] === \"string\")\n find(\"mouse-\" + name).setAttribute(\n \"aria-label\",\n message.labels[name],\n );\n updateMouseButtons();\n break;\n }\n case \"init\":\n nativeVideoActive = false;\n image.style.visibility = \"visible\";\n desktopScale = null;\n reportedScaleMode = null;\n if (config.desktop) {\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n }\n viewerSized = false;\n followRest = null;\n cursorNeedsEntry = true;\n stopPanAnimation();\n resetCursor();\n control = false;\n release();\n pending = [];\n sending = false;\n seq = 0;\n epoch = message.epoch;\n clipboardShortcuts =\n config.desktop && message.clipboardShortcuts === true;\n clipboardModifier =\n message.clipboardModifier === \"meta\" ? \"meta\" : \"control\";\n dw = message.width;\n dh = message.height;\n fillHeight = message.fillHeight === true;\n video.muted = !message.audio;\n trickleIce = message.trickleIce === true;\n retries = 0;\n render();\n if (!config.nativeMedia) connect();\n break;\n case \"nativeVideo\":\n if (!config.nativeMedia || message.epoch !== epoch) break;\n nativeVideoActive = message.active === true;\n image.style.visibility = nativeVideoActive ? \"hidden\" : \"visible\";\n paintBackground();\n break;\n case \"nativeCursor\":\n if (config.nativeMedia && message.epoch === epoch)\n receiveCursor(message.cursor);\n break;\n case \"viewport\":\n fillHeight = message.fillHeight === true;\n release();\n render();\n break;\n case \"answer\":\n if (message.epoch === epoch) void receiveAnswer(message);\n break;\n case \"iceConfig\":\n if (message.epoch === epoch) void receiveIceConfig(message);\n break;\n case \"ice\":\n if (message.epoch === epoch) void receiveIce(message);\n break;\n case \"fallback\":\n if (message.epoch === epoch && message.attemptId === attemptId)\n failRtc(\n message.capturePending === true ? \"capture-pending\" : \"host\",\n message.retry !== false,\n );\n break;\n case \"frame\": {\n if (\"cursor\" in message) receiveCursor(message.cursor);\n else resetCursor();\n const frameEpoch = epoch;\n image.onload = () => {\n if (epoch === frameEpoch) {\n scheduleBackgroundDraw();\n post({ type: \"framePresented\" });\n }\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\":\n release();\n control = message.enabled;\n if (!control) showKeyboard(false);\n pending = [];\n updateMouseButtons();\n render();\n break;\n case \"mode\":\n release();\n if (message.mode !== \"pointer\") followRest = null;\n settlePan();\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n mode = message.mode;\n render();\n break;\n case \"zoom\":\n stopEdgePan();\n if (\n !config.desktop ||\n !Number.isFinite(message.factor) ||\n message.factor <= 0\n )\n break;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = true;\n stopPanAnimation();\n const fitScale = Math.min(viewportWidth() / dw, viewportHeight() / dh);\n // Include actual size even when it lies outside the fit-relative range.\n desktopScale = Math.max(\n Math.min(fitScale, 1) * 0.1,\n Math.min(Math.max(5 * fitScale, 5), layout().scale * message.factor),\n );\n if (Math.abs(desktopScale - fitScale) < 1e-9) desktopScale = null;\n if (desktopScale === null) {\n fx = 0.5;\n fy = 0.5;\n manualViewMoved = false;\n }\n render();\n settlePan();\n break;\n case \"actualSize\":\n stopEdgePan();\n if (!config.desktop) break;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = true;\n stopPanAnimation();\n desktopScale = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"fit\":\n stopEdgePan();\n desktopScale = null;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = false;\n stopPanAnimation();\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"rightClick\":\n click(2);\n break;\n case \"events\":\n for (const e of message.events) queue(e);\n flush();\n break;\n case \"ack\":\n if (message.epoch === epoch && message.sequence === seq)\n sending = false;\n break;\n case \"stop\":\n nativeVideoActive = false;\n image.style.visibility = \"visible\";\n showKeyboard(false);\n control = false;\n release();\n pending = [];\n sending = false;\n epoch = null;\n closeRtc(message.preserveFrame === true);\n updateMouseButtons();\n render();\n break;\n }\n }\n // iOS can report equal left/right safe areas in both landscape directions.\n // Its interface angle distinguishes the notch side even on a 180-degree turn.\n const reportOrientation = () => {\n const angle =\n typeof window.orientation === \"number\"\n ? window.orientation\n : window.screen?.orientation?.angle;\n if (Number.isFinite(angle)) post({ type: \"orientation\", angle });\n };\n listen(window, \"orientationchange\", reportOrientation);\n if (window.screen?.orientation?.addEventListener)\n listen(window.screen.orientation, \"change\", reportOrientation);\n render();\n reportOrientation();\n post({ type: \"ready\" });\n return {\n receive: (message) => receive({ data: JSON.stringify(message) }),\n dispose: () => {\n release();\n epoch = null;\n closeRtc(false);\n if (bgDrawFrame !== null) cancelAnimationFrame(bgDrawFrame);\n bgDrawFrame = null;\n for (const cleanup of cleanups) cleanup();\n },\n };\n}\n";
+export const DESKTOP_VIEWER_SOURCE = "/** Shared browser viewer. Mobile bundles this exact source; Desktop imports it as a CSP-safe module. */\nfunction mountRemoteDesktopViewer(root, postMessage, config) {\n const cleanups = [];\n const listen = (target, type, fn, options) => {\n target.addEventListener(type, fn, options);\n cleanups.push(() => target.removeEventListener(type, fn, options));\n };\n const find = (id) =>\n root.getElementById\n ? root.getElementById(id)\n : root.querySelector(\"#\" + id);\n const { net, iceServers } = config;\n let nativeVideoActive = false;\n const validKeys = new Set(config.keyCodes);\n const transform =\n /* BEGIN TRANSFORM */\n function desktopTransform(\n vw,\n vh,\n dw,\n dh,\n zoom,\n fx,\n fy,\n fillHeight = false,\n ) {\n const scale =\n (fillHeight\n ? vh / Math.max(1, dh)\n : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh))) *\n Math.max(1, Math.min(5, zoom));\n const width = dw * scale;\n const height = dh * scale;\n const x =\n width <= vw\n ? (vw - width) / 2\n : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));\n const y =\n height <= vh\n ? (vh - height) / 2\n : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));\n return { x, y, width, height, scale };\n };\n /* END TRANSFORM */ const networkStats =\n /* BEGIN NETWORK_STATS */\n function networkStats(stats, previous) {\n const rows = [...stats.values()];\n const video = rows.find(\n (s) =>\n s.type === \"inbound-rtp\" &&\n (s.kind === \"video\" || s.mediaType === \"video\"),\n );\n const transport = rows.find(\n (s) => s.type === \"transport\" && s.selectedCandidatePairId,\n );\n const pair = transport\n ? stats.get(transport.selectedCandidatePairId)\n : rows.find(\n (s) =>\n s.type === \"candidate-pair\" &&\n s.state === \"succeeded\" &&\n s.nominated,\n );\n const local = pair && stats.get(pair.localCandidateId),\n remote = pair && stats.get(pair.remoteCandidateId);\n const direct = [\"host\", \"srflx\", \"prflx\"];\n const route =\n local?.candidateType === \"relay\" || remote?.candidateType === \"relay\"\n ? \"relay\"\n : direct.includes(local?.candidateType) &&\n direct.includes(remote?.candidateType)\n ? \"direct\"\n : \"video\";\n const sample =\n video &&\n Number.isFinite(video.bytesReceived) &&\n Number.isFinite(video.timestamp)\n ? {\n id: video.id,\n path: pair?.id,\n bytes: video.bytesReceived,\n time: video.timestamp,\n }\n : null;\n let bytesPerSecond = null;\n if (\n sample &&\n previous &&\n sample.id === previous.id &&\n sample.path === previous.path &&\n sample.time > previous.time &&\n sample.bytes >= previous.bytes\n )\n bytesPerSecond =\n ((sample.bytes - previous.bytes) * 1000) /\n (sample.time - previous.time);\n const latencyMs =\n Number.isFinite(pair?.currentRoundTripTime) &&\n pair.currentRoundTripTime >= 0\n ? pair.currentRoundTripTime * 1000\n : null;\n return { transport: route, bytesPerSecond, latencyMs, sample };\n };\n\n /* END NETWORK_STATS */ const stage = find(\"stage\"),\n image = find(\"image\"),\n video = find(\"video\"),\n cursor = find(\"cursor\");\n // Shared ambient backdrop. Minimal viewer embeds may omit its subtree.\n const bg = find(\"bg\") || null,\n bgCanvas = find(\"bg-canvas\") || null,\n bgContext = bgCanvas ? bgCanvas.getContext(\"2d\") : null;\n let dw = 1920,\n dh = 1080,\n viewerSized = false,\n zoom = 1,\n desktopScale = null,\n reportedScaleMode = null,\n desktopPan = null,\n edgePointer = null,\n edgeFrame = null,\n edgeTime = 0,\n fx = 0.5,\n fy = 0.5,\n mode = \"pointer\",\n control = false,\n clipboardShortcuts = false,\n clipboardModifier = \"control\",\n deferredClipboardModifier = null,\n pc = null,\n dc = null,\n seq = 0,\n generation = 0,\n epoch = null,\n gestureFrame = null;\n let remoteCursor = null,\n lastLocalMove = 0,\n localCursorAwake = false;\n let touchCursor = null,\n touchCursorTimer = null,\n touchCursorVisible = false;\n const reducedMotion = matchMedia(\"(prefers-reduced-motion: reduce)\");\n const cursorImage = find(\"cursor-image\");\n let pending = [],\n sending = false,\n cx = 0.5,\n cy = 0.5,\n drag = false,\n start = null,\n last = null,\n multi = null,\n hold = null,\n moved = false;\n const pointers = new Map();\n const mouseButtons = find(\"mouse-buttons\"),\n wheel = find(\"mouse-wheel\"),\n wheelGrip = find(\"mouse-wheel-grip\");\n let nativeMouseControls = false;\n const mouseControlHandlers = new Map();\n function listenMouse(el, type, handler) {\n listen(el, type, handler);\n mouseControlHandlers.set(el.id + \":\" + type, handler);\n }\n const keyboardInput = find(\"keyboard-input\");\n let keyboardEnabled = false,\n composing = false;\n const keyboardSentinel = \"\\u200b\";\n function resetKeyboard() {\n keyboardInput.value = keyboardSentinel;\n keyboardInput.setSelectionRange(1, 1);\n }\n function showKeyboard(enabled) {\n keyboardEnabled = enabled && control;\n if (!keyboardEnabled) {\n composing = false;\n resetKeyboard();\n keyboardInput.blur();\n return;\n }\n if (composing) return;\n if (config.desktop && document.activeElement === keyboardInput) return;\n // Keep focus inside the native evaluateJavaScript call; WebKit can reject\n // keyboard presentation after requestAnimationFrame loses user activation.\n keyboardInput.blur();\n resetKeyboard();\n keyboardInput.focus({ preventScroll: true });\n }\n function keyboardKey(code) {\n if (!keyboardEnabled || !control) return;\n queue({ kind: \"key\", code, down: true });\n queue({ kind: \"key\", code, down: false });\n flush();\n }\n function commitKeyboard() {\n if (!keyboardEnabled || !control || composing) return;\n const text = keyboardInput.value.replace(keyboardSentinel, \"\");\n if (text) {\n for (let i = 0; i < text.length; i += 4096)\n queue({ kind: \"text\", text: text.slice(i, i + 4096) });\n flush();\n }\n resetKeyboard();\n }\n listen(keyboardInput, \"compositionstart\", () => {\n composing = true;\n });\n listen(keyboardInput, \"compositionend\", () => {\n composing = false;\n commitKeyboard();\n });\n listen(keyboardInput, \"input\", (e) => {\n if (!e.isComposing) commitKeyboard();\n });\n listen(keyboardInput, \"beforeinput\", (e) => {\n if (composing || e.isComposing) return;\n if (e.inputType === \"deleteContentBackward\") {\n e.preventDefault();\n keyboardKey(\"Backspace\");\n resetKeyboard();\n } else if (\n e.inputType === \"insertLineBreak\" ||\n e.inputType === \"insertParagraph\"\n ) {\n e.preventDefault();\n keyboardKey(\"Enter\");\n resetKeyboard();\n }\n });\n const heldMouse = new Map();\n let showMouseButtons = false,\n wheelY = null;\n function resetWheel() {\n wheelY = null;\n wheelGrip.style.transform = \"translateY(0px)\";\n }\n let statsTimer = null,\n statsSample = null;\n const post = (message) => postMessage({ ...message, epoch });\n const clamp = (v) => Math.max(0, Math.min(1, v));\n let fillHeight = false;\n let fitToInsets = false;\n const usesViewportInsets = () => viewerSized || fitToInsets;\n let panAnimation = null,\n viewportRightInset = 0,\n viewportLeftInset = 0,\n viewportBottomInset = 0,\n viewportTopInset = 0,\n keyboardViewportInset = 0,\n portraitKeyboardTopInset = 0;\n let keyboardViewportOpen = false;\n let keyboardFitWidth = null;\n let cursorNeedsEntry = true,\n manualViewMoved = false,\n followRest = null;\n // Insets guide centering and pan limits without clipping the full-screen\n // video surface or adding an opaque strip beside the Dynamic Island.\n const viewportLeft = () => (fillHeight ? viewportLeftInset : 0);\n const usableHeight = () =>\n Math.max(1, stage.clientHeight - viewportTopInset - viewportBottomInset);\n const viewportHeight = () =>\n usesViewportInsets() ? usableHeight() : Math.max(1, stage.clientHeight);\n const viewportWidth = () =>\n Math.max(\n 1,\n stage.clientWidth -\n viewportLeft() -\n (fillHeight ? viewportRightInset : 0),\n );\n // Center between the measured top controls and the keyboard edge (stage bottom).\n // The usable center is (topInset + stageHeight) / 2, so shift by topInset / 2.\n // Keep the fitted size and cap the shift when the desktop is too tall to fit.\n const verticalOffset = (height) =>\n (usesViewportInsets() ? viewportTopInset : 0) +\n (fillHeight\n ? 0\n : Math.min(\n Math.max(\n 0,\n portraitKeyboardTopInset - (usesViewportInsets() ? viewportTopInset : 0),\n ) / 2,\n Math.max(0, (viewportHeight() - height) / 2),\n ));\n const layout = () => {\n const r =\n config.desktop && desktopScale !== null\n ? {\n scale: desktopScale,\n width: dw * desktopScale,\n height: dh * desktopScale,\n }\n : transform(\n keyboardFitWidth?.stageWidth === stage.clientWidth\n ? keyboardFitWidth.width : viewportWidth(),\n viewportHeight(),\n dw,\n dh,\n zoom,\n fx,\n fy,\n // Mobile fits both axes; retain Desktop scale semantics.\n config.desktop ? fillHeight && !viewerSized : false,\n );\n return {\n ...r,\n x: viewportLeft() + viewportWidth() / 2 - fx * r.width,\n y: viewportHeight() / 2 + verticalOffset(r.height) - fy * r.height,\n };\n };\n // The backdrop uses 5% / 90% / 5% source segments. The middle 90%\n // keeps the fitted picture's scale; each outer 5% stretches uniformly\n // to fill the remaining space, horizontally or vertically as needed.\n // Zoom and pan never move the backdrop: where the picture covers it, the\n // opaque picture simply occludes it, so input mapping stays uniform. Returns\n // null when the fitted picture already covers the stage, unless a Desktop\n // viewer has shrunk its foreground below fit and still needs the backdrop.\n const bgEdgeFraction = 0.05;\n const bgCenterFraction = 1 - 2 * bgEdgeFraction;\n function backgroundSegments(vw, vh, dw, dh, fill, includeFitted = false) {\n if (!(vw > 0 && vh > 0 && dw > 0 && dh > 0)) return null;\n const s = fill\n ? vh / Math.max(1, dh)\n : Math.min(vw / dw, vh / Math.max(1, dh));\n const w = dw * s,\n h = dh * s;\n if (w < vw || (includeFitted && w === vw && h === vh)) {\n const centerW = w * bgCenterFraction,\n centerX = vw / 2 - centerW / 2,\n sideW = centerX,\n top = (vh - h) / 2;\n return { axis: \"x\", s, w, h, top, centerW, centerX, sideW };\n }\n if (h < vh) {\n const centerH = h * bgCenterFraction,\n centerY = vh / 2 - centerH / 2,\n sideH = centerY,\n left = (vw - w) / 2;\n return { axis: \"y\", s, w, h, left, centerH, centerY, sideH };\n }\n return null;\n }\n function paintBackground() {\n if (nativeVideoActive) {\n if (bg) bg.style.display = \"none\";\n return;\n }\n if (!bg || !bgCanvas || !bgContext) return;\n const vw = stage.clientWidth,\n vh = stage.clientHeight;\n const picture = config.desktop ? layout() : null;\n const coversStage =\n picture &&\n picture.x <= 0 &&\n picture.y <= 0 &&\n picture.x + picture.width >= vw &&\n picture.y + picture.height >= vh;\n const seg = coversStage\n ? null\n : backgroundSegments(vw, vh, dw, dh, config.desktop ? fillHeight : false, config.desktop);\n if (!seg) {\n bg.style.display = \"none\";\n bgRects = null;\n stopBackgroundLoop();\n return;\n }\n bg.style.display = \"block\";\n bgAxis = seg.axis;\n // The ambient layer also fills the notch and the area beneath native\n // controls. Only the interactive picture respects viewport insets.\n const originX = 0;\n // Source segments are resolved at draw time from the live source dimensions;\n // these dest rects only encode where each segment lands on the stage.\n bgRects =\n seg.axis === \"x\"\n ? [\n {\n x: originX,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX,\n y: seg.top,\n w: seg.centerW,\n h: seg.h,\n },\n {\n x: originX + seg.centerX + seg.centerW,\n y: seg.top,\n w: seg.sideW,\n h: seg.h,\n },\n ]\n : [\n {\n x: seg.left,\n y: 0,\n w: seg.w,\n h: seg.sideH,\n },\n {\n x: seg.left,\n y: seg.centerY,\n w: seg.w,\n h: seg.centerH,\n },\n {\n x: seg.left,\n y: seg.centerY + seg.centerH,\n w: seg.w,\n h: seg.sideH,\n },\n ];\n // Keep the backing store at stage resolution (capped) so the stretched\n // edges stay crisp without oversized allocations.\n bgDpr = Math.min(2, window.devicePixelRatio || 1);\n const bw = Math.round(stage.clientWidth * bgDpr),\n bh = Math.round(vh * bgDpr);\n if (bgCanvas.width !== bw || bgCanvas.height !== bh) {\n bgCanvas.width = bw;\n bgCanvas.height = bh;\n }\n scheduleBackgroundDraw();\n startBackgroundLoop();\n }\n // One canvas, three draws: each source segment stretches into whatever bar\n // the picture leaves open. The live video feeds it once presented; until\n // then the decoded JPEG frame does, so the backdrop always matches the\n // picture's own pixels and scale in the center segment.\n let bgRects = null,\n bgAxis = \"x\",\n bgDpr = 1,\n bgDrawFrame = null,\n bgLoopFrame = null;\n function drawBackground() {\n if (!bgContext || !bgRects) return;\n const useVideo =\n videoPresented && video.videoWidth > 0 && video.videoHeight > 0;\n const src = useVideo ? video : image;\n // drawImage source rects live in the source's own pixel space, which can\n // differ from dw/dh; fractions of the real bitmap keep every segment lined\n // up with what the picture element actually shows.\n const sw = useVideo ? video.videoWidth : image.naturalWidth;\n const sh = useVideo ? video.videoHeight : image.naturalHeight;\n // Cursor updates can schedule a repaint while the next JPEG is loading.\n // Keep the last backdrop until the replacement has drawable pixels.\n if ((!useVideo && !image.complete) || !(sw > 0 && sh > 0)) return;\n bgContext.setTransform(bgDpr, 0, 0, bgDpr, 0, 0);\n bgContext.clearRect(0, 0, stage.clientWidth, stage.clientHeight);\n const horizontal = bgAxis === \"x\";\n const sourceLength = horizontal ? sw : sh;\n const cuts = [0, bgEdgeFraction, 1 - bgEdgeFraction, 1];\n for (let i = 0; i < bgRects.length; i++) {\n const rect = bgRects[i];\n const origin = cuts[i] * sourceLength;\n const length = (cuts[i + 1] - cuts[i]) * sourceLength;\n bgContext.drawImage(\n src,\n horizontal ? origin : 0,\n horizontal ? 0 : origin,\n horizontal ? length : sw,\n horizontal ? sh : length,\n rect.x,\n rect.y,\n rect.w,\n rect.h,\n );\n }\n }\n function scheduleBackgroundDraw() {\n if (bgDrawFrame !== null || !bgRects || !bgContext) return;\n bgDrawFrame = requestAnimationFrame(() => {\n bgDrawFrame = null;\n drawBackground();\n });\n }\n function startBackgroundLoop() {\n if (\n bgLoopFrame !== null ||\n !bgContext ||\n !bgRects ||\n !videoPresented ||\n typeof video.requestVideoFrameCallback !== \"function\"\n )\n return;\n const frame = video.requestVideoFrameCallback(() => {\n if (bgLoopFrame !== frame) return;\n bgLoopFrame = null;\n drawBackground();\n startBackgroundLoop();\n });\n bgLoopFrame = frame;\n }\n // Only the streaming loop stops here; a pending one-shot draw is harmless\n // (it re-paints the preserved frame) and must survive reconnects.\n function stopBackgroundLoop() {\n if (bgLoopFrame !== null) video.cancelVideoFrameCallback?.(bgLoopFrame);\n bgLoopFrame = null;\n }\n function clearBackground() {\n stopBackgroundLoop();\n bgRects = null;\n // Resizing a canvas resets its bitmap; same-value assignment still clears.\n if (bgCanvas) bgCanvas.width = bgCanvas.width;\n }\n listen(image, \"load\", () => scheduleBackgroundDraw());\n // Older WebViews update the ambient layer on media progress, never with an\n // idle display-refresh loop. Geometry changes still get a one-shot repaint.\n listen(video, \"timeupdate\", () => {\n if (videoPresented && typeof video.requestVideoFrameCallback !== \"function\")\n scheduleBackgroundDraw();\n });\n function panBounds(r) {\n const vw = viewportWidth(),\n vh = viewportHeight();\n // Grow extra resting travel continuously from zero at fit to 180 screen\n // points at maximum zoom. Never count the unused space of a fitting axis.\n const clearance = (180 * (Math.max(1, Math.min(5, zoom)) - 1)) / 4;\n const axis = (viewport, content) =>\n content <= viewport\n ? {\n min: (viewport - content) / 2 - clearance,\n max: (viewport - content) / 2 + clearance,\n }\n : { min: viewport - content - clearance, max: clearance };\n const x = axis(vw, r.width),\n y = axis(vh, r.height);\n const bounds = {\n minX: viewportLeft() + x.min,\n maxX: viewportLeft() + x.max,\n minY: y.min + verticalOffset(r.height),\n maxY: y.max + verticalOffset(r.height),\n };\n // A camera position required to expose the cursor is a valid resting point,\n // not elastic overshoot. Preserve it across the next pan/pinch handoff.\n if (followRest) {\n const restX = viewportLeft() + vw / 2 - followRest.fx * r.width,\n restY = vh / 2 + verticalOffset(r.height) - followRest.fy * r.height;\n const weight =\n followRest.zoom > 1 ? clamp((zoom - 1) / (followRest.zoom - 1)) : 1;\n bounds.minX += Math.min(0, restX - bounds.minX) * weight;\n bounds.maxX += Math.max(0, restX - bounds.maxX) * weight;\n bounds.minY += Math.min(0, restY - bounds.minY) * weight;\n bounds.maxY += Math.max(0, restY - bounds.maxY) * weight;\n }\n return bounds;\n }\n const bounded = (v, min, max) => Math.max(min, Math.min(max, v));\n // Convert displayed overshoot back to finger travel before the next delta,\n // so reversing direction unwinds smoothly without an edge jump.\n function rubber(v, min, max, inverse = false) {\n const edge = bounded(v, min, max),\n d = v - edge;\n const reach = 40 + 10 * (Math.max(1, Math.min(5, zoom)) - 1);\n return (\n edge +\n Math.sign(d) *\n (inverse\n ? (reach * Math.abs(d)) / Math.max(1, reach - Math.abs(d))\n : (reach * Math.abs(d)) / (reach + Math.abs(d)))\n );\n }\n function place(x, y, r) {\n fx = (viewportLeft() + viewportWidth() / 2 - x) / r.width;\n fy = (viewportHeight() / 2 + verticalOffset(r.height) - y) / r.height;\n }\n function cursorViewport() {\n const hotX = remoteCursor?.hotX ?? 9,\n hotY = remoteCursor?.hotY ?? 9;\n const w = remoteCursor?.width ?? 18,\n h = remoteCursor?.height ?? 18;\n const left = viewportLeft(),\n right = left + viewportWidth(),\n bottom = Math.max(1, stage.clientHeight - viewportBottomInset);\n // Keep the entire cursor, including its hotspot offset, clear of chrome.\n const minX = Math.min(right - 1, left + 8 + hotX),\n minY = Math.min(\n bottom - 1,\n (usesViewportInsets() ? viewportTopInset : 0) + 8 + hotY,\n );\n return {\n minX,\n maxX: Math.max(minX, right - 8 - (w - hotX)),\n minY,\n maxY: Math.max(minY, bottom - 8 - (h - hotY)),\n };\n }\n function moveTouchpad(dx, dy) {\n stopPanAnimation();\n const r = layout(),\n v = cursorViewport();\n if (cursorNeedsEntry) {\n // Re-enter at the nearest visible edge; do not pull a manually positioned\n // desktop back to the old off-screen cursor before applying this movement.\n cx = clamp((bounded(r.x + cx * r.width, v.minX, v.maxX) - r.x) / r.width);\n cy = clamp(\n (bounded(r.y + cy * r.height, v.minY, v.maxY) - r.y) / r.height,\n );\n cursorNeedsEntry = false;\n }\n cx = clamp(cx + dx / r.width);\n cy = clamp(cy + dy / r.height);\n const x = r.x + cx * r.width,\n y = r.y + cy * r.height;\n if (\n zoom > 1 ||\n r.width > viewportWidth() ||\n r.height > stage.clientHeight - viewportBottomInset\n ) {\n place(\n r.x + bounded(x, v.minX, v.maxX) - x,\n r.y + bounded(y, v.minY, v.maxY) - y,\n r,\n );\n followRest = { fx, fy, zoom };\n }\n manualViewMoved = false;\n }\n function stopPanAnimation() {\n if (panAnimation !== null) cancelAnimationFrame(panAnimation);\n panAnimation = null;\n }\n function settlePan() {\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r),\n x = bounded(r.x, b.minX, b.maxX),\n y = bounded(r.y, b.minY, b.maxY);\n if (x === r.x && y === r.y) return;\n if (reducedMotion.matches) {\n place(x, y, r);\n render();\n return;\n }\n const started = performance.now();\n const tick = (now) => {\n const t = Math.min(1, (now - started) / 280),\n ease = 1 - Math.pow(1 - t, 3);\n place(r.x + (x - r.x) * ease, r.y + (y - r.y) * ease, r);\n render();\n panAnimation = t < 1 ? requestAnimationFrame(tick) : null;\n };\n panAnimation = requestAnimationFrame(tick);\n }\n function render() {\n const r = layout();\n if (config.nativeMedia && epoch)\n post({\n type: \"nativeViewport\",\n fillHeight: false,\n x: r.x,\n y: r.y,\n width: r.width,\n height: r.height,\n });\n if (config.desktop && epoch) {\n const scaleMode =\n desktopScale === null\n ? \"fit\"\n : desktopScale === 1\n ? \"actual\"\n : \"custom\";\n if (reportedScaleMode !== scaleMode) {\n reportedScaleMode = scaleMode;\n post({ type: \"scaleMode\", mode: scaleMode });\n }\n }\n const touchFeedback = control && mode === \"touch\" && touchCursorVisible;\n const cursorX = mode === \"touch\" && touchCursor ? touchCursor.x : cx;\n const cursorY = mode === \"touch\" && touchCursor ? touchCursor.y : cy;\n cursor.style.transition =\n mode === \"touch\" && !touchFeedback && !reducedMotion.matches\n ? \"opacity 120ms ease-out\"\n : \"none\";\n for (const el of [image, video]) {\n el.style.width = r.width + \"px\";\n el.style.height = r.height + \"px\";\n el.style.left = r.x + \"px\";\n el.style.top = r.y + \"px\";\n }\n paintBackground();\n if (remoteCursor) {\n cursor.style.width = remoteCursor.width + \"px\";\n cursor.style.height = remoteCursor.height + \"px\";\n cursor.style.border = \"0\";\n cursor.style.borderRadius = \"0\";\n cursor.style.transform = \"none\";\n cursor.style.left = r.x + cursorX * r.width - remoteCursor.hotX + \"px\";\n cursor.style.top = r.y + cursorY * r.height - remoteCursor.hotY + \"px\";\n cursor.style.display = \"block\";\n cursor.style.opacity = (\n mode === \"touch\"\n ? touchFeedback\n : remoteCursor.visible ||\n (control && mode === \"pointer\" && localCursorAwake)\n )\n ? \"1\"\n : \"0\";\n } else {\n cursor.style.opacity = (mode === \"touch\" ? !touchFeedback : false)\n ? \"0\"\n : \"1\";\n cursor.style.width = \"18px\";\n cursor.style.height = \"18px\";\n cursor.style.border = \"2px solid var(--foreground)\";\n cursor.style.borderRadius = \"50%\";\n cursor.style.transform = \"translate(-50%,-50%)\";\n cursor.style.left = r.x + cursorX * r.width + \"px\";\n cursor.style.top = r.y + cursorY * r.height + \"px\";\n cursor.style.display =\n !config.desktop && control && (mode === \"pointer\" || mode === \"touch\")\n ? \"block\"\n : \"none\";\n }\n if (config.desktop) {\n // Let the local OS own pointer size, DPI and accessibility preferences.\n // Never use a remote URL or bitmap as the desktop's native cursor.\n cursor.style.display = \"none\";\n const shape = remoteCursor?.shape;\n stage.style.cursor =\n control &&\n [\n \"default\",\n \"text\",\n \"vertical-text\",\n \"pointer\",\n \"crosshair\",\n \"grab\",\n \"grabbing\",\n \"ew-resize\",\n \"ns-resize\",\n \"nwse-resize\",\n \"nesw-resize\",\n \"move\",\n \"not-allowed\",\n \"copy\",\n \"alias\",\n \"wait\",\n \"progress\",\n \"help\",\n ].includes(shape)\n ? shape\n : \"default\";\n }\n }\n // Literal source is required: Hermes function.toString() yields bytecode.\n function validCursor(v) {\n return (\n !!v &&\n typeof v === \"object\" &&\n typeof v.visible === \"boolean\" &&\n [v.x, v.y, v.width, v.height, v.hotX, v.hotY].every(Number.isFinite) &&\n v.x >= 0 &&\n v.x <= 1 &&\n v.y >= 0 &&\n v.y <= 1 &&\n v.width > 0 &&\n v.width <= 256 &&\n v.height > 0 &&\n v.height <= 256 &&\n v.hotX >= 0 &&\n v.hotX <= v.width &&\n v.hotY >= 0 &&\n v.hotY <= v.height &&\n typeof v.png === \"string\" &&\n v.png.length <= 65536 &&\n /^iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(v.png)\n );\n }\n function receiveCursor(value) {\n if (value === null) {\n if (remoteCursor) {\n remoteCursor = { ...remoteCursor, visible: false };\n render();\n }\n return;\n }\n if (!validCursor(value)) return;\n if (!remoteCursor || remoteCursor.png !== value.png)\n cursorImage.src = \"data:image/png;base64,\" + value.png;\n // Keep delayed host coordinates from pulling the local touchpad backwards.\n if (\n !remoteCursor ||\n !control ||\n mode !== \"pointer\" ||\n (!pointers.size && performance.now() - lastLocalMove > 200)\n ) {\n cx = value.x;\n cy = value.y;\n }\n if (value.visible) localCursorAwake = false;\n remoteCursor = value;\n render();\n }\n function resetCursor() {\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n touchCursor = null;\n localCursorAwake = false;\n remoteCursor = null;\n cursorImage.removeAttribute(\"src\");\n render();\n }\n function queue(event) {\n if (!control) return;\n if (config.desktop && (event.kind === \"button\" || event.kind === \"scroll\"))\n flushClipboardModifier();\n // Remote visibility can remain hidden after synthetic mouse movement. Wake\n // the local touchpad cursor until the host reports a visible cursor again.\n if (event.kind === \"move\" && mode === \"pointer\") localCursorAwake = true;\n if (event.kind === \"key\" || event.kind === \"text\") {\n localCursorAwake = false;\n render();\n }\n if (event.kind === \"move\" || event.kind === \"button\")\n lastLocalMove = performance.now();\n const tail = pending[pending.length - 1];\n if (event.kind === \"move\" && tail?.kind === \"move\")\n pending[pending.length - 1] = event;\n // Coalesce only adjacent scrolls, preserving button/key ordering. Bound the\n // accumulated distance so a delayed ACK cannot replay a large scroll backlog.\n else if (event.kind === \"scroll\" && tail?.kind === \"scroll\") {\n tail.dx = Math.max(-2000, Math.min(2000, tail.dx + event.dx));\n tail.dy = Math.max(-2000, Math.min(2000, tail.dy + event.dy));\n } else pending.push(event);\n if (pending.length > 64) {\n pending = [{ kind: \"release\" }];\n control = false;\n post({ type: \"inputOverflow\" });\n }\n }\n function flush() {\n if (!pending.length || sending) return;\n const events = pending.splice(0, 64),\n sequence = ++seq;\n if (\n pc?.connectionState === \"connected\" &&\n dc &&\n dc.readyState === \"open\" &&\n dc.bufferedAmount < 16384\n ) {\n dc.send(JSON.stringify({ sequence, events }));\n } else {\n sending = true;\n post({ type: \"input\", sequence, events });\n }\n }\n const inputTimer = setInterval(() => {\n // Hold displacement controls speed, even without further pointer moves.\n // Skip missed ticks while awaiting ACK instead of building a scroll backlog.\n if (wheelY?.moved && !sending) {\n const offset = Math.max(-24, Math.min(24, wheelY.y - wheelY.start));\n if (Math.abs(offset) > 4)\n scrollMouse(Math.sign(offset) * (Math.abs(offset) - 4) * 1.5);\n }\n flush();\n }, 33);\n cleanups.push(() => clearInterval(inputTimer));\n function release() {\n stopEdgePan();\n desktopPan = null;\n deferredClipboardModifier = null;\n clearTimeout(hold);\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n if (control) {\n queue({ kind: \"release\" });\n flush();\n }\n heldMouse.clear();\n resetWheel();\n updateMouseButtons();\n drag = false;\n pointers.clear();\n start = null;\n last = null;\n multi = null;\n }\n function updateMouseButtons() {\n mouseButtons.style.display =\n showMouseButtons && control && !nativeMouseControls ? \"block\" : \"none\";\n for (const [name, button] of [\n [\"left\", 0],\n [\"right\", 2],\n ])\n find(\"mouse-\" + name).setAttribute(\n \"aria-pressed\",\n String(heldMouse.has(button)),\n );\n }\n for (const [name, button] of [\n [\"left\", 0],\n [\"right\", 2],\n ]) {\n const el = find(\"mouse-\" + name);\n listenMouse(el, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || heldMouse.has(button)) return;\n clearTimeout(hold);\n if (!e.nativeInput) el.setPointerCapture(e.pointerId);\n heldMouse.set(button, e.pointerId);\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n flush();\n updateMouseButtons();\n });\n const up = (e) => {\n e.preventDefault();\n if (heldMouse.get(button) !== e.pointerId) return;\n heldMouse.delete(button);\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n flush();\n updateMouseButtons();\n };\n listenMouse(el, \"pointerup\", up);\n listenMouse(el, \"pointercancel\", up);\n listenMouse(el, \"lostpointercapture\", up);\n listenMouse(el, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(button);\n flush();\n }\n });\n }\n const scrollMouse = (dy) => {\n if (control && showMouseButtons && Number.isFinite(dy)) {\n queue({ kind: \"scroll\", dx: 0, dy: Math.max(-2000, Math.min(2000, dy)) });\n }\n };\n listenMouse(wheel, \"pointerdown\", (e) => {\n e.preventDefault();\n if (!control || !showMouseButtons || wheelY) return;\n if (!e.nativeInput) wheel.setPointerCapture(e.pointerId);\n wheelY = { id: e.pointerId, y: e.clientY, start: e.clientY, moved: false };\n });\n // A small dead zone preserves middle clicks; displacement drives the timer.\n listenMouse(wheel, \"pointermove\", (e) => {\n if (!wheelY || wheelY.id !== e.pointerId) return;\n e.preventDefault();\n wheelGrip.style.transform =\n \"translateY(\" +\n Math.max(-24, Math.min(24, e.clientY - wheelY.start)) +\n \"px)\";\n wheelY.y = e.clientY;\n if (Math.abs(e.clientY - wheelY.start) > 4) wheelY.moved = true;\n });\n listenMouse(wheel, \"pointerup\", (e) => {\n if (!wheelY || wheelY.id !== e.pointerId) return;\n e.preventDefault();\n if (!wheelY.moved && control && showMouseButtons) {\n click(1);\n flush();\n }\n resetWheel();\n });\n const cancelWheel = (e) => {\n if (wheelY?.id === e.pointerId) resetWheel();\n };\n listenMouse(wheel, \"pointercancel\", cancelWheel);\n listenMouse(wheel, \"lostpointercapture\", cancelWheel);\n listenMouse(wheel, \"click\", (e) => {\n if (e.detail === 0 && control && showMouseButtons) {\n click(1);\n flush();\n }\n });\n listenMouse(wheel, \"keydown\", (e) => {\n if (e.key === \"ArrowUp\" || e.key === \"ArrowDown\") {\n e.preventDefault();\n scrollMouse(e.key === \"ArrowUp\" ? -120 : 120);\n }\n });\n function insideDesktop(p) {\n const r = layout();\n return (\n p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.height\n );\n }\n function point(p) {\n const r = layout();\n return {\n x: clamp((p.x - r.x) / r.width),\n y: clamp((p.y - r.y) / r.height),\n };\n }\n const desktopPoint = (e) => {\n const bounds = stage.getBoundingClientRect();\n return { x: e.clientX - bounds.left, y: e.clientY - bounds.top };\n };\n function stopEdgePan() {\n if (edgeFrame !== null) cancelAnimationFrame(edgeFrame);\n edgeFrame = null;\n edgePointer = null;\n }\n function edgePanTick(now) {\n edgeFrame = null;\n if (!edgePointer || desktopPan || !epoch) return;\n const r = layout(),\n vw = viewportWidth(),\n vh = viewportHeight();\n const p = edgePointer;\n const dt = Math.min(32, Math.max(0, now - edgeTime)) / 1000;\n edgeTime = now;\n // rAF timestamps describe the frame start and can precede the pointer\n // handler's performance.now(). A zero-time first frame is not a boundary.\n if (dt === 0) {\n edgeFrame = requestAnimationFrame(edgePanTick);\n return;\n }\n // A narrow edge band accelerates smoothly to 720 local pixels per second.\n const velocity = (position, extent) => {\n const band = Math.min(28, extent / 4);\n return position < band\n ? -(1 - position / band)\n : position > extent - band\n ? (position - extent + band) / band\n : 0;\n };\n const x =\n r.width > vw\n ? bounded(\n r.x - velocity(p.x - viewportLeft(), vw) * 720 * dt,\n viewportLeft() + vw - r.width,\n viewportLeft(),\n )\n : r.x;\n const y =\n r.height > vh\n ? bounded(r.y - velocity(p.y, vh) * 720 * dt, vh - r.height, 0)\n : r.y;\n if (Math.abs(x - r.x) < 0.001 && Math.abs(y - r.y) < 0.001) return;\n stopPanAnimation();\n manualViewMoved = true;\n place(x, y, r);\n // Keep remote hover/drag attached to the local pointer as the picture moves.\n if (control) {\n const next = point(p);\n cx = next.x;\n cy = next.y;\n queue({ kind: \"move\", x: cx, y: cy });\n }\n render();\n edgeFrame = requestAnimationFrame(edgePanTick);\n }\n function trackEdgePointer(e) {\n const p = desktopPoint(e);\n if (\n !epoch ||\n desktopPan ||\n p.x < viewportLeft() ||\n p.x > viewportLeft() + viewportWidth() ||\n p.y < 0 ||\n p.y > viewportHeight() ||\n !insideDesktop(p)\n ) {\n stopEdgePan();\n return;\n }\n edgePointer = p;\n if (edgeFrame === null) {\n edgeTime = performance.now();\n edgeFrame = requestAnimationFrame(edgePanTick);\n }\n }\n listen(stage, \"pointerleave\", stopEdgePan);\n function mouse(e, down) {\n if (!control || ![0, 1, 2].includes(e.button)) return;\n const local = desktopPoint(e);\n if (down && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n if (down) {\n showKeyboard(true);\n stage.setPointerCapture(e.pointerId);\n heldMouse.set(e.button, e.pointerId);\n } else if (!heldMouse.delete(e.button)) return;\n queue({ kind: \"button\", button: e.button, down, x: cx, y: cy });\n flush();\n render();\n }\n function click(button = 0) {\n if (control && mode === \"touch\") {\n clearTimeout(touchCursorTimer);\n touchCursor = { x: cx, y: cy };\n touchCursorVisible = true;\n render();\n touchCursorTimer = setTimeout(() => {\n touchCursorVisible = false;\n render();\n }, 450);\n }\n queue({ kind: \"button\", button, down: true, x: cx, y: cy });\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n }\n function pan(dx, dy) {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n stopPanAnimation();\n const r = layout(),\n b = panBounds(r);\n place(\n rubber(rubber(r.x, b.minX, b.maxX, true) + dx, b.minX, b.maxX),\n rubber(rubber(r.y, b.minY, b.maxY, true) + dy, b.minY, b.maxY),\n r,\n );\n render();\n }\n function pair() {\n const [a, b] = [...pointers.values()];\n return {\n x: (a.x + b.x) / 2,\n y: (a.y + b.y) / 2,\n d: Math.hypot(a.x - b.x, a.y - b.y),\n };\n }\n function movePair() {\n gestureFrame = null;\n if (pointers.size < 2 || !multi) return;\n const next = pair(),\n span = Math.abs(next.d - multi.d),\n travel = Math.hypot(next.x - multi.x, next.y - multi.y);\n if (multi.kind !== \"pinch\") {\n const pinchSlop = Math.max(6, Math.min(12, multi.d * 0.04));\n if (span >= pinchSlop && span > travel * 0.65) {\n // A parallel scroll may deliver its two pointer updates in different\n // frames. Confirm separation briefly before taking over as a pinch.\n if (!multi.candidate)\n multi.candidate = {\n at: Date.now(),\n d: next.d,\n zoom,\n anchor: point(next),\n };\n if (Date.now() - multi.candidate.at >= 40) {\n if (multi.kind === \"scroll\") {\n multi.d = multi.candidate.d;\n multi.zoom = multi.candidate.zoom;\n multi.anchor = multi.candidate.anchor;\n }\n multi.kind = \"pinch\";\n multi.candidate = null;\n } else {\n gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n } else {\n multi.candidate = null;\n if (!multi.kind && travel > 8 && travel > span) multi.kind = \"scroll\";\n }\n }\n if (multi.kind === \"pinch\") {\n manualViewMoved = true;\n cursorNeedsEntry = true;\n zoom = Math.max(\n 1,\n Math.min(5, (multi.zoom * next.d) / Math.max(1, multi.d)),\n );\n const r = layout();\n fx =\n multi.anchor.x +\n (viewportLeft() + viewportWidth() / 2 - next.x) / r.width;\n fy =\n multi.anchor.y +\n (viewportHeight() / 2 + verticalOffset(r.height) - next.y) / r.height;\n const moved = layout(),\n b = panBounds(moved);\n place(\n rubber(moved.x, b.minX, b.maxX),\n rubber(moved.y, b.minY, b.maxY),\n moved,\n );\n } else if (multi.kind === \"scroll\") {\n const dx = next.x - multi.lastX,\n dy = next.y - multi.lastY;\n if (control && mode !== \"pan\")\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, -dx)),\n dy: Math.max(-2000, Math.min(2000, -dy)),\n });\n else pan(dx, dy);\n }\n if (multi.kind) {\n multi.lastX = next.x;\n multi.lastY = next.y;\n }\n render();\n }\n listen(stage, \"pointerdown\", (e) => {\n if (config.desktop) {\n e.preventDefault();\n if (\n e.button === 1 &&\n (layout().width > viewportWidth() || layout().height > viewportHeight())\n ) {\n stopEdgePan();\n stopPanAnimation();\n desktopPan = {\n id: e.pointerId,\n x: e.clientX,\n y: e.clientY,\n start: e,\n moved: false,\n };\n stage.setPointerCapture(e.pointerId);\n return;\n }\n mouse(e, true);\n return;\n }\n e.preventDefault();\n stopPanAnimation();\n stage.setPointerCapture(e.pointerId);\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size === 1) {\n cursorNeedsEntry = true;\n start = { x: e.clientX, y: e.clientY };\n last = start;\n moved = false;\n hold = setTimeout(() => {\n if (\n control &&\n mode !== \"pan\" &&\n !moved &&\n pointers.size === 1 &&\n !heldMouse.size &&\n (mode !== \"touch\" || insideDesktop(start))\n ) {\n if (mode === \"touch\") {\n const p = point(start);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"button\", button: 0, down: true, x: cx, y: cy });\n drag = true;\n }\n }, 400);\n } else {\n clearTimeout(hold);\n if (drag) queue({ kind: \"release\" });\n drag = false;\n start = null;\n const p = pair();\n multi = {\n ...p,\n lastX: p.x,\n lastY: p.y,\n zoom,\n anchor: point(p),\n kind: null,\n };\n }\n });\n listen(stage, \"pointermove\", (e) => {\n if (config.desktop) {\n if (desktopPan?.id === e.pointerId) {\n const dx = e.clientX - desktopPan.x,\n dy = e.clientY - desktopPan.y;\n if (!desktopPan.moved && Math.hypot(dx, dy) < 3) return;\n desktopPan.moved = true;\n desktopPan.x = e.clientX;\n desktopPan.y = e.clientY;\n pan(dx, dy);\n return;\n }\n trackEdgePointer(e);\n if (!control) return;\n const local = desktopPoint(e);\n if (!heldMouse.size && !insideDesktop(local)) return;\n const p = point(local);\n cx = p.x;\n cy = p.y;\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n e.preventDefault();\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (pointers.size >= 2) {\n if (gestureFrame === null) gestureFrame = requestAnimationFrame(movePair);\n return;\n }\n if (!start || !last) return;\n const now = { x: e.clientX, y: e.clientY },\n dx = now.x - last.x,\n dy = now.y - last.y;\n last = now;\n if (Math.hypot(now.x - start.x, now.y - start.y) > 6) {\n moved = true;\n clearTimeout(hold);\n }\n if (\n !control ||\n mode === \"pan\" ||\n (mode === \"touch\" && !drag && !heldMouse.size)\n ) {\n pan(dx, dy);\n return;\n }\n if (mode === \"pointer\") {\n moveTouchpad(dx, dy);\n } else {\n const p = point(now);\n cx = p.x;\n cy = p.y;\n }\n queue({ kind: \"move\", x: cx, y: cy });\n render();\n });\n function up(e) {\n if (config.desktop) {\n if (desktopPan?.id === e.pointerId) {\n const gesture = desktopPan;\n desktopPan = null;\n if (gesture.moved) settlePan();\n else {\n mouse(gesture.start, true);\n mouse(e, false);\n }\n return;\n }\n mouse(e, false);\n return;\n }\n if (!pointers.has(e.pointerId)) return;\n clearTimeout(hold);\n if (pointers.size >= 2 && multi) {\n pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n movePair();\n if (gestureFrame !== null) cancelAnimationFrame(gestureFrame);\n gestureFrame = null;\n }\n pointers.delete(e.pointerId);\n if (drag) {\n queue({ kind: \"button\", button: 0, down: false, x: cx, y: cy });\n drag = false;\n } else if (\n start &&\n !moved &&\n control &&\n mode !== \"pan\" &&\n !heldMouse.size &&\n e.type === \"pointerup\" &&\n (mode !== \"touch\" || insideDesktop({ x: e.clientX, y: e.clientY }))\n ) {\n if (mode === \"touch\") {\n const p = point({ x: e.clientX, y: e.clientY });\n cx = p.x;\n cy = p.y;\n }\n click();\n }\n start = null;\n last = null;\n multi = null;\n render();\n if (!pointers.size && manualViewMoved) settlePan();\n }\n listen(stage, \"pointerup\", up);\n listen(stage, \"pointercancel\", () => {\n release();\n settlePan();\n });\n listen(stage, \"lostpointercapture\", () => {\n desktopPan = null;\n if (config.desktop && heldMouse.size) release();\n });\n if (config.desktop)\n listen(\n stage,\n \"wheel\",\n (e) => {\n e.preventDefault();\n if (!control) return;\n const factor =\n e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? stage.clientHeight : 1;\n queue({\n kind: \"scroll\",\n dx: Math.max(-2000, Math.min(2000, e.deltaX * factor)),\n dy: Math.max(-2000, Math.min(2000, e.deltaY * factor)),\n });\n flush();\n },\n { passive: false },\n );\n listen(config.desktop ? stage : document, \"contextmenu\", (e) =>\n e.preventDefault(),\n );\n // Scope selection suppression to the desktop surface, preserving the hidden\n // textarea's native keyboard/IME editing and programmatic selection.\n listen(stage, \"selectstart\", (e) => e.preventDefault());\n listen(stage, \"dragstart\", (e) => e.preventDefault());\n const normalizedKey = (code) =>\n /^(Shift|Control|Alt|Meta)Right$/.test(code)\n ? code.replace(/Right$/, \"Left\")\n : code;\n const hardwareKeys = new Set();\n function flushClipboardModifier() {\n if (!deferredClipboardModifier) return;\n const code = deferredClipboardModifier;\n deferredClipboardModifier = null;\n hardwareKeys.add(code);\n queue({ kind: \"key\", code, down: true });\n }\n listen(document, \"keydown\", (e) => {\n if (config.desktop) {\n if (e.ctrlKey && e.altKey && e.code === \"Escape\") {\n e.preventDefault();\n release();\n showKeyboard(false);\n post({ type: \"releaseFocus\" });\n return;\n }\n if (\n document.activeElement !== keyboardInput ||\n e.isComposing ||\n composing\n )\n return;\n if ((e.metaKey || e.ctrlKey) && e.code === \"KeyW\") return; // always retain a local close shortcut\n if (\n control &&\n clipboardShortcuts &&\n normalizedKey(e.code) ===\n (clipboardModifier === \"meta\" ? \"MetaLeft\" : \"ControlLeft\")\n ) {\n e.preventDefault();\n if (!hardwareKeys.has(normalizedKey(e.code)))\n deferredClipboardModifier = normalizedKey(e.code);\n return;\n }\n if (\n control &&\n clipboardShortcuts &&\n (clipboardModifier === \"meta\"\n ? e.metaKey && !e.ctrlKey\n : e.ctrlKey && !e.metaKey) &&\n !e.altKey &&\n !e.shiftKey &&\n (e.code === \"KeyC\" || e.code === \"KeyV\")\n ) {\n e.preventDefault();\n if (!e.repeat) {\n release();\n hardwareKeys.clear();\n post({\n type: \"clipboard\",\n action: e.code === \"KeyC\" ? \"copy\" : \"paste\",\n });\n }\n return;\n }\n if (\n !e.ctrlKey &&\n !e.metaKey &&\n !e.altKey &&\n (e.key?.length === 1 || e.key === \"Process\" || e.key === \"Dead\")\n )\n return;\n }\n if (control && validKeys.has(normalizedKey(e.code))) {\n e.preventDefault();\n flushClipboardModifier();\n hardwareKeys.add(normalizedKey(e.code));\n queue({ kind: \"key\", code: normalizedKey(e.code), down: true });\n }\n });\n listen(document, \"keyup\", (e) => {\n const code = normalizedKey(e.code);\n if (config.desktop && control && deferredClipboardModifier === code) {\n flushClipboardModifier();\n }\n if (config.desktop && !hardwareKeys.delete(code)) return;\n if (control && validKeys.has(code)) {\n e.preventDefault();\n queue({ kind: \"key\", code, down: false });\n }\n });\n if (config.desktop)\n listen(keyboardInput, \"blur\", () => {\n hardwareKeys.clear();\n release();\n });\n listen(window, \"blur\", () => {\n release();\n settlePan();\n });\n function reportViewport() {\n post({\n type: \"viewportChanged\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n }\n const observer = new ResizeObserver(() => {\n reportViewport();\n release();\n settlePan();\n render();\n });\n observer.observe(stage);\n cleanups.push(\n () => observer.disconnect(),\n () => stopPanAnimation(),\n () => stopBackgroundLoop(),\n () => clearTimeout(touchCursorTimer),\n );\n // Keep one bounded frame in this document only; never persist desktop pixels.\n // Snapshot before detaching the track. A JPEG fallback already lives in image.\n function retainFrame() {\n if (\n !videoPresented ||\n video.style.display !== \"block\" ||\n video.readyState < 2 ||\n !video.videoWidth ||\n !video.videoHeight\n )\n return;\n const canvas = document.createElement(\"canvas\");\n try {\n const scale = Math.min(\n 1,\n 1280 / Math.max(video.videoWidth, video.videoHeight),\n );\n canvas.width = Math.max(1, Math.round(video.videoWidth * scale));\n canvas.height = Math.max(1, Math.round(video.videoHeight * scale));\n const context = canvas.getContext(\"2d\");\n if (context) {\n context.drawImage(video, 0, 0, canvas.width, canvas.height);\n image.src = canvas.toDataURL(\"image/jpeg\", 0.7);\n }\n } catch {\n /* Keep the previous compatibility frame if WebKit cannot read video. */\n } finally {\n canvas.width = 0;\n canvas.height = 0;\n }\n }\n /* BEGIN RTC */\n\n let trickleIce = false,\n attemptId = null,\n retries = 0,\n exchangeId = 0;\n let configPending = false;\n let videoPresented = false,\n videoFrameCallback = null,\n videoPaintCallback = null;\n function cancelVideoHandoff() {\n if (videoFrameCallback !== null)\n video.cancelVideoFrameCallback?.(videoFrameCallback);\n if (videoPaintCallback !== null) cancelAnimationFrame(videoPaintCallback);\n videoFrameCallback = videoPaintCallback = null;\n }\n function revealVideo(g) {\n post({ type: \"videoFrameReady\", attemptId });\n // Keep the JPEG decoded and painted as a backing layer. Promote the video\n // only after its first frame; removing the image exposes WebKit repaint gaps.\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = requestAnimationFrame(() => {\n if (g !== generation) return;\n videoPaintCallback = null;\n videoPresented = true;\n video.style.zIndex = \"2\";\n if (typeof startBackgroundLoop === \"function\") startBackgroundLoop();\n post({ type: \"streaming\", attemptId });\n post({\n type: \"pipCapability\",\n supported: !!(\n video.webkitSupportsPresentationMode?.(\"picture-in-picture\") ||\n document.pictureInPictureEnabled\n ),\n });\n });\n });\n }\n function waitForVideoFrame(g) {\n if (g !== generation) return;\n if (\n video.readyState >= 2 &&\n video.videoWidth > 0 &&\n video.videoHeight > 0\n ) {\n revealVideo(g);\n return;\n }\n videoPaintCallback = requestAnimationFrame(() => waitForVideoFrame(g));\n }\n let retryTimer = null,\n deadlineTimer = null,\n disconnectTimer = null,\n stableTimer = null,\n iceTimer = null,\n gatherTimer = null,\n gatherDone = null;\n let localCandidates = [],\n localAck = 0,\n remoteAfter = 0,\n icePending = null,\n remoteSeen = new Set(),\n exchangeUntil = 0,\n remoteComplete = false;\n function clearRtcTimers() {\n for (const timer of [\n retryTimer,\n deadlineTimer,\n disconnectTimer,\n stableTimer,\n iceTimer,\n gatherTimer,\n ])\n clearTimeout(timer);\n retryTimer =\n deadlineTimer =\n disconnectTimer =\n stableTimer =\n iceTimer =\n gatherTimer =\n null;\n if (gatherDone) {\n gatherDone();\n gatherDone = null;\n }\n }\n function closeRtc(preserveFrame = true) {\n configPending = false;\n if (preserveFrame) retainFrame();\n generation++;\n clearRtcTimers();\n cancelVideoHandoff();\n videoPresented = false;\n localCandidates = [];\n localAck = remoteAfter = 0;\n icePending = null;\n remoteSeen = new Set();\n attemptId = null;\n clearInterval(statsTimer);\n statsTimer = null;\n statsSample = null;\n if (dc) dc.close();\n if (pc) pc.close();\n pc = null;\n dc = null;\n video.onplaying = null;\n video.srcObject = null;\n video.style.display = \"none\";\n video.style.zIndex = \"0\";\n image.style.display = \"block\";\n if (typeof stopBackgroundLoop === \"function\") stopBackgroundLoop();\n if (!preserveFrame) {\n image.removeAttribute(\"src\");\n if (typeof clearBackground === \"function\") clearBackground();\n }\n }\n function failRtc(reason, canRetry = true) {\n const failedAttempt = attemptId;\n release();\n closeRtc();\n post({ type: \"fallback\", attemptId: failedAttempt, reason });\n // Local consent is bounded by the host's picker lifetime. Reuse this retry\n // timer without consuming the finite network-recovery attempts.\n const capturePending = reason === \"capture-pending\";\n if (canRetry && epoch && (capturePending || retries < net.retryMs.length)) {\n const delay = capturePending\n ? net.retryMs[net.retryMs.length - 1]\n : net.retryMs[retries++];\n retryTimer = setTimeout(() => {\n retryTimer = null;\n if (epoch) connect();\n }, delay);\n }\n }\n function pollIce() {\n if (\n !pc ||\n !trickleIce ||\n !pc.remoteDescription ||\n icePending ||\n Date.now() >= exchangeUntil\n )\n return;\n const candidates = localCandidates.slice(\n localAck,\n localAck + net.batchSize,\n );\n icePending = {\n after: remoteAfter,\n sent: candidates.length,\n exchangeId: ++exchangeId,\n };\n post({\n type: \"ice\",\n attemptId,\n candidates,\n after: remoteAfter,\n exchangeId,\n });\n iceTimer = setTimeout(() => {\n icePending = null;\n pollIce();\n }, 4500);\n }\n async function receiveIce(message) {\n if (\n !pc ||\n !icePending ||\n message.attemptId !== attemptId ||\n message.exchangeId !== icePending.exchangeId\n )\n return;\n const rtc = pc,\n g = generation,\n batch = icePending;\n clearTimeout(iceTimer);\n try {\n if (message.error) {\n icePending = null;\n iceTimer = setTimeout(pollIce, 1000);\n return;\n }\n if (\n !Array.isArray(message.candidates) ||\n message.candidates.length > net.batchSize ||\n message.next !== batch.after + message.candidates.length ||\n message.next > net.maxCandidates\n )\n throw new Error();\n for (const candidate of message.candidates) {\n if (g !== generation) return;\n const key = JSON.stringify(candidate);\n if (remoteSeen.has(key)) continue;\n if (remoteSeen.size >= net.maxCandidates) throw new Error();\n await rtc.addIceCandidate(candidate);\n if (g !== generation) return;\n remoteSeen.add(key);\n }\n if (g !== generation) return;\n localAck += batch.sent;\n remoteAfter = message.next;\n remoteComplete = message.complete === true;\n icePending = null;\n if (!(\n remoteComplete &&\n rtc.iceGatheringState === \"complete\" &&\n localAck === localCandidates.length\n ))\n iceTimer = setTimeout(pollIce, net.pollMs);\n } catch {\n if (g === generation) failRtc(\"candidates\");\n }\n }\n async function receiveAnswer(message) {\n if (!pc || message.attemptId !== attemptId) return;\n const rtc = pc,\n g = generation;\n try {\n await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n if (g !== generation) return;\n clearTimeout(deadlineTimer);\n deadlineTimer = setTimeout(() => {\n if (g === generation && rtc.connectionState !== \"connected\")\n failRtc(\"connect-timeout\");\n }, net.connectMs);\n exchangeUntil = Date.now() + net.exchangeMs;\n pollIce();\n } catch {\n if (g === generation) failRtc(\"answer\");\n }\n }\n async function connect() {\n closeRtc();\n const g = generation;\n attemptId = String(g);\n if (!window.RTCPeerConnection) {\n failRtc(\"unsupported\", false);\n return;\n }\n configPending = true;\n deadlineTimer = setTimeout(\n () => {\n if (g === generation && configPending) {\n configPending = false;\n void startRtc(g, iceServers);\n }\n },\n (net.iceConfigMs ?? 8000) + (net.iceConfigBridgeMs ?? 500),\n );\n return post({ type: \"iceConfig\", attemptId });\n }\n async function receiveIceConfig(message) {\n if (!epoch || !configPending || message.attemptId !== attemptId) return;\n configPending = false;\n clearTimeout(deadlineTimer);\n deadlineTimer = null;\n await startRtc(generation, message.iceServers);\n }\n async function startRtc(g, servers) {\n try {\n const rtc = new RTCPeerConnection({ iceServers: servers });\n pc = rtc;\n dc = rtc.createDataChannel(\"input-v1\");\n rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n rtc.onicecandidate = ({ candidate }) => {\n if (g !== generation || !candidate?.candidate || !trickleIce) return;\n if (localCandidates.length >= net.maxCandidates) {\n failRtc(\"candidate-limit\", false);\n return;\n }\n localCandidates.push({\n candidate: candidate.candidate,\n sdpMid: candidate.sdpMid,\n sdpMLineIndex: candidate.sdpMLineIndex,\n ...(candidate.usernameFragment\n ? { usernameFragment: candidate.usernameFragment }\n : {}),\n });\n // Gathering continues after the offer; the serial exchange flushes late addresses.\n };\n dc.onmessage = (e) => {\n try {\n if (g !== generation || pc !== rtc) return;\n if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n const message = JSON.parse(e.data);\n if (message.type === \"cursor\") receiveCursor(message.cursor);\n if (\n (video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video) &&\n message.type === \"viewPing\" &&\n typeof message.challenge === \"string\" &&\n message.challenge.length <= 64 &&\n dc?.readyState === \"open\"\n )\n dc.send(message.challenge);\n } catch {}\n };\n let readingStats = false;\n statsTimer = setInterval(async () => {\n if (readingStats || g !== generation) return;\n readingStats = true;\n try {\n const stats = await rtc.getStats();\n if (g !== generation || pc !== rtc) return;\n const result = networkStats(stats, statsSample);\n statsSample = result.sample;\n post({\n type: \"network\",\n transport: result.transport,\n bytesPerSecond: result.bytesPerSecond,\n latencyMs: result.latencyMs,\n });\n } catch {\n } finally {\n readingStats = false;\n }\n }, 1000);\n rtc.ontrack = (e) => {\n if (g !== generation) return;\n video.srcObject = e.streams[0] || new MediaStream([e.track]);\n video.play().catch(() => {});\n };\n video.onplaying = () => {\n if (\n g !== generation ||\n videoPresented ||\n videoFrameCallback !== null ||\n videoPaintCallback !== null\n )\n return;\n video.style.display = \"block\";\n render();\n if (typeof scheduleBackgroundDraw === \"function\")\n scheduleBackgroundDraw();\n if (typeof video.requestVideoFrameCallback === \"function\") {\n videoFrameCallback = video.requestVideoFrameCallback(() => {\n if (g !== generation) return;\n videoFrameCallback = null;\n revealVideo(g);\n });\n } else waitForVideoFrame(g);\n };\n rtc.onconnectionstatechange = () => {\n if (g !== generation) return;\n if ([\"failed\", \"closed\"].includes(rtc.connectionState)) {\n failRtc(\"transport\");\n return;\n }\n if (rtc.connectionState === \"disconnected\") {\n clearTimeout(stableTimer);\n stableTimer = null;\n if (!disconnectTimer) {\n release();\n post({ type: \"reconnecting\", attemptId });\n disconnectTimer = setTimeout(() => {\n if (g === generation) failRtc(\"disconnected\");\n }, net.disconnectedMs);\n }\n } else if (rtc.connectionState === \"connected\") {\n clearTimeout(disconnectTimer);\n disconnectTimer = null;\n clearTimeout(deadlineTimer);\n if (!stableTimer)\n stableTimer = setTimeout(() => {\n if (g === generation) retries = 0;\n }, net.stableMs);\n if (videoPresented) post({ type: \"streaming\", attemptId });\n }\n };\n await rtc.setLocalDescription(await rtc.createOffer());\n if (!trickleIce)\n await new Promise((resolve) => {\n if (rtc.iceGatheringState === \"complete\") return resolve();\n gatherDone = resolve;\n gatherTimer = setTimeout(resolve, net.legacyGatherMs);\n rtc.onicegatheringstatechange = () => {\n if (rtc.iceGatheringState === \"complete\") {\n clearTimeout(gatherTimer);\n resolve();\n }\n };\n });\n if (g !== generation) return;\n post({ type: \"offer\", attemptId, sdp: rtc.localDescription.sdp });\n deadlineTimer = setTimeout(() => {\n if (g === generation) failRtc(\"answer-timeout\");\n }, net.answerMs);\n } catch {\n if (g === generation) failRtc(\"setup\");\n }\n }\n\n /* END RTC */\n function reportPresentation() {\n post({\n type: \"presentation\",\n active:\n video.webkitPresentationMode === \"picture-in-picture\" ||\n document.pictureInPictureElement === video,\n });\n }\n listen(video, \"webkitpresentationmodechanged\", reportPresentation);\n listen(video, \"enterpictureinpicture\", reportPresentation);\n listen(video, \"leavepictureinpicture\", reportPresentation);\n function receive(event) {\n let message;\n try {\n message = JSON.parse(event.data);\n } catch {\n return;\n }\n switch (message.type) {\n case \"measureViewport\":\n post({\n type: \"viewportSize\",\n width: viewportWidth(),\n height: usableHeight(),\n });\n break;\n case \"presentation\":\n if (config.nativeMedia) {\n release();\n showKeyboard(false);\n break;\n }\n try {\n if (message.enabled) {\n release();\n showKeyboard(false);\n if (video.webkitSupportsPresentationMode?.(\"picture-in-picture\"))\n video.webkitSetPresentationMode(\"picture-in-picture\");\n else if (video.requestPictureInPicture)\n video\n .requestPictureInPicture()\n .catch(() => post({ type: \"presentationFailed\" }));\n else post({ type: \"presentationFailed\" });\n } else if (video.webkitSetPresentationMode)\n video.webkitSetPresentationMode(\"inline\");\n else if (document.pictureInPictureElement)\n document.exitPictureInPicture().catch(() => {});\n } catch {\n post({ type: \"presentationFailed\" });\n }\n break;\n case \"videoSettings\":\n if (\n Number.isInteger(message.width) &&\n Number.isInteger(message.height) &&\n message.width >= 320 &&\n message.height >= 320 &&\n (message.restore === true ||\n (message.width <= 2560 && message.height <= 2560))\n ) {\n release();\n stopPanAnimation();\n viewerSized = message.restore !== true;\n zoom = 1;\n desktopScale = null;\n fx = fy = 0.5;\n followRest = null;\n dw = message.width;\n dh = message.height;\n render();\n }\n video.muted = !message.audio;\n retries = 0;\n if (!config.nativeMedia) connect();\n break;\n case \"keyboard\":\n showKeyboard(message.enabled === true);\n break;\n case \"resume\":\n if (video.srcObject) video.play().catch(() => {});\n break;\n case \"releaseInput\":\n release();\n break;\n case \"theme\":\n if (/^#[0-9a-f]{3,8}$/i.test(message.surface)) {\n document.body.style.background = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.background = config.nativeMedia\n ? \"transparent\"\n : message.surface;\n document.documentElement.style.setProperty(\n \"--surface\",\n message.surface,\n );\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.foreground)) {\n cursor.style.borderColor = message.foreground;\n document.documentElement.style.setProperty(\n \"--foreground\",\n message.foreground,\n );\n }\n break;\n case \"networkStatus\": {\n const status = document.getElementById(\"network-status\");\n if (!status) break;\n status.textContent =\n typeof message.text === \"string\" ? message.text : \"\";\n status.style.display = status.textContent ? \"block\" : \"none\";\n for (const key of [\"top\", \"right\", \"fontSize\"]) {\n if (Number.isFinite(message[key]) && message[key] >= 0)\n status.style[key] = message[key] + \"px\";\n }\n if (/^#[0-9a-f]{3,8}$/i.test(message.color))\n status.style.color = message.color;\n break;\n }\n case \"nativeTouchpad\": {\n if (!nativeMouseControls || !control) break;\n if (message.tap === true) {\n if (!heldMouse.size) { click(); flush(); }\n break;\n }\n if (!Number.isFinite(message.dx) || !Number.isFinite(message.dy)) break;\n moveTouchpad(message.dx, message.dy);\n queue({ kind: \"move\", x: cx, y: cy });\n touchCursor = { x: cx, y: cy };\n touchCursorVisible = true;\n render();\n break;\n }\n case \"nativeMouse\": {\n if (\n !nativeMouseControls ||\n ![\"left\", \"right\", \"wheel\"].includes(message.control)\n )\n break;\n if (\n ![\n \"pointerdown\",\n \"pointermove\",\n \"pointerup\",\n \"pointercancel\",\n \"click\",\n ].includes(message.event)\n )\n break;\n if (!Number.isFinite(message.id) || !Number.isFinite(message.y)) break;\n mouseControlHandlers.get(\n \"mouse-\" + message.control + \":\" + message.event,\n )?.({\n pointerId: message.id,\n clientY: message.y,\n detail: 0,\n nativeInput: true,\n preventDefault() {},\n });\n break;\n }\n case \"mouseButtons\": {\n nativeMouseControls = message.native === true;\n const before = layout(),\n previousTopInset = viewportTopInset,\n previousBottomInset = viewportBottomInset,\n keyboardOpen = fillHeight && message.keyboardOpen === true;\n const keepHorizontal =\n fillHeight && (keyboardOpen || keyboardViewportOpen);\n // Hiding the rail for the keyboard must not enlarge a width-fitted desktop.\n if (keyboardOpen && (!keyboardViewportOpen || !keyboardFitWidth)) {\n keyboardFitWidth = { stageWidth: stage.clientWidth, width: viewportWidth() };\n }\n if (!keyboardOpen) keyboardFitWidth = null;\n // Opening is observable before the native keyboard has a measured height.\n keyboardViewportOpen = keyboardOpen;\n const fitChanged = fitToInsets !== (message.fitToInsets === true);\n fitToInsets = message.fitToInsets === true;\n const previousOffset = portraitKeyboardTopInset;\n if (Number.isFinite(message.portraitKeyboardTopInset))\n portraitKeyboardTopInset = Math.max(\n 0,\n message.portraitKeyboardTopInset,\n );\n const offsetChanged = previousOffset !== portraitKeyboardTopInset;\n let sideInsetsChanged = false;\n if (Number.isFinite(message.topInset))\n viewportTopInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.topInset),\n );\n if (Number.isFinite(message.bottomInset))\n viewportBottomInset = Math.max(\n 0,\n Math.min(stage.clientHeight - 1, message.bottomInset),\n );\n if (Number.isFinite(message.leftInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.leftInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportLeftInset;\n viewportLeftInset = inset;\n }\n if (Number.isFinite(message.rightInset)) {\n const inset = Math.max(\n 0,\n Math.min(stage.clientWidth - 1, message.rightInset),\n );\n sideInsetsChanged = sideInsetsChanged || inset !== viewportRightInset;\n viewportRightInset = inset;\n }\n // Hiding the side toolbar changes the viewport center. Keep the image's\n // actual horizontal position instead of following that center sideways.\n if (keepHorizontal) {\n stopPanAnimation();\n const r = layout();\n place(before.x, r.y, r);\n }\n const keyboardInset = keyboardOpen ? viewportBottomInset : 0;\n if (keyboardInset !== keyboardViewportInset) {\n const wasOpen = keyboardViewportInset > 0;\n keyboardViewportInset = keyboardInset;\n if (fillHeight && (keyboardInset > 0 || wasOpen)) {\n const r = layout(),\n v = cursorViewport();\n place(r.x, (v.minY + v.maxY) / 2 - cy * r.height, r);\n cursorNeedsEntry = false;\n manualViewMoved = false;\n }\n }\n if (keepHorizontal) {\n // Restoring the toolbar can cover the cursor even after a zero-height opening.\n if (!keyboardOpen || keyboardInset > 0) {\n const r = layout(),\n v = cursorViewport(),\n x = r.x + cx * r.width;\n place(r.x + bounded(x, v.minX, v.maxX) - x, r.y, r);\n }\n followRest = { fx, fy, zoom };\n render();\n } else if (\n fitChanged ||\n sideInsetsChanged ||\n offsetChanged ||\n (usesViewportInsets() && previousTopInset !== viewportTopInset) ||\n (usesViewportInsets() && previousBottomInset !== viewportBottomInset)\n ) {\n settlePan();\n render();\n }\n reportViewport();\n if (!message.enabled) {\n for (const button of heldMouse.keys())\n queue({ kind: \"button\", button, down: false, x: cx, y: cy });\n heldMouse.clear();\n resetWheel();\n flush();\n }\n for (const [edge, value] of [\n [\"bottom\", message.bottomInset],\n [\"right\", message.rightInset],\n ])\n if (Number.isFinite(value) && value >= 0 && value <= 4096)\n mouseButtons.style[edge] = value + \"px\";\n showMouseButtons = message.enabled === true;\n for (const name of [\"left\", \"right\", \"wheel\"])\n if (typeof message.labels?.[name] === \"string\")\n find(\"mouse-\" + name).setAttribute(\n \"aria-label\",\n message.labels[name],\n );\n updateMouseButtons();\n break;\n }\n case \"init\":\n nativeVideoActive = false;\n image.style.visibility = \"visible\";\n desktopScale = null;\n reportedScaleMode = null;\n if (config.desktop) {\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n }\n viewerSized = false;\n followRest = null;\n cursorNeedsEntry = true;\n stopPanAnimation();\n resetCursor();\n control = false;\n release();\n pending = [];\n sending = false;\n seq = 0;\n epoch = message.epoch;\n clipboardShortcuts =\n config.desktop && message.clipboardShortcuts === true;\n clipboardModifier =\n message.clipboardModifier === \"meta\" ? \"meta\" : \"control\";\n dw = message.width;\n dh = message.height;\n fillHeight = message.fillHeight === true;\n video.muted = !message.audio;\n trickleIce = message.trickleIce === true;\n retries = 0;\n render();\n if (!config.nativeMedia) connect();\n break;\n case \"nativeVideo\":\n if (!config.nativeMedia || message.epoch !== epoch) break;\n nativeVideoActive = message.active === true;\n image.style.visibility = nativeVideoActive ? \"hidden\" : \"visible\";\n paintBackground();\n break;\n case \"nativeCursor\":\n if (config.nativeMedia && message.epoch === epoch)\n receiveCursor(message.cursor);\n break;\n case \"viewport\":\n if (fillHeight !== (message.fillHeight === true)) keyboardFitWidth = null;\n fillHeight = message.fillHeight === true;\n release();\n render();\n break;\n case \"answer\":\n if (message.epoch === epoch) void receiveAnswer(message);\n break;\n case \"iceConfig\":\n if (message.epoch === epoch) void receiveIceConfig(message);\n break;\n case \"ice\":\n if (message.epoch === epoch) void receiveIce(message);\n break;\n case \"fallback\":\n if (message.epoch === epoch && message.attemptId === attemptId)\n failRtc(\n message.capturePending === true ? \"capture-pending\" : \"host\",\n message.retry !== false,\n );\n break;\n case \"frame\": {\n if (\"cursor\" in message) receiveCursor(message.cursor);\n else resetCursor();\n const frameEpoch = epoch;\n image.onload = () => {\n if (epoch === frameEpoch) {\n scheduleBackgroundDraw();\n post({ type: \"framePresented\" });\n }\n };\n image.src = \"data:image/jpeg;base64,\" + message.jpeg;\n break;\n }\n case \"control\":\n release();\n control = message.enabled;\n if (!control) showKeyboard(false);\n pending = [];\n updateMouseButtons();\n render();\n break;\n case \"mode\":\n release();\n if (message.mode !== \"pointer\") followRest = null;\n settlePan();\n clearTimeout(touchCursorTimer);\n touchCursorVisible = false;\n mode = message.mode;\n render();\n break;\n case \"zoom\":\n stopEdgePan();\n if (\n !config.desktop ||\n !Number.isFinite(message.factor) ||\n message.factor <= 0\n )\n break;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = true;\n stopPanAnimation();\n const fitScale = Math.min(viewportWidth() / dw, viewportHeight() / dh);\n // Include actual size even when it lies outside the fit-relative range.\n desktopScale = Math.max(\n Math.min(fitScale, 1) * 0.1,\n Math.min(Math.max(5 * fitScale, 5), layout().scale * message.factor),\n );\n if (Math.abs(desktopScale - fitScale) < 1e-9) desktopScale = null;\n if (desktopScale === null) {\n fx = 0.5;\n fy = 0.5;\n manualViewMoved = false;\n }\n render();\n settlePan();\n break;\n case \"actualSize\":\n stopEdgePan();\n if (!config.desktop) break;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = true;\n stopPanAnimation();\n desktopScale = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"fit\":\n stopEdgePan();\n desktopScale = null;\n followRest = null;\n cursorNeedsEntry = true;\n manualViewMoved = false;\n stopPanAnimation();\n zoom = 1;\n fx = 0.5;\n fy = 0.5;\n render();\n break;\n case \"rightClick\":\n click(2);\n break;\n case \"events\":\n for (const e of message.events) queue(e);\n flush();\n break;\n case \"ack\":\n if (message.epoch === epoch && message.sequence === seq)\n sending = false;\n break;\n case \"stop\":\n nativeVideoActive = false;\n image.style.visibility = \"visible\";\n showKeyboard(false);\n control = false;\n release();\n pending = [];\n sending = false;\n epoch = null;\n closeRtc(message.preserveFrame === true);\n updateMouseButtons();\n render();\n break;\n }\n }\n // iOS can report equal left/right safe areas in both landscape directions.\n // Its interface angle distinguishes the notch side even on a 180-degree turn.\n const reportOrientation = () => {\n const angle =\n typeof window.orientation === \"number\"\n ? window.orientation\n : window.screen?.orientation?.angle;\n if (Number.isFinite(angle)) post({ type: \"orientation\", angle });\n };\n listen(window, \"orientationchange\", reportOrientation);\n if (window.screen?.orientation?.addEventListener)\n listen(window.screen.orientation, \"change\", reportOrientation);\n render();\n reportOrientation();\n post({ type: \"ready\" });\n return {\n receive: (message) => receive({ data: JSON.stringify(message) }),\n dispose: () => {\n release();\n epoch = null;\n closeRtc(false);\n if (bgDrawFrame !== null) cancelAnimationFrame(bgDrawFrame);\n bgDrawFrame = null;\n for (const cleanup of cleanups) cleanup();\n },\n };\n}\n";