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): 统一尾部滚动控制并恢复越界位置 (#3974)

Dash608cd5b801f0
diff --git a/apps/mobile/src/__tests__/messageFollowGesture.test.ts b/apps/mobile/src/__tests__/messageFollowGesture.test.ts
index a4dca43e30..87b68b9855 100644
--- a/apps/mobile/src/__tests__/messageFollowGesture.test.ts
+++ b/apps/mobile/src/__tests__/messageFollowGesture.test.ts
@@ -3,6 +3,7 @@ import { resolve } from 'node:path';
import ts from 'typescript';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as scrollModel from '@/session/messageScroll';
+import { createMobileTailFollower } from '@/session/messageTailFollower';
// 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.
@@ -14,7 +15,7 @@ const renderer = source.statements.find((node): node is ts.FunctionDeclaration =
));
const callbackNames = [
'markProgrammaticScroll', 'clearProgrammaticScroll', 'markMobileMvcpSettle',
- 'isUserControllingScroll', 'scrollToEndProgrammatically', 'runStickToLatestVerify',
+ 'isUserControllingScroll', 'getTailFollower', 'scrollToEndProgrammatically', 'runStickToLatestVerify',
'scrollToOffsetProgrammatically', 'scrollToIndexProgrammatically',
'scrollToBottom', 'handleScroll', 'handleHistoryTouchStart', 'maybeTriggerHistoryTouch',
'handleHistoryTouchMove', 'handleHistoryTouchEnd', 'handleHistoryTouchCancel',
@@ -49,21 +50,25 @@ function harness() {
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()),
+ tailFollowerRef: ref(null),
historyPrependTransactionRef: ref(null), nativeScrollEventSequenceRef: ref(0),
shareSelectionActiveRef: ref(false),
scrollMetricsRef: ref({ contentHeight: 2000, offsetY: 1200, viewportHeight: 800 }),
};
- const scrollToEnd = vi.fn(() => {
+ const tailScroll = vi.fn((_options: { animated: boolean }) => {
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,
+ ...scrollModel, ...state, createMobileTailFollower,
+ listRef: ref({
+ scrollToEnd: tailScroll,
+ scrollToIndex: vi.fn(),
+ scrollToOffset: ({ offset, animated }: { offset: number; animated: boolean }) => {
+ tailScroll({ animated });
+ state.scrollMetricsRef.current.offsetY = offset;
+ },
+ }), bottomOverlayHeight: undefined,
useCallback: (callback: unknown) => callback,
attemptAutoLoadEarlier: vi.fn(), handoffHistoryPrependToUser: vi.fn(),
scheduleHistoryPrependUserHandoffSettle: vi.fn(), scheduleQueuedLoadEarlierFlush: vi.fn(),
@@ -80,7 +85,7 @@ function harness() {
contentOffset: { y: offsetY }, layoutMeasurement: { height: 800 },
} });
return {
- ...callbacks, state, scrollToEnd, scrollEvent,
+ ...callbacks, state, tailScroll, scrollEvent,
handleScrollEndDrag: (event = scrollEvent(state.scrollMetricsRef.current.offsetY)) => (
callbacks.handleScrollEndDrag(event)
),
@@ -108,13 +113,13 @@ describe('streaming follow yields to the reader', () => {
h.handleHistoryTouchCancel();
if (end === 'after-verify') {
settle();
- expect(h.scrollToEnd).toHaveBeenCalledTimes(1);
- h.scrollToEnd.mockClear();
+ expect(h.tailScroll).toHaveBeenCalledTimes(1);
+ h.tailScroll.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.tailScroll).toHaveBeenCalledTimes(offset === 1196 ? 1 : 0);
expect(h.state.isDraggingRef.current).toBe(false);
if (end !== 'missing') expect(h.state.dragStartOffsetYRef.current).toBeNull();
},
@@ -125,12 +130,12 @@ describe('streaming follow yields to the reader', () => {
h.handleScrollBeginDrag(h.scrollEvent(1200));
h.handleHistoryTouchCancel();
settle();
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
h.handleScrollEndDrag(h.scrollEvent(1180));
h.handleContentSize(400, 2500);
settle();
expect(h.state.nearBottomRef.current).toBe(false);
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
});
it('ignores layout corrections after cancel but consumes the final drag sample', () => {
@@ -144,7 +149,7 @@ describe('streaming follow yields to the reader', () => {
h.handleScrollEndDrag(h.scrollEvent(1180));
settle();
expect(h.state.nearBottomRef.current).toBe(false);
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
});
it.each(['end', 'index'])('discards the cancelled drag sample when explicit %s takes over', (target) => {
@@ -156,7 +161,7 @@ describe('streaming follow yields to the reader', () => {
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 });
+ if (target === 'end') expect(h.tailScroll).toHaveBeenCalledExactlyOnceWith({ animated: true });
});
it('keeps the cancelled drag sample through automatic offset compensation', () => {
@@ -179,7 +184,7 @@ describe('streaming follow yields to the reader', () => {
expect(h.state.nearBottomRef.current).toBe(true);
h.handleContentSize(400, 2500);
settle();
- expect(h.scrollToEnd).toHaveBeenCalledTimes(1);
+ expect(h.tailScroll).toHaveBeenCalledTimes(1);
});
it('allows native scrolling to take ownership after Android cancels the JS touch', () => {
@@ -189,12 +194,12 @@ describe('streaming follow yields to the reader', () => {
h.handleScrollBeginDrag(h.scrollEvent(1200));
h.handleContentSize(400, 2500);
settle();
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
h.handleScroll(h.scrollEvent(1180));
h.handleScrollEndDrag();
settle();
expect(h.state.nearBottomRef.current).toBe(false);
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
});
it('waits for independently reported momentum after cancelling a touch', () => {
@@ -205,10 +210,10 @@ describe('streaming follow yields to the reader', () => {
h.handleHistoryTouchCancel();
h.handleContentSize(400, 2500);
settle();
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
h.handleMomentumScrollEnd();
settle();
- expect(h.scrollToEnd).toHaveBeenCalledTimes(1);
+ expect(h.tailScroll).toHaveBeenCalledTimes(1);
});
it('keeps an active drag when another finger touches the list', () => {
@@ -219,13 +224,13 @@ describe('streaming follow yields to the reader', () => {
h.handleHistoryTouchStart(touch());
h.handleContentSize(400, 2500);
settle();
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).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();
+ expect(h.tailScroll).not.toHaveBeenCalled();
});
it.each([false, true])('preserves an explicit animated jump when touchEnd precedes onPress: %s', (releaseFirst) => {
@@ -233,20 +238,20 @@ describe('streaming follow yields to the reader', () => {
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.tailScroll.mockImplementation(() => {});
h.handleHistoryTouchStart(touch());
if (releaseFirst) h.handleHistoryTouchEnd(touch());
h.scrollToBottom();
- expect(h.scrollToEnd).toHaveBeenCalledExactlyOnceWith({ animated: true });
+ expect(h.tailScroll).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 });
+ expect(h.tailScroll).toHaveBeenCalledExactlyOnceWith({ animated: true });
h.handleScroll(h.scrollEvent(1400));
settle();
- expect(h.scrollToEnd).toHaveBeenCalledExactlyOnceWith({ animated: true });
+ expect(h.tailScroll).toHaveBeenCalledExactlyOnceWith({ animated: true });
});
it('lets a new upward drag interrupt verification after an explicit animated jump', () => {
@@ -260,7 +265,7 @@ describe('streaming follow yields to the reader', () => {
h.handleScrollEndDrag();
settle();
expect(h.state.nearBottomRef.current).toBe(false);
- expect(h.scrollToEnd).toHaveBeenCalledExactlyOnceWith({ animated: true });
+ expect(h.tailScroll).toHaveBeenCalledExactlyOnceWith({ animated: true });
});
it('allows an upward drag to unpin while content grows before the first scroll event', () => {
@@ -269,7 +274,7 @@ describe('streaming follow yields to the reader', () => {
h.handleContentSize(400, 2040);
h.handleScrollBeginDrag(h.scrollEvent(1200));
h.handleContentSize(400, 2080);
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
h.handleScroll(h.scrollEvent(1180));
expect(h.state.nearBottomRef.current).toBe(false);
h.handleHistoryTouchEnd(touch(420));
@@ -279,9 +284,9 @@ describe('streaming follow yields to the reader', () => {
h.handleMomentumScrollEnd();
settle();
h.handleContentSize(400, 2240);
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
h.scrollToBottom();
- expect(h.scrollToEnd).toHaveBeenLastCalledWith({ animated: true });
+ expect(h.tailScroll).toHaveBeenLastCalledWith({ animated: true });
});
it.each(['handleHistoryTouchEnd', 'handleHistoryTouchCancel'] as const)(
@@ -290,10 +295,10 @@ describe('streaming follow yields to the reader', () => {
h.handleHistoryTouchStart(touch());
h.handleContentSize(400, 2300);
settle();
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
h[release](touch());
settle();
- expect(h.scrollToEnd).toHaveBeenCalledTimes(1);
+ expect(h.tailScroll).toHaveBeenCalledTimes(1);
expect(h.state.scrollMetricsRef.current.offsetY).toBe(1500);
},
);
@@ -309,14 +314,14 @@ describe('streaming follow yields to the reader', () => {
expect(h.state.nearBottomRef.current).toBe(trailingOffset >= 1192);
settle();
if (trailingOffset < 1192) {
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
return;
}
- expect(h.scrollToEnd).toHaveBeenCalledTimes(1);
+ expect(h.tailScroll).toHaveBeenCalledTimes(1);
h.handleScroll(h.scrollEvent(1700));
expect(h.state.nearBottomRef.current).toBe(true);
h.handleContentSize(400, 2540);
- expect(h.scrollToEnd).toHaveBeenCalledTimes(2);
+ expect(h.tailScroll).toHaveBeenCalledTimes(2);
});
it.each([false, true])('unpins a trailing drag across momentum-start ordering: %s', (momentumFirst) => {
@@ -333,7 +338,7 @@ describe('streaming follow yields to the reader', () => {
h.handleContentSize(400, 2500);
settle();
expect(h.state.nearBottomRef.current).toBe(false);
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
});
it('retires a completed drag after a no-op release verification', () => {
@@ -342,12 +347,12 @@ describe('streaming follow yields to the reader', () => {
h.handleScroll(h.scrollEvent(1200));
h.handleScrollEndDrag();
settle();
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
h.handleScroll(h.scrollEvent(1190));
h.handleContentSize(400, 2500);
settle();
expect(h.state.nearBottomRef.current).toBe(true);
- expect(h.scrollToEnd).toHaveBeenCalledTimes(1);
+ expect(h.tailScroll).toHaveBeenCalledTimes(1);
});
it.each([1180, 900])('preserves a short drag through a post-release layout correction to %i', (offset) => {
@@ -360,7 +365,7 @@ describe('streaming follow yields to the reader', () => {
h.handleScroll(h.scrollEvent(offset));
expect(h.state.nearBottomRef.current).toBe(true);
settle();
- expect(h.scrollToEnd).toHaveBeenCalledExactlyOnceWith({ animated: false });
+ expect(h.tailScroll).toHaveBeenCalledExactlyOnceWith({ animated: false });
expect(h.state.scrollMetricsRef.current.offsetY).toBe(1700);
});
@@ -404,15 +409,15 @@ describe('streaming follow yields to the reader', () => {
h.runStickToLatestVerify();
h.handleHistoryTouchStart(touch());
settle();
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
h.handleHistoryTouchEnd(touch());
h.handleMomentumScrollBegin();
h.handleContentSize(400, 2300);
settle();
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
h.handleMomentumScrollEnd();
settle();
- expect(h.scrollToEnd).toHaveBeenCalledTimes(1);
+ expect(h.tailScroll).toHaveBeenCalledTimes(1);
});
it('keeps the drag dead zone authoritative when the tail grows beyond the distance threshold', () => {
@@ -422,12 +427,12 @@ describe('streaming follow yields to the reader', () => {
h.handleContentSize(400, 2500);
h.handleScroll(h.scrollEvent(1194));
expect(h.state.nearBottomRef.current).toBe(true);
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
h.handleScroll(h.scrollEvent(1190));
expect(h.state.nearBottomRef.current).toBe(false);
h.handleScrollEndDrag();
settle();
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
});
it('still unpins a real momentum fling after a short drag', () => {
@@ -441,18 +446,18 @@ describe('streaming follow yields to the reader', () => {
h.handleContentSize(400, 2500);
h.handleMomentumScrollEnd();
settle();
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).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();
+ expect(console.warn).toHaveBeenCalledTimes(1);
+ h.tailScroll.mockClear();
h.handleHistoryTouchStart(touch());
settle();
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
h.handleHistoryTouchEnd(touch());
settle();
expect(h.state.scrollMetricsRef.current.offsetY).toBe(1300);
@@ -466,6 +471,6 @@ describe('streaming follow yields to the reader', () => {
h.handleContentSize(400, 2500);
h.handleHistoryTouchEnd(touch());
settle();
- expect(h.scrollToEnd).not.toHaveBeenCalled();
+ expect(h.tailScroll).not.toHaveBeenCalled();
});
});
diff --git a/apps/mobile/src/__tests__/messageListVirtualization.test.ts b/apps/mobile/src/__tests__/messageListVirtualization.test.ts
index e550dea2f7..585e5e3a83 100644
--- a/apps/mobile/src/__tests__/messageListVirtualization.test.ts
+++ b/apps/mobile/src/__tests__/messageListVirtualization.test.ts
@@ -220,8 +220,8 @@ describe('mobile message list container', () => {
it('bounds the hidden initial correction while keeping full history mounted', () => {
const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
expect(source).toContain('programmaticScrollInFlight: programmaticScrollInFlightRef.current');
- expect(source).toContain('evaluateMobileAnchorVerify({');
- expect(source).toContain('initialAnchorVerifyFrameRef');
+ expect(source).toContain('createMobileTailFollower({');
+ expect(source).not.toContain('initialAnchorVerifyFrameRef');
expect(source).toContain('scrollToEndProgrammatically(false)');
// mVCP 只对 size 常开;流式 resize 仍需记 settle 安静窗,跟随 verifier 不能只依赖
// readingOlderRef 判断是否等待。
@@ -230,8 +230,7 @@ describe('mobile message list container', () => {
expect(source).toContain('mobileMessageListKeysSignature(itemKeys)');
expect(source).toContain('[itemKeysSignature, markMobileMvcpSettle]');
expect(source).not.toContain('[itemKeys, markMobileMvcpSettle]');
- expect(source.match(/isMobileMvcpSettling\(Date\.now\(\), mvcpSettleAtRef\.current\)/g))
- .toHaveLength(2);
+ expect(source).toContain('layoutSettleAt: mvcpSettleAtRef.current');
expect(source).toContain('const nextStableFrames = settled ? stableFrames + 1 : 0;');
expect(source).toContain('key={scrollResetKey}');
@@ -255,10 +254,10 @@ describe('mobile message list container', () => {
const initialAnchorEffectSource = source.slice(initialAnchorEffectStart, initialAnchorEffectEnd);
expect(initialAnchorEffectSource).toContain('Animated.timing(initialRevealProgress, {');
expect(initialAnchorEffectSource).toContain('useNativeDriver: true');
- expect(initialAnchorEffectSource).toContain('Date.now() >= revealDeadlineAt');
+ expect(initialAnchorEffectSource).not.toContain('const verify =');
expect(initialAnchorEffectSource).not.toContain('setTimeout(');
expect(initialAnchorEffectSource).toContain('scrollToEndProgrammatically(false);');
- expect(initialAnchorEffectSource).toContain('initialAnchorVerifyFrameRef.current = requestAnimationFrame(() => {');
+ expect(initialAnchorEffectSource).not.toContain('requestAnimationFrame(');
expect(source).not.toContain('initialRevealTimerRef');
expect(source).not.toContain('messageListSettling');
});
@@ -283,52 +282,42 @@ describe('mobile message list container', () => {
expect(expandedStateSource).toContain('blockId ? store.subscribe(listener) : () => {}');
});
- it('clears stale history intent before verifying an explicit follow-latest request', () => {
+ it('uses the same explicit action for sending and jumping to the latest message', () => {
const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
- const effectStart = source.indexOf('// 「跳到最新」请求');
+ const effectStart = source.indexOf('// Sending and the jump button');
const effectEnd = source.indexOf('// 自动加载更早', effectStart);
- const effectSource = source.slice(effectStart, effectEnd);
- const clearHistoryIntentAt = effectSource.indexOf('userScrollForOlderRef.current = false');
- const verifyAt = effectSource.indexOf('runStickToLatestVerify();');
-
- expect(effectStart).toBeGreaterThan(-1);
- expect(effectEnd).toBeGreaterThan(effectStart);
- expect(clearHistoryIntentAt).toBeGreaterThan(-1);
- expect(verifyAt).toBeGreaterThan(clearHistoryIntentAt);
- expect(effectSource).toContain("scrollToEndProgrammatically(true, 'explicit');");
+ expect(source.slice(effectStart, effectEnd)).toContain('scrollToBottom();');
+ const jump = source.slice(source.indexOf('const scrollToBottom'), source.indexOf('const jumpToPreviousUserMessage'));
+ expect(jump.indexOf('userScrollForOlderRef.current = false')).toBeLessThan(
+ jump.indexOf("scrollToEndProgrammatically(true, 'explicit')"),
+ );
});
- it('verifies a manual jump-to-latest after issuing the animated scroll', () => {
+ it('routes manual jump-to-latest through the controller that owns seek and verification', () => {
const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
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, 'explicit');");
- const verifyAt = callbackSource.indexOf('runStickToLatestVerify();');
expect(callbackStart).toBeGreaterThan(-1);
expect(callbackEnd).toBeGreaterThan(callbackStart);
expect(scrollAt).toBeGreaterThan(-1);
- expect(verifyAt).toBeGreaterThan(scrollAt);
+ expect(callbackSource).not.toContain('runStickToLatestVerify();');
expect(callbackSource).toContain(
- '}, [cancelHistoryPrependTransaction, runStickToLatestVerify, scrollToEndProgrammatically]);',
+ '}, [cancelHistoryPrependTransaction, scrollToEndProgrammatically]);',
);
});
- it('waits for an animated follow scroll to settle before issuing non-animated verification retries', () => {
+ it('passes native geometry and animation ownership into the tail controller', () => {
const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
- const verifyStart = source.indexOf('const runStickToLatestVerify = useCallback');
- const verifyEnd = source.indexOf('// DEV-only:', verifyStart);
- const verifySource = source.slice(verifyStart, verifyEnd);
- const contentSizeStart = source.indexOf('const handleContentSize = useCallback');
- const contentSizeEnd = source.indexOf('// 冷开落底', contentSizeStart);
- const contentSizeSource = source.slice(contentSizeStart, contentSizeEnd);
-
- expect(verifySource).toContain('mobileFollowVerifyStartDelayMs({');
- expect(verifySource).toContain('followVerifyTimerRef.current = setTimeout');
- expect(contentSizeSource).toContain('if (programmaticAnimatedScrollInFlightRef.current)');
- expect(contentSizeSource.indexOf('if (programmaticAnimatedScrollInFlightRef.current)'))
- .toBeLessThan(contentSizeSource.indexOf('scrollToEndProgrammatically(false)'));
+ const adapter = source.slice(source.indexOf('const getTailFollower'), source.indexOf('const scrollToEndProgrammatically'));
+ expect(adapter).toContain('metrics: scrollMetricsRef.current');
+ expect(adapter).toContain('programmaticAnimatedScrollInFlightRef.current');
+ expect(adapter).toContain('programmaticScrollSettleAtRef.current');
+ expect(adapter).toContain('scrollToOffset({ animated: false, offset })');
+ expect(source).not.toContain('followVerifyFrameRef');
+ expect(source).not.toContain('followEndPinRecoveryTimerRef');
});
it('clears stale history intent when a manual downward scroll re-pins at the bottom', () => {
@@ -346,8 +335,8 @@ describe('mobile message list container', () => {
it('keeps follow verification enabled for a dead-zone drag that never actually unpins', () => {
const source = readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8');
- const verifyStart = source.indexOf('const runStickToLatestVerify');
- const verifyEnd = source.indexOf('// DEV-only:', verifyStart);
+ const verifyStart = source.indexOf('const getTailFollower');
+ const verifyEnd = source.indexOf('const scrollToEndProgrammatically', verifyStart);
const verifySource = source.slice(verifyStart, verifyEnd);
expect(verifyStart).toBeGreaterThan(-1);
diff --git a/apps/mobile/src/__tests__/messageScroll.test.ts b/apps/mobile/src/__tests__/messageScroll.test.ts
index 6c8b7a6b59..d7e665664f 100644
--- a/apps/mobile/src/__tests__/messageScroll.test.ts
+++ b/apps/mobile/src/__tests__/messageScroll.test.ts
@@ -17,7 +17,6 @@ import {
isNearMobileMessageListBottom,
isNearMessageListTop,
isMobileMvcpSettling,
- mobileFollowVerifyStartDelayMs,
mobileMessageListKeysSignature,
mobileMvcpSettleDeadline,
MOBILE_ANCHOR_VERIFY_MAX_ATTEMPTS,
@@ -680,6 +679,7 @@ describe('evaluateMobileAnchorVerify (落底校验/补滚有界重试环——
listVisible: true,
preserveVisibleContentPosition: false,
stickToLatest: true,
+ userControllingScroll: false,
waitRounds: 0,
};
@@ -713,6 +713,40 @@ describe('evaluateMobileAnchorVerify (落底校验/补滚有界重试环——
})).toBe('retry');
});
+ it('rejects overshoot beyond the end while allowing two-sided rounding tolerance', () => {
+ expect(evaluateMobileAnchorVerify({
+ ...baseInput, metrics: metricsAt(1200 + MOBILE_ANCHOR_VERIFY_TOLERANCE),
+ })).toBe('settled');
+ for (const offsetY of [1200 + MOBILE_ANCHOR_VERIFY_TOLERANCE + 1, 1800]) {
+ expect(evaluateMobileAnchorVerify({ ...baseInput, metrics: metricsAt(offsetY) })).toBe('retry');
+ expect(evaluateMobileAnchorVerify({
+ ...baseInput, attempts: MOBILE_ANCHOR_VERIFY_MAX_ATTEMPTS, metrics: metricsAt(offsetY),
+ })).toBe('give-up');
+ }
+ });
+
+ it('corrects a stale offset after content shrinks below the viewport', () => {
+ const metrics = { contentHeight: 400, viewportHeight: 800, offsetY: 600 };
+ expect(evaluateMobileAnchorVerify({ ...baseInput, metrics })).toBe('retry');
+ expect(evaluateMobileAnchorVerify({
+ ...baseInput, metrics: { ...metrics, offsetY: 0 },
+ })).toBe('settled');
+ });
+
+ it('waits through native bounce and resumes correction only after gesture ownership ends', () => {
+ const metrics = metricsAt(1800);
+ expect(evaluateMobileAnchorVerify({
+ ...baseInput, userControllingScroll: true, metrics,
+ })).toBe('wait');
+ expect(evaluateMobileAnchorVerify({
+ ...baseInput, userControllingScroll: true, waitRounds: MOBILE_ANCHOR_VERIFY_MAX_WAIT_ROUNDS, metrics,
+ })).toBe('give-up');
+ expect(evaluateMobileAnchorVerify({ ...baseInput, metrics })).toBe('retry');
+ expect(evaluateMobileAnchorVerify({
+ ...baseInput, stickToLatest: false, metrics,
+ })).toBe('settled');
+ });
+
it('重试次数达到上限后仍未落底 → give-up(不无限重试)', () => {
expect(evaluateMobileAnchorVerify({
...baseInput, attempts: MOBILE_ANCHOR_VERIFY_MAX_ATTEMPTS, metrics: metricsAt(0),
@@ -779,31 +813,3 @@ describe('mobile mVCP settle quiet window', () => {
);
});
});
-
-describe('mobileFollowVerifyStartDelayMs (动画贴底完成后再启动 verifier)', () => {
- it('动画仍在 settle 窗口内时返回剩余等待时间', () => {
- expect(mobileFollowVerifyStartDelayMs({
- animatedScrollInFlight: true,
- now: 600,
- settleAt: 1400,
- })).toBe(800);
- });
-
- it('非动画、已结束或时钟已越过 settle 时立即校验', () => {
- expect(mobileFollowVerifyStartDelayMs({
- animatedScrollInFlight: false,
- now: 600,
- settleAt: 1400,
- })).toBe(0);
- expect(mobileFollowVerifyStartDelayMs({
- animatedScrollInFlight: true,
- now: 1400,
- settleAt: 1400,
- })).toBe(0);
- expect(mobileFollowVerifyStartDelayMs({
- animatedScrollInFlight: true,
- now: 1500,
- settleAt: 1400,
- })).toBe(0);
- });
-});
diff --git a/apps/mobile/src/__tests__/messageTailFollower.test.ts b/apps/mobile/src/__tests__/messageTailFollower.test.ts
new file mode 100644
index 0000000000..4369f6bf92
--- /dev/null
+++ b/apps/mobile/src/__tests__/messageTailFollower.test.ts
@@ -0,0 +1,274 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createMobileTailFollower, type MobileTailSnapshot } from '@/session/messageTailFollower';
+import { MOBILE_ANCHOR_VERIFY_MAX_ATTEMPTS } from '@/session/messageScroll';
+
+function harness() {
+ const snapshot: MobileTailSnapshot = {
+ metrics: { contentHeight: 2000, viewportHeight: 800, offsetY: 1200 },
+ stickToLatest: true,
+ userControllingScroll: false,
+ preservingHistory: false,
+ layoutSettleAt: 0,
+ animatedScrollUntil: 0,
+ };
+ const seekEnd = vi.fn((animated: boolean): void | Promise<void> => {
+ if (animated) snapshot.animatedScrollUntil = Date.now() + 800;
+ });
+ const correctOffset = vi.fn((offset: number) => { snapshot.metrics.offsetY = offset; });
+ const onMeasurementOscillation = vi.fn();
+ const follower = createMobileTailFollower({
+ read: () => snapshot, seekEnd, correctOffset, onMeasurementOscillation,
+ });
+ return { snapshot, seekEnd, correctOffset, onMeasurementOscillation, follower };
+}
+
+function deferredSeek() {
+ let resolve!: () => void;
+ let reject!: () => void;
+ const promise = new Promise<void>((done, fail) => { resolve = done; reject = fail; });
+ return { promise, resolve, reject };
+}
+
+describe('one mobile tail follower', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1000);
+ vi.stubGlobal('requestAnimationFrame', (fn: () => void) => setTimeout(fn, 16));
+ vi.stubGlobal('cancelAnimationFrame', (id: ReturnType<typeof setTimeout>) => clearTimeout(id));
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ it('seeks unmeasured rows once, then corrects against native geometry in either direction', () => {
+ const h = harness();
+ h.snapshot.metrics.offsetY = 1800;
+ h.follower.requestEnd(false);
+ h.follower.reconcile(); // The entry animation and layout share the same pending check.
+ vi.advanceTimersByTime(200);
+ expect(h.seekEnd).toHaveBeenCalledExactlyOnceWith(false);
+ expect(h.correctOffset).toHaveBeenCalledExactlyOnceWith(1200);
+ h.snapshot.metrics.offsetY = 900;
+ h.follower.reconcile();
+ vi.advanceTimersByTime(200);
+ expect(h.correctOffset).toHaveBeenLastCalledWith(1200);
+ expect(h.seekEnd).toHaveBeenCalledTimes(1);
+ });
+
+ it('allows a queued last-index seek to discover the tail before correcting native geometry', async () => {
+ const h = harness();
+ const seek = deferredSeek();
+ let pending = true;
+ let cancelled = false;
+ h.seekEnd.mockReturnValue(seek.promise);
+ // Like LegendList, an offset command cancels a queued last-index command.
+ h.correctOffset.mockImplementation((offset) => {
+ if (pending) cancelled = true;
+ h.snapshot.metrics.offsetY = offset;
+ });
+ h.follower.requestEnd(false);
+ h.snapshot.metrics.contentHeight = 2500;
+ h.follower.contentChanged();
+ h.follower.reconcile();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(h.correctOffset).not.toHaveBeenCalled();
+ expect(cancelled).toBe(false);
+ // Completing the seek exposes the real tail, but its estimated landing still overshoots.
+ pending = false;
+ h.snapshot.metrics = { contentHeight: 3000, viewportHeight: 800, offsetY: 2800 };
+ seek.resolve();
+ await vi.advanceTimersByTimeAsync(200);
+ expect(h.correctOffset).toHaveBeenCalledExactlyOnceWith(2200);
+ });
+
+ it('reconciles native geometry after a failed seek without an unhandled rejection', async () => {
+ const h = harness();
+ const seek = deferredSeek();
+ h.seekEnd.mockReturnValue(seek.promise);
+ h.snapshot.metrics.offsetY = 1800;
+ h.follower.requestEnd(false);
+ seek.reject();
+ await vi.advanceTimersByTimeAsync(200);
+ expect(h.correctOffset).toHaveBeenCalledExactlyOnceWith(1200);
+ });
+
+ it('discards old seek completions across reset and replacement requests', async () => {
+ const h = harness();
+ const oldSeek = deferredSeek();
+ const newSeek = deferredSeek();
+ h.seekEnd.mockReturnValueOnce(oldSeek.promise).mockReturnValueOnce(newSeek.promise);
+ h.snapshot.metrics.offsetY = 1800;
+ h.follower.requestEnd(false);
+ h.follower.reset();
+ h.follower.requestEnd(false);
+ oldSeek.resolve();
+ await vi.advanceTimersByTimeAsync(200);
+ expect(h.correctOffset).not.toHaveBeenCalled();
+ h.follower.reset();
+ newSeek.resolve();
+ await vi.advanceTimersByTimeAsync(200);
+ expect(h.correctOffset).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('yields to a gesture that takes ownership while a seek is pending', async () => {
+ const h = harness();
+ const seek = deferredSeek();
+ h.seekEnd.mockReturnValue(seek.promise);
+ h.snapshot.metrics.offsetY = 1800;
+ h.follower.requestEnd(false);
+ h.snapshot.userControllingScroll = true;
+ seek.resolve();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(h.correctOffset).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ h.snapshot.userControllingScroll = false;
+ h.follower.reconcile();
+ await vi.advanceTimersByTimeAsync(200);
+ expect(h.correctOffset).toHaveBeenCalledExactlyOnceWith(1200);
+ });
+
+ it('recovers shrinkage below one screen after layout settles', () => {
+ const h = harness();
+ h.snapshot.metrics.contentHeight = 500;
+ h.snapshot.layoutSettleAt = Date.now() + 120;
+ h.follower.contentChanged();
+ vi.advanceTimersByTime(100);
+ expect(h.correctOffset).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(200);
+ expect(h.correctOffset).toHaveBeenCalledExactlyOnceWith(0);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('rechecks a larger viewport even when no content-size event follows', () => {
+ const h = harness();
+ h.snapshot.metrics.viewportHeight = 1000;
+ h.follower.reconcile();
+ vi.advanceTimersByTime(200);
+ expect(h.correctOffset).toHaveBeenCalledExactlyOnceWith(1000);
+ });
+
+ it('does not scroll an aligned short list', () => {
+ const h = harness();
+ h.snapshot.metrics = { contentHeight: 500, viewportHeight: 800, offsetY: 0 };
+ h.follower.contentChanged();
+ vi.advanceTimersByTime(200);
+ expect(h.correctOffset).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('does not poll during a held gesture and resumes on release even after output stops', () => {
+ const h = harness();
+ h.snapshot.userControllingScroll = true;
+ h.snapshot.metrics.contentHeight = 2500;
+ h.follower.contentChanged();
+ h.follower.reconcile();
+ expect(vi.getTimerCount()).toBe(0);
+ vi.advanceTimersByTime(10_000);
+ expect(h.correctOffset).not.toHaveBeenCalled();
+ h.snapshot.userControllingScroll = false;
+ h.follower.reconcile();
+ vi.advanceTimersByTime(200);
+ expect(h.correctOffset).toHaveBeenCalledExactlyOnceWith(1700);
+ });
+
+ it('stops a pending correction if a gesture or history reader takes over', () => {
+ for (const owner of ['userControllingScroll', 'preservingHistory'] as const) {
+ const h = harness();
+ h.snapshot.metrics.offsetY = 1800;
+ h.follower.reconcile();
+ h.snapshot[owner] = true;
+ vi.advanceTimersByTime(200);
+ expect(h.correctOffset).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ }
+ });
+
+ it('never reclaims the viewport after follow has been released', () => {
+ const h = harness();
+ h.snapshot.stickToLatest = false;
+ h.snapshot.metrics.contentHeight = 2500;
+ h.follower.contentChanged();
+ h.follower.reconcile();
+ vi.advanceTimersByTime(1000);
+ expect(h.correctOffset).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('lets explicit jumps precede touch-end without cutting their animation short', () => {
+ const h = harness();
+ h.snapshot.userControllingScroll = true;
+ h.follower.requestEnd(true, true);
+ expect(h.seekEnd).toHaveBeenCalledExactlyOnceWith(true);
+ h.snapshot.userControllingScroll = false;
+ h.snapshot.metrics.contentHeight = 2500;
+ h.follower.reconcile();
+ h.follower.contentChanged();
+ vi.advanceTimersByTime(799);
+ expect(h.correctOffset).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(200);
+ expect(h.correctOffset).toHaveBeenCalledExactlyOnceWith(1700);
+ });
+
+ it('keeps live growth immediate and coalesces repeated verification requests', () => {
+ const h = harness();
+ h.snapshot.metrics.contentHeight = 2500;
+ h.snapshot.layoutSettleAt = Date.now() + 120;
+ h.follower.contentChanged();
+ expect(h.correctOffset).toHaveBeenCalledExactlyOnceWith(1700);
+ for (let i = 0; i < 20; i++) h.follower.reconcile();
+ expect(vi.getTimerCount()).toBe(1);
+ vi.advanceTimersByTime(300);
+ expect(h.correctOffset).toHaveBeenCalledTimes(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('wakes promptly when touching cancels an explicit animation before its old deadline', () => {
+ const h = harness();
+ h.follower.requestEnd(true, true);
+ vi.advanceTimersByTime(100);
+ h.snapshot.userControllingScroll = true;
+ h.snapshot.animatedScrollUntil = 0;
+ h.snapshot.metrics.contentHeight = 2500;
+ vi.advanceTimersByTime(50);
+ h.snapshot.userControllingScroll = false;
+ h.follower.reconcile();
+ vi.advanceTimersByTime(32);
+ expect(h.correctOffset).toHaveBeenCalledExactlyOnceWith(1700);
+ });
+
+ it('bounds retries when native never acknowledges and discards work on task reset', () => {
+ const h = harness();
+ h.correctOffset.mockImplementation(() => {});
+ h.snapshot.metrics.offsetY = 1800;
+ for (let i = 0; i < 20; i++) h.follower.reconcile();
+ vi.advanceTimersByTime(1000);
+ expect(h.correctOffset).toHaveBeenCalledTimes(MOBILE_ANCHOR_VERIFY_MAX_ATTEMPTS);
+ expect(vi.getTimerCount()).toBe(0);
+ h.follower.reconcile();
+ h.follower.reset();
+ vi.advanceTimersByTime(1000);
+ expect(h.correctOffset).toHaveBeenCalledTimes(MOBILE_ANCHOR_VERIFY_MAX_ATTEMPTS);
+ });
+
+ it('applies the oscillation circuit to the shared verifier as well as immediate growth', () => {
+ const h = harness();
+ h.correctOffset.mockImplementation(() => {});
+ for (let i = 0; i < 8; i++) {
+ h.snapshot.metrics.contentHeight = i % 2 === 0 ? 2100 : 2000;
+ h.follower.contentChanged();
+ vi.advanceTimersByTime(16);
+ }
+ expect(h.onMeasurementOscillation).toHaveBeenCalledTimes(1);
+ h.snapshot.metrics.contentHeight = 2100;
+ h.follower.contentChanged();
+ const count = h.correctOffset.mock.calls.length;
+ vi.advanceTimersByTime(1000);
+ expect(h.correctOffset).toHaveBeenCalledTimes(count);
+ h.correctOffset.mockImplementation((offset) => { h.snapshot.metrics.offsetY = offset; });
+ vi.advanceTimersByTime(1500);
+ expect(h.correctOffset).toHaveBeenCalledTimes(count + 1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/apps/mobile/src/__tests__/scrollWindowModel.test.ts b/apps/mobile/src/__tests__/scrollWindowModel.test.ts
index af03251899..399fb1373a 100644
--- a/apps/mobile/src/__tests__/scrollWindowModel.test.ts
+++ b/apps/mobile/src/__tests__/scrollWindowModel.test.ts
@@ -138,6 +138,7 @@ describe('evaluateMobileAnchorVerify (贴底锚定校验判定)', () => {
metrics: anchoredMetrics,
preserveVisibleContentPosition: false,
stickToLatest: true,
+ userControllingScroll: false,
waitRounds: 0,
};
@@ -147,11 +148,16 @@ describe('evaluateMobileAnchorVerify (贴底锚定校验判定)', () => {
...base,
metrics: { ...anchoredMetrics, offsetY: 1200 - MOBILE_ANCHOR_VERIFY_TOLERANCE },
})).toBe('settled');
- // iOS bounce 超滚(offset 超过 end)同样视为贴底。
+ // iOS bounce belongs to the gesture; only correct a stale overshoot after it ends.
expect(evaluateMobileAnchorVerify({
...base,
+ userControllingScroll: true,
metrics: { ...anchoredMetrics, offsetY: 1210 },
- })).toBe('settled');
+ })).toBe('wait');
+ expect(evaluateMobileAnchorVerify({
+ ...base,
+ metrics: { ...anchoredMetrics, offsetY: 1210 },
+ })).toBe('retry');
});
it('retries when the drop-to-bottom silently fell short of the content end', () => {
@@ -188,7 +194,7 @@ describe('evaluateMobileAnchorVerify (贴底锚定校验判定)', () => {
})).toBe('wait');
});
- it('treats sub-viewport content as anchored regardless of offset', () => {
+ it('treats sub-viewport content as anchored at zero offset', () => {
expect(evaluateMobileAnchorVerify({
...base,
metrics: { contentHeight: 400, offsetY: 0, viewportHeight: 800 },
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 82e5af088b..ea3c8ad1a6 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -319,19 +319,13 @@ import { logUnhandledRenderItem } from '@/session/assertNever';
import type { OrcaCollabCard as OrcaCollabCardModel } from '@/session/orcaCollab';
import {
buildMessageLoadEarlierAction,
- createMobileFollowEndPinState,
evaluateMessageWindowUpdate,
- evaluateMobileAnchorVerify,
- evaluateMobileFollowEndContentSizePin,
- isMobileMvcpSettling,
MOBILE_ANCHOR_VERIFY_TOLERANCE,
- mobileFollowVerifyStartDelayMs,
mobileLoadEarlierPrefetchThreshold,
mobileMessageListKeysSignature,
mobileMvcpSettleDeadline,
mobileMessageListTopPadding,
MOBILE_FOLLOW_UNPIN_DRAG_DEAD_ZONE,
- MOBILE_FOLLOW_END_PIN_SUPPRESS_MS,
MOBILE_MESSAGE_LIST_BOTTOM_PADDING,
type MessageScrollMetrics,
mobileMessageListBottomPadding,
@@ -341,6 +335,7 @@ import {
shouldPreserveMobileHistoryBrowseIntent,
shouldUnpinMobileFollowOnDrag,
} from '@/session/messageScroll';
+import { createMobileTailFollower, type MobileTailFollower } from '@/session/messageTailFollower';
import {
captureMobileHistoryAnchor,
isMobileHistoryAnchorSettled,
@@ -823,19 +818,11 @@ export function MessageRenderer({
offsetY: 0,
viewportHeight: 0,
});
- // 贴底补滚护栏状态(死区 + 振荡断路器,语义见 messageScroll.ts 的护栏段注释):
- // 掐断 onContentSizeChange → scrollToEnd → 重测 的洪泛环(JS 忙死、消息区空白)。
- const followEndPinStateRef = useRef(createMobileFollowEndPinState());
- // 断路到期后的 one-shot 贴底清账 timer:断路窗内错过的最终高度可能停在半空且
- // 之后再无 contentSize 事件,到期补一次(仍在贴底跟随时)把账清平(review P1)。
- const followEndPinRecoveryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- // 首次进入锚定:完整历史从挂载起就在列表中,命令式落底与测量校正只在短暂
- // opacity 遮罩下运行;揭示动画启动后完全交给 UI 线程,首批复杂消息占满 JS 时也不会
- // 把 300ms 窗口拖成长达数秒的白屏。
+ const tailFollowerRef = useRef<MobileTailFollower | null>(null);
+ // 完整历史从挂载起就在列表中;首次揭示交给 UI 线程,首批复杂消息占满 JS 时也不会
+ // 把 300ms 窗口拖成长达数秒的白屏。位置校验由 tail follower 独立管理。
const initialAnchorDoneRef = useRef(false);
- const initialAnchorGenerationRef = useRef(0);
- const initialAnchorVerifyFrameRef = useRef<number | null>(null);
- const initialAnchorFrameRef = useRef<number | null>(null);
+ const initialRevealGenerationRef = useRef(0);
const initialRevealAnimationRef = useRef<Animated.CompositeAnimation | null>(null);
const initialRevealProgress = useMemo(
() => new Animated.Value(0),
@@ -849,9 +836,6 @@ export function MessageRenderer({
],
outputRange: [0, 0, 1],
}), [initialRevealProgress]);
- const followVerifyGenerationRef = useRef(0);
- const followVerifyFrameRef = useRef<number | null>(null);
- const followVerifyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [listRevealed, setListRevealed] = useState(false);
// Re-evaluate the near-start predicate after a prepend request releases its ref-only lock.
// Without a render tick, a user who remains at the top can stall after one page because the
@@ -911,28 +895,11 @@ export function MessageRenderer({
firstVisibleIndexRef.current = 0;
nativeScrollEventSequenceRef.current = 0;
scrollMetricsRef.current = { contentHeight: 0, offsetY: 0, viewportHeight: 0 };
- followEndPinStateRef.current = createMobileFollowEndPinState();
+ tailFollowerRef.current?.reset();
initialAnchorDoneRef.current = false;
- initialAnchorGenerationRef.current += 1;
- if (initialAnchorFrameRef.current !== null) {
- cancelAnimationFrame(initialAnchorFrameRef.current);
- initialAnchorFrameRef.current = null;
- }
- if (initialAnchorVerifyFrameRef.current !== null) {
- cancelAnimationFrame(initialAnchorVerifyFrameRef.current);
- initialAnchorVerifyFrameRef.current = null;
- }
+ initialRevealGenerationRef.current += 1;
initialRevealAnimationRef.current?.stop();
initialRevealAnimationRef.current = null;
- followVerifyGenerationRef.current += 1;
- if (followVerifyTimerRef.current !== null) {
- clearTimeout(followVerifyTimerRef.current);
- followVerifyTimerRef.current = null;
- }
- if (followVerifyFrameRef.current !== null) {
- cancelAnimationFrame(followVerifyFrameRef.current);
- followVerifyFrameRef.current = null;
- }
setListRevealed(false);
}
const lastAppliedFocusKeyRef = useRef<string | null>(null);
@@ -1019,19 +986,42 @@ export function MessageRenderer({
|| isMomentumScrollingRef.current
), []);
+ const getTailFollower = useCallback(() => {
+ if (!tailFollowerRef.current) {
+ tailFollowerRef.current = createMobileTailFollower({
+ read: () => ({
+ metrics: scrollMetricsRef.current,
+ stickToLatest: nearBottomRef.current,
+ userControllingScroll: isUserControllingScroll(),
+ preservingHistory: readingOlderRef.current,
+ layoutSettleAt: mvcpSettleAtRef.current,
+ animatedScrollUntil: programmaticAnimatedScrollInFlightRef.current
+ ? programmaticScrollSettleAtRef.current : 0,
+ }),
+ seekEnd: (animated) => {
+ markProgrammaticScroll(animated);
+ return listRef.current?.scrollToEnd({ animated });
+ },
+ correctOffset: (offset) => {
+ markProgrammaticScroll(false);
+ void listRef.current?.scrollToOffset({ animated: false, offset });
+ },
+ onMeasurementOscillation: () => console.warn(
+ '[message-list] contentSize follow-pin circuit tripped: oscillating item measurements suspected',
+ ),
+ });
+ }
+ return tailFollowerRef.current;
+ }, [isUserControllingScroll, markProgrammaticScroll]);
+
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.
+ // Only an explicit destination supersedes a pending final drag sample.
if (intent === 'explicit') dragStartOffsetYRef.current = null;
- markProgrammaticScroll(animated);
- void listRef.current?.scrollToEnd({ animated });
- }, [isUserControllingScroll, markProgrammaticScroll]);
+ getTailFollower().requestEnd(animated, intent === 'explicit');
+ }, [getTailFollower]);
const scrollToOffsetProgrammatically = useCallback((offset: number, animated: boolean) => {
markProgrammaticScroll(animated);
@@ -1090,7 +1080,8 @@ export function MessageRenderer({
readingOlderRef.current = false;
setHistoryPrependNativeMvcpDisabled(false);
setLoadEarlierEvaluationVersion((version) => version + 1);
- }, []);
+ getTailFollower().reconcile();
+ }, [getTailFollower]);
const maybeFinishHistoryPrependTransaction = useCallback((generation: number) => {
const transaction = historyPrependTransactionRef.current;
@@ -1351,85 +1342,10 @@ export function MessageRenderer({
});
}, [maybeFinishHistoryPrependTransaction, scheduleHistoryAnchorRestore]);
- // 贴底跟随的落底校验/补滚环:两条手动补滚路径——「跳到最新」(followLatestRequestKey)
- // 与 handleContentSize 的贴底追赶——都只发一次命令式 scrollToEnd,不校验是否真的到达内容
- // 末端。落地一刻的 native metrics 可能仍是陈旧值(测量结算未完成),或 mVCP 尚未真正关闭
- // 吸收了这次滚动:两者都会让最新消息静默停在 composer 浮层后面(bug 现场)。复用冷开锚定
- // 同一判定(evaluateMobileAnchorVerify)、同样的双帧节奏 + 有界重试,命中 settled/give-up
- // 就收手——不吃冷开锚定的 generation/frame ref,两条校验环各自独立生命周期,互不打断。
+ // Initial entry, layout, content growth and release events share one tail controller.
const runStickToLatestVerify = useCallback(() => {
- const generation = followVerifyGenerationRef.current + 1;
- followVerifyGenerationRef.current = generation;
- if (followVerifyFrameRef.current !== null) {
- cancelAnimationFrame(followVerifyFrameRef.current);
- followVerifyFrameRef.current = null;
- }
- if (followVerifyTimerRef.current !== null) {
- clearTimeout(followVerifyTimerRef.current);
- followVerifyTimerRef.current = null;
- }
- 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,
- // 下一轮判定自然 settle。
- const action = evaluateMobileAnchorVerify({
- attempts,
- listVisible: true,
- metrics: scrollMetricsRef.current,
- preserveVisibleContentPosition: readingOlderRef.current
- || isMobileMvcpSettling(Date.now(), mvcpSettleAtRef.current),
- stickToLatest: nearBottomRef.current,
- waitRounds,
- });
- if (action === 'settled' || action === 'give-up') {
- followVerifyFrameRef.current = null;
- return;
- }
- if (action === 'retry') scrollToEndProgrammatically(false);
- followVerifyFrameRef.current = requestAnimationFrame(() => {
- followVerifyFrameRef.current = requestAnimationFrame(() => {
- followVerifyFrameRef.current = null;
- step(
- attempts + (action === 'retry' ? 1 : 0),
- waitRounds + (action === 'wait' ? 1 : 0),
- );
- });
- });
- };
- const start = () => {
- if (followVerifyGenerationRef.current !== generation) return;
- // 双帧等待:与冷开锚定环同源——命令式 scrollToEnd 已由调用方发出,这里只负责校验,
- // 给原生布局至少一帧结算再读 metrics,不把「刚发出去还没生效」误判成落空。
- followVerifyFrameRef.current = requestAnimationFrame(() => {
- followVerifyFrameRef.current = requestAnimationFrame(() => {
- followVerifyFrameRef.current = null;
- step(0, 0);
- });
- });
- };
- const startDelayMs = mobileFollowVerifyStartDelayMs({
- animatedScrollInFlight: programmaticAnimatedScrollInFlightRef.current,
- now: Date.now(),
- settleAt: programmaticScrollSettleAtRef.current,
- });
- if (startDelayMs > 0) {
- followVerifyTimerRef.current = setTimeout(() => {
- if (followVerifyGenerationRef.current !== generation) return;
- followVerifyTimerRef.current = null;
- start();
- }, startDelayMs);
- } else {
- start();
- }
- }, [isUserControllingScroll, scrollToEndProgrammatically]);
+ getTailFollower().reconcile();
+ }, [getTailFollower]);
// DEV-only:把列表控制器 + 滚动 metrics 暴露给性能 harness(临时,profiling/回归测量用)。
useEffect(() => {
@@ -1808,20 +1724,11 @@ export function MessageRenderer({
nearBottomRef.current = true;
cancelHistoryPrependTransaction();
userScrollForOlderRef.current = false;
- // 用户主动跳底是明确的重锚意图:重建补滚护栏(清掉可能仍开着的断路窗,
- // 让跳底后的贴底跟随立即恢复;振荡若还在会重新跳闸,review P2)。在飞的
- // 断路清账 timer 一并作废——本次显式跳底就是清账。
- followEndPinStateRef.current = createMobileFollowEndPinState();
- if (followEndPinRecoveryTimerRef.current) {
- clearTimeout(followEndPinRecoveryTimerRef.current);
- followEndPinRecoveryTimerRef.current = null;
- }
setIsAwayFromBottom(false);
setHasNewMessages(false);
setPreviousUserTarget(null);
scrollToEndProgrammatically(true, 'explicit');
- runStickToLatestVerify();
- }, [cancelHistoryPrependTransaction, runStickToLatestVerify, scrollToEndProgrammatically]);
+ }, [cancelHistoryPrependTransaction, scrollToEndProgrammatically]);
const jumpToPreviousUserMessage = useCallback(() => {
const target = previousUserMessageJumpTarget(
@@ -1839,36 +1746,13 @@ export function MessageRenderer({
scrollToIndexProgrammatically(target.index, 0.12);
}, [scrollToIndexProgrammatically]);
- // 「跳到最新」请求(会话外部触发,含发送消息后的跟随):命令式滚到底,随后跑一轮有界
- // 校验/补滚(runStickToLatestVerify)——单发的 scrollToEnd 落地一刻的 metrics 可能仍陈旧,
- // 或被仍开着的 mVCP 吸收掉,不校验就会静默停在旧消息上(bug 现场,与冷开锚定同一根因)。
- // 之后的贴底由 handleContentSize 补滚维持。
+ // Sending and the jump button share the same explicit follow action.
useEffect(() => {
if (previousFollowLatestRequestKeyRef.current === followLatestRequestKey) return;
previousFollowLatestRequestKeyRef.current = followLatestRequestKey;
if (followLatestRequestKey === null || followLatestRequestKey === undefined) return;
- nearBottomRef.current = true;
- cancelHistoryPrependTransaction();
- // 发送后的显式贴底已经取代旧的历史浏览意图。先清掉该标记,否则 verifier 的
- // stickToLatest 会被一次更早的拖动永久压成 false,退化回不可靠的单次 scrollToEnd。
- // 用户若在校验期间再次拖动,onScrollBeginDrag 会重新置 true 并自然中止补滚。
- userScrollForOlderRef.current = false;
- // 与 scrollToBottom 同语义:显式重锚清掉补滚护栏的断路窗与在飞清账 timer。
- followEndPinStateRef.current = createMobileFollowEndPinState();
- if (followEndPinRecoveryTimerRef.current) {
- clearTimeout(followEndPinRecoveryTimerRef.current);
- followEndPinRecoveryTimerRef.current = null;
- }
- setHasNewMessages(false);
- setIsAwayFromBottom(false);
- scrollToEndProgrammatically(true, 'explicit');
- runStickToLatestVerify();
- }, [
- cancelHistoryPrependTransaction,
- followLatestRequestKey,
- runStickToLatestVerify,
- scrollToEndProgrammatically,
- ]);
+ scrollToBottom();
+ }, [followLatestRequestKey, scrollToBottom]);
// 自动加载更早:电平触发判定(shouldAutoLoadEarlier),在所有可能改变判定结果的时机重评估
// (scroll 事件 / LegendList onStartReached 边沿 / eligibility 变化 effect)。
@@ -2325,7 +2209,9 @@ export function MessageRenderer({
const viewportHeight = event.nativeEvent.layout.height;
if (!Number.isFinite(viewportHeight) || viewportHeight <= 0) return;
scrollMetricsRef.current = { ...scrollMetricsRef.current, viewportHeight };
- }, []);
+ markMobileMvcpSettle();
+ if (nearBottomRef.current) runStickToLatestVerify();
+ }, [markMobileMvcpSettle, runStickToLatestVerify]);
const handleListMetricsChange = useCallback((metrics: LegendListMetrics) => {
listMetricsRef.current = metrics;
@@ -2350,7 +2236,6 @@ export function MessageRenderer({
// LegendList 内置 maintainScrollAtEnd 已弃用(见 LegendList props 注释),不存在双机制叠加。
const handleContentSize = useCallback((_width: number, height: number) => {
markMobileMvcpSettle();
- const { viewportHeight } = scrollMetricsRef.current;
scrollMetricsRef.current = { ...scrollMetricsRef.current, contentHeight: height };
// readingOlderRef:load-earlier 的 prepend 也会撑高 contentHeight,但那是顶部增长、不该贴底(review P1)。
if (readingOlderRef.current) {
@@ -2370,57 +2255,12 @@ 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
- // would visibly cut the smooth scroll short and jump straight to the end.
- if (programmaticAnimatedScrollInFlightRef.current) {
- runStickToLatestVerify();
- return;
- }
- // 补滚护栏:死区去噪 + 振荡断路,掐断「scrollToEnd → 重测 → onContentSizeChange」
- // 洪泛环(JS 忙死、冷开消息区空白;语义与参数见 messageScroll.ts 护栏段)。
- // 单调增长(流式/冷开/回填)不限流,每次跟进;只有高度往返振荡才跳闸。
- const decision = evaluateMobileFollowEndContentSizePin(followEndPinStateRef.current, {
- now: Date.now(),
- contentHeight: height,
- });
- if (decision.trippedNow) {
- // 诊断告警(每个护栏周期一次——护栏状态随会话切换/显式跳底重建后可再报):
- // 现场无日志通道,这条 warn 是洪泛环被触发的唯一取证点。
- console.warn(
- '[message-list] contentSize follow-pin circuit tripped: '
- + `oscillating item measurements suspected (height=${Math.round(height)}, viewport=${Math.round(viewportHeight)})`,
- );
- }
- if (decision.suppressionStarted) {
- // 断路到期 + 缓冲一帧后清账:仍在贴底跟随(用户没上翻)时补一次落底,
- // 覆盖「振荡在断路窗内自然停息、最终高度停在半空」的收尾状态。
- if (followEndPinRecoveryTimerRef.current) clearTimeout(followEndPinRecoveryTimerRef.current);
- followEndPinRecoveryTimerRef.current = setTimeout(() => {
- followEndPinRecoveryTimerRef.current = null;
- if (nearBottomRef.current && !readingOlderRef.current) {
- scrollToEndProgrammatically(false);
- // 清账补滚同样不保证真的落底(measurement 结算 / mVCP 吸收的静默落空同源风险),
- // 跑一轮校验/补滚兜底。
- runStickToLatestVerify();
- }
- }, MOBILE_FOLLOW_END_PIN_SUPPRESS_MS + 50);
- }
- if (decision.shouldScroll) {
- scrollToEndProgrammatically(false);
- // 贴底追赶的落底一样不校验就可能落空(陈旧 metrics / mVCP 吸收),补一轮有界校验。
- runStickToLatestVerify();
- }
- }
+ getTailFollower().contentChanged();
}, [
- isUserControllingScroll,
+ getTailFollower,
markMobileMvcpSettle,
restoreHistoryAnchorOnce,
- runStickToLatestVerify,
scheduleHistoryAnchorRestore,
- scrollToEndProgrammatically,
]);
// 首次落底:完整历史已经在列表里。短暂遮住命令式落底与首轮测量校正,随后由 native
@@ -2435,22 +2275,13 @@ export function MessageRenderer({
}
initialAnchorDoneRef.current = true;
- const generation = initialAnchorGenerationRef.current + 1;
- initialAnchorGenerationRef.current = generation;
- if (initialAnchorFrameRef.current !== null) cancelAnimationFrame(initialAnchorFrameRef.current);
- if (initialAnchorVerifyFrameRef.current !== null) cancelAnimationFrame(initialAnchorVerifyFrameRef.current);
+ const generation = initialRevealGenerationRef.current + 1;
+ initialRevealGenerationRef.current = generation;
initialRevealAnimationRef.current?.stop();
initialRevealProgress.setValue(0);
setListRevealed(false);
- const revealDeadlineAt = Date.now() + MOBILE_INITIAL_REVEAL_MAX_MS;
-
const finish = () => {
- if (initialAnchorGenerationRef.current !== generation) return;
- if (initialAnchorVerifyFrameRef.current !== null) {
- cancelAnimationFrame(initialAnchorVerifyFrameRef.current);
- initialAnchorVerifyFrameRef.current = null;
- }
- setListRevealed(true);
+ if (initialRevealGenerationRef.current === generation) setListRevealed(true);
};
const revealAnimation = Animated.timing(initialRevealProgress, {
@@ -2467,57 +2298,8 @@ export function MessageRenderer({
if (finished) finish();
});
- const verify = (attempts: number, waitRounds: number) => {
- if (initialAnchorGenerationRef.current !== generation) return;
- // The native reveal is a real wall-clock deadline. If JS resumes after it, do not expose a
- // late corrective scroll on an already-visible list.
- if (Date.now() >= revealDeadlineAt) {
- initialAnchorVerifyFrameRef.current = null;
- setListRevealed(true);
- return;
- }
- const preserveVisibleContentPosition = readingOlderRef.current
- || isMobileMvcpSettling(Date.now(), mvcpSettleAtRef.current);
- const action = evaluateMobileAnchorVerify({
- attempts,
- listVisible: true,
- metrics: scrollMetricsRef.current,
- preserveVisibleContentPosition,
- stickToLatest: nearBottomRef.current && !userScrollForOlderRef.current,
- waitRounds,
- });
- if (action === 'settled' || action === 'give-up') {
- // The native animation owns the visual deadline. Settling early only stops verification;
- // it must not replace that deadline or expose the hidden correction frames.
- initialAnchorVerifyFrameRef.current = null;
- return;
- }
- if (action === 'retry') scrollToEndProgrammatically(false);
- initialAnchorVerifyFrameRef.current = requestAnimationFrame(() => {
- initialAnchorVerifyFrameRef.current = requestAnimationFrame(() => {
- initialAnchorVerifyFrameRef.current = null;
- verify(
- attempts + (action === 'retry' ? 1 : 0),
- waitRounds + (action === 'wait' ? 1 : 0),
- );
- });
- });
- };
-
- // Issue the first correction synchronously in the layout effect so native receives it before
- // the UI-thread reveal starts, even when subsequent Markdown/cell work blocks JS.
+ // The controller seeks unmeasured rows once and owns all subsequent native correction.
scrollToEndProgrammatically(false);
- initialAnchorFrameRef.current = requestAnimationFrame(() => {
- initialAnchorFrameRef.current = null;
- if (initialAnchorGenerationRef.current !== generation) return;
- initialAnchorVerifyFrameRef.current = requestAnimationFrame(() => {
- initialAnchorVerifyFrameRef.current = requestAnimationFrame(() => {
- initialAnchorVerifyFrameRef.current = null;
- if (initialAnchorGenerationRef.current !== generation) return;
- verify(0, 0);
- });
- });
- });
}, [
initialRevealProgress,
listData.length,
@@ -2530,11 +2312,6 @@ export function MessageRenderer({
// 竞态误触发自动拉历史),此处不重复。
useEffect(() => {
lastAppliedFocusKeyRef.current = null;
- // 上个会话遗留的断路清账 timer 作废(护栏状态本体已在渲染期同步块重建)。
- if (followEndPinRecoveryTimerRef.current) {
- clearTimeout(followEndPinRecoveryTimerRef.current);
- followEndPinRecoveryTimerRef.current = null;
- }
setIsAwayFromBottom(false);
setPreviousUserTarget(null);
setHasNewMessages(false);
@@ -2542,18 +2319,13 @@ export function MessageRenderer({
// 卸载时清掉在飞的定时器/rAF(闭包引用 listRef,卸载后触发是无害 no-op,
// 但不留悬挂句柄)。
useEffect(() => () => {
- initialAnchorGenerationRef.current += 1;
+ initialRevealGenerationRef.current += 1;
readingOlderRequestGenerationRef.current += 1;
historyPrependTransactionRef.current = null;
- followVerifyGenerationRef.current += 1;
- if (followEndPinRecoveryTimerRef.current) clearTimeout(followEndPinRecoveryTimerRef.current);
+ tailFollowerRef.current?.reset();
clearProgrammaticScroll();
- if (initialAnchorFrameRef.current !== null) cancelAnimationFrame(initialAnchorFrameRef.current);
- if (initialAnchorVerifyFrameRef.current !== null) cancelAnimationFrame(initialAnchorVerifyFrameRef.current);
- if (followVerifyFrameRef.current !== null) cancelAnimationFrame(followVerifyFrameRef.current);
if (queuedLoadEarlierFlushFrameRef.current !== null) cancelAnimationFrame(queuedLoadEarlierFlushFrameRef.current);
if (historyAnchorVerifyFrameRef.current !== null) cancelAnimationFrame(historyAnchorVerifyFrameRef.current);
- if (followVerifyTimerRef.current !== null) clearTimeout(followVerifyTimerRef.current);
if (scrollHistoryEvaluationTimerRef.current !== null) clearTimeout(scrollHistoryEvaluationTimerRef.current);
initialRevealAnimationRef.current?.stop();
}, [clearProgrammaticScroll]);
diff --git a/apps/mobile/src/session/messageScroll.ts b/apps/mobile/src/session/messageScroll.ts
index 458cb26ee3..4d10189564 100644
--- a/apps/mobile/src/session/messageScroll.ts
+++ b/apps/mobile/src/session/messageScroll.ts
@@ -338,30 +338,14 @@ export function mobileMessageListKeysSignature(keys: readonly string[]): string
return keys.join('\0');
}
-export interface MobileFollowVerifyStartDelayInput {
- animatedScrollInFlight: boolean;
- now: number;
- settleAt: number;
-}
-
-/**
- * Animated `scrollToEnd` must own the viewport until its bounded settle window closes.
- * Starting the verifier earlier would read an expected in-flight offset and replace the
- * smooth animation with an immediate non-animated retry.
- */
-export function mobileFollowVerifyStartDelayMs(
- input: MobileFollowVerifyStartDelayInput,
-): number {
- if (!input.animatedScrollInFlight) return 0;
- return Math.max(0, input.settleAt - input.now);
-}
-
export interface MobileAnchorVerifyInput {
attempts: number;
listVisible: boolean;
metrics: MessageScrollMetrics;
preserveVisibleContentPosition: boolean;
stickToLatest: boolean;
+ /** Finger drag / native momentum owns the viewport, including iOS overscroll bounce. */
+ userControllingScroll: boolean;
waitRounds: number;
}
@@ -381,21 +365,21 @@ export type MobileAnchorVerifyAction =
* 背景:贴底跟随的落底 scrollToOffset 存在两类静默落空——
* (a) 行坐标或 size 锚定尚在结算的帧里执行,被后续布局调整吸收/抵消;
* (b) 落底一刻 scrollMetricsRef 里的 contentHeight / viewportHeight 是陈旧值,目标
- * offset 偏短,且之后再无 contentSize / layout 事件来纠正。
- * 两类的共同结果都是「最新消息停在底部浮层(composer)后面」。verify 环在每次落底后
- * 校验 offset 是否真到内容末端,未到位则带上限补滚,从机制上兜掉所有此类竞态。
+ * offset 偏短或内容收缩后偏长,且之后再无 contentSize / layout 事件来纠正。
+ * 偏短会把最新消息留在 composer 后面,偏长会把消息顶上去并留下尾部空白。
+ * 用户没有控制滚动时,校验 offset 与真实末端的双向距离,未到位则带上限补滚。
*/
export function evaluateMobileAnchorVerify(input: MobileAnchorVerifyInput): MobileAnchorVerifyAction {
if (!input.stickToLatest || !input.listVisible) return 'settled';
// 行坐标 / size 锚定仍在 settle 窗口:此刻补滚可能被后续布局吸收,下一轮再判。
// 等待走独立预算,不消耗补滚额度。
const { contentHeight, offsetY, viewportHeight } = input.metrics;
- if (input.preserveVisibleContentPosition || contentHeight <= 0 || viewportHeight <= 0) {
+ if (input.userControllingScroll || input.preserveVisibleContentPosition || contentHeight <= 0 || viewportHeight <= 0) {
return input.waitRounds >= MOBILE_ANCHOR_VERIFY_MAX_WAIT_ROUNDS ? 'give-up' : 'wait';
}
- // 内容不足一屏时 end offset 为 0,任何非负 offset 都算贴底(iOS bounce 可为负,同样无遮挡)。
+ // 不足一屏时也必须回到 0;原生测量收缩后残留的正 offset 不是有效的贴底位置。
const endOffset = mobileMessageListEndOffset(input.metrics);
- if (offsetY >= endOffset - MOBILE_ANCHOR_VERIFY_TOLERANCE) return 'settled';
+ if (Math.abs(offsetY - endOffset) <= MOBILE_ANCHOR_VERIFY_TOLERANCE) return 'settled';
if (input.attempts >= MOBILE_ANCHOR_VERIFY_MAX_ATTEMPTS) return 'give-up';
return 'retry';
}
diff --git a/apps/mobile/src/session/messageTailFollower.ts b/apps/mobile/src/session/messageTailFollower.ts
new file mode 100644
index 0000000000..2a82a7e8a4
--- /dev/null
+++ b/apps/mobile/src/session/messageTailFollower.ts
@@ -0,0 +1,177 @@
+import {
+ createMobileFollowEndPinState,
+ evaluateMobileAnchorVerify,
+ evaluateMobileFollowEndContentSizePin,
+ isMobileMvcpSettling,
+ mobileMessageListEndOffset,
+ MOBILE_ANCHOR_VERIFY_TOLERANCE,
+ type MessageScrollMetrics,
+} from './messageScroll';
+
+export interface MobileTailSnapshot {
+ metrics: MessageScrollMetrics;
+ stickToLatest: boolean;
+ userControllingScroll: boolean;
+ preservingHistory: boolean;
+ layoutSettleAt: number;
+ animatedScrollUntil: number;
+}
+
+export interface MobileTailFollowerAdapter {
+ read: () => MobileTailSnapshot;
+ /** Initial / explicit seeking can materialize the last unmeasured virtualized rows. */
+ seekEnd: (animated: boolean) => void | Promise<void>;
+ /** Correct using the same native coordinate system used to verify the result. */
+ correctOffset: (offset: number) => void;
+ onMeasurementOscillation?: () => void;
+}
+
+/**
+ * One tail writer and one bounded reconciliation loop for initial entry, live growth and jumps.
+ * History anchoring remains owned by the platform adapter. Gesture release / layout events wake
+ * this controller; holding a finger never polls. Presentation (including reveal) owns no scrolling.
+ */
+export function createMobileTailFollower(adapter: MobileTailFollowerAdapter) {
+ let generation = 0;
+ let active = false;
+ let frame: number | null = null;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ let timerDeadline = 0;
+ let resumeTimer: (() => void) | null = null;
+ let pendingSeek: object | null = null;
+ let pinState = createMobileFollowEndPinState();
+
+ function cancel() {
+ generation += 1;
+ active = false;
+ if (frame !== null) cancelAnimationFrame(frame);
+ if (timer !== null) clearTimeout(timer);
+ frame = null;
+ timer = null;
+ resumeTimer = null;
+ }
+
+ function reset() {
+ cancel();
+ pendingSeek = null;
+ pinState = createMobileFollowEndPinState();
+ }
+
+ function reconcile() {
+ if (pendingSeek) return;
+ if (active) {
+ const snapshot = adapter.read();
+ // A touch can cancel an animation before its old deadline. Wake the same run without
+ // renewing its retry budget; schedule still respects gesture/history and measurement guards.
+ if (timer !== null
+ && Math.max(snapshot.animatedScrollUntil, pinState.suppressedUntil) < timerDeadline) {
+ clearTimeout(timer);
+ const resume = resumeTimer;
+ timer = null;
+ resumeTimer = null;
+ resume?.();
+ }
+ return;
+ }
+ active = true;
+ const run = ++generation;
+ const schedule = (attempts: number, waitRounds: number) => {
+ const snapshot = adapter.read();
+ if (!snapshot.stickToLatest || snapshot.userControllingScroll || snapshot.preservingHistory) {
+ active = false;
+ return;
+ }
+ const delay = Math.max(snapshot.animatedScrollUntil, pinState.suppressedUntil) - Date.now();
+ if (delay > 0) {
+ timerDeadline = Date.now() + delay;
+ resumeTimer = () => {
+ if (generation === run) schedule(attempts, waitRounds);
+ };
+ timer = setTimeout(() => {
+ timer = null;
+ resumeTimer = null;
+ if (generation === run) schedule(attempts, waitRounds);
+ }, delay);
+ return;
+ }
+ frame = requestAnimationFrame(() => {
+ if (generation !== run) return;
+ frame = requestAnimationFrame(() => {
+ frame = null;
+ if (generation !== run) return;
+ const current = adapter.read();
+ if (!current.stickToLatest || current.userControllingScroll || current.preservingHistory) {
+ active = false;
+ return;
+ }
+ // An explicit animation or a measurement circuit may have begun after scheduling.
+ if (Math.max(current.animatedScrollUntil, pinState.suppressedUntil) > Date.now()) {
+ schedule(attempts, waitRounds);
+ return;
+ }
+ const action = evaluateMobileAnchorVerify({
+ attempts,
+ waitRounds,
+ listVisible: true,
+ metrics: current.metrics,
+ stickToLatest: current.stickToLatest,
+ userControllingScroll: current.userControllingScroll,
+ preserveVisibleContentPosition: isMobileMvcpSettling(Date.now(), current.layoutSettleAt),
+ });
+ if (action === 'settled' || action === 'give-up') {
+ active = false;
+ return;
+ }
+ if (action === 'retry') adapter.correctOffset(mobileMessageListEndOffset(current.metrics));
+ if (generation !== run) return;
+ schedule(attempts + (action === 'retry' ? 1 : 0), waitRounds + (action === 'wait' ? 1 : 0));
+ });
+ });
+ };
+ schedule(0, 0);
+ }
+
+ function requestEnd(animated: boolean, explicit = false) {
+ const snapshot = adapter.read();
+ if (!snapshot.stickToLatest || snapshot.preservingHistory) return;
+ if (!explicit && snapshot.userControllingScroll) return;
+ reset();
+ const seek = {};
+ pendingSeek = seek;
+ const finish = () => {
+ if (pendingSeek !== seek) return;
+ pendingSeek = null;
+ reconcile();
+ };
+ // LegendList queues seeking by last index. Any offset command would cancel that seek.
+ // Its promise settles the command lifecycle, not the native position: verify afterwards.
+ const completion = adapter.seekEnd(animated);
+ if (completion) void completion.then(finish, finish);
+ else finish();
+ }
+
+ function contentChanged() {
+ if (pendingSeek) return;
+ const snapshot = adapter.read();
+ if (!snapshot.stickToLatest || snapshot.userControllingScroll || snapshot.preservingHistory) return;
+ const { contentHeight, viewportHeight, offsetY } = snapshot.metrics;
+ if (contentHeight <= 0 || viewportHeight <= 0) return;
+ if (snapshot.animatedScrollUntil <= Date.now()) {
+ const decision = evaluateMobileFollowEndContentSizePin(pinState, {
+ now: Date.now(), contentHeight,
+ });
+ if (decision.trippedNow) adapter.onMeasurementOscillation?.();
+ // Live growth stays immediate. A short list needs only reconciliation after measurement.
+ const end = mobileMessageListEndOffset(snapshot.metrics);
+ if (decision.shouldScroll && contentHeight > viewportHeight
+ && Math.abs(offsetY - end) > MOBILE_ANCHOR_VERIFY_TOLERANCE) {
+ adapter.correctOffset(end);
+ }
+ }
+ reconcile();
+ }
+
+ return { requestEnd, contentChanged, reconcile, reset };
+}
+
+export type MobileTailFollower = ReturnType<typeof createMobileTailFollower>;