Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 流式输出时让自动滚底避让手势 (#3964)
Dash1eceafcc8960
diff --git a/apps/mobile/src/__tests__/messageFollowGesture.test.ts b/apps/mobile/src/__tests__/messageFollowGesture.test.tsnew file mode 100644index 0000000000..a4dca43e30--- /dev/null+++ b/apps/mobile/src/__tests__/messageFollowGesture.test.ts@@ -0,0 +1,471 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import * as scrollModel from '@/session/messageScroll';++// 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.+const source = ts.createSourceFile('MessageRenderer.tsx', readFileSync(+ resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8',+), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const renderer = source.statements.find((node): node is ts.FunctionDeclaration => (+ ts.isFunctionDeclaration(node) && node.name?.text === 'MessageRenderer'+));+const callbackNames = [+ 'markProgrammaticScroll', 'clearProgrammaticScroll', 'markMobileMvcpSettle',+ 'isUserControllingScroll', 'scrollToEndProgrammatically', 'runStickToLatestVerify',+ 'scrollToOffsetProgrammatically', 'scrollToIndexProgrammatically',+ 'scrollToBottom', 'handleScroll', 'handleHistoryTouchStart', 'maybeTriggerHistoryTouch',+ 'handleHistoryTouchMove', 'handleHistoryTouchEnd', 'handleHistoryTouchCancel',+ 'handleScrollBeginDrag', 'handleScrollEndDrag', 'handleMomentumScrollBegin',+ 'handleMomentumScrollEnd', 'handleContentSize',+] as const;+type CallbackName = typeof callbackNames[number];+const declarations = renderer!.body!.statements.filter((node) => (+ ts.isVariableStatement(node) && node.declarationList.declarations.some((declaration) => (+ ts.isIdentifier(declaration.name) && callbackNames.includes(declaration.name.text as CallbackName)+ ))+));+const constants = source.statements.filter((node) => (+ ts.isVariableStatement(node) && node.declarationList.declarations.some((declaration) => (+ ts.isIdentifier(declaration.name) && /^MOBILE_PROGRAMMATIC_.*_MS$/.test(declaration.name.text)+ ))+));+const compiled = ts.transpileModule([+ ...constants.map((node) => node.getText(source)),+ ...declarations.map((node) => node.getText(source)),+ `return { ${callbackNames.join(', ')} };`,+].join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;++function harness() {+ const ref = <T>(current: T) => ({ current });+ const state = {+ nearBottomRef: ref(true), readingOlderRef: ref(false),+ isDraggingRef: ref(false), isMomentumScrollingRef: ref(false),+ historyTouchStartYRef: ref<number | null>(null), historyTouchTriggeredRef: ref(false),+ dragStartOffsetYRef: ref<number | null>(null), userScrollForOlderRef: ref(false),+ lastAutoLoadEarlierKeyRef: ref<string | null>(null),+ programmaticScrollGenerationRef: ref(0), programmaticScrollTimerRef: ref<unknown>(null),+ programmaticScrollInFlightRef: ref(false), programmaticAnimatedScrollInFlightRef: ref(false),+ programmaticScrollSettleAtRef: ref(0), mvcpSettleAtRef: ref(0),+ followVerifyGenerationRef: ref(0), followVerifyFrameRef: ref<unknown>(null),+ followVerifyTimerRef: ref<unknown>(null), followEndPinRecoveryTimerRef: ref<unknown>(null),+ followEndPinStateRef: ref(scrollModel.createMobileFollowEndPinState()),+ historyPrependTransactionRef: ref(null), nativeScrollEventSequenceRef: ref(0),+ shareSelectionActiveRef: ref(false),+ scrollMetricsRef: ref({ contentHeight: 2000, offsetY: 1200, viewportHeight: 800 }),+ };+ const scrollToEnd = vi.fn(() => {+ const metrics = state.scrollMetricsRef.current;+ metrics.offsetY = metrics.contentHeight - metrics.viewportHeight;+ });+ const environment = {+ ...scrollModel, ...state,+ listRef: ref({ scrollToEnd, scrollToOffset: vi.fn(), scrollToIndex: vi.fn() }),+ bottomOverlayHeight: undefined,+ useCallback: (callback: unknown) => callback,+ attemptAutoLoadEarlier: vi.fn(), handoffHistoryPrependToUser: vi.fn(),+ scheduleHistoryPrependUserHandoffSettle: vi.fn(), scheduleQueuedLoadEarlierFlush: vi.fn(),+ refreshPreviousUserTarget: vi.fn(), scheduleStickyShareCheck: vi.fn(),+ scheduleHistoryAnchorRestore: vi.fn(), restoreHistoryAnchorOnce: vi.fn(),+ cancelHistoryPrependTransaction: vi.fn(),+ setIsAwayFromBottom: vi.fn(), setHasNewMessages: vi.fn(), setPreviousUserTarget: vi.fn(),+ };+ const callbacks = new Function(...Object.keys(environment), compiled)(+ ...Object.values(environment),+ ) as Record<CallbackName, (...args: unknown[]) => void>;+ const scrollEvent = (offsetY: number) => ({ nativeEvent: {+ contentSize: { height: state.scrollMetricsRef.current.contentHeight },+ contentOffset: { y: offsetY }, layoutMeasurement: { height: 800 },+ } });+ return {+ ...callbacks, state, scrollToEnd, scrollEvent,+ handleScrollEndDrag: (event = scrollEvent(state.scrollMetricsRef.current.offsetY)) => (+ callbacks.handleScrollEndDrag(event)+ ),+ };+}+const touch = (pageY = 400) => ({ nativeEvent: { pageY } });+const settle = () => vi.advanceTimersByTime(4000);++beforeEach(() => {+ vi.useFakeTimers();+ vi.stubGlobal('requestAnimationFrame', (callback: () => void) => setTimeout(callback, 16));+ vi.stubGlobal('cancelAnimationFrame', (timer: ReturnType<typeof setTimeout>) => clearTimeout(timer));+});+afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); vi.restoreAllMocks(); });++describe('streaming follow yields to the reader', () => {+ it.each([1196, 1180].flatMap((offset) => ['missing', 'before-verify', 'after-verify'].map((end) => ({ offset, end }))))(+ 'releases a cancelled drag at $offset with end event $end', ({ offset, end }) => {+ const h = harness();+ h.handleHistoryTouchStart(touch());+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(end === 'missing' ? offset : 1196));+ h.handleContentSize(400, 2500);+ h.handleHistoryTouchCancel();+ h.handleHistoryTouchCancel();+ if (end === 'after-verify') {+ settle();+ expect(h.scrollToEnd).toHaveBeenCalledTimes(1);+ h.scrollToEnd.mockClear();+ }+ if (end !== 'missing') h.handleScrollEndDrag(h.scrollEvent(offset));+ settle();+ expect(h.state.nearBottomRef.current).toBe(offset === 1196);+ expect(h.scrollToEnd).toHaveBeenCalledTimes(offset === 1196 ? 1 : 0);+ expect(h.state.isDraggingRef.current).toBe(false);+ if (end !== 'missing') expect(h.state.dragStartOffsetYRef.current).toBeNull();+ },+ );++ it('consumes a late final sample even after a no-op cancellation verification', () => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleHistoryTouchCancel();+ settle();+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ h.handleScrollEndDrag(h.scrollEvent(1180));+ h.handleContentSize(400, 2500);+ settle();+ expect(h.state.nearBottomRef.current).toBe(false);+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ });++ it('ignores layout corrections after cancel but consumes the final drag sample', () => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1196));+ h.handleContentSize(400, 2500);+ h.handleHistoryTouchCancel();+ h.handleScroll(h.scrollEvent(900));+ expect(h.state.nearBottomRef.current).toBe(true);+ h.handleScrollEndDrag(h.scrollEvent(1180));+ settle();+ expect(h.state.nearBottomRef.current).toBe(false);+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ });++ it.each(['end', 'index'])('discards the cancelled drag sample when explicit %s takes over', (target) => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1196));+ h.handleHistoryTouchCancel();+ if (target === 'end') h.scrollToBottom();+ else h.scrollToIndexProgrammatically(10, 0.45);+ h.handleScrollEndDrag(h.scrollEvent(1180));+ expect(h.state.nearBottomRef.current).toBe(true);+ if (target === 'end') expect(h.scrollToEnd).toHaveBeenCalledExactlyOnceWith({ animated: true });+ });++ it('keeps the cancelled drag sample through automatic offset compensation', () => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleHistoryTouchCancel();+ h.scrollToOffsetProgrammatically(900, false);+ h.handleScroll(h.scrollEvent(900));+ expect(h.state.nearBottomRef.current).toBe(true);+ h.handleScrollEndDrag(h.scrollEvent(1180));+ expect(h.state.nearBottomRef.current).toBe(false);+ });++ it('can return to the bottom in the final drag sample after cancellation', () => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1180));+ h.handleHistoryTouchCancel();+ h.handleScrollEndDrag(h.scrollEvent(1200));+ expect(h.state.nearBottomRef.current).toBe(true);+ h.handleContentSize(400, 2500);+ settle();+ expect(h.scrollToEnd).toHaveBeenCalledTimes(1);+ });++ it('allows native scrolling to take ownership after Android cancels the JS touch', () => {+ const h = harness();+ h.handleHistoryTouchStart(touch());+ h.handleHistoryTouchCancel();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleContentSize(400, 2500);+ settle();+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ h.handleScroll(h.scrollEvent(1180));+ h.handleScrollEndDrag();+ settle();+ expect(h.state.nearBottomRef.current).toBe(false);+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ });++ it('waits for independently reported momentum after cancelling a touch', () => {+ const h = harness();+ h.handleHistoryTouchStart(touch());+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleMomentumScrollBegin();+ h.handleHistoryTouchCancel();+ h.handleContentSize(400, 2500);+ settle();+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ h.handleMomentumScrollEnd();+ settle();+ expect(h.scrollToEnd).toHaveBeenCalledTimes(1);+ });++ it('keeps an active drag when another finger touches the list', () => {+ const h = harness();+ h.handleHistoryTouchStart(touch());+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1196));+ h.handleHistoryTouchStart(touch());+ h.handleContentSize(400, 2500);+ settle();+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ h.handleScroll(h.scrollEvent(1180));+ h.handleHistoryTouchEnd(touch());+ h.handleScrollEndDrag();+ settle();+ expect(h.state.nearBottomRef.current).toBe(false);+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ });++ it.each([false, true])('preserves an explicit animated jump when touchEnd precedes onPress: %s', (releaseFirst) => {+ const h = harness();+ h.state.nearBottomRef.current = false;+ h.state.scrollMetricsRef.current.offsetY = 300;+ // Native animation has not landed yet; command dispatch does not acknowledge its offset.+ h.scrollToEnd.mockImplementation(() => {});+ h.handleHistoryTouchStart(touch());+ if (releaseFirst) h.handleHistoryTouchEnd(touch());+ h.scrollToBottom();+ expect(h.scrollToEnd).toHaveBeenCalledExactlyOnceWith({ animated: true });+ if (!releaseFirst) h.handleHistoryTouchEnd(touch());+ h.handleContentSize(400, 2200);+ const remaining = h.state.programmaticScrollSettleAtRef.current - Date.now();+ vi.advanceTimersByTime(remaining - 1);+ // Releasing the button and receiving new content must not truncate the animation.+ expect(h.scrollToEnd).toHaveBeenCalledExactlyOnceWith({ animated: true });+ h.handleScroll(h.scrollEvent(1400));+ settle();+ expect(h.scrollToEnd).toHaveBeenCalledExactlyOnceWith({ animated: true });+ });++ it('lets a new upward drag interrupt verification after an explicit animated jump', () => {+ const h = harness();+ h.scrollToBottom();+ h.handleHistoryTouchStart(touch());+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1180));+ h.handleContentSize(400, 2200);+ h.handleHistoryTouchEnd(touch(420));+ h.handleScrollEndDrag();+ settle();+ expect(h.state.nearBottomRef.current).toBe(false);+ expect(h.scrollToEnd).toHaveBeenCalledExactlyOnceWith({ animated: true });+ });++ it('allows an upward drag to unpin while content grows before the first scroll event', () => {+ const h = harness();+ h.handleHistoryTouchStart(touch());+ h.handleContentSize(400, 2040);+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleContentSize(400, 2080);+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ h.handleScroll(h.scrollEvent(1180));+ expect(h.state.nearBottomRef.current).toBe(false);+ h.handleHistoryTouchEnd(touch(420));+ h.handleScrollEndDrag();+ h.handleMomentumScrollBegin();+ h.handleContentSize(400, 2200);+ h.handleMomentumScrollEnd();+ settle();+ h.handleContentSize(400, 2240);+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ h.scrollToBottom();+ expect(h.scrollToEnd).toHaveBeenLastCalledWith({ animated: true });+ });++ it.each(['handleHistoryTouchEnd', 'handleHistoryTouchCancel'] as const)(+ 'catches up after %s when output ended during a stationary touch', (release) => {+ const h = harness();+ h.handleHistoryTouchStart(touch());+ h.handleContentSize(400, 2300);+ settle();+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ h[release](touch());+ settle();+ expect(h.scrollToEnd).toHaveBeenCalledTimes(1);+ expect(h.state.scrollMetricsRef.current.offsetY).toBe(1500);+ },+ );++ it.each([1196, 1194, 1192, 1190])('applies the cumulative drag threshold to a trailing offset of %i after large growth', (trailingOffset) => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1196));+ h.handleContentSize(400, 2500);+ h.handleScrollEndDrag(h.scrollEvent(trailingOffset));+ // End-drag carries the final offset even when the matching onScroll is delivered later.+ h.handleScroll(h.scrollEvent(trailingOffset));+ expect(h.state.nearBottomRef.current).toBe(trailingOffset >= 1192);+ settle();+ if (trailingOffset < 1192) {+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ return;+ }+ expect(h.scrollToEnd).toHaveBeenCalledTimes(1);+ h.handleScroll(h.scrollEvent(1700));+ expect(h.state.nearBottomRef.current).toBe(true);+ h.handleContentSize(400, 2540);+ expect(h.scrollToEnd).toHaveBeenCalledTimes(2);+ });++ it.each([false, true])('unpins a trailing drag across momentum-start ordering: %s', (momentumFirst) => {+ const h = harness();+ h.handleHistoryTouchStart(touch());+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1196));+ h.handleHistoryTouchEnd(touch());+ h.handleScrollEndDrag(h.scrollEvent(1190));+ if (momentumFirst) h.handleMomentumScrollBegin();+ h.handleScroll(h.scrollEvent(1190));+ if (!momentumFirst) h.handleMomentumScrollBegin();+ h.handleMomentumScrollEnd();+ h.handleContentSize(400, 2500);+ settle();+ expect(h.state.nearBottomRef.current).toBe(false);+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ });++ it('retires a completed drag after a no-op release verification', () => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1200));+ h.handleScrollEndDrag();+ settle();+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ h.handleScroll(h.scrollEvent(1190));+ h.handleContentSize(400, 2500);+ settle();+ expect(h.state.nearBottomRef.current).toBe(true);+ expect(h.scrollToEnd).toHaveBeenCalledTimes(1);+ });++ it.each([1180, 900])('preserves a short drag through a post-release layout correction to %i', (offset) => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1196));+ h.handleContentSize(400, 2500);+ h.handleScrollEndDrag(h.scrollEvent(1196));+ // MVCP may correct the visible anchor before the release verifier runs.+ h.handleScroll(h.scrollEvent(offset));+ expect(h.state.nearBottomRef.current).toBe(true);+ settle();+ expect(h.scrollToEnd).toHaveBeenCalledExactlyOnceWith({ animated: false });+ expect(h.state.scrollMetricsRef.current.offsetY).toBe(1700);+ });++ it('can unpin again after returning to the bottom within the same drag', () => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1180));+ expect(h.state.nearBottomRef.current).toBe(false);+ h.handleScroll(h.scrollEvent(1200));+ expect(h.state.nearBottomRef.current).toBe(true);+ h.handleScroll(h.scrollEvent(1180));+ expect(h.state.nearBottomRef.current).toBe(false);+ });++ it('forgets the previous drag when an explicit command owns native scroll events', () => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1196));+ h.handleScrollEndDrag();+ h.scrollToBottom();+ h.handleScroll(h.scrollEvent(1190));+ expect(h.state.nearBottomRef.current).toBe(true);+ });++ it('measures a new drag from its own starting offset', () => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1196));+ h.handleScrollEndDrag();+ h.handleHistoryTouchStart(touch());+ h.handleScrollBeginDrag(h.scrollEvent(1196));+ h.handleScroll(h.scrollEvent(1190));+ expect(h.state.nearBottomRef.current).toBe(true);+ h.handleScroll(h.scrollEvent(1186));+ expect(h.state.nearBottomRef.current).toBe(false);+ });++ it('pauses already queued verification and waits for momentum to end before catching up', () => {+ const h = harness();+ h.state.scrollMetricsRef.current.contentHeight = 2200;+ h.runStickToLatestVerify();+ h.handleHistoryTouchStart(touch());+ settle();+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ h.handleHistoryTouchEnd(touch());+ h.handleMomentumScrollBegin();+ h.handleContentSize(400, 2300);+ settle();+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ h.handleMomentumScrollEnd();+ settle();+ expect(h.scrollToEnd).toHaveBeenCalledTimes(1);+ });++ it('keeps the drag dead zone authoritative when the tail grows beyond the distance threshold', () => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1196));+ h.handleContentSize(400, 2500);+ h.handleScroll(h.scrollEvent(1194));+ expect(h.state.nearBottomRef.current).toBe(true);+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ h.handleScroll(h.scrollEvent(1190));+ expect(h.state.nearBottomRef.current).toBe(false);+ h.handleScrollEndDrag();+ settle();+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ });++ it('still unpins a real momentum fling after a short drag', () => {+ const h = harness();+ h.handleScrollBeginDrag(h.scrollEvent(1200));+ h.handleScroll(h.scrollEvent(1196));+ h.handleScrollEndDrag();+ h.handleMomentumScrollBegin();+ h.handleScroll(h.scrollEvent(900));+ expect(h.state.nearBottomRef.current).toBe(false);+ h.handleContentSize(400, 2500);+ h.handleMomentumScrollEnd();+ settle();+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ });++ it('blocks a previously scheduled circuit recovery while the finger owns the viewport', () => {+ const h = harness();+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ for (let i = 0; i < 12; i++) h.handleContentSize(400, i % 2 ? 2100 : 2200);+ expect(h.state.followEndPinRecoveryTimerRef.current).not.toBeNull();+ h.scrollToEnd.mockClear();+ h.handleHistoryTouchStart(touch());+ settle();+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ h.handleHistoryTouchEnd(touch());+ settle();+ expect(h.state.scrollMetricsRef.current.offsetY).toBe(1300);+ });++ it('does not resume tail follow while a history page owns the anchor', () => {+ const h = harness();+ h.state.readingOlderRef.current = true;+ h.state.nearBottomRef.current = false;+ h.handleHistoryTouchStart(touch());+ h.handleContentSize(400, 2500);+ h.handleHistoryTouchEnd(touch());+ settle();+ expect(h.scrollToEnd).not.toHaveBeenCalled();+ });+});diff --git a/apps/mobile/src/__tests__/messageListVirtualization.test.ts b/apps/mobile/src/__tests__/messageListVirtualization.test.tsindex 156407dcda..e550dea2f7 100644--- a/apps/mobile/src/__tests__/messageListVirtualization.test.ts+++ b/apps/mobile/src/__tests__/messageListVirtualization.test.ts@@ -207,7 +207,7 @@ describe('mobile message list container', () => {)).toContain('return;');expect(scrollSource).toContain('shouldPreserveMobileHistoryBrowseIntent({');expect(scrollSource).toContain('historyBrowseIntent: userScrollForOlderRef.current');- expect(scrollSource).toContain('userControllingScroll: isDraggingRef.current');+ expect(scrollSource).toContain('userControllingScroll: isDragSample');// 深链 / 搜索定位本身就是明确的历史浏览意图,后续近顶自动补页无需再拖一下。const focusEffectStart = source.indexOf('// 深链/搜索:滚到指定消息');const focusEffectEnd = source.indexOf('// 新消息红点', focusEffectStart);@@ -295,6 +295,7 @@ describe('mobile message list container', () => {expect(effectEnd).toBeGreaterThan(effectStart);expect(clearHistoryIntentAt).toBeGreaterThan(-1);expect(verifyAt).toBeGreaterThan(clearHistoryIntentAt);+ expect(effectSource).toContain("scrollToEndProgrammatically(true, 'explicit');");});it('verifies a manual jump-to-latest after issuing the animated scroll', () => {@@ -302,7 +303,7 @@ describe('mobile message list container', () => {const callbackStart = source.indexOf('const scrollToBottom = useCallback');const callbackEnd = source.indexOf('const jumpToPreviousUserMessage', callbackStart);const callbackSource = source.slice(callbackStart, callbackEnd);- const scrollAt = callbackSource.indexOf('scrollToEndProgrammatically(true);');+ const scrollAt = callbackSource.indexOf("scrollToEndProgrammatically(true, 'explicit');");const verifyAt = callbackSource.indexOf('runStickToLatestVerify();');expect(callbackStart).toBeGreaterThan(-1);diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 48ec0ea8f4..82e5af088b 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -816,7 +816,7 @@ export function MessageRenderer({const previousFollowLatestRequestKeyRef = useRef(followLatestRequestKey);const previousItemKeysRef = useRef<readonly string[]>([]);// LegendList updates getState().scroll optimistically before an imperative native scroll lands.- // This sequence advances only from ScrollView onScroll and is the ack source for Android prepend.+ // Only native ScrollView scroll/end-drag samples advance this ack source for Android prepend.const nativeScrollEventSequenceRef = useRef(0);const scrollMetricsRef = useRef<MessageScrollMetrics>({contentHeight: 0,@@ -1013,10 +1013,25 @@ export function MessageRenderer({);}, []);- const scrollToEndProgrammatically = useCallback((animated: boolean) => {+ const isUserControllingScroll = useCallback(() => (+ historyTouchStartYRef.current !== null+ || isDraggingRef.current+ || isMomentumScrollingRef.current+ ), []);++ const scrollToEndProgrammatically = useCallback((+ animated: boolean,+ intent: 'follow' | 'explicit' = 'follow',+ ) => {+ // Automatic growth/recovery/anchor retries yield to gestures. Explicit jump/send actions+ // own their scroll even if onPress arrives before the ancestor's touchEnd clears the finger.+ if (intent === 'follow' && isUserControllingScroll()) return;+ // Only a new explicit destination supersedes a pending final drag sample. Automatic+ // follow and offset compensation must leave that sample available to endDrag.+ if (intent === 'explicit') dragStartOffsetYRef.current = null;markProgrammaticScroll(animated);void listRef.current?.scrollToEnd({ animated });- }, [markProgrammaticScroll]);+ }, [isUserControllingScroll, markProgrammaticScroll]);const scrollToOffsetProgrammatically = useCallback((offset: number, animated: boolean) => {markProgrammaticScroll(animated);@@ -1024,6 +1039,7 @@ export function MessageRenderer({}, [markProgrammaticScroll]);const scrollToIndexProgrammatically = useCallback((index: number, viewPosition: number) => {+ dragStartOffsetYRef.current = null;markProgrammaticScroll(true);void listRef.current?.scrollToIndex({ animated: true, index, viewPosition });}, [markProgrammaticScroll]);@@ -1182,7 +1198,7 @@ export function MessageRenderer({// LegendList moves getState().scroll to an imperative target before the native ScrollView// receives it. Using that optimistic value here used to self-confirm the correction in two// frames, release MVCP, and leave Android briefly rendering the target cell window at the- // old physical offset. Only onScroll-backed metrics can prove the viewport actually moved.+ // old physical offset. Only native scroll/end-drag metrics prove the viewport actually moved.const currentOffset = scrollMetricsRef.current.offsetY;const pendingCorrection = currentTransaction.pendingCorrection;const correctionStatus = pendingCorrection@@ -1354,6 +1370,12 @@ export function MessageRenderer({}const step = (attempts: number, waitRounds: number) => {if (followVerifyGenerationRef.current !== generation) return;+ // Release handlers restart this bounded verifier, including when the stream ends while+ // a finger is held still. Do not poll or issue corrections during a gesture.+ if (isUserControllingScroll()) {+ followVerifyFrameRef.current = null;+ return;+ }// 贴底跟随意图只认 nearBottomRef:死区内轻触 / 小幅拖动并没有真实解除贴底,// 不能让 userScrollForOlderRef 这根“允许加载历史”的手势记录把校验永久关掉。// 真正上移超过死区时 shouldUnpinMobileFollowOnDrag 会把 nearBottomRef 翻 false,@@ -1407,7 +1429,7 @@ export function MessageRenderer({} else {start();}- }, [scrollToEndProgrammatically]);+ }, [isUserControllingScroll, scrollToEndProgrammatically]);// DEV-only:把列表控制器 + 滚动 metrics 暴露给性能 harness(临时,profiling/回归测量用)。useEffect(() => {@@ -1797,7 +1819,7 @@ export function MessageRenderer({setIsAwayFromBottom(false);setHasNewMessages(false);setPreviousUserTarget(null);- scrollToEndProgrammatically(true);+ scrollToEndProgrammatically(true, 'explicit');runStickToLatestVerify();}, [cancelHistoryPrependTransaction, runStickToLatestVerify, scrollToEndProgrammatically]);@@ -1839,7 +1861,7 @@ export function MessageRenderer({}setHasNewMessages(false);setIsAwayFromBottom(false);- scrollToEndProgrammatically(true);+ scrollToEndProgrammatically(true, 'explicit');runStickToLatestVerify();}, [cancelHistoryPrependTransaction,@@ -2080,7 +2102,14 @@ export function MessageRenderer({// 「恢复跟随」走 resolveMobileNearBottomOnScroll:距离 + 明确向下方向。读历史// (readingOlderRef)期间禁止方向性恢复——load-earlier prepend 的 mVCP 补偿会产生// 程序化向下增量,短会话里会被误判成「用户滑回底部」。- const handleScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {+ const handleScroll = useCallback((+ event: NativeSyntheticEvent<NativeScrollEvent>,+ isFinalDragSample = false,+ ) => {+ // 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+ || (isFinalDragSample && dragStartOffsetYRef.current !== null);nativeScrollEventSequenceRef.current += 1;const metrics = {contentHeight: event.nativeEvent.contentSize.height,@@ -2091,7 +2120,7 @@ export function MessageRenderer({scrollMetricsRef.current = metrics;if (readingOlderRef.current) {if (- isDraggingRef.current+ isDragSample|| isMomentumScrollingRef.current|| historyTouchTriggeredRef.current) {@@ -2109,7 +2138,7 @@ export function MessageRenderer({if (nearBottomRef.current&& shouldUnpinMobileFollowOnDrag({- dragging: isDraggingRef.current,+ dragging: isDragSample,dragStartOffsetY: dragStartOffsetYRef.current,metrics,})@@ -2118,14 +2147,20 @@ export function MessageRenderer({setIsAwayFromBottom(true);} else {const preserveHistoryBrowseIntent = shouldPreserveMobileHistoryBrowseIntent({- historyBrowseIntent: userScrollForOlderRef.current,- userControllingScroll: isDraggingRef.current+ // Only preserve an actual unpin. A dead-zone drag also enables pagination, but its+ // final native event must not turn a temporary follow suspension into an unpin.+ historyBrowseIntent: userScrollForOlderRef.current && !nearBottomRef.current,+ userControllingScroll: isDragSample|| isMomentumScrollingRef.current|| historyTouchStartYRef.current !== null,});+ // Dragging (including end-drag's final native metrics) owns the cumulative dead zone.+ // Outside a drag, layout/MVCP corrections cannot prove user intent. Preserve follow;+ // actual momentum retains the existing direction/distance fallback.+ const preserveFollowIntent = nearBottomRef.current && !isMomentumScrollingRef.current;const nearBottom = preserveHistoryBrowseIntent? false- : resolveMobileNearBottomOnScroll({+ : preserveFollowIntent || resolveMobileNearBottomOnScroll({wasNearBottom: nearBottomRef.current,metrics,programmaticScrollInFlight: programmaticScrollInFlightRef.current,@@ -2163,10 +2198,11 @@ export function MessageRenderer({isMomentumScrollingRef.current = false;historyTouchStartYRef.current = event.nativeEvent.pageY;historyTouchTriggeredRef.current = false;+ clearProgrammaticScroll();// Touch-start only means the finger holds the ScrollView; it is not a viewport takeover yet.// maybeTriggerHistoryTouch / onScrollBeginDrag report the real move once it clears the dead zone.handoffHistoryPrependToUser(false);- }, [handoffHistoryPrependToUser]);+ }, [clearProgrammaticScroll, handoffHistoryPrependToUser]);const maybeTriggerHistoryTouch = useCallback((pageY: number) => {const startY = historyTouchStartYRef.current;@@ -2194,18 +2230,24 @@ export function MessageRenderer({historyTouchTriggeredRef.current = false;scheduleHistoryPrependUserHandoffSettle();scheduleQueuedLoadEarlierFlush();+ runStickToLatestVerify();}, [maybeTriggerHistoryTouch,+ runStickToLatestVerify,scheduleHistoryPrependUserHandoffSettle,scheduleQueuedLoadEarlierFlush,]);const handleHistoryTouchCancel = useCallback(() => {+ // An interrupted drag may never emit endDrag. Android's normal native takeover emits+ // touchCancel before beginDrag, so that subsequent beginDrag establishes its own ownership.+ isDraggingRef.current = false;historyTouchStartYRef.current = null;historyTouchTriggeredRef.current = false;scheduleHistoryPrependUserHandoffSettle();scheduleQueuedLoadEarlierFlush();- }, [scheduleHistoryPrependUserHandoffSettle, scheduleQueuedLoadEarlierFlush]);+ runStickToLatestVerify();+ }, [runStickToLatestVerify, scheduleHistoryPrependUserHandoffSettle, scheduleQueuedLoadEarlierFlush]);// 用户开始拖动 → 标记「上翻意图」,放行自动加载更早(onScrollBeginDrag 仅用户手势触发,// 程序化 scrollToEnd 不会触发,故不会误置);同时记录拖动起点 offset,供@@ -2230,19 +2272,23 @@ export function MessageRenderer({// 翻完 refs 立即补一次电平评估:列表已顶死时(Android 无 bounce 尤甚)这次拖动不产生// offset 变化,不会有 onScroll / onStartReached,ref 写入也不驱动 effect——没有这一刀,// 「失败后停在顶部再拖一下重试」的信号会整体丢失(review P2)。- }, [attemptAutoLoadEarlier, handoffHistoryPrependToUser]);+ }, [attemptAutoLoadEarlier, clearProgrammaticScroll, handoffHistoryPrependToUser]);- // 拖动结束(手指离开,可能进入惯性滚动)→ 关闭拖动追踪。惯性阶段的上滑不需要再判- // 解除:上滑手势的拖动段必然已越过死区完成解除;下滑回底的恢复由 scroll 方向判定接手。- const handleScrollEndDrag = useCallback(() => {+ // 原生 endDrag 自带最终位置,不依赖最后一帧 onScroll 的投递顺序。+ // 先结算本次拖动再清理起点,避免把后续 MVCP 布局校正误判成用户上翻。+ const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {+ handleScroll(event, true);isDraggingRef.current = false;dragStartOffsetYRef.current = null;refreshPreviousUserTarget();// Wait one frame so Android can report whether this drag transitioned into momentum.scheduleHistoryPrependUserHandoffSettle();scheduleQueuedLoadEarlierFlush();+ runStickToLatestVerify();}, [+ handleScroll,refreshPreviousUserTarget,+ runStickToLatestVerify,scheduleHistoryPrependUserHandoffSettle,scheduleQueuedLoadEarlierFlush,]);@@ -2256,8 +2302,10 @@ export function MessageRenderer({refreshPreviousUserTarget();scheduleHistoryPrependUserHandoffSettle();scheduleQueuedLoadEarlierFlush();+ runStickToLatestVerify();}, [refreshPreviousUserTarget,+ runStickToLatestVerify,scheduleHistoryPrependUserHandoffSettle,scheduleQueuedLoadEarlierFlush,]);@@ -2322,6 +2370,7 @@ export function MessageRenderer({}return;}+ if (isUserControllingScroll()) return;if (nearBottomRef.current && viewportHeight > 0 && height > viewportHeight) {// Animated jump/send follow owns the viewport until its settle window closes. Content// growth during that animation only reschedules the verifier; a false-animated pin here@@ -2366,6 +2415,7 @@ export function MessageRenderer({}}}, [+ isUserControllingScroll,markMobileMvcpSettle,restoreHistoryAnchorOnce,runStickToLatestVerify,