Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): avoid reloading worker history on remount
Dash28a39702bcce
diff --git a/apps/desktop/src/renderer/__tests__/sessionScrollStore.test.ts b/apps/desktop/src/renderer/__tests__/sessionScrollStore.test.tsnew file mode 100644index 0000000000..b0c54177dd--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/sessionScrollStore.test.ts@@ -0,0 +1,119 @@+import { afterEach, describe, expect, it } from 'vitest';++import {+ clearSessionScroll,+ markSessionAutomaticHistoryLoadStarted,+ readSessionScroll,+ restoreSessionAutomaticHistoryLoadAttempts,+ saveSessionScroll,+ type SessionScrollSnapshot,+} from '../lib/sessionScrollStore';+import {+ decideAutoFillAction,+ decideUserIntentFillAction,+ MAX_AUTO_LOAD_ATTEMPTS,+} from '../components/chat/viewportFillDetect';+import {+ NAV_RAIL_BACKFILL_MAX_ROUNDS,+ shouldBackfillForNavRail,+} from '../components/chat/messageNavRailModel';++const SESSION_A = 'worker-a';+const SESSION_B = 'worker-b';++const bottomSnapshot: SessionScrollSnapshot = {+ windowAnchorKey: null,+ viewportTopKey: 'message-tail',+ offset: 0,+ isNearBottom: true,+};++afterEach(() => {+ clearSessionScroll(SESSION_A);+ clearSessionScroll(SESSION_B);+});++describe('session automatic history load memory', () => {+ it('keeps a started auto-fill run exhausted across an A → B → A remount', () => {+ saveSessionScroll(SESSION_A, bottomSnapshot);++ const firstMountAttempts = restoreSessionAutomaticHistoryLoadAttempts(+ SESSION_A,+ MAX_AUTO_LOAD_ATTEMPTS,+ );+ expect(firstMountAttempts).toBe(0);+ expect(+ decideAutoFillAction({+ scrollHeight: 600,+ clientHeight: 600,+ windowAtTop: true,+ hasMoreMessages: true,+ isLoadingMore: false,+ attemptCount: firstMountAttempts,+ }),+ ).toBe('load-from-db');++ markSessionAutomaticHistoryLoadStarted(SESSION_A);++ // 真实卸载顺序是先 mark 自动加载,再由 layout cleanup 保存滚动快照。+ // 保存快照不能把已启动标记覆盖掉。+ saveSessionScroll(SESSION_A, bottomSnapshot);++ // 切到另一个 Worker 不会继承 A 的预算。+ expect(restoreSessionAutomaticHistoryLoadAttempts(SESSION_B, MAX_AUTO_LOAD_ATTEMPTS)).toBe(0);++ // 再切回 A 时,即使仍是“视口未撑满 + DB 有更早历史”,也不重拉同一页。+ const remountAttempts = restoreSessionAutomaticHistoryLoadAttempts(+ SESSION_A,+ MAX_AUTO_LOAD_ATTEMPTS,+ );+ expect(remountAttempts).toBe(MAX_AUTO_LOAD_ATTEMPTS);+ expect(+ decideAutoFillAction({+ scrollHeight: 600,+ clientHeight: 600,+ windowAtTop: true,+ hasMoreMessages: true,+ isLoadingMore: false,+ attemptCount: remountAttempts,+ }),+ ).toBe('none');++ const remountNavRailRounds = restoreSessionAutomaticHistoryLoadAttempts(+ SESSION_A,+ NAV_RAIL_BACKFILL_MAX_ROUNDS,+ );+ expect(remountNavRailRounds).toBe(NAV_RAIL_BACKFILL_MAX_ROUNDS);+ expect(+ shouldBackfillForNavRail({+ entryCount: 1,+ hasMoreMessages: true,+ isLoadingMore: false,+ rounds: remountNavRailRounds,+ }),+ ).toBe(false);++ // 自动预算耗尽不参与用户意图判定;用户继续向上翻仍然可以加载。+ expect(+ decideUserIntentFillAction({+ scrollHeight: 600,+ clientHeight: 600,+ scrollTop: 0,+ windowAtTop: true,+ hasMoreMessages: true,+ isLoadingMore: false,+ }),+ ).toBe('load-from-db');++ // 自动补载标记与滚动快照共存在同一份 session view memory 中。+ expect(readSessionScroll(SESSION_A)).toEqual(bottomSnapshot);+ });++ it('clears the automatic load marker together with the session view memory', () => {+ markSessionAutomaticHistoryLoadStarted(SESSION_A);+ clearSessionScroll(SESSION_A);++ expect(readSessionScroll(SESSION_A)).toBeUndefined();+ expect(restoreSessionAutomaticHistoryLoadAttempts(SESSION_A, MAX_AUTO_LOAD_ATTEMPTS)).toBe(0);+ });+});diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 2189732c26..c43aceb471 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -65,7 +65,9 @@ import { createLogger } from '@/lib/logger';import { stopAllMedia } from '@/lib/mediaPlaybackBus';import { cn } from '@/lib/utils';import {+ markSessionAutomaticHistoryLoadStarted,readSessionScroll,+ restoreSessionAutomaticHistoryLoadAttempts,saveSessionScroll,type SessionScrollSnapshot,} from '@/lib/sessionScrollStore';@@ -200,6 +202,7 @@ import { usePrevUserMessageInView } from './usePrevUserMessageInView';import { JumpToBottomChip } from './JumpToBottomChip';import { MessageNavRail } from './MessageNavRail';import {+ NAV_RAIL_BACKFILL_MAX_ROUNDS,NAV_RAIL_JUMP_TOP_OFFSET_PX,deriveNavRailEntries,shouldBackfillForNavRail,@@ -209,6 +212,7 @@ import { detectScrollAnchoringApplied } from './scrollAnchoringDetect';import {decideAutoFillAction,decideUserIntentFillAction,+ MAX_AUTO_LOAD_ATTEMPTS,TOP_HISTORY_TRIGGER_PX,NO_SCROLL_TOLERANCE_PX,} from './viewportFillDetect';@@ -3253,8 +3257,10 @@ export function MessageStream({// 2. windowAtTop=y AND hasMoreMessages=false → DB 真的没历史了// 3. attemptCount >= MAX_AUTO_LOAD_ATTEMPTS → 退化保护 (只数 IPC, 不数 expand)//- // attemptCount 用 ref 持有, 跟着 mount 生命周期走; sessionId 切换时父组件用- // key={sessionId} 重挂载本组件, ref 自动归零 (单 session 内独立计数, 无需手动 reset).+ // attemptCount 用 ref 持有,让同一次 mount 内仍可按原预算连续补页。第一次真的+ // 发起自动补载时同时在 sessionScrollStore 记 started;切走再切回的新 mount+ // 直接从耗尽态开始,避免 leaveView 裁掉已补前缀后把同一页重新拉一遍。+ // 用户明确向上滚动 / 翻页走 decideUserIntentFillAction,不读取这份自动预算。// useLayoutEffect 而不是 useEffect — 在 commit 同步阶段读 scrollH/clientH,// 避免 useEffect 滞后一帧导致跟 ResizeObserver/pinToBottom 的副作用错序.//@@ -3263,7 +3269,9 @@ export function MessageStream({// 当前触发条件下 (scrollH===clientH) scrollTop 必为 0, 视觉收敛主要靠 line 716// 的 pinToBottom effect, 这两个 ref 在这是防御层 (避免 IPC race window 里// handleScroll 误覆盖 ref 用错快照 → F-SYNC-2 算错 delta).- const autoLoadAttemptCountRef = useRef<number>(0);+ const autoLoadAttemptCountRef = useRef<number>(+ restoreSessionAutomaticHistoryLoadAttempts(sessionId, MAX_AUTO_LOAD_ATTEMPTS),+ );useLayoutEffect(() => {const el = scrollRef.current;if (!el) return;@@ -3293,6 +3301,7 @@ export function MessageStream({autoLoadAttemptCountRef.current += 1;prevScrollHeightRef.current = el.scrollHeight;prevScrollTopAtLoadRef.current = el.scrollTop;+ if (sessionId) markSessionAutomaticHistoryLoadStarted(sessionId);onLoadMore();return;}@@ -3316,6 +3325,7 @@ export function MessageStream({hasMoreMessages,isLoadingMore,onLoadMore,+ sessionId,windowAtTop,expandWindow,windowCoversEnd,@@ -4061,12 +4071,12 @@ export function MessageStream({// 打开后本 effect 依赖变化会重新评估补页。// 调度 effect 的依赖含 sessionId(与 MessageNavRail 的 resetKey 同款惯例):// 两个会话的条目数 / hasMore 恰好相同且 onLoadMore 身份未变时,切会话也要- // 取消旧会话待发的空闲回调、并按归零后的轮数预算为新会话重新评估- // (Copilot review)。- const navRailBackfillRoundsRef = useRef(0);- useEffect(() => {- navRailBackfillRoundsRef.current = 0;- }, [sessionId]);+ // 取消旧会话待发的空闲回调。轮数预算只在 mount 时按会话记忆恢复一次;+ // 不能在 passive effect 再读,否则同一 mount 的 viewport-fill 先 mark 后会+ // 提前封死导航条自己的本轮预算。+ const navRailBackfillRoundsRef = useRef(+ restoreSessionAutomaticHistoryLoadAttempts(sessionId, NAV_RAIL_BACKFILL_MAX_ROUNDS),+ );useEffect(() => {if (!navRailEnabled) return;if (!onLoadMore) return;@@ -4086,6 +4096,7 @@ export function MessageStream({navRailBackfillRoundsRef.current += 1;prevScrollHeightRef.current = el.scrollHeight;prevScrollTopAtLoadRef.current = el.scrollTop;+ if (sessionId) markSessionAutomaticHistoryLoadStarted(sessionId);onLoadMore();};// 空闲期执行,别跟首屏渲染 / 两段式扩窗抢主线程;测试等无 ric 环境退化。diff --git a/apps/desktop/src/renderer/lib/sessionScrollStore.ts b/apps/desktop/src/renderer/lib/sessionScrollStore.tsindex e6a37a872e..62be6b267a 100644--- a/apps/desktop/src/renderer/lib/sessionScrollStore.ts+++ b/apps/desktop/src/renderer/lib/sessionScrollStore.ts@@ -33,14 +33,46 @@ export interface SessionScrollSnapshot {anchoredForwardCount?: number;}-const store = new Map<string, SessionScrollSnapshot>();+interface SessionViewMemory {+ scroll?: SessionScrollSnapshot;+ /**+ * 本次 app 运行期内,该会话是否已经启动过一轮自动历史补载。+ *+ * 这里只记 started,不记精确轮数:一次 mount 可能只拉 1 页就撑满视口,+ * 离开时消息缓存又会裁掉刚补进来的前缀。若下次 mount 从 1/5 继续算,+ * 仍会把同一页历史重新拉一遍。重挂载时应把自动预算整体视作已用完;+ * 用户明确上滑 / 翻页的加载路径不读取这个标记,仍可继续加载。+ */+ automaticHistoryLoadStarted?: true;+}++const store = new Map<string, SessionViewMemory>();export function saveSessionScroll(sessionId: string, snapshot: SessionScrollSnapshot): void {- store.set(sessionId, snapshot);+ const previous = store.get(sessionId);+ store.set(sessionId, { ...previous, scroll: snapshot });}export function readSessionScroll(sessionId: string): SessionScrollSnapshot | undefined {- return store.get(sessionId);+ return store.get(sessionId)?.scroll;+}++/** 记录该会话在当前 app 运行期已经启动过自动历史补载。 */+export function markSessionAutomaticHistoryLoadStarted(sessionId: string): void {+ const previous = store.get(sessionId);+ store.set(sessionId, { ...previous, automaticHistoryLoadStarted: true });+}++/**+ * 为一次新的 MessageStream mount 恢复自动补载计数。+ * 旧 mount 已经启动过补载时直接返回上限,避免切走再切回后重启同一轮补载。+ */+export function restoreSessionAutomaticHistoryLoadAttempts(+ sessionId: string | null | undefined,+ maxAttempts: number,+): number {+ if (!sessionId) return 0;+ return store.get(sessionId)?.automaticHistoryLoadStarted ? maxAttempts : 0;}export function clearSessionScroll(sessionId: string): void {