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): 重连补同步时消息列表不再跳动、旧历史不再被丢弃 (#5812)

Dash02d5f32a4911
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 875d0169f7..f6ebce8d72 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -539,6 +539,7 @@ import {
type MobileVoiceDictionaryLearningTracker,
} from '@/session/mobileVoiceDictionaryLearning';
import {
+ bridgeLatestMessagePage,
hasOlderMessagesAfterReopen,
hasOlderMessagesByServerCount,
listMessagesWithPayloadRetry,
@@ -3800,7 +3801,7 @@ export default function SessionScreen() {
return { messages: [], limit: 20, reducedByPayloadTooLarge: false };
}
if (!isHistoryViewUnavailable(viewState.error)) throw viewState.error;
- return retryRead(() => listMessagesWithPayloadRetry(
+ const latest = await retryRead(() => listMessagesWithPayloadRetry(
(limit) => runSessionMessagesSnapshotSingleFlight(
snapshotScope,
limit,
@@ -3809,6 +3810,17 @@ export default function SessionScreen() {
),
isReopen ? REOPEN_MESSAGE_WINDOW_LIMITS : undefined,
));
+ // 整窗替换不保留旧段,无需补读。
+ if (options.replaceMessages) return latest;
+ return bridgeLatestMessagePage(latest, {
+ needsBridge: (rows, more) =>
+ remoteSessionStore.latestMessageWindowNeedsBridge(sessionId, rows, more),
+ // 与最新页同一套瞬态重试;仍失败时整轮同步失败,不提交接不上的窗口。
+ readBefore: (before) => retryRead(() => listMessagesWithPayloadRetry(
+ (limit) => maker.listMessages(sessionId, { limit, before }),
+ )),
+ isCurrent,
+ });
},
isCurrent,
commitMessages: (history) => {
diff --git a/apps/mobile/src/__tests__/messageListVirtualization.test.ts b/apps/mobile/src/__tests__/messageListVirtualization.test.ts
index 1f381a287e..af0482a53d 100644
--- a/apps/mobile/src/__tests__/messageListVirtualization.test.ts
+++ b/apps/mobile/src/__tests__/messageListVirtualization.test.ts
@@ -35,12 +35,16 @@ describe('mobile message list container', () => {
expect(source).not.toContain('MOBILE_TAIL_REVEAL_ITEM_COUNT');
expect(listSource).not.toMatch(/\binitialScrollIndex\s*=/);
// Manual data prepend 不能与 Android native MVCP 并行:它会在 cell 位置提交后异步补
- // offset,中间坐标窗无 cell 而白屏。普通 data / size 变化仍由 LegendList 锚定。
+ // offset,中间坐标窗无 cell 而白屏。size 变化始终由 LegendList 锚定;data 变化只在读历史
+ // 时锚定——贴底跟随时锚定会把被整批替换的旧可见行钉住,重连补同步时先跳上去再拉回底部。
expect(listSource).toContain('alignItemsAtEnd');
expect(listSource).toContain('maintainScrollAtEnd');
expect(listSource).toContain('maintainVisibleContentPosition={historyPrependNativeMvcpDisabled');
expect(listSource).toContain('? false');
- expect(listSource).toContain(': { data: true, size: true }}');
+ expect(listSource).toContain(': { data: anchorVisibleRowsOnDataChange, size: true }}');
+ expect(source).toContain(
+ 'const anchorVisibleRowsOnDataChange = isAwayFromBottom || readingOlderRef.current;',
+ );
expect(source).toContain('mobileHistoryPrependUsesAppOwnedAnchor(');
expect(source).toContain('MOBILE_HISTORY_PREPEND_USES_APP_OWNED_ANCHOR');
expect(source).toContain('captureMobileHistoryAnchor(');
diff --git a/apps/mobile/src/__tests__/messagePaging.test.ts b/apps/mobile/src/__tests__/messagePaging.test.ts
index e4b4dfafcc..ee653413cb 100644
--- a/apps/mobile/src/__tests__/messagePaging.test.ts
+++ b/apps/mobile/src/__tests__/messagePaging.test.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
+ bridgeLatestMessagePage,
hasMoreOlderMessages,
hasOlderMessagesAfterReopen,
collectCompleteIncrementalMessages,
@@ -8,6 +9,7 @@ import {
latestMessageCursor,
listMessagesWithPayloadRetry,
MESSAGE_PAGE_SIZE,
+ type MessagePageRetryResult,
oldestMessageCursor,
projectLoadedMessageWindow,
projectLoadedMessageWindowIncrementally,
@@ -670,4 +672,62 @@ describe('messagePaging', () => {
expect(hasOlderMessagesByServerCount(3, withSystemCard)).toBe(true);
});
});
+
+ describe('bridgeLatestMessagePage', () => {
+ const at = (second: number) => `2026-01-01T00:00:${String(second).padStart(2, '0')}.000Z`;
+ const page = (ids: number[], limit = 2): MessagePageRetryResult => ({
+ messages: ids.map((id) => message(`m${id}`, at(id))),
+ limit,
+ reducedByPayloadTooLarge: false,
+ });
+ // m1..m9 on the host; the client already verified up to m3.
+ const host = (before: string) => {
+ const index = Number(before.slice(1));
+ return Promise.resolve(page([index - 2, index - 1].filter((id) => id >= 1)));
+ };
+ const reachesM3 = (rows: readonly RemoteMessage[]) => !rows.some((row) => row.id === 'm3');
+
+ it('returns the latest page unchanged when it already joins', async () => {
+ const latest = page([8, 9]);
+ const readBefore = vi.fn(host);
+ await expect(bridgeLatestMessagePage(latest, {
+ needsBridge: () => false, readBefore, isCurrent: () => true,
+ })).resolves.toBe(latest);
+ expect(readBefore).not.toHaveBeenCalled();
+ });
+
+ it('reads older pages until the window joins and keeps the oldest page continuation', async () => {
+ const readBefore = vi.fn(host);
+ const bridged = await bridgeLatestMessagePage(page([8, 9]), {
+ needsBridge: reachesM3, readBefore, isCurrent: () => true,
+ });
+ expect(readBefore.mock.calls.map(([before]) => before)).toEqual(['m8', 'm6', 'm4']);
+ expect(bridged.messages.map((row) => row.id)).toEqual(['m2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9']);
+ expect(shouldKeepOlderMessagesAffordance(bridged)).toBe(true);
+ });
+
+ it('stops at the page budget, at history start, or when superseded', async () => {
+ const capped = await bridgeLatestMessagePage(page([8, 9]), {
+ needsBridge: reachesM3, readBefore: host, isCurrent: () => true, maxPages: 1,
+ });
+ expect(capped.messages.map((row) => row.id)).toEqual(['m6', 'm7', 'm8', 'm9']);
+
+ const start = await bridgeLatestMessagePage(page([2, 3]), {
+ needsBridge: () => true, readBefore: host, isCurrent: () => true,
+ });
+ expect(start.messages.map((row) => row.id)).toEqual(['m1', 'm2', 'm3']);
+ expect(shouldKeepOlderMessagesAffordance(start)).toBe(false);
+
+ const latest = page([8, 9]);
+ await expect(bridgeLatestMessagePage(latest, {
+ needsBridge: reachesM3, readBefore: host, isCurrent: () => false,
+ })).resolves.toBe(latest);
+ });
+
+ it('fails the snapshot when a bridge read fails, so recovery retries instead of committing a gap', async () => {
+ await expect(bridgeLatestMessagePage(page([8, 9]), {
+ needsBridge: reachesM3, readBefore: () => Promise.reject(new Error('INVOKE_TIMEOUT')), isCurrent: () => true,
+ })).rejects.toThrow('INVOKE_TIMEOUT');
+ });
+ });
});
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 36c917f39b..13b4a0fadd 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -2435,6 +2435,94 @@ describe('remoteSessionStore', () => {
]);
});
+ it('断流期间漏收超过一页:补读到已验证上界后,整段旧历史保留', () => {
+ remoteSessionStore.setMessages('s1', [
+ messageAt('old-1', 's1', '2026-01-01T09:00:01.000Z'),
+ messageAt('old-2', 's1', '2026-01-01T09:00:02.000Z'),
+ ]);
+ remoteSessionStore.noteLiveStreamInterrupted();
+ const latestPage = [
+ messageAt('gap-3', 's1', '2026-01-01T09:00:05.000Z'),
+ messageAt('gap-4', 's1', '2026-01-01T09:00:06.000Z'),
+ ];
+ // 本页最旧行晚于已验证上界:直接提交会丢掉 old-*,所以需要先补读。
+ expect(remoteSessionStore.latestMessageWindowNeedsBridge('s1', latestPage, true)).toBe(true);
+ // 本页不满页(历史到头)、或已验证区间不存在时,补读不改变结果。
+ expect(remoteSessionStore.latestMessageWindowNeedsBridge('s1', latestPage, false)).toBe(false);
+ expect(remoteSessionStore.latestMessageWindowNeedsBridge('s2', latestPage, true)).toBe(false);
+
+ const bridged = [
+ messageAt('old-2', 's1', '2026-01-01T09:00:02.000Z'),
+ messageAt('gap-1', 's1', '2026-01-01T09:00:03.000Z'),
+ messageAt('gap-2', 's1', '2026-01-01T09:00:04.000Z'),
+ ...latestPage,
+ ];
+ expect(remoteSessionStore.latestMessageWindowNeedsBridge('s1', bridged, true)).toBe(false);
+ remoteSessionStore.setLatestMessageWindow('s1', bridged, { moreBeyondWindow: true });
+
+ expect(remoteSessionStore.getMessages('s1').map((item) => item.id)).toEqual([
+ 'old-1',
+ 'old-2',
+ 'gap-1',
+ 'gap-2',
+ 'gap-3',
+ 'gap-4',
+ ]);
+ });
+
+ it('漏推提示后只信区间下界:补读覆盖整段才相接,旧历史不被整段丢弃', () => {
+ remoteSessionStore.noteLiveStreamAcked('s1');
+ remoteSessionStore.setMessages('s1', [
+ messageAt('old-1', 's1', '2026-01-01T09:00:01.000Z'),
+ messageAt('old-2', 's1', '2026-01-01T09:00:02.000Z'),
+ ]);
+ // 订阅内的 push 把上界推过了一条被漏推的 gap-3。
+ remoteSessionStore.appendMessage('s1', messageAt('live-4', 's1', '2026-01-01T09:00:04.000Z'));
+ remoteSessionStore.applyRemotePush('dev-1', SESSION_SYNC_CHANNEL, { sessionId: 's1', resyncRequired: true });
+
+ const latestPage = [
+ messageAt('live-4', 's1', '2026-01-01T09:00:04.000Z'),
+ messageAt('new-5', 's1', '2026-01-01T09:00:05.000Z'),
+ ];
+ // 上界已不可信:即使最新页与 live-4 有交集,也要补读到区间下界。
+ expect(remoteSessionStore.latestMessageWindowNeedsBridge('s1', latestPage, true)).toBe(true);
+ const bridged = [
+ messageAt('old-1', 's1', '2026-01-01T09:00:01.000Z'),
+ messageAt('old-2', 's1', '2026-01-01T09:00:02.000Z'),
+ messageAt('gap-3', 's1', '2026-01-01T09:00:03.000Z'),
+ ...latestPage,
+ ];
+ expect(remoteSessionStore.latestMessageWindowNeedsBridge('s1', bridged, true)).toBe(false);
+ remoteSessionStore.setLatestMessageWindow('s1', bridged, { moreBeyondWindow: true });
+ expect(remoteSessionStore.getMessages('s1').map((item) => item.id)).toEqual([
+ 'old-1', 'old-2', 'gap-3', 'live-4', 'new-5',
+ ]);
+ });
+
+ it('漏推提示后没补读到区间下界时,仍按未验证处置', () => {
+ remoteSessionStore.noteLiveStreamAcked('s1');
+ remoteSessionStore.setMessages('s1', [
+ messageAt('old-1', 's1', '2026-01-01T09:00:01.000Z'),
+ messageAt('old-2', 's1', '2026-01-01T09:00:02.000Z'),
+ ]);
+ remoteSessionStore.appendMessage('s1', messageAt('live-4', 's1', '2026-01-01T09:00:04.000Z'));
+ remoteSessionStore.applyRemotePush('dev-1', SESSION_SYNC_CHANNEL, { sessionId: 's1', resyncRequired: true });
+ remoteSessionStore.setLatestMessageWindow('s1', [
+ messageAt('gap-3', 's1', '2026-01-01T09:00:03.000Z'),
+ messageAt('live-4', 's1', '2026-01-01T09:00:04.000Z'),
+ ], { moreBeyondWindow: true });
+ expect(remoteSessionStore.getMessages('s1').map((item) => item.id)).toEqual(['gap-3', 'live-4']);
+ });
+
+ it('来源不明的缓存段没有已验证区间可接,不触发补读', () => {
+ remoteSessionStore.hydrateMessagesIfEmpty('s1', [
+ messageAt('cached-old', 's1', '2026-01-01T00:00:01.000Z'),
+ ]);
+ expect(remoteSessionStore.latestMessageWindowNeedsBridge('s1', [
+ messageAt('latest-1', 's1', '2026-01-01T10:00:01.000Z'),
+ ], true)).toBe(false);
+ });
+
it('rejects late paging whose anchor was removed by a concurrent latest-window refresh', () => {
const old = messageAt('old-anchor', 's1', '2026-01-01T09:00:00.000Z');
const latest = messageAt('new-anchor', 's1', '2026-01-01T10:00:00.000Z');
diff --git a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts
index 76909702ff..6c725ed7d7 100644
--- a/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts
+++ b/apps/mobile/src/__tests__/sessionMessageMemoryWiring.test.ts
@@ -78,7 +78,9 @@ describe('任务消息内存治理页面接线', () => {
expect(screen).toContain('remoteSessionStore.mergeMessages(sessionIdAtStart, rows, { authority: messageAuthority });');
// First open and reopen now share the same authority-fenced history read.
expect(screen).toContain('syncSessionMessageWindow({');
- expect(screen.match(/maker\.listMessages\(/g)).toHaveLength(3);
+ // 第 4 处是重连补读(bridgeLatestMessagePage)沿 before 的往前读,结果仍经同一 authority 的
+ // setLatestMessageWindow 提交。
+ expect(screen.match(/maker\.listMessages\(/g)).toHaveLength(4);
});
it('schedule 关闭翻历史入口,页面工作租约覆盖发送与附件状态', () => {
diff --git a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
index 1778ad43fb..bd2cbea73b 100644
--- a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
+++ b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
@@ -6,7 +6,11 @@ import { createRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';
import { runConnectionScopedSessionMetadataRead, waitForIndependentSnapshotReads } from '@/device-link/sessionSnapshotSingleFlight';
import { syncSessionMessageWindow } from '@/session/sessionMessageWindowSync';
import { shouldClearOperationErrorAfterSync } from '@/session/sessionSyncErrorRecovery';
-import { hasOlderMessagesAfterReopen, shouldKeepOlderMessagesAffordance } from '@/session/messagePaging';
+import {
+ bridgeLatestMessagePage,
+ hasOlderMessagesAfterReopen,
+ shouldKeepOlderMessagesAffordance,
+} from '@/session/messagePaging';
import { HistoryViewController, isHistoryViewUnavailable, projectHistoryView } from '@cindy/maker-shared/message-window';
// Execute the actual page callbacks, not a duplicate orchestration written for tests.
@@ -52,7 +56,9 @@ function historyAvailable(status: string, presence: boolean | null): boolean {
}
const tick = () => new Promise((done) => setTimeout(done, 0));
const session = { id: 's1', updatedAt: '2026-09-06T00:00:00Z', _count: { messages: 100 } };
-const page = { messages: [{ id: 'm1' }], limit: 1, reducedByPayloadTooLarge: false };
+const page = {
+ messages: [{ id: 'm1' }] as { id: string; clientId?: string }[], limit: 1, reducedByPayloadTooLarge: false,
+};
function fixture(reopen = false, remoteHistoryAvailable = true) {
const state = {
@@ -81,6 +87,7 @@ function fixture(reopen = false, remoteHistoryAvailable = true) {
isSessionMessageWindowSynced: vi.fn(() => false),
setMessages: vi.fn((_id, rows) => { state.rows = rows; }),
setLatestMessageWindow: vi.fn((_id, rows) => { state.rows = rows; }),
+ latestMessageWindowNeedsBridge: vi.fn(() => false),
markSessionMessagesSynced: vi.fn(),
setPendingInteractions: vi.fn(), setInputProjectionIfCurrent: vi.fn(),
setActiveSessionSnapshots: vi.fn(),
@@ -117,6 +124,7 @@ function fixture(reopen = false, remoteHistoryAvailable = true) {
getSubscriptionIdentity: (): number | null => null, notificationResponse: null,
syncedNotificationResponseRef: { current: null },
shouldKeepOlderMessagesAffordance, hasOlderMessagesAfterReopen,
+ bridgeLatestMessagePage,
messageWindowReconciledRef: { current: false },
setHasOlderMessages: (value: boolean) => { state.older = value; },
setLoading: (value: boolean) => { state.loading = value; },
@@ -247,6 +255,34 @@ describe('production session recovery callbacks', () => {
expect(f.state.rows).toEqual(page.messages);
expect(f.store.markSessionMessagesSynced).toHaveBeenCalled();
});
+ it('reads before the latest page until it joins the verified window, then commits once', async () => {
+ const f = fixture(true);
+ f.store.latestMessageWindowNeedsBridge.mockReturnValueOnce(true).mockReturnValue(false);
+ f.maker.listMessages
+ .mockResolvedValueOnce({ ...page, messages: [{ id: 'm2', clientId: 'm2' }], limit: 1 })
+ .mockResolvedValueOnce({ ...page, messages: [{ id: 'm1', clientId: 'm1' }], limit: 1 });
+ await f.sync();
+ expect(f.maker.listMessages.mock.calls.map((call) => (call as unknown[])[1])).toEqual([
+ { limit: 20 },
+ { limit: 20, before: 'm2' },
+ ]);
+ expect(f.store.setLatestMessageWindow).toHaveBeenCalledTimes(1);
+ expect(f.state.rows.map((row) => row.id)).toEqual(['m1', 'm2']);
+ });
+
+ it('does not commit an unbridged window when a bridge read fails', async () => {
+ const f = fixture(true);
+ const cached = f.state.rows;
+ f.store.latestMessageWindowNeedsBridge.mockReturnValue(true);
+ f.maker.listMessages
+ .mockResolvedValueOnce({ ...page, messages: [{ id: 'm2', clientId: 'm2' }], limit: 1 })
+ .mockRejectedValueOnce(new Error('INVOKE_TIMEOUT'));
+ await f.sync().catch(() => undefined);
+ expect(f.store.setLatestMessageWindow).not.toHaveBeenCalled();
+ expect(f.state.rows).toBe(cached);
+ expect(f.state.syncError).not.toBeNull();
+ });
+
it('accepts a history view without certifying sparse rows as a complete raw window', async () => {
const f = fixture();
f.bindings.historyView.view.getSnapshot = () => ({ ready: true, error: null });
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 3a843297b0..c7e82b8700 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -162,7 +162,11 @@ import {
updatePresenceAvailability,
} from '@/device-link/presenceRecovery';
import { createOfflineMirrorWipeQueue } from '@/device-link/offlineMirrorWipeQueue';
-import { hasMoreOlderMessages } from '@/session/messagePaging';
+import {
+ bridgeLatestMessagePage,
+ listMessagesWithPayloadRetry,
+ shouldKeepOlderMessagesAffordance,
+} from '@/session/messagePaging';
import type { InputProjection, PendingInteraction, RemoteMessage } from '@/session/types';
import { prepareVisualMockDeviceLinkContext } from '@/debug/visualMock';
import { meterDeviceLinkInvokes, recordDeviceLinkPush } from '@/debug/deviceLinkTraffic';
@@ -1766,15 +1770,14 @@ async function rebuildSessionSnapshot(
// 其余(旧实现共用一个 catch,任一失败三份快照全丢)。goal 覆盖断连窗口内
// 丢失的 maker:goal:status-changed push;model-pref / turn-cost 无对应查询通道,
// 暂不在补齐范围(需扩桌面端 invoke 白名单)。
- const applyHistory = (value: RemoteMessage[]) => {
+ const applyHistory = (value: RemoteMessage[], moreBeyondWindow: boolean) => {
if (!isCurrent()) return false;
if (Array.isArray(value)) {
// moreBeyondWindow:这一页上沿之外服务端还有历史(满 80 条,或被 device-link 裁过行)。为真时
- // store 不保留早于本页的缓存段 —— 断连期间漏收的 push 可能正落在两段之间,保留就在窗口里
- // 留下孤岛,而漏收的量不大时两侧时间差很小、时间阈值的空洞检测发现不了(#1222)。
- const windowOptions = {
- moreBeyondWindow: hasMoreOlderMessages(value, RECONNECT_MESSAGE_WINDOW_LIMIT),
- };
+ // store 不保留接不上已验证区间的缓存段 —— 断连期间漏收的 push 可能正落在两段之间,保留就在
+ // 窗口里留下孤岛,而漏收的量不大时两侧时间差很小、时间阈值的空洞检测发现不了(#1222)。
+ // readHistory 会先补读到接上为止,接上的旧段因此得以保留。
+ const windowOptions = { moreBeyondWindow };
if (messageAuthorityAtRequestStart) {
return remoteSessionStore.setLatestMessageWindow(sessionId, value, {
...windowOptions,
@@ -1854,7 +1857,27 @@ async function rebuildSessionSnapshot(
if (!snapshot.error && snapshot.ready) return true;
if (!isHistoryViewUnavailable(snapshot.error)) throw snapshot.error;
}
- return applyHistory(await readRawHistory());
+ const latest = await readRawHistory();
+ if (!Array.isArray(latest)) return applyHistory(latest, false);
+ // 断线期间漏收超过一页时,最新一页接不上已验证区间;先往前补读,避免旧历史被整段丢弃。
+ const page = await bridgeLatestMessagePage(
+ { messages: latest, limit: RECONNECT_MESSAGE_WINDOW_LIMIT, reducedByPayloadTooLarge: false },
+ {
+ needsBridge: (rows, more) =>
+ remoteSessionStore.latestMessageWindowNeedsBridge(sessionId, rows, more),
+ readBefore: (before) => listMessagesWithPayloadRetry(
+ (limit) => sendInvokeWithAccessHandling<RemoteMessage[]>(
+ client,
+ deviceId,
+ 'local-db:messages:list',
+ [sessionId, { limit, before }],
+ sendOpts,
+ ),
+ ),
+ isCurrent,
+ },
+ );
+ return applyHistory(page.messages, shouldKeepOlderMessagesAffordance(page));
};
const [history, pending, projection, goal] = await Promise.all([
measured('history', readHistory(), (applied) => applied),
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index cdd2f625fc..ffaf57fd50 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -2761,6 +2761,13 @@ export function MessageRenderer({
// native detach/attach batches and try to mount a child that still belongs to
// the previous row. listperf keeps the DEV-only override for explicit A/Bs.
const recycleItems = __DEV__ ? devRecycleItems === true : false;
+ // 贴底跟随时数据变化不做可见位置锚定:重连补同步会整批替换 / 丢弃尾部行,锚定会把旧的可见行
+ // 钉在原屏幕位置,先露出新内容的开头(甚至列表顶部)再被贴底跟随拉回,表现为「跳一下又跳回来」。
+ // 不锚定时内容变短由原生滚动范围直接截到新底部,变长由贴底跟随补滚。读历史(离开底部,或
+ // 「加载更早」事务进行中——它可能由自动补齐在贴底时发起)仍靠锚定保住正在看的行。
+ // readingOlderRef 在事务开始与结束时都会伴随一次重渲染(loadingEarlier / 事务收尾的 state),
+ // 这里在渲染期读取它足以让 prepend 那次数据提交带上锚定。
+ const anchorVisibleRowsOnDataChange = isAwayFromBottom || readingOlderRef.current;
return (
// chat-text-quote:Provider 恒挂载(值可为 null),避免启用态翻转时整棵消息树
@@ -2796,12 +2803,12 @@ export function MessageRenderer({
// 二分实锤,3.3.2 / 3.3.3 均复现)。
alignItemsAtEnd
maintainScrollAtEnd={false}
- // iOS always uses LegendList/RN's atomic data/size anchoring. Android history prepends
- // temporarily disable the whole prop because RN exposes one native switch: leaving either
- // flag on would race the app-owned key/offset correction there.
+ // iOS uses LegendList/RN's atomic data/size anchoring while reading history. Android history
+ // prepends temporarily disable the whole prop because RN exposes one native switch: leaving
+ // either flag on would race the app-owned key/offset correction there.
maintainVisibleContentPosition={historyPrependNativeMvcpDisabled
? false
- : { data: true, size: true }}
+ : { data: anchorVisibleRowsOnDataChange, size: true }}
contentContainerStyle={[
styles.messages,
{ paddingBottom: bottomPadding, paddingTop: topPadding },
diff --git a/apps/mobile/src/session/messagePaging.ts b/apps/mobile/src/session/messagePaging.ts
index 55f014cb7b..bd94019f65 100644
--- a/apps/mobile/src/session/messagePaging.ts
+++ b/apps/mobile/src/session/messagePaging.ts
@@ -188,6 +188,8 @@ export interface MessagePageRetryResult {
messages: RemoteMessage[];
limit: number;
reducedByPayloadTooLarge: boolean;
+ /** Set when several pages were joined; then the oldest page decides whether history continues. */
+ moreBeyondWindow?: boolean;
}
export async function listMessagesWithPayloadRetry(
@@ -215,9 +217,57 @@ export async function listMessagesWithPayloadRetry(
export function shouldKeepOlderMessagesAffordance(page: MessagePageRetryResult): boolean {
if (page.messages.length === 0) return false;
+ if (page.moreBeyondWindow !== undefined) return page.moreBeyondWindow;
return page.reducedByPayloadTooLarge || hasMoreOlderMessages(page.messages, page.limit);
}
+/**
+ * Older pages a reconnect may read so the latest page reaches the verified window. Bridge reads
+ * use the ordinary wire ladder (`MESSAGE_PAGE_RETRY_LIMITS`, 20 rows first): an 80-row page can
+ * outlive the request deadline on a slow link, and the ladder only shrinks oversized frames, not
+ * timeouts. 20 pages keep the budget at about 400 rows.
+ */
+export const LATEST_WINDOW_BRIDGE_MAX_PAGES = 20;
+
+/**
+ * 重连补同步时,最新一页可能接不上手机已验证连续的那段窗口(断线期间漏收超过一页)。
+ * 直接提交会让 store 丢掉旧历史、列表整段变短(见 setLatestMessageWindow 的 moreBeyondWindow)。
+ * 这里在提交前沿 before 继续往前读,直到 `needsBridge` 判定已接上、历史到头或达到页数上限,
+ * 再把这几页合成一页返回;预算用尽仍接不上时与原来一样按最新一页处置。没有补读时原样返回 `latest`。
+ * 补读请求失败时向上抛出,与最新页读取失败同等对待:本轮不提交,交给调用方既有的同步重试。
+ */
+export async function bridgeLatestMessagePage(
+ latest: MessagePageRetryResult,
+ options: {
+ needsBridge: (messages: readonly RemoteMessage[], moreBeyondWindow: boolean) => boolean;
+ readBefore: (before: string) => Promise<MessagePageRetryResult>;
+ isCurrent: () => boolean;
+ maxPages?: number;
+ },
+): Promise<MessagePageRetryResult> {
+ let messages = latest.messages;
+ let moreBeyondWindow = shouldKeepOlderMessagesAffordance(latest);
+ let pages = 0;
+ while (
+ pages < (options.maxPages ?? LATEST_WINDOW_BRIDGE_MAX_PAGES)
+ && moreBeyondWindow
+ && options.isCurrent()
+ && options.needsBridge(messages, moreBeyondWindow)
+ ) {
+ const before = oldestMessageCursor(messages);
+ if (!before) break;
+ // A failed bridge read fails this snapshot like a failed latest read: committing the
+ // unbridged page would drop the verified segment and hide the failure from recovery retries.
+ const older = await options.readBefore(before);
+ pages += 1;
+ const known = new Set(messages.map((message) => message.id));
+ messages = [...older.messages.filter((message) => !known.has(message.id)), ...messages];
+ moreBeyondWindow = shouldKeepOlderMessagesAffordance(older);
+ if (older.messages.length === 0) break;
+ }
+ return pages === 0 ? latest : { ...latest, messages, moreBeyondWindow };
+}
+
type SessionMessageVersion = Pick<RemoteSession, '_count' | 'updatedAt'>;
export function shouldRefreshLatestMessageWindowOnReopen(input: {
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 4715a01d0b..86450bac41 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -423,7 +423,10 @@ const sessionMessageSyncMarkers = new Map<string, SessionMessageSyncMarker>();
* 冷开 hydrate 与空洞补齐 `mergeMessages` 刻意不登记:前者来源不明;后者补的是窗口内部的洞,补完
* 要算准新区间得先确认窗口里没有别的洞——而这正是补齐本身在解决的问题(保守不动的代价是补回来
* 的段可能在下一次满页同步时被丢弃,下次打开会重新补,方向上是安全的那一侧)。
- * 清空 / rewind / 会话回收一律删除(重置为未知),下次最新窗口同步会重建。
+ * 清空 / rewind / 会话回收一律删除(重置为未知),下次最新窗口同步会重建。被控端提示漏推
+ * (`resyncRequired`)只收缩到下界那一点(见 `narrowWindowCoverageToStart`):行没有被改写,只是
+ * `until` 不再可信。最新页接不上时,同步方先沿 before 补读到上界再提交(`bridgeLatestMessagePage`),
+ * 接上的旧段得以保留;补读不到才按未知处置。
*
* 事实自检:最新页若在 `[since, until]` 内带来窗口没有的行,说明旧结论已被服务端事实推翻(桌面侧
* 改写历史、迟到落库等),当次按"未知"处置,见 `joinableWindowCoverage`。
@@ -467,6 +470,18 @@ function forgetWindowCoverage(sessionId: string): void {
sessionWindowCoverage.delete(sessionId);
}
+/**
+ * 被控端提示漏推(`resyncRequired`):订阅内的推送不再完整,`until` 可能已被漏推之后的 push 越过空洞
+ * 往后推,区间内部不能再信。但区间下界那一行确实来自权威页,只保留这一点 —— 下一次最新窗口同步
+ * 必须补读到 `since`、用权威页重新覆盖整段后才能相接(见 `latestMessageWindowNeedsBridge`),
+ * 补读不到时与整段遗忘相同。整段遗忘会让满页同步直接丢掉用户正在看的旧历史。
+ */
+function narrowWindowCoverageToStart(sessionId: string): void {
+ const current = sessionWindowCoverage.get(sessionId);
+ if (!current) return;
+ sessionWindowCoverage.set(sessionId, { since: current.since, until: current.since, liveTailTrusted: false });
+}
+
/**
* 这一页落库时尾部是否可信:订阅已 ACK → 之后的行会被推过来,`until` 可由 push 续推;订阅还没
* ACK(页比订阅先到,屏幕侧的常态)→ 空窗里被控端写下的行既不在这一页、也不会被推来,尾部不可信。
@@ -3542,6 +3557,26 @@ export const remoteSessionStore = {
emit();
},
+ /**
+ * 这一页最新窗口是否值得先往前补读:满页、窗口里有已验证连续段,但本页最旧行晚于该段上界 ——
+ * 直接提交时 `joinableWindowCoverage` 判不相接,`setLatestMessageWindow` 会丢掉整段旧历史。
+ * 补读到本页最旧行不晚于上界后就能相接(区间内的事实自检仍由提交时判定)。schedule 窗口本就
+ * 按条数裁剪,不补读。
+ */
+ latestMessageWindowNeedsBridge(
+ sessionId: string,
+ list: readonly RemoteMessage[],
+ moreBeyondWindow: boolean,
+ ): boolean {
+ if (!moreBeyondWindow || retentionForSession(sessionId) === 'schedule') return false;
+ if ((messages.get(sessionId) ?? []).length === 0) return false;
+ const coverage = sessionWindowCoverage.get(sessionId);
+ const pageOldest = oldestCreatedAt(list);
+ return coverage !== undefined
+ && pageOldest !== undefined
+ && pageOldest.localeCompare(coverage.until) > 0;
+ },
+
setLatestMessageWindow(
sessionId: string,
list: readonly RemoteMessage[],
@@ -4421,7 +4456,7 @@ export const remoteSessionStore = {
}),
invalidateHistory: (sessionId) => {
sessionMessageSyncMarkers.delete(sessionId);
- forgetWindowCoverage(sessionId);
+ narrowWindowCoverageToStart(sessionId);
pendingRefreshSessions.add(sessionId);
bumpMessageVersion(sessionId);
emit();