Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): Android 首页抽屉退场期返回键与搜索聚焦收口
MagicLizib89978364190
diff --git a/apps/mobile/src/__tests__/homeChromeDrawer.test.tsx b/apps/mobile/src/__tests__/homeChromeDrawer.test.tsxnew file mode 100644index 0000000000..da4eae1508--- /dev/null+++ b/apps/mobile/src/__tests__/homeChromeDrawer.test.tsx@@ -0,0 +1,238 @@+// @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 { HomeChromeDrawer } from '@/session/HomeChromeDrawer';+import { CompanionNavigationDrawer } from '@/session/CompanionNavigationDrawer';++/**+ * HomeChromeDrawer 行为测试:Android 独立窗口(Modal)的挂载、返回键接管、+ * 退场生命周期与关闭后动作的执行时机。此前只有源码字符串断言,挂载/返回键/+ * 关闭后导航都无回归覆盖(伙伴页面测试还把整个抽屉 mock 掉了)。+ */+const h = vi.hoisted(() => ({+ timing: [] as Array<(finished: boolean) => void>,+ emit: vi.fn(),+ modal: null as Record<string, any> | null,+ reduceMotion: false,+ platform: {+ OS: 'android' as 'android' | 'ios',+ select: (values: Record<string, unknown>) => values.android ?? values.default,+ },+ auth: {+ user: null as null | Record<string, unknown>,+ accountGeneration: 1,+ logout: vi.fn(),+ beginAddAccount: vi.fn(),+ },+}));++vi.mock('react-native', async () => {+ const { createElement } = await import('react');+ type Props = {+ children?: ReactNode;+ testID?: string;+ onPress?: () => void;+ accessibilityState?: { busy?: boolean; disabled?: boolean };+ };+ const View = ({ children, testID, onPress }: Props) =>+ createElement('div', { 'data-testid': testID, onClick: onPress }, children);+ return {+ View,+ Pressable: View,+ Image: () => null,+ AccessibilityInfo: { setAccessibilityFocus: vi.fn() },+ Alert: { alert: vi.fn() },+ DeviceEventEmitter: { emit: h.emit },+ findNodeHandle: () => null,+ Modal: ({ children, ...props }: Props & Record<string, unknown>) => {+ h.modal = props;+ return createElement('div', { 'data-testid': 'rn.modal' }, children);+ },+ Platform: h.platform,+ StyleSheet: {+ create: (value: unknown) => value,+ hairlineWidth: 1,+ absoluteFill: {},+ },+ useWindowDimensions: () => ({ width: 390, height: 844 }),+ };+});++vi.mock('react-native-reanimated', async () => {+ const { useRef } = await import('react');+ const { View } = await import('react-native');+ return {+ default: { View },+ useSharedValue: (value: number) => useRef({ value }).current,+ useAnimatedStyle: () => ({}),+ Easing: { bezier: () => undefined },+ runOnJS: (fn: unknown) => fn,+ // 退场完成回调由测试手动投递,用来模拟退出动画结束。+ withTiming: (value: number, _config?: unknown, done?: (finished: boolean) => void) => {+ if (done) h.timing.push(done);+ return value;+ },+ };+});++vi.mock('react-native-screens', async () => {+ const { createElement } = await import('react');+ return {+ FullWindowOverlay: ({ children }: { children?: ReactNode }) =>+ createElement('div', { 'data-testid': 'rn.fullWindowOverlay' }, children),+ };+});++vi.mock('react-native-safe-area-context', () => ({+ useSafeAreaInsets: () => ({ left: 0, top: 0, bottom: 0 }),+}));++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++vi.mock('lucide-react-native', () => ({+ LogOut: () => null, Monitor: () => null, Search: () => null, Settings: () => null, UsersRound: () => null,+}));++vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).View }));++vi.mock('@/theme', () => ({ useThemedStyles: () => ({}), useTheme: () => ({ colors: {} }) }));++vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => h.reduceMotion }));++vi.mock('@/platform/gestureHandler', () => {+ const chain = {+ enabled: () => chain, activeOffsetX: () => chain, failOffsetX: () => chain,+ failOffsetY: () => chain, onUpdate: () => chain, onEnd: () => chain,+ };+ return {+ Gesture: { Pan: () => chain },+ GestureDetector: ({ children }: { children?: ReactNode }) => children,+ GestureHandlerRootView: ({ children }: { children?: ReactNode }) => children,+ };+});++vi.mock('@/session/HomeModeSwitch', () => ({ HomeModeSwitch: () => null }));++vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));+vi.mock('@/utils/useGuardedPush', () => ({ useGuardedPush: () => vi.fn() }));+vi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: String }));+vi.mock('@/session/AccountSwitcherSheet', () => ({ AccountSwitcherSheet: () => null }));+vi.mock('@/session/remoteSessionStore', () => ({+ remoteSessionStore: { subscribe: () => () => {}, getSessions: () => [], isSessionRunning: () => false },+}));+vi.mock('@/session/useTeammateNavigation', () => ({ useTeammateNavigation: () => ({ chooseMode: vi.fn() }) }));++const drawerProps = (over: Partial<Parameters<typeof HomeChromeDrawer>[0]> = {}) => ({+ onClose: vi.fn(),+ onClosed: vi.fn(),+ onOpenSearch: vi.fn(),+ onOpenAccounts: vi.fn(),+ onOpenDevices: vi.fn(),+ onOpenSettings: vi.fn(),+ onLogout: vi.fn(),+ open: true,+ user: null,+ ...over,+});++const finishTiming = async () => {+ const pending = h.timing.splice(0);+ await act(async () => pending.forEach((done) => done(true)));+};++describe('Android home drawer window and close lifecycle', () => {+ let root: Root;+ let container: HTMLDivElement;+ beforeEach(() => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ h.modal = null;+ h.timing.splice(0);+ h.reduceMotion = false;+ h.platform.OS = 'android';+ vi.clearAllMocks();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ });+ afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ });++ it('mounts the drawer in its own transparent window instead of an in-route overlay', async () => {+ await act(async () => root.render(<HomeChromeDrawer {...drawerProps()} />));+ // Android 走独立 Dialog 窗口:整窗透明、状态栏/导航栏可穿透,抽屉自己播动画。+ expect(h.modal).toMatchObject({+ animationType: 'none',+ navigationBarTranslucent: true,+ statusBarTranslucent: true,+ transparent: true,+ visible: true,+ });+ expect(typeof h.modal!.onRequestClose).toBe('function');+ expect(container.querySelector('[data-testid="rn.modal"]')).not.toBeNull();+ expect(container.querySelector('[data-testid="home.chromeDrawer"]')).not.toBeNull();+ });++ it('keeps iOS on the FullWindowOverlay window with no Modal', async () => {+ h.platform.OS = 'ios';+ await act(async () => root.render(<HomeChromeDrawer {...drawerProps()} />));+ expect(h.modal).toBeNull();+ expect(container.querySelector('[data-testid="rn.fullWindowOverlay"]')).not.toBeNull();+ expect(container.querySelector('[data-testid="home.chromeDrawer"]')).not.toBeNull();+ });++ it('turns Android back into close while open, but forwards it to the app during the exit animation', async () => {+ const props = drawerProps();+ await act(async () => root.render(<HomeChromeDrawer {...props} />));+ await act(async () => h.modal!.onRequestClose());+ expect(props.onClose).toHaveBeenCalledOnce();+ expect(h.emit).not.toHaveBeenCalled();+ // 关闭后退场动画期间:back 属于底层页面,不得再调 onClose(会清掉调用方+ // 记下的待执行动作),而是把事件补发回 app 的返回键链。+ await act(async () => root.render(<HomeChromeDrawer {...props} open={false} />));+ await act(async () => h.modal!.onRequestClose());+ expect(props.onClose).toHaveBeenCalledOnce();+ expect(h.emit).toHaveBeenCalledExactlyOnceWith('hardwareBackPress');+ expect(props.onClosed).not.toHaveBeenCalled();+ });++ it('keeps the drawer mounted until the exit animation ends, then reports onClosed after unmount', async () => {+ const props = drawerProps();+ await act(async () => root.render(<HomeChromeDrawer {...props} />));+ await act(async () => root.render(<HomeChromeDrawer {...props} open={false} />));+ // 退场中:窗口还在播离场动画,不能提前卸载,也不提前回调 onClosed。+ expect(h.modal).not.toBeNull();+ expect(container.querySelector('[data-testid="home.chromeDrawer"]')).not.toBeNull();+ expect(props.onClosed).not.toHaveBeenCalled();+ await finishTiming();+ expect(container.querySelector('[data-testid="rn.modal"]')).toBeNull();+ expect(container.querySelector('[data-testid="home.chromeDrawer"]')).toBeNull();+ // onClosed 只在窗口真正卸载后触发一次:调用方的延后动作以此为信号执行。+ expect(props.onClosed).toHaveBeenCalledOnce();+ });++ it('opens search through the deferred action and survives a back press during the exit animation', async () => {+ const onSearch = vi.fn();+ const onClose = vi.fn();+ const host = (open: boolean) => (+ <CompanionNavigationDrawer open={open} onClose={onClose} onSearch={onSearch} />+ );+ await act(async () => root.render(host(true)));+ await act(async () => {+ (container.querySelector('[data-testid="home.chromeDrawer.search"]') as HTMLElement).click();+ });+ // 动作延后到抽屉完全关闭后执行,关闭请求先回到调用方。+ expect(onSearch).not.toHaveBeenCalled();+ expect(onClose).toHaveBeenCalledOnce();+ await act(async () => root.render(host(false)));+ // 退场期间的返回键不得清掉待执行动作。+ await act(async () => h.modal!.onRequestClose());+ expect(h.emit).toHaveBeenCalledExactlyOnceWith('hardwareBackPress');+ expect(onSearch).not.toHaveBeenCalled();+ await finishTiming();+ expect(onSearch).toHaveBeenCalledOnce();+ expect(container.querySelector('[data-testid="home.chromeDrawer"]')).toBeNull();+ });+});diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.tsindex 5fc2750d32..aa61a36d39 100644--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts@@ -796,4 +796,11 @@ describe('home menu presentation', () => {expect(drawer).toContain('navigationBarTranslucent');expect(drawer).not.toContain('BackHandler');});++ it('mounts the drawer search only after the Android dialog fully unmounts', () => {+ const home = readSource('src/session/HomeSurface.tsx');+ // 退场期间 Dialog 仍占着窗口焦点,搜索框 autoFocus 挂早了首次聚焦和软键盘+ // 会丢;搜索动作和其它菜单动作一样延后到 onClosed 再执行。+ expect(home).toContain('pendingMenuActionRef.current = () => setSearchOpen(true);');+ });});diff --git a/apps/mobile/src/session/HomeChromeDrawer.tsx b/apps/mobile/src/session/HomeChromeDrawer.tsxindex d6fd78fe20..4aab1e8a9a 100644--- a/apps/mobile/src/session/HomeChromeDrawer.tsx+++ b/apps/mobile/src/session/HomeChromeDrawer.tsx@@ -14,6 +14,7 @@ import { LogOut, Monitor, Search, Settings, UsersRound } from 'lucide-react-natiimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {AccessibilityInfo,+ DeviceEventEmitter,findNodeHandle,Image,Modal,@@ -193,10 +194,18 @@ export function HomeChromeDrawer({reduceMotion,]);- // Android 返回键落在抽屉的 Dialog 窗口上。只有打开态才转成关闭:退场动画期间- // 调用方可能已记下关闭后的动作,再调 onClose 会把它清掉。+ // Android 返回键落在抽屉的 Dialog 窗口上:+ // - 打开态:转成关闭。+ // - 退场动画期间(open 已 false、Dialog 还没卸载)这颗键属于底层页面:不能调+ // onClose——调用方记下的待执行动作会被它清掉;RN Modal 会吞掉原生 back,+ // 这里把 hardwareBackPress 补发回 app 的返回键监听链,等价于抽屉已卸载时+ // 的按下(无人消费时走系统默认返回)。const requestClose = useCallback(() => {- if (openRef.current) onClose();+ if (openRef.current) {+ onClose();+ return;+ }+ DeviceEventEmitter.emit("hardwareBackPress");}, [onClose]);const closeFromGesture = useCallback(() => onClose(), [onClose]);diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsxindex 09dbfe8fc7..76fdd3f233 100644--- a/apps/mobile/src/session/HomeSurface.tsx+++ b/apps/mobile/src/session/HomeSurface.tsx@@ -3014,7 +3014,9 @@ function HomeScreenContent({ active = true, onModeChange, width, onDismiss, newShandleChromeMenuClosed();}}onOpenSearch={() => {- setSearchOpen(true);+ // 搜索框 autoFocus 要等菜单窗口完全卸载(onClosed)后再挂载:Android 的+ // Dialog 还在退场时底层 Activity 没有窗口焦点,首次聚焦和软键盘请求会丢。+ pendingMenuActionRef.current = () => setSearchOpen(true);setChromeMenuCloseInstant(false);setChromeMenuOpen(false);}}