Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复长任务历史滚动跳转并提前预取 (#4236)
Dash786701d8b8ce
diff --git a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.tsindex d29b371dd2..7e3a8c6c3f 100644--- a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts+++ b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts@@ -27,6 +27,7 @@ import {hasBotAssistantOutputInCurrentTurn,isGeneratedFilesTurnSealed,findRestorableViewportItemIdx,+ renderItemContainsClientId,groupWorkRuns,insertForkOriginItem,isScrollNavigationKey,@@ -1622,6 +1623,61 @@ describe('groupWorkRuns — work-group collapsing', () => {expect(findRestorableViewportItemIdx(visibleItems, 'seg-t1')).toBe(0);});+ it('restores a completed group after an older activity joins the same turn', () => {+ const tail = [mkAssistant('draft', 'Reading.'), mkTool('tool-later', 'Read'), mkAssistant('final', 'Done.')];+ const previous = build([mkUser('user'), ...tail], false).find((item) => item.type === 'work_group')!;+ const expanded = build([mkUser('user'), mkTool('tool-earlier', 'Bash'), ...tail], false);+ expect(previous.key).toBe('work-summary-tool-later');+ const index = findRestorableViewportItemIdx(expanded, previous.key);+ expect(index).toBe(1);+ expect(expanded[index].key).toBe('work-summary-tool-earlier');+ });++ it('restores an anchor to a nested deferred group without requiring loaded children', () => {+ const group = build(+ [mkUser('user'), mkTool('tool-earlier', 'Bash'), mkAssistant('final', 'Done.')], false,+ ).find((item): item is Extract<RenderItem, { type: 'work_group' }> => item.type === 'work_group')!;+ const deferred = { ...group, key: 'work-tool-later', children: [] };+ const regrouped = { ...group, children: [deferred] };+ expect(findRestorableViewportItemIdx([regrouped], 'work-summary-tool-later')).toBe(0);+ expect(findRestorableViewportItemIdx([regrouped], 'work-summary-missing')).toBe(-1);+ });++ it.each(['work-rs_old-anchor', 'work-earlier|work-rs_old-anchor', 'work-summary-rs_old-anchor'])(+ 'restores a remote summary through its retained deferred identity: %s',+ (key) => {+ const group = build(+ [mkUser('user'), mkTool('new-anchor', 'Bash'), mkAssistant('final', 'Done.')],+ false,+ ).find((item): item is Extract<RenderItem, { type: 'work_group' }> => item.type === 'work_group')!;+ const child = {+ ...group,+ children: [],+ deferred: {+ key, expanded: false, loading: false, failed: false,+ toggle: () => { throw new Error('Recovery must not load details'); },+ retry: () => { throw new Error('Recovery must not load details'); },+ },+ };+ const items = [{ ...group, children: [child] }];+ expect(findRestorableViewportItemIdx(items, 'work-summary-rs_old-anchor')).toBe(0);+ expect(findRestorableViewportItemIdx(items, 'work-rs_old-anchor')).toBe(0);+ expect(findRestorableViewportItemIdx(items, 'work-summary-anchor')).toBe(-1);+ expect(findRestorableViewportItemIdx(items, 'work-summary-missing')).toBe(-1);+ // The same identity must survive the deletion guard, even while its+ // exact child is unloaded. Near-suffix matches are not identities.+ expect(renderItemContainsClientId(items[0], 'rs_old-anchor')).toBe(true);+ expect(renderItemContainsClientId(items[0], 'anchor')).toBe(false);+ expect(renderItemContainsClientId(items[0], 'missing')).toBe(false);+ const deleted = {+ ...items[0],+ children: [{ ...child, key: 'work-rs_old-anchor', deferred: undefined }],+ };+ // A stale group key alone must not keep a genuinely deleted child alive.+ expect(renderItemContainsClientId(deleted, 'rs_old-anchor')).toBe(false);+ },+ );+it('keeps completed prior turns folded while a later turn streams', () => {const items = build([diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.tsindex ebcfe9ecdb..d395c6ede9 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts@@ -943,6 +943,55 @@ describe('device-link controller mirror — end-to-end scenarios', () => {}});+ it.each([false, true])('propagates remote pagination loading synchronously to the rendered light state (fails=%s)', async (fails) => {+ const s = sid();+ host.enableHistoryView();+ const rows = Array.from({ length: 30 }, (_, index) => dbMessage(s, String(index), 'visible',+ new Date(1_750_000_000_000 + index * 1000).toISOString(), 'user'));+ host.seedSession(s, {}, rows);+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);+ makerChatStore.ensureInitialMessages(s);+ await flush(); await flush();+ const view = getRemoteHistoryView(s)!;+ const previousItems = view.getSnapshot().items;+ expect(view.getSnapshot()).toMatchObject({ ready: true, loading: false, hasMore: true });+ const invoke = host.invoke.getMockImplementation()!;+ let release!: () => void;+ host.invoke.mockImplementation(async (device, channel, args) => {+ if (channel === 'local-db:messages:view') {+ await new Promise<void>((resolve) => { release = resolve; });+ if (fails) throw new Error('page unavailable');+ }+ return invoke(device, channel, args);+ });+ const observed: boolean[] = [];+ // MessageStream subscribes to this view while its parent reads the light+ // store. Check both at the same notification, before any React scheduling.+ const unsubscribe = view.subscribe(() => {+ const loading = view.getSnapshot().loading;+ expect(makerChatStore.getSnapshot(s).isLoadingMore).toBe(loading);+ expect(makerChatStore.getLightSnapshot(s).isLoadingMore).toBe(loading);+ observed.push(loading);+ });+ try {+ const result = makerChatStore.loadOlderMessages(s).then(+ (advanced) => ({ advanced }),+ (error: Error) => ({ error: error.message }),+ );+ expect(observed).toEqual([true]);+ expect(view.getSnapshot().items).toBe(previousItems);+ expect(makerChatStore.getLightSnapshot(s).isLoadingMore).toBe(true);+ release();+ expect(await result).toEqual(fails ? { error: 'page unavailable' } : { advanced: true });+ expect(observed).toEqual([true, false]);+ expect(view.getSnapshot().items).toHaveLength(fails ? 20 : 30);+ expect(makerChatStore.getLightSnapshot(s).isLoadingMore).toBe(false);+ } finally {+ unsubscribe();+ makerChatStore.purgeSession(s);+ }+ });+it.each(['delete', 'clear'])('retires loaded older projection pages after a remote %s', async (operation) => {const s = sid();host.enableHistoryView();diff --git a/apps/desktop/src/renderer/__tests__/historyPrefetch.test.ts b/apps/desktop/src/renderer/__tests__/historyPrefetch.test.tsnew file mode 100644index 0000000000..0453a01edf--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/historyPrefetch.test.ts@@ -0,0 +1,158 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';+import { historyPrefetchThreshold } from '@cindy/maker-shared/message-window';+import {+ isUpwardWheelIntent,+ shouldUnpinOnWheel,+ shouldRepinOnWheel,+} from '../components/chat/autoFollowIntent';+import { decideUserIntentFillAction } from '../components/chat/viewportFillDetect';++const source = readFileSync(+ resolve(__dirname, '../components/chat/MessageStream.tsx'),+ 'utf8',+).replace(/\r\n/g, '\n');+const start = source.indexOf(' const triggerUserIntentFill =');+const end = source.indexOf('\n useEffect(', start);+const callback = ts.transpileModule(source.slice(start, end), {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+}).outputText;++describe('history prefetch', () => {+ it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])(+ 'uses a bounded fallback for viewport %s',+ (height) => {+ expect(historyPrefetchThreshold(height)).toBe(96);+ },+ );+ it('shares the mobile two-screen threshold', () => {+ expect(historyPrefetchThreshold(754)).toBe(1508);+ });+ it('keeps passive boundary checks narrow while allowing explicit early prefetch', () => {+ const input = {+ scrollTop: 1200,+ scrollHeight: 9000,+ clientHeight: 754,+ windowAtTop: true,+ hasMoreMessages: true,+ isLoadingMore: false,+ };+ expect(decideUserIntentFillAction(input)).toBe('none');+ expect(+ decideUserIntentFillAction({ ...input, triggerDistancePx: historyPrefetchThreshold(754) }),+ ).toBe('load-from-db');+ expect(+ decideUserIntentFillAction({ ...input, isLoadingMore: true, triggerDistancePx: 1508 }),+ ).toBe('none');+ expect(+ decideUserIntentFillAction({ ...input, hasMoreMessages: false, triggerDistancePx: 1508 }),+ ).toBe('none');+ expect(+ decideUserIntentFillAction({ ...input, windowAtTop: false, triggerDistancePx: 1508 }),+ ).toBe('expand-window');+ });+ it.each([true, false])(+ 'captures current position and releases same-frame request latch (reject=%s)',+ async (reject) => {+ let settle!: () => void;+ const order: string[] = [];+ const onLoadMore = vi.fn(+ () =>+ new Promise<boolean>((resolve, fail) => {+ order.push('request');+ settle = () => (reject ? fail(new Error('offline')) : resolve(false));+ }),+ );+ const latch = { current: false };+ const bindings = {+ useCallback: (fn: unknown) => fn,+ scrollRef: { current: { scrollTop: 1200, scrollHeight: 9000, clientHeight: 754 } },+ visibleRenderItems: [{}],+ chipJumpInProgressRef: { current: false },+ windowAtTop: true,+ hasMoreMessages: true,+ isLoadingMore: false,+ historyPrefetchThreshold,+ decideUserIntentFillAction,+ userIntentLoadInFlightRef: latch,+ prevScrollHeightRef: { current: 0 },+ prevScrollTopAtLoadRef: { current: 0 },+ onLoadMore,+ expandWindow: vi.fn(),+ refreshViewportAnchor: () => order.push('anchor'),+ };+ const trigger = new Function(+ ...Object.keys(bindings),+ callback + ';return triggerUserIntentFill;',+ )(...Object.values(bindings));+ trigger();+ trigger();+ expect(order).toEqual(['anchor', 'request']);+ expect(onLoadMore).toHaveBeenCalledTimes(1);+ settle();+ await Promise.resolve();+ expect(latch.current).toBe(false);+ trigger();+ expect(onLoadMore).toHaveBeenCalledTimes(2);+ settle();+ await Promise.resolve();+ },+ );+});++describe('wheel history intent', () => {+ it.each([500, 9000])(+ 'ignores zoom and horizontal noise before a vertical gesture (height=%s)',+ (scrollHeight) => {+ const fill = vi.fn();+ const unpin = vi.fn();+ let nestedOwnsScroll = false;+ const bindings = {+ root: { scrollHeight, clientHeight: 754, scrollTop: 0 },+ clearChipJumpSuppression: vi.fn(),+ isUpwardWheelIntent,+ shouldUnpinOnWheel,+ shouldRepinOnWheel,+ hasNestedScrollableAncestorThatCanScrollUp: () => nestedOwnsScroll,+ hasNestedScrollableAncestorThatCanScrollDown: () => false,+ unpinAutoFollowForUserUpIntent: unpin,+ pinAutoFollowForUserDownIntent: vi.fn(),+ triggerUserIntentFill: fill,+ };+ const start = source.indexOf(' const onWheel = (event: WheelEvent) => {');+ const end = source.indexOf(' const onTouchStart =', start);+ const code = ts.transpileModule(source.slice(start, end), {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText;+ const wheel = new Function(...Object.keys(bindings), code + ';return onWheel;')(+ ...Object.values(bindings),+ );+ for (const modifier of ['ctrlKey', 'metaKey']) {+ for (const deltaY of [-40, 40]) {+ wheel({ deltaX: 0, deltaY, [modifier]: true });+ }+ }+ expect(fill).not.toHaveBeenCalled();+ expect(unpin).not.toHaveBeenCalled();+ expect(bindings.pinAutoFollowForUserDownIntent).not.toHaveBeenCalled();+ expect(bindings.clearChipJumpSuppression).not.toHaveBeenCalled();+ wheel({ deltaX: 40, deltaY: -1 });+ wheel({ deltaX: -40, deltaY: -1 });+ wheel({ deltaX: 0, deltaY: 0 });+ expect(fill).not.toHaveBeenCalled();+ expect(unpin).not.toHaveBeenCalled();+ wheel({ deltaX: 1, deltaY: -40 });+ expect(fill).toHaveBeenCalledTimes(1);+ expect(unpin).toHaveBeenCalledTimes(scrollHeight > 754 ? 1 : 0);+ wheel({ deltaX: 0, deltaY: 40 });+ expect(fill).toHaveBeenCalledTimes(1);+ wheel({ deltaX: 40, deltaY: -40 });+ expect(fill).toHaveBeenCalledTimes(2);+ nestedOwnsScroll = true;+ wheel({ deltaX: 0, deltaY: -40 });+ expect(fill).toHaveBeenCalledTimes(2);+ },+ );+});diff --git a/apps/desktop/src/renderer/__tests__/historyViewportCompensation.test.ts b/apps/desktop/src/renderer/__tests__/historyViewportCompensation.test.tsnew file mode 100644index 0000000000..be209fa8f1--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/historyViewportCompensation.test.ts@@ -0,0 +1,91 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';+import { toRenderItemViewportSnapshot } from '../components/chat/MessageStream';+import { viewportAnchorCorrection } from '../components/chat/messageViewportCompensation';+import { detectScrollAnchoringApplied } from '../components/chat/scrollAnchoringDetect';++const source = readFileSync(resolve(__dirname, '../components/chat/MessageStream.tsx'), 'utf8')+ .replace(/\r\n/g, '\n');+function between(start: string, end: string) {+ const from = source.indexOf(start);+ const to = source.indexOf(end, from);+ if (from < 0 || to < 0) throw new Error('Missing production scroll block');+ return source.slice(from, to);+}+// Run the production restoration callbacks and history effect against measured+// geometry. Remote details can change total height independently of the anchor.+const compiled = ts.transpileModule(+ between(' const scrollKeyToViewportTop =', ' const restoreViewportSnapshotOrRebuildWindow =') ++ between(+ ' useEffect(() => {\n const el = scrollRef.current;\n if (!el || isLoadingMore) return;',+ '\n // ── 删除靠前 message',+ ),+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },+).outputText;++function run({ targetTop = 42, missing = false, loading = false, exact = false } = {}) {+ let top = 1058;+ const writes: number[] = [];+ const el = {+ scrollHeight: 38877,+ get scrollTop() {+ return top;+ },+ set scrollTop(value: number) {+ top = value;+ writes.push(value);+ },+ getBoundingClientRect: () => ({ top: 0 }),+ };+ const target = { getBoundingClientRect: () => ({ top: 1058 + targetTop - top, height: 100 }) };+ const items = [{ key: 'anchor' }];+ const previousHeight = { current: 38313 };+ const bindings = {+ useCallback: (fn: unknown) => fn,+ useEffect: (fn: () => void) => fn(),+ scrollRef: { current: el },+ itemsRef: { current: { children: missing ? [] : [target] } },+ visibleRenderItemsRef: { current: items },+ visibleRenderItems: items,+ prevScrollHeightRef: previousHeight,+ prevScrollTopAtLoadRef: { current: 282 },+ lastViewportTopRef: {+ current: {+ viewportTopKey: 'anchor',+ offset: 0,+ ...(exact ? { messageClientId: 'message', messageOffset: 0 } : {}),+ },+ },+ isNearBottomRef: { current: false },+ isLoadingMore: loading,+ queryMessageElement: () => (exact && !missing ? target : null),+ toRenderItemViewportSnapshot,+ detectScrollAnchoringApplied,+ viewportAnchorCorrection,+ beginProgrammaticScroll: vi.fn(() => 1),+ finishProgrammaticScroll: vi.fn(),+ requestAnimationFrame: vi.fn(),+ };+ new Function(...Object.keys(bindings), compiled)(...Object.values(bindings));+ return { top, writes, previousHeight: previousHeight.current };+}++describe('history viewport compensation', () => {+ it.each([false, true])(+ 'uses actual anchor displacement, not unrelated total growth (exact=%s)',+ (exact) => {+ expect(run({ exact })).toEqual({ top: 1100, writes: [1100], previousHeight: 0 });+ },+ );+ it('does not compensate twice when the browser already aligned the anchor', () => {+ expect(run({ targetTop: 0 })).toEqual({ top: 1058, writes: [], previousHeight: 0 });+ });+ it('retains the height fallback when the anchor DOM is missing', () => {+ expect(run({ missing: true })).toEqual({ top: 1622, writes: [1622], previousHeight: 0 });+ });+ it('preserves the pending snapshot until loading completes', () => {+ expect(run({ loading: true })).toEqual({ top: 1058, writes: [], previousHeight: 38313 });+ });+});diff --git a/apps/desktop/src/renderer/__tests__/messageViewportDeletionIntegration.test.ts b/apps/desktop/src/renderer/__tests__/messageViewportDeletionIntegration.test.tsindex dc46a63e7b..5ca2850e55 100644--- a/apps/desktop/src/renderer/__tests__/messageViewportDeletionIntegration.test.ts+++ b/apps/desktop/src/renderer/__tests__/messageViewportDeletionIntegration.test.ts@@ -12,6 +12,7 @@ import {isVisibleDeleteCompensationElement,pickDeleteCompensationAnchorKey,resolveDeleteCompensationLanding,+ renderItemContainsClientId,toRenderItemViewportSnapshot,} from '../components/chat/MessageStream';import {@@ -47,7 +48,6 @@ const helpers = source.statements.filter((node) => ts.isFunctionDeclaration(node) && ['queryMessageElement','queryVisibleAggregateContainer',- 'renderItemContainsClientId','renderItemKeyForClientId',].includes(node.name?.text ?? ''),);@@ -130,6 +130,7 @@ function setup({ deleted = true, hidden = false, nativeShift = 0 } = {}) {finishProgrammaticScroll: () => { programmaticScrollRef.current = false; },canCompensateMessageHeight,viewportAnchorCorrection,+ renderItemContainsClientId,toRenderItemViewportSnapshot,consumePendingReanchorForAutoFollow,findRestorableViewportItemIdx,@@ -148,6 +149,7 @@ function setup({ deleted = true, hidden = false, nativeShift = 0 } = {}) {restoringRef: ref(false),isNearBottomRef: ref(false),prevScrollHeightRef: ref(0),+ prevScrollTopAtLoadRef: ref(0),saveRafRef: ref(null),scrollbarDragStartTopRef: ref(null),suppressHeightCompensationUntilRef: ref(0),diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 5ea2ab8814..3bd1b12bbc 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -28,7 +28,7 @@ import {type CSSProperties,type ReactNode,} from 'react';-import { HistoryViewHandoff, renderHistoryView } from '@cindy/maker-shared/message-window';+import { HistoryViewHandoff, renderHistoryView, historyPrefetchThreshold } from '@cindy/maker-shared/message-window';import { getRemoteHistoryView, type HistoryChatMessage } from '@/lib/makerChatStore';import { createPortal } from 'react-dom';import { GitFork } from 'lucide-react';@@ -360,6 +360,7 @@ import {shouldUnpinOnScrollbarDrag,shouldUnpinOnUpIntent,shouldUnpinOnWheel,+ isUpwardWheelIntent,} from './autoFollowIntent';import { countUnreadAdded } from './unreadCount';import {@@ -1026,6 +1027,17 @@ export function collectTurnFinalAssistantClientIds(messages: readonly ChatMessag* `agent_plan` item in the chat timeline. The composer capsule observes the* latest inline card and only takes over after that card leaves the viewport.*/+function deferredWorkContainsClientId(+ item: Extract<RenderItem, { type: 'work_group' }>,+ clientId: string,+): boolean {+ return (+ item.deferred?.key?.split('|').some(+ (key) => key === `work-${clientId}` || key === `work-summary-${clientId}`,+ ) ?? false+ );+}+/*** 锚点丢失恢复:DB 加载更老历史 prepend 时,若新拉回的末尾是 tool_use 且当前* 首段 render item 是 tool_segment,segment 会向前合并吸收这些 toolCall —— 原@@ -1050,7 +1062,10 @@ export function collectTurnFinalAssistantClientIds(messages: readonly ChatMessagfunction recoverLostAnchorIdx(items: RenderItem[], lostKey: string): number {const dashIdx = lostKey.indexOf('-');if (dashIdx < 0) return -1;- const lostCid = lostKey.slice(dashIdx + 1);+ // Completed groups have a compound prefix; the message id can itself contain dashes.+ const lostCid = lostKey.startsWith('work-summary-')+ ? lostKey.slice('work-summary-'.length)+ : lostKey.slice(dashIdx + 1);if (!lostCid) return -1;for (let i = 0; i < items.length; i++) {@@ -1073,8 +1088,16 @@ function recoverLostAnchorIdx(items: RenderItem[], lostKey: string): number {} else if (it.type === 'work_group') {// work_group 可能嵌套完成态时间线 — 老锚点(`seg-${cid}` /// `msg-${cid}` / `work-${cid}`)递归落到任一后代即由外组接住。- if (it.key === lostKey || it.key.endsWith(`-${lostCid}`)) return i;- if (renderItemContainsClientId(it, lostCid)) return i;+ // Remote placeholders can merge and disappear from children; their original+ // summary identities remain in deferred.key even when the visible key changes.+ if (+ it.key === lostKey ||+ it.key === `work-${lostCid}` ||+ it.key === `work-summary-${lostCid}` ||+ deferredWorkContainsClientId(it, lostCid)+ ) return i;+ // Remote deferred groups retain their key before their children are loaded.+ if (recoverLostAnchorIdx(it.children, lostKey) >= 0) return i;} else if (it.type !== 'fork_origin') {// tool_media / ghost_card:其 key 派生自 stable message clientId,精确后缀匹配if (it.key === lostKey || it.key.endsWith(`-${lostCid}`)) return i;@@ -2282,7 +2305,7 @@ function collectWorkGroupClientIds(children: readonly RenderItem[]): string[] {return collectDeleteAnchorClientIds(children);}-function renderItemContainsClientId(item: RenderItem, clientId: string): boolean {+export function renderItemContainsClientId(item: RenderItem, clientId: string): boolean {if (item.type === 'fork_origin') return false;if (item.type === 'message') return item.message.clientId === clientId;if (item.type === 'tool_segment')@@ -2290,7 +2313,12 @@ function renderItemContainsClientId(item: RenderItem, clientId: string): booleanif (item.type === 'agent_task') return item.toolCall?.clientId === clientId;if (item.type === 'agent_plan') return item.sourceClientIds.includes(clientId);if (item.type === 'work_group') {- return item.children.some((child) => renderItemContainsClientId(child, clientId));+ // Retained remote identities survive unloaded children; a group key alone+ // does not prove that a previously rendered child still exists.+ return (+ deferredWorkContainsClientId(item, clientId) ||+ item.children.some((child) => renderItemContainsClientId(child, clientId))+ );}return item.key.endsWith(`-${clientId}`);}@@ -3142,18 +3170,25 @@ export function MessageStream({const idx = visibleRenderItemsRef.current.findIndex((item) => item.key === key);const child =idx >= 0 ? (itemsRef.current?.children[idx] as HTMLElement | undefined) : undefined;- if (!container || !child) return;+ if (!container || !child) return false;const delta = viewportAnchorCorrection(container.getBoundingClientRect().top,child.getBoundingClientRect().top,offset,);- if (delta === 0) return;+ // 已按真实锚点保位(含零位移)时,不能再叠加同次布局的历史高度补偿。+ // 仍在请求中的历史尚未进入 DOM,保留它的快照供返回后补偿。+ if (!isLoadingMore) {+ prevScrollHeightRef.current = 0;+ prevScrollTopAtLoadRef.current = 0;+ }+ if (delta === 0) return true;const generation = beginProgrammaticScroll();container.scrollTop += delta;requestAnimationFrame(() => finishProgrammaticScroll(generation));+ return true;},- [beginProgrammaticScroll, finishProgrammaticScroll],+ [beginProgrammaticScroll, finishProgrammaticScroll, isLoadingMore],);const scrollMessageToViewportTop = useCallback((clientId: string, offset: number) => {@@ -3165,13 +3200,17 @@ export function MessageStream({const rect = target.getBoundingClientRect();if (rect.height <= 0) return false;const delta = viewportAnchorCorrection(container.getBoundingClientRect().top, rect.top, offset);+ if (!isLoadingMore) {+ prevScrollHeightRef.current = 0;+ prevScrollTopAtLoadRef.current = 0;+ }if (delta === 0) return true;const generation = beginProgrammaticScroll();container.scrollTop += delta;requestAnimationFrame(() => finishProgrammaticScroll(generation));return true;},- [beginProgrammaticScroll, finishProgrammaticScroll],+ [beginProgrammaticScroll, finishProgrammaticScroll, isLoadingMore],);const restoreViewportSnapshot = useCallback((snapshot: ViewportTopSnapshot, itemOffset = snapshot.offset): boolean => {@@ -3185,8 +3224,7 @@ export function MessageStream({const itemSnapshot = toRenderItemViewportSnapshot(snapshot, itemOffset);lastViewportTopRef.current = itemSnapshot;if (visibleRenderItemsRef.current.some((item) => item.key === itemSnapshot.viewportTopKey)) {- scrollKeyToViewportTop(itemSnapshot.viewportTopKey, itemSnapshot.offset);- return true;+ return scrollKeyToViewportTop(itemSnapshot.viewportTopKey, itemSnapshot.offset);}return false;},@@ -4103,6 +4141,7 @@ export function MessageStream({const action = decideUserIntentFillAction({scrollTop: el.scrollTop,+ triggerDistancePx: historyPrefetchThreshold(el.clientHeight),scrollHeight: el.scrollHeight,clientHeight: el.clientHeight,windowAtTop,@@ -4110,6 +4149,10 @@ export function MessageStream({isLoadingMore: (isLoadingMore ?? false) || userIntentLoadInFlightRef.current,});+ // Input may arrive before the queued scroll snapshot frame. Capture the+ // current reading position before expanding or starting a remote read.+ if (action !== 'none') refreshViewportAnchor();+switch (action) {case 'expand-window': {prevScrollHeightRef.current = el.scrollHeight;@@ -4122,7 +4165,8 @@ export function MessageStream({userIntentLoadInFlightRef.current = true;prevScrollHeightRef.current = el.scrollHeight;prevScrollTopAtLoadRef.current = el.scrollTop;- onLoadMore();+ const release = () => { userIntentLoadInFlightRef.current = false; };+ void onLoadMore().then(release, release);return;}case 'none':@@ -4135,6 +4179,7 @@ export function MessageStream({isLoadingMore,onLoadMore,expandWindow,+ refreshViewportAnchor,]);useEffect(() => {const root = scrollRef.current;@@ -4142,8 +4187,11 @@ export function MessageStream({// wheel/touchstart 挂在 scroll 容器上(与上 chip 抑制对称)。容器不可滚时// 不会产生 scroll 事件,所以用户继续向上滚动的意图必须在这里接住。const onWheel = (event: WheelEvent) => {+ // Chromium reports pinch/modified-wheel zoom as wheel events. Filter at+ // the input boundary before navigation, follow-state or history effects.+ if (event.ctrlKey || event.metaKey) return;clearChipJumpSuppression();- if (event.deltaY < 0) {+ if (isUpwardWheelIntent(event)) {if (hasNestedScrollableAncestorThatCanScrollUp(root, event.target)) return;if (shouldUnpinOnWheel({@@ -4755,6 +4803,11 @@ export function MessageStream({if (!el || isLoadingMore) return;if (prevScrollHeightRef.current > 0) {+ // Remote details can settle while a page is loading, so total height is+ // not the displacement of the message being read. Prefer its live DOM+ // anchor; browser anchoring may already have preserved that position.+ const snapshot = lastViewportTopRef.current;+ if (!isNearBottomRef.current && snapshot && restoreViewportSnapshot(snapshot)) return;const newScrollHeight = el.scrollHeight;const delta = newScrollHeight - prevScrollHeightRef.current;// [mr-16 review #1] 判定从"scrollTop > snapshot + 8"收紧成"scrollTop 增量@@ -4778,7 +4831,7 @@ export function MessageStream({prevScrollHeightRef.current = 0;prevScrollTopAtLoadRef.current = 0;}- }, [visibleRenderItems, isLoadingMore, beginProgrammaticScroll, finishProgrammaticScroll]);+ }, [visibleRenderItems, isLoadingMore, beginProgrammaticScroll, finishProgrammaticScroll, restoreViewportSnapshot]);// ── 删除靠前 message 后的视口保位(#2289)──// 快照来自滚动/跳转落定;删除提交后再量会使 delta 恒为 0。贴底交给 pin-to-bottom。@@ -5052,12 +5105,20 @@ export function MessageStream({prevScrollTopRef.current = el.scrollTop;return;}+ const draggingUp = draggingScrollbar+ && currentScrollTop < prevScrollTopRef.current - SCROLL_DIRECTION_DEAD_ZONE_PX;if (!programmaticScrollRef.current || draggingScrollbar) {// 用户手动滚动 = 接管浏览,退出「还原中」,后续恢复正常 auto-follow 判定。restoringRef.current = false;// 持续保存浏览位置(rAF 节流,DOM 必然存活),内含删除前快照刷新——纯滚动后// 快照停在陈旧 key 会让删除补偿失配。- if (saveRafRef.current === null) {+ if (isLoadingMore || prevScrollHeightRef.current > 0) {+ // A remote response can commit before the next rAF. Keep its restoration+ // anchor at the user's latest position throughout the request.+ if (saveRafRef.current !== null) cancelAnimationFrame(saveRafRef.current);+ saveRafRef.current = null;+ saveScrollSnapshot();+ } else if (saveRafRef.current === null) {saveRafRef.current = requestAnimationFrame(() => {saveRafRef.current = null;saveScrollSnapshot();@@ -5180,6 +5241,11 @@ export function MessageStream({});}+ // Scrollbar drags share explicit-input prefetch, without also expanding below.+ if (draggingUp) {+ triggerUserIntentFill();+ return;+ }// 滚到顶 50px 内才触发后续加载逻辑(阈值与 decideUserIntentFillAction 的// "停在顶部"判定共用 TOP_HISTORY_TRIGGER_PX,两条路径合起来覆盖// "穿过顶部区间"与"停在顶部继续上滚"的完整触发面)@@ -5215,6 +5281,7 @@ export function MessageStream({windowAtTop,expandWindow,saveScrollSnapshot,+ triggerUserIntentFill,refreshViewportAnchor,finishProgrammaticScroll,windowCoversEnd,diff --git a/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts b/apps/desktop/src/renderer/components/chat/autoFollowIntent.tsindex abdd147390..7c314dc681 100644--- a/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts+++ b/apps/desktop/src/renderer/components/chat/autoFollowIntent.ts@@ -54,6 +54,14 @@ export interface WheelUnpinArgs {clientHeight: number;}+/** Direction is independent of whether the current content can scroll. */+export function isUpwardWheelIntent({+ deltaX,+ deltaY,+}: Pick<WheelUnpinArgs, 'deltaX' | 'deltaY'>): boolean {+ return deltaY < 0 && Math.abs(deltaY) >= Math.abs(deltaX);+}+/*** wheel 事件是否构成「用户想向上滚、应解除 auto-follow」。*@@ -73,8 +81,7 @@ export function shouldUnpinOnWheel({scrollHeight,clientHeight,}: WheelUnpinArgs): boolean {- if (deltaY >= 0) return false;- if (Math.abs(deltaY) < Math.abs(deltaX)) return false;+ if (!isUpwardWheelIntent({ deltaX, deltaY })) return false;return scrollHeight - clientHeight > UNPIN_MIN_SCROLLABLE_PX;}diff --git a/apps/desktop/src/renderer/components/chat/viewportFillDetect.ts b/apps/desktop/src/renderer/components/chat/viewportFillDetect.tsindex 4d70fe1a1f..92b19a49d7 100644--- a/apps/desktop/src/renderer/components/chat/viewportFillDetect.ts+++ b/apps/desktop/src/renderer/components/chat/viewportFillDetect.ts@@ -193,6 +193,8 @@ export type UserIntentFillDecisionArgs = Omit<> & {/** scroll 容器当前的 scrollTop(判定"停在顶部"用) */scrollTop: number;+ /** Explicit upward input can prefetch before reaching the history boundary. */+ triggerDistancePx?: number;};/**@@ -266,9 +268,10 @@ export function decideUserIntentFillAction({windowAtTop,hasMoreMessages,isLoadingMore,+ triggerDistancePx = TOP_HISTORY_TRIGGER_PX,}: UserIntentFillDecisionArgs): AutoFillAction {const unscrollable = Math.abs(scrollHeight - clientHeight) <= NO_SCROLL_TOLERANCE_PX;- const parkedNearTop = scrollTop < TOP_HISTORY_TRIGGER_PX;+ const parkedNearTop = scrollTop < triggerDistancePx;if (!unscrollable && !parkedNearTop) return 'none';// expand 优先于 load,原因同 decideAutoFillAction 的「优先级」注释;expand 不看// isLoadingMore(纯本地扩窗与 in-flight IPC 不冲突,与既有语义一致)。diff --git a/apps/mobile/src/session/messageScroll.ts b/apps/mobile/src/session/messageScroll.tsindex 2c2fa85a27..7aa31e0d17 100644--- a/apps/mobile/src/session/messageScroll.ts+++ b/apps/mobile/src/session/messageScroll.ts@@ -1,5 +1,6 @@import {DEFAULT_NEAR_BOTTOM_THRESHOLD,+ historyPrefetchThreshold,isNearMessageListBottom,type MessageScrollMetrics,} from '@cindy/maker-shared/message-window';@@ -438,8 +439,7 @@ export function mobileTopPaddingCompensationOffset(input: MobileTopPaddingCompen* 且有 loadingEarlier 门禁串行化,最坏是多拉一页,不会失控循环。*/export function mobileLoadEarlierPrefetchThreshold(viewportHeight: number): number {- if (!Number.isFinite(viewportHeight) || viewportHeight <= 0) return 96;- return Math.max(96, Math.ceil(viewportHeight * 2));+ return historyPrefetchThreshold(viewportHeight);}export interface MobileAutoLoadEarlierDecisionInput {diff --git a/packages/maker-shared/src/messageWindow.ts b/packages/maker-shared/src/messageWindow.tsindex 2649068ef3..b8a0483652 100644--- a/packages/maker-shared/src/messageWindow.ts+++ b/packages/maker-shared/src/messageWindow.ts@@ -14,6 +14,12 @@ export interface MessageScrollMetrics {export const DEFAULT_NEAR_BOTTOM_THRESHOLD = 96;export const DEFAULT_LOAD_EARLIER_THRESHOLD = 96;+/** Start reading older history two viewports ahead of the loaded boundary. */+export function historyPrefetchThreshold(viewportHeight: number): number {+ if (!Number.isFinite(viewportHeight) || viewportHeight <= 0) return DEFAULT_LOAD_EARLIER_THRESHOLD;+ return Math.max(DEFAULT_LOAD_EARLIER_THRESHOLD, Math.ceil(viewportHeight * 2));+}+export function isNearMessageListBottom(metrics: MessageScrollMetrics,threshold = DEFAULT_NEAR_BOTTOM_THRESHOLD,