Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 减少隐藏弹层键盘处理并修正性能诊断 (#5999)

Dash118a91911350
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index eb269fe65a..3925ba40bc 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1,4 +1,5 @@
import { useSessionHistorySearch } from '@/session/useSessionHistorySearch';
+import { useContentRecoveryDiagnostics } from '@/debug/useContentRecoveryDiagnostics';
import { modelNeedsReselection } from '@/session/modelReselection';
import { getCachedDeviceProviders } from '@/device-link/deviceProvidersCache';
import { MountOnFirstOpen } from '@/session/MountOnFirstOpen';
@@ -2332,12 +2333,7 @@ function SessionScreenContent() {
&& readAckSyncedKey === `${sessionId}:${connectionEpoch}`
&& !outboxRecoverySyncHeld
? 'recovered' : 'syncing';
- const recoveryStartedAtRef = useRef(Date.now());
- useEffect(() => {
- if (contentRecoveryState === 'syncing') recoveryStartedAtRef.current = Date.now();
- else console.debug('[device-link] content recovered', { elapsedMs: Date.now() - recoveryStartedAtRef.current });
- mobileDebugLog('debug', 'recovery', 'content recovery state', { state: contentRecoveryState, elapsedMs: Date.now() - recoveryStartedAtRef.current });
- }, [contentRecoveryState]);
+ useContentRecoveryDiagnostics(contentRecoveryState, `${deviceId}:${sessionId}`);
const showConnectionBanner = useShowConnectionBanner(
status,
bannerError,
diff --git a/apps/mobile/docs/simulator-debugging.md b/apps/mobile/docs/simulator-debugging.md
index f4f875eb9a..e23fb02a62 100644
--- a/apps/mobile/docs/simulator-debugging.md
+++ b/apps/mobile/docs/simulator-debugging.md
@@ -311,6 +311,15 @@ Release 也可在设置 → 调试 / 开发者打开 Debug 日志,复现后导
配置日志服务的构建还可手动上传筛选后的运行摘要(最近 7 天最多 500 条),成功自动复制编号。
上传摘要不包含详细 Debug 文件,需要详细现场时用导出或开发设备容器读取。
+滚动几何在交互状态不变时最多每 250 ms 记录一次;拖动结束、拖动/惯性/读历史/贴底
+状态变化仍立即记录。键盘日志只记录实际几何或显隐变化,关闭且已退出的弹层、不需要
+键盘避让的弹层不注册键盘监听。日志条数不能直接当作原生事件次数或监听器数量。
+`content recovery state` 的 `elapsedMs` / `foregroundElapsedMs` 只累计该任务页聚焦且
+App 为 active 的等待时间,`wallElapsedMs` 单独保留包含后台与离开页面的总时长。
+旧版本仅有 `elapsedMs`,其中可能包含后台时间,不能直接解读成用户等待或界面卡死。
+实现与回归见 `src/debug/useContentRecoveryDiagnostics.ts`、`scrollDebugSampler.ts`
+及相邻测试,键盘回归见 `src/__tests__/composerKeyboard.test.tsx`、`sheetKeyboardSubscription.test.tsx`。
+
### 从开发版 iPhone 读取历史 Debug 文件
手机与 Mac 配对、开启 Developer Mode 后,可通过 Xcode 设备管理窗口
diff --git a/apps/mobile/src/__tests__/composerKeyboard.test.tsx b/apps/mobile/src/__tests__/composerKeyboard.test.tsx
index 2cbd572734..b1831b88dc 100644
--- a/apps/mobile/src/__tests__/composerKeyboard.test.tsx
+++ b/apps/mobile/src/__tests__/composerKeyboard.test.tsx
@@ -82,8 +82,8 @@ vi.mock('@/hooks/useReduceMotion', () => ({
useReduceMotionEnabled: () => native.reducedMotion,
}));
-function Harness({ active = false, inset = 0 }) {
- const keyboard = useMobileKeyboardState();
+function Harness({ active = false, inset = 0, enabled = true }) {
+ const keyboard = useMobileKeyboardState(enabled);
useComposerCardTransition(active, keyboard);
return (
<ComposerKeyboardAvoidingView
@@ -155,6 +155,37 @@ afterEach(() => {
});
describe('composer keyboard geometry and motion', () => {
+ it('does no keyboard work while disabled and refreshes native geometry when enabled again', () => {
+ render({ enabled: false });
+ expect(native.listeners.size).toBe(0);
+ emit('keyboardDidShow');
+ expect(height()).toBe(0);
+ render();
+ expect(height()).toBe(300);
+ expect(native.schedule).not.toHaveBeenCalled();
+ expect(native.configure).not.toHaveBeenCalled();
+ render({ enabled: false });
+ expect([...native.listeners.values()].every(listeners => listeners.size === 0)).toBe(true);
+ emit('keyboardDidHide');
+ render();
+ expect(height()).toBe(0);
+ emit('keyboardWillShow');
+ expect(height()).toBe(300);
+ expect(native.schedule).toHaveBeenCalledOnce();
+ });
+
+ it('ignores a delayed cross-fade query after disabling and reopening', async () => {
+ let finish!: (crossFade: boolean) => void;
+ native.crossFade.mockImplementation(() => new Promise(resolve => { finish = resolve; }));
+ render();
+ emit('keyboardWillShow', keyboardEvent(0, 844));
+ render({ enabled: false });
+ emit('keyboardDidShow', keyboardEvent(444, 400));
+ render();
+ await act(async () => finish(true));
+ expect(height()).toBe(400);
+ });
+
it('updates both available height and iOS avoidance when an already-open keyboard changes height', () => {
render();
emit('keyboardWillShow');
diff --git a/apps/mobile/src/__tests__/messageFollowGesture.test.ts b/apps/mobile/src/__tests__/messageFollowGesture.test.ts
index 757f0c49b3..e7f3a75288 100644
--- a/apps/mobile/src/__tests__/messageFollowGesture.test.ts
+++ b/apps/mobile/src/__tests__/messageFollowGesture.test.ts
@@ -6,6 +6,7 @@ import * as scrollModel from '@/session/messageScroll';
import { createMobileTailFollower } from '@/session/messageTailFollower';
import { RichContentRuntime } from '@/session/richContentRuntime';
import { mobileDebugEnabled, mobileDebugLog, setMobileDebugSink } from '@/debug/mobileDebugLog';
+import { createScrollDebugSampler } from '@/debug/scrollDebugSampler';
// Execute the production callbacks without mounting Markdown/media/native views. Unlike source
// assertions, this harness interleaves touch, native scroll, content-size, timers and frame delivery.
@@ -83,6 +84,7 @@ function harness(richContent: RichContentRuntime | null = new RichContentRuntime
getCurrentHistoryTopOffsetAdjustment: vi.fn(() => 0),
resolveMobileMessageHistoryAnchorOffset: vi.fn(() => 600),
...scrollModel, ...state, createMobileTailFollower, mobileDebugEnabled, mobileDebugLog,
+ sampleScrollDebug: createScrollDebugSampler(),
initialRevealProgress: { setValue: vi.fn() }, setListRevealed: vi.fn(),
listRef: ref({
getState: () => ({ scrollLength: 800, scroll: state.scrollMetricsRef.current.offsetY,
diff --git a/apps/mobile/src/__tests__/sheetKeyboardSubscription.test.tsx b/apps/mobile/src/__tests__/sheetKeyboardSubscription.test.tsx
new file mode 100644
index 0000000000..153ef1643c
--- /dev/null
+++ b/apps/mobile/src/__tests__/sheetKeyboardSubscription.test.tsx
@@ -0,0 +1,79 @@
+// @vitest-environment jsdom
+import { act, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { SheetModal } from '@/session/SheetModal';
+
+const native = vi.hoisted(() => ({
+ platform: { OS: 'ios' },
+ keyboard: vi.fn((enabled: boolean) => ({ height: enabled ? 300 : 0 })),
+ finish: undefined as undefined | ((result: { finished: boolean }) => void),
+}));
+vi.mock('react-native', () => {
+ const View = ({ children }: { children?: ReactNode }) => <div>{children}</div>;
+ return {
+ View, KeyboardAvoidingView: View, Pressable: View,
+ Modal: ({ visible, children }: { visible: boolean; children: ReactNode }) => visible ? <div>{children}</div> : null,
+ Platform: native.platform,
+ useWindowDimensions: () => ({ width: 390, height: 844 }),
+ StyleSheet: { absoluteFill: {} },
+ Easing: { bezier: () => 0 },
+ Animated: {
+ View,
+ Value: class { interpolate() { return 0; } },
+ timing: () => ({ start: (finish: typeof native.finish) => { native.finish = finish; } }),
+ },
+ };
+});
+vi.mock('@/session/useMobileKeyboardState', () => ({ useMobileKeyboardState: native.keyboard }));
+vi.mock('@/session/NativeBottomSheet', () => ({ NativeBottomSheet: () => null }));
+vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => false }));
+vi.mock('@/theme', () => ({ useThemedStyles: () => ({}) }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/platform/AdaptiveWindowContext', () => ({
+ useAdaptiveWindow: () => ({ height: 844, width: 390, regions: [], barEdge: 'none', insets: { left: 0, right: 0 } }),
+ PaneViewportProvider: ({ children }: { children: ReactNode }) => children,
+ FloatingSheetContext: { Provider: ({ children }: { children: ReactNode }) => children },
+}));
+vi.mock('@/platform/modalLayout', () => ({ modalLayout: () => ({ region: { x: 0, y: 0, width: 390, height: 844 }, floating: false }) }));
+vi.mock('@/platform/gestureHandler', () => ({ GestureHandlerRootView: ({ children }: { children: ReactNode }) => children }));
+vi.mock('@/session/BlurBackdrop', () => ({ BlurBackdrop: () => null }));
+
+let root: Root;
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ native.platform.OS = 'ios';
+ native.keyboard.mockClear();
+ native.finish = undefined;
+ root = createRoot(document.createElement('div'));
+});
+afterEach(() => act(() => root.unmount()));
+function render(visible: boolean, keyboardAvoiding = true) {
+ act(() => root.render(<SheetModal visible={visible} keyboardAvoiding={keyboardAvoiding}
+ onRequestClose={() => {}} onBackdropPress={() => {}}>content</SheetModal>));
+}
+function enabled() { return native.keyboard.mock.calls.at(-1)?.[0]; }
+
+it('subscribes only for an avoiding sheet, through closing and rapid reopening', () => {
+ render(false);
+ expect(enabled()).toBe(false);
+ render(true);
+ expect(enabled()).toBe(true);
+ render(false);
+ expect(enabled()).toBe(true);
+ const oldFinish = native.finish;
+ render(true);
+ act(() => oldFinish?.({ finished: true }));
+ expect(enabled()).toBe(true);
+ render(false);
+ act(() => native.finish?.({ finished: true }));
+ expect(enabled()).toBe(false);
+});
+
+it('never subscribes action-only sheets or Android native-resize sheets', () => {
+ render(true, false);
+ expect(enabled()).toBe(false);
+ native.platform.OS = 'android';
+ render(true);
+ expect(enabled()).toBe(false);
+});
diff --git a/apps/mobile/src/debug/scrollDebugSampler.test.ts b/apps/mobile/src/debug/scrollDebugSampler.test.ts
new file mode 100644
index 0000000000..aeb0a7872a
--- /dev/null
+++ b/apps/mobile/src/debug/scrollDebugSampler.test.ts
@@ -0,0 +1,17 @@
+import { expect, it } from 'vitest';
+import { createScrollDebugSampler } from './scrollDebugSampler';
+
+it('bounds continuous frame logs but always keeps interaction changes and final drag samples', () => {
+ let now = 0;
+ const sample = createScrollDebugSampler(() => now);
+ let count = 0;
+ for (now = 0; now < 1000; now += 5) if (sample(1, false)) count++;
+ expect(count).toBe(4);
+ now = 999;
+ expect(sample(2, false)).toBe(true);
+ expect(sample(2, true)).toBe(true);
+ expect(sample(2, false)).toBe(false);
+ now += 250;
+ expect(sample(2, false)).toBe(true);
+ expect(createScrollDebugSampler(() => now)(2, false)).toBe(true);
+});
diff --git a/apps/mobile/src/debug/scrollDebugSampler.ts b/apps/mobile/src/debug/scrollDebugSampler.ts
new file mode 100644
index 0000000000..3e61d6a994
--- /dev/null
+++ b/apps/mobile/src/debug/scrollDebugSampler.ts
@@ -0,0 +1,12 @@
+/** Per-list sampling: retain interaction changes/final drag samples, at most 4 Hz otherwise. */
+export function createScrollDebugSampler(now = () => performance.now()) {
+ let lastAt = -Infinity;
+ let lastFlags = -1;
+ return (flags: number, finalSample: boolean): boolean => {
+ const at = now();
+ if (!finalSample && flags === lastFlags && at - lastAt < 250) return false;
+ lastAt = at;
+ lastFlags = flags;
+ return true;
+ };
+}
diff --git a/apps/mobile/src/debug/useContentRecoveryDiagnostics.test.tsx b/apps/mobile/src/debug/useContentRecoveryDiagnostics.test.tsx
new file mode 100644
index 0000000000..6fe2c91de3
--- /dev/null
+++ b/apps/mobile/src/debug/useContentRecoveryDiagnostics.test.tsx
@@ -0,0 +1,113 @@
+// @vitest-environment jsdom
+import { act, useEffect } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { useContentRecoveryDiagnostics } from './useContentRecoveryDiagnostics';
+
+const native = vi.hoisted(() => ({
+ focused: true,
+ currentState: 'active',
+ listeners: new Set<(state: string) => void>(),
+ log: vi.fn(),
+}));
+vi.mock('react-native', () => ({ AppState: {
+ get currentState() { return native.currentState; },
+ addEventListener: (_: string, listener: (state: string) => void) => {
+ native.listeners.add(listener);
+ return { remove: () => native.listeners.delete(listener) };
+ },
+} }));
+vi.mock('expo-router', () => ({
+ useFocusEffect: (callback: () => () => void) => {
+ useEffect(() => native.focused ? callback() : undefined, [callback, native.focused]);
+ },
+}));
+vi.mock('./mobileDebugLog', () => ({ mobileDebugLog: native.log }));
+
+let now = 0;
+let root: Root;
+let container: HTMLDivElement;
+function Harness({ state, identity }: { state: 'syncing' | 'recovered'; identity: string }) {
+ useContentRecoveryDiagnostics(state, identity);
+ return null;
+}
+function render(state: 'syncing' | 'recovered', identity = 'a') {
+ act(() => root.render(<Harness state={state} identity={identity} />));
+}
+function lifecycle(state: string) {
+ act(() => {
+ native.currentState = state;
+ for (const listener of native.listeners) listener(state);
+ });
+}
+function last() { return native.log.mock.calls.at(-1)?.[3]; }
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ now = 0;
+ vi.spyOn(performance, 'now').mockImplementation(() => now);
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ native.focused = true;
+ native.currentState = 'active';
+ native.log.mockClear();
+ native.listeners.clear();
+ container = document.createElement('div');
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ expect(native.listeners.size).toBe(0);
+ vi.restoreAllMocks();
+});
+
+it('excludes inactive/background time, including repeated lifecycle events', () => {
+ render('syncing');
+ now = 1000;
+ lifecycle('inactive');
+ now = 1200;
+ lifecycle('background');
+ now = 601000;
+ lifecycle('active');
+ now = 602000;
+ lifecycle('active');
+ now = 603000;
+ render('recovered');
+ expect(last()).toEqual({ state: 'recovered', elapsedMs: 3000, foregroundElapsedMs: 3000, wallElapsedMs: 603000 });
+});
+
+it('excludes time on another page and starts a fresh measurement for the next recovery', () => {
+ render('syncing');
+ now = 1000;
+ native.focused = false;
+ render('syncing');
+ expect(native.listeners.size).toBe(0);
+ now = 10000;
+ native.focused = true;
+ render('syncing');
+ now = 12000;
+ render('recovered');
+ expect(last().elapsedMs).toBe(3000);
+ render('syncing');
+ now = 12500;
+ render('recovered');
+ expect(last().elapsedMs).toBe(500);
+});
+
+it('does not attribute another task or an initially cached page to a completed recovery', () => {
+ render('recovered');
+ expect(native.log).not.toHaveBeenCalled();
+ render('syncing');
+ now = 10000;
+ render('syncing', 'b');
+ now = 11000;
+ render('recovered', 'b');
+ expect(last().elapsedMs).toBe(1000);
+ expect(JSON.stringify(native.log.mock.calls)).not.toContain('identity');
+});
+
+it('records zero visible wait when recovery begins and ends entirely in the background', () => {
+ lifecycle('background');
+ render('syncing');
+ now = 10000;
+ render('recovered');
+ expect(last()).toEqual({ state: 'recovered', elapsedMs: 0, foregroundElapsedMs: 0, wallElapsedMs: 10000 });
+});
diff --git a/apps/mobile/src/debug/useContentRecoveryDiagnostics.ts b/apps/mobile/src/debug/useContentRecoveryDiagnostics.ts
new file mode 100644
index 0000000000..44228e30ab
--- /dev/null
+++ b/apps/mobile/src/debug/useContentRecoveryDiagnostics.ts
@@ -0,0 +1,59 @@
+import { useCallback, useEffect, useRef } from 'react';
+import { AppState } from 'react-native';
+import { useFocusEffect } from 'expo-router';
+import { mobileDebugLog } from './mobileDebugLog';
+
+type RecoveryState = 'syncing' | 'recovered';
+
+/** Measure only the time the user can see this page; keep total time separately. */
+export function useContentRecoveryDiagnostics(state: RecoveryState, identity: string): void {
+ const active = useRef(false);
+ const pending = useRef<{
+ identity: string;
+ wallStartedAt: number;
+ activeStartedAt: number | null;
+ foregroundMs: number;
+ } | null>(null);
+ const setActive = useCallback((next: boolean) => {
+ active.current = next;
+ const current = pending.current;
+ if (!current) return;
+ const now = performance.now();
+ if (current.activeStartedAt !== null) {
+ current.foregroundMs += Math.max(0, now - current.activeStartedAt);
+ }
+ current.activeStartedAt = next ? now : null;
+ }, []);
+
+ useEffect(() => {
+ if (pending.current?.identity !== identity) pending.current = null;
+ if (state === 'syncing') {
+ pending.current = {
+ identity, wallStartedAt: Date.now(), foregroundMs: 0,
+ activeStartedAt: active.current ? performance.now() : null,
+ };
+ mobileDebugLog('debug', 'recovery', 'content recovery state', {
+ state, elapsedMs: 0, foregroundElapsedMs: 0, wallElapsedMs: 0,
+ });
+ } else if (pending.current) {
+ setActive(active.current);
+ const current = pending.current;
+ mobileDebugLog('debug', 'recovery', 'content recovery state', {
+ state,
+ elapsedMs: current.foregroundMs,
+ foregroundElapsedMs: current.foregroundMs,
+ wallElapsedMs: Math.max(0, Date.now() - current.wallStartedAt),
+ });
+ pending.current = null;
+ }
+ }, [identity, setActive, state]);
+
+ useFocusEffect(useCallback(() => {
+ setActive(AppState.currentState === 'active');
+ const subscription = AppState.addEventListener('change', next => setActive(next === 'active'));
+ return () => {
+ setActive(false);
+ subscription.remove();
+ };
+ }, [setActive]));
+}
diff --git a/apps/mobile/src/platform/ModalContentArea.tsx b/apps/mobile/src/platform/ModalContentArea.tsx
index f1e3945eeb..354c1f467e 100644
--- a/apps/mobile/src/platform/ModalContentArea.tsx
+++ b/apps/mobile/src/platform/ModalContentArea.tsx
@@ -8,7 +8,7 @@ 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 keyboard = useMobileKeyboardState(Platform.OS !== 'android');
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 }}>
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 742c94ee18..1946686750 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -22,6 +22,7 @@ import { collectBotMessageTimeGroups, formatBotMessageGroupTime } from '@cindy/m
import { CompanionMessageCard } from '@/session/CompanionMessageCard';
import { CompanionEntering } from '@/session/CompanionEntering';
import { mobileDebugEnabled, mobileDebugLog } from '@/debug/mobileDebugLog';
+import { createScrollDebugSampler } from '@/debug/scrollDebugSampler';
import { errorText, resolvedUrlKind } from '@/debug/fileDiagnostics';
import { createContext, Fragment, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type Dispatch, type ReactNode, type SetStateAction } from 'react';
import { useTranslation } from 'react-i18next';
@@ -944,6 +945,7 @@ export function MessageRenderer({
// LegendList updates getState().scroll optimistically before an imperative native scroll lands.
// Only native ScrollView scroll/end-drag samples advance this ack source for Android prepend.
const nativeScrollEventSequenceRef = useRef(0);
+ const [sampleScrollDebug] = useState(createScrollDebugSampler);
const scrollMetricsRef = useRef<MessageScrollMetrics>({
contentHeight: 0,
offsetY: 0,
@@ -2254,7 +2256,9 @@ export function MessageRenderer({
}
// Preloads need real geometry, but must not publish bookmarks or trigger user work.
if (!historyActiveRef.current) return;
- if (mobileDebugEnabled()) mobileDebugLog('debug', 'scroll', 'list scroll', {
+ const debugFlags = Number(isDragSample) | (Number(isMomentumScrollingRef.current) << 1)
+ | (Number(readingOlderRef.current) << 2) | (Number(nearBottomRef.current) << 3);
+ if (mobileDebugEnabled() && sampleScrollDebug(debugFlags, isFinalDragSample)) mobileDebugLog('debug', 'scroll', 'list scroll', {
...metrics, dragging: isDragSample, momentum: isMomentumScrollingRef.current,
readingOlder: readingOlderRef.current, nearBottom: nearBottomRef.current,
});
diff --git a/apps/mobile/src/session/SessionDetailsNative.ios.tsx b/apps/mobile/src/session/SessionDetailsNative.ios.tsx
index 9fe0268a20..ad9d2a4994 100644
--- a/apps/mobile/src/session/SessionDetailsNative.ios.tsx
+++ b/apps/mobile/src/session/SessionDetailsNative.ios.tsx
@@ -111,7 +111,7 @@ export function SessionDetailsNative({
*/
function useKeyboardOverlap(enabled: boolean) {
const ref = useRef<View>(null);
- const keyboard = useMobileKeyboardState();
+ const keyboard = useMobileKeyboardState(enabled);
const { height: windowHeight } = useWindowDimensions();
const [bottom, setBottom] = useState<number | null>(null);
const measure = useCallback(() => {
diff --git a/apps/mobile/src/session/SheetModal.tsx b/apps/mobile/src/session/SheetModal.tsx
index 1c6fe9e39d..a820c29f96 100644
--- a/apps/mobile/src/session/SheetModal.tsx
+++ b/apps/mobile/src/session/SheetModal.tsx
@@ -78,10 +78,6 @@ function CompatibleSheetModal({
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。
// sheet 是重浮层:入场 motionDuration.enter / 退场 exit(§14.4);减弱动态效果(含未查询到的
@@ -92,6 +88,12 @@ function CompatibleSheetModal({
outMs: reduceMotion === false ? motionDuration.exit : 0,
onClosed,
});
+ // Closed sheets (including each message's action menu) must not subscribe.
+ // Keep avoidance through the exit animation; Android uses native resize.
+ const keyboard = useMobileKeyboardState(keyboardAvoiding && (visible || mounted) && Platform.OS !== 'android');
+ const { region, floating } = modalLayout(geometry, keyboard.height);
+ const displaced = floating || geometry.regions.length > 0 || geometry.barEdge !== 'none'
+ || geometry.insets.left > 0 || geometry.insets.right > 0;
// 快速重开的高度残留窗口:拖拽下拉 dismiss 会让 SheetSurface 内部 heightAnim 停在低位;
// 若用户在 ~120ms 淡出播完前重新打开,children 一直没卸载,面板会卡在残高。
diff --git a/apps/mobile/src/session/useMobileKeyboardState.ts b/apps/mobile/src/session/useMobileKeyboardState.ts
index 8201f2d8c2..b9b58271e3 100644
--- a/apps/mobile/src/session/useMobileKeyboardState.ts
+++ b/apps/mobile/src/session/useMobileKeyboardState.ts
@@ -27,30 +27,31 @@ export interface MobileKeyboardState {
* iOS 的输入卡片、消息区域和避让容器共用这份坐标与动画,不再让 KAV
* 另行监听 show/hide 并覆盖动画。Android 保留 KAV 的 did 事件避让。
*/
-export function useMobileKeyboardState(): MobileKeyboardState {
+export function useMobileKeyboardState(enabled = true): MobileKeyboardState {
const viewport = useWindowDimensions();
- const [state, setState] = useState(() => {
- // Web 的 Keyboard shim 没有原生几何快照 API,沿用零占位初值。
- if (Platform.OS === 'web') return { shown: false, frame: null };
- const frame = Keyboard.metrics() ?? null;
- return {
- shown: Keyboard.isVisible(),
- // 已开键盘时导航进来,也先排除 cross-fade 的 screenY=0 特例。
- frame: Platform.OS === 'ios' && frame?.screenY === 0 ? null : frame,
- };
- });
+ const [state, setState] = useState(() => readKeyboardSnapshot(enabled));
const snapshot = useRef(state);
const transition = useRef<MobileKeyboardState['transition']['current']>(null);
useLayoutEffect(() => {
+ transition.current = null;
+ if (!enabled) return;
+ // A hidden consumer missed native events. Reconcile before paint without
+ // replaying an animation, including reopening while the keyboard is up.
+ const current = readKeyboardSnapshot(true);
+ if (snapshot.current.shown !== current.shown || !sameKeyboardFrame(snapshot.current.frame, current.frame)) {
+ setState(current);
+ }
+ snapshot.current = current;
let disposed = false;
- let shown = snapshot.current.shown;
+ let shown = current.shown;
let latestEvent: KeyboardEvent | null = null;
const publish = (event: KeyboardEvent, frame: KeyboardMetrics | null) => {
// cross-fade 查询晚于 hide / 下一次 frame 返回时,不得恢复旧键盘占位。
if (disposed || latestEvent !== event) return;
const previous = snapshot.current;
if (previous.shown === shown && sameKeyboardFrame(previous.frame, frame)) return;
+ mobileDebugLog('debug', 'keyboard', 'frame received', { shown, durationMs: event.duration, easing: event.easing, frame: event.endCoordinates });
const next = { shown, frame };
snapshot.current = next;
transition.current = { event, startedAt: Date.now() };
@@ -65,7 +66,6 @@ export function useMobileKeyboardState(): MobileKeyboardState {
setState(next);
};
const update = (event: KeyboardEvent) => {
- mobileDebugLog('debug', 'keyboard', 'frame received', { shown, durationMs: event.duration, easing: event.easing, frame: event.endCoordinates });
latestEvent = event;
if (Platform.OS === 'ios' && shown && event.endCoordinates.screenY === 0) {
// 保留 RN KAV 的系统交叉淡化兼容:此时 screenY=0 不是全屏遮挡。
@@ -115,9 +115,9 @@ export function useMobileKeyboardState(): MobileKeyboardState {
disposed = true;
for (const subscription of subscriptions) subscription.remove();
};
- }, []);
+ }, [enabled]);
- const frame = state.shown ? state.frame : null;
+ const frame = enabled && state.shown ? state.frame : null;
const height = !frame ? 0 : Platform.OS === 'ios'
? isDockedKeyboard({ x: frame.screenX, y: frame.screenY, ...frame }, viewport.width)
&& frame.screenY + frame.height >= viewport.height
@@ -127,6 +127,17 @@ export function useMobileKeyboardState(): MobileKeyboardState {
return { height, visible: height > 0, transition };
}
+function readKeyboardSnapshot(enabled: boolean) {
+ // Web's Keyboard shim has no native snapshot APIs.
+ if (!enabled || Platform.OS === 'web') return { shown: false, frame: null };
+ const frame = Keyboard.metrics() ?? null;
+ return {
+ shown: Keyboard.isVisible(),
+ // Avoid a full-screen inset while the cross-fade preference is queried.
+ frame: Platform.OS === 'ios' && frame?.screenY === 0 ? null : frame,
+ };
+}
+
function sameKeyboardFrame(a: KeyboardMetrics | null, b: KeyboardMetrics | null): boolean {
return a === b || (a !== null && b !== null
&& a.screenX === b.screenX && a.screenY === b.screenY