Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): align worker history memory with cache lifecycle
Dash7e6aacca0a9c
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.tsindex fd73696459..79f8c346cc 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts@@ -47,6 +47,10 @@ vi.mock('@/lib/composerDraftStore', () => ({import { makerChatStore } from '@/lib/makerChatStore';import * as messageService from '@/lib/messageService';+import {+ markSessionAutomaticHistoryLoadCompleted,+ restoreSessionAutomaticHistoryLoadAttempts,+} from '@/lib/sessionScrollStore';const BASE_TIME = new Date('2026-05-20T00:00:00.000Z');@@ -970,10 +974,11 @@ describe('makerChatStore active view tracking', () => {.mockResolvedValueOnce(fullPage(sessionId, 999)).mockRejectedValueOnce(new Error('tunnel dropped'));- makerChatStore.loadOlderMessages(sessionId);- await flushPagingLoop();+ const didAdvanceWindow = await makerChatStore.loadOlderMessages(sessionId, true);const snapshot = makerChatStore.getSnapshot(sessionId);+ expect(didAdvanceWindow).toBe(true);+ expect(restoreSessionAutomaticHistoryLoadAttempts(sessionId, 5)).toBe(5);expect(snapshot.isLoadingMore).toBe(false);// 第 1 页已进 UI(游标推进、内容不丢),失败只终止追页,保持可重试。expect(snapshot.hasMoreMessages).toBe(true);@@ -988,15 +993,29 @@ describe('makerChatStore active view tracking', () => {vi.mocked(messageService.list).mockRejectedValueOnce(new Error('tunnel dropped'));- makerChatStore.loadOlderMessages(sessionId);- await flushPagingLoop();+ const didAdvanceWindow = await makerChatStore.loadOlderMessages(sessionId, true);const snapshot = makerChatStore.getSnapshot(sessionId);+ expect(didAdvanceWindow).toBe(false);+ expect(restoreSessionAutomaticHistoryLoadAttempts(sessionId, 5)).toBe(0);expect(snapshot.isLoadingMore).toBe(false);expect(snapshot.hasMoreMessages).toBe(true);expect(snapshot.oldestMessageId).toBe('current');});+ it('reports an empty authoritative page as no cached-window advance', async () => {+ const sessionId = sid('older-backfill-empty');+ await seedSession(sessionId);++ vi.mocked(messageService.list).mockResolvedValueOnce([]);++ const didAdvanceWindow = await makerChatStore.loadOlderMessages(sessionId, true);++ expect(didAdvanceWindow).toBe(false);+ expect(makerChatStore.getSnapshot(sessionId).hasMoreMessages).toBe(false);+ expect(restoreSessionAutomaticHistoryLoadAttempts(sessionId, 5)).toBe(0);+ });+// rewind 竞态守卫:追页 in-flight 期间 reloadMessages(rewind commit 后的强制// 重载)把切片清空重置,晚到的翻页窗口必须整体作废——merge 回去会让服务端// 已软删的行复活。守卫走 _messagesEpoch 代际比对。@@ -1035,17 +1054,20 @@ describe('makerChatStore active view tracking', () => {.mockReturnValueOnce(olderPagePromise) // loadOlderMessages 第 1 页(挂起中).mockResolvedValueOnce([]); // reloadMessages → ensureInitialMessages(重载后空历史)- makerChatStore.loadOlderMessages(sessionId);+ markSessionAutomaticHistoryLoadCompleted(sessionId);+ const loadResult = makerChatStore.loadOlderMessages(sessionId, true);expect(makerChatStore.getSnapshot(sessionId).isLoadingMore).toBe(true);makerChatStore.reloadMessages(sessionId);await Promise.resolve();+ expect(restoreSessionAutomaticHistoryLoadAttempts(sessionId, 5)).toBe(0);// 翻页此刻才返回(短页 → 循环立即收口进入提交),但代际已变 → 作废。resolveOlderPage(fullPage(sessionId, 999).slice(0, 10));await flushPagingLoop();const snapshot = makerChatStore.getSnapshot(sessionId);+ await expect(loadResult).resolves.toBe(false);expect(snapshot.isLoadingMore).toBe(false);expect(snapshot.messages).toHaveLength(0); // 旧窗口没有被 merge 回清空后的切片expect(snapshot.oldestMessageId).toBeNull();@@ -1102,7 +1124,9 @@ describe('makerChatStore active view tracking', () => {const sessionId = sid('demote');const dispose = enter(sessionId);addMessage(sessionId);+ markSessionAutomaticHistoryLoadCompleted(sessionId);expect(makerChatStore.getSnapshot(sessionId).messages).toHaveLength(1);+ expect(restoreSessionAutomaticHistoryLoadAttempts(sessionId, 5)).toBe(5);dispose(); // 写 lastViewedAt = BASE_TIME// 4:59 仍保留,5:00 的 demote timer 才清空(检查间隔 30s)。@@ -1113,6 +1137,7 @@ describe('makerChatStore active view tracking', () => {expect(makerChatStore.getSnapshot(sessionId).messages).toHaveLength(0);expect(makerChatStore.getSnapshot(sessionId).historyLoaded).toBe(false);+ expect(restoreSessionAutomaticHistoryLoadAttempts(sessionId, 5)).toBe(0);});it('demotes a prefetched session that never enters a mounted view', async () => {diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.tsindex 515398ce62..cd709d05f5 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts@@ -72,6 +72,10 @@ vi.mock('@/lib/composerDraftStore', () => ({import { makerChatStore } from '@/lib/makerChatStore';import { aroundMessagesByClientIdFor, listMessagesFor } from '@/lib/makerTransport';+import {+ markSessionAutomaticHistoryLoadCompleted,+ restoreSessionAutomaticHistoryLoadAttempts,+} from '@/lib/sessionScrollStore';import type { Message } from '@/lib/ccAgent.types';const SID = 'sess-jump-backfill';@@ -1331,6 +1335,7 @@ describe('跳转补齐 — 窗口连续,不留历史空洞', () => {await makerChatStore.loadAroundMessageClientId(SID, 'island-trim', { radius: 60 });expect(makerChatStore.getSnapshot(SID).historyWindowHasIsland).toBe(true);expect(makerChatStore.getSnapshot(SID).messages.length).toBeGreaterThan(300);+ markSessionAutomaticHistoryLoadCompleted(SID);// 离开视图 → 触发 _trimMessagesIfNeeded。const leave = makerChatStore.enterView(SID);@@ -1339,6 +1344,8 @@ describe('跳转补齐 — 窗口连续,不留历史空洞', () => {expect(makerChatStore.getSnapshot(SID).messages).toHaveLength(200);// 关键:裁剪不清标记 —— 保留的 200 行未必连续。expect(makerChatStore.getSnapshot(SID).historyWindowHasIsland).toBe(true);+ // 普通裁剪正是原问题的重挂载场景:消息窗口仍属同一代,自动补载预算必须保持耗尽。+ expect(restoreSessionAutomaticHistoryLoadAttempts(SID, 5)).toBe(5);});it('Y2. 超长裁剪丢掉当前计划边界时,允许重入重新首拉补回计划', async () => {diff --git a/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts b/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.tsindex c460f8fb6c..386e7573cf 100644--- a/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts+++ b/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts@@ -30,6 +30,10 @@ vi.mock('@/lib/sessionService', () => ({import { makerChatStore } from '@/lib/makerChatStore';import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';+import {+ markSessionAutomaticHistoryLoadCompleted,+ restoreSessionAutomaticHistoryLoadAttempts,+} from '@/lib/sessionScrollStore';const DEVICE_ID = 'dev-A';const DEVICE_B_ID = 'dev-B';@@ -509,6 +513,7 @@ describe('makerChatStore.reconcileRemoteMessages', () => {dbMessage(s, 'old-cache', 'old cached text', '2026-06-15T00:00:00.000Z'),dbMessage(s, 'cached-future', 'controller clock ahead text', '2026-06-16T00:00:00.000Z'),]);+ markSessionAutomaticHistoryLoadCompleted(s);const remoteHistory = Array.from({ length: 550 }, (_, index) =>dbMessage(@@ -531,6 +536,7 @@ describe('makerChatStore.reconcileRemoteMessages', () => {expect(snapshot.messages.at(-1)?.clientId).toBe('client-new-549');expect(snapshot.oldestMessageId).toBe('new-50');expect(snapshot.hasMoreMessages).toBe(true);+ expect(restoreSessionAutomaticHistoryLoadAttempts(s, 5)).toBe(0);});it('远程会话:无重叠对账保留分页期间新到的 remote push', async () => {diff --git a/apps/desktop/src/renderer/__tests__/sessionScrollStore.test.ts b/apps/desktop/src/renderer/__tests__/sessionScrollStore.test.tsindex b0c54177dd..85301a2ad1 100644--- a/apps/desktop/src/renderer/__tests__/sessionScrollStore.test.ts+++ b/apps/desktop/src/renderer/__tests__/sessionScrollStore.test.ts@@ -2,8 +2,9 @@ import { afterEach, describe, expect, it } from 'vitest';import {clearSessionScroll,- markSessionAutomaticHistoryLoadStarted,+ markSessionAutomaticHistoryLoadCompleted,readSessionScroll,+ resetSessionAutomaticHistoryLoadCompletion,restoreSessionAutomaticHistoryLoadAttempts,saveSessionScroll,type SessionScrollSnapshot,@@ -34,7 +35,7 @@ afterEach(() => {});describe('session automatic history load memory', () => {- it('keeps a started auto-fill run exhausted across an A → B → A remount', () => {+ it('keeps a completed auto-fill run exhausted across an A → B → A remount', () => {saveSessionScroll(SESSION_A, bottomSnapshot);const firstMountAttempts = restoreSessionAutomaticHistoryLoadAttempts(@@ -53,10 +54,10 @@ describe('session automatic history load memory', () => {}),).toBe('load-from-db');- markSessionAutomaticHistoryLoadStarted(SESSION_A);+ markSessionAutomaticHistoryLoadCompleted(SESSION_A);- // 真实卸载顺序是先 mark 自动加载,再由 layout cleanup 保存滚动快照。- // 保存快照不能把已启动标记覆盖掉。+ // 真实卸载顺序是先完成自动加载,再由 layout cleanup 保存滚动快照。+ // 保存快照不能把已完成标记覆盖掉。saveSessionScroll(SESSION_A, bottomSnapshot);// 切到另一个 Worker 不会继承 A 的预算。@@ -109,8 +110,18 @@ describe('session automatic history load memory', () => {expect(readSessionScroll(SESSION_A)).toEqual(bottomSnapshot);});+ it('restores the automatic budget when the cached message window is discarded', () => {+ saveSessionScroll(SESSION_A, bottomSnapshot);+ markSessionAutomaticHistoryLoadCompleted(SESSION_A);++ resetSessionAutomaticHistoryLoadCompletion(SESSION_A);++ expect(readSessionScroll(SESSION_A)).toEqual(bottomSnapshot);+ expect(restoreSessionAutomaticHistoryLoadAttempts(SESSION_A, MAX_AUTO_LOAD_ATTEMPTS)).toBe(0);+ });+it('clears the automatic load marker together with the session view memory', () => {- markSessionAutomaticHistoryLoadStarted(SESSION_A);+ markSessionAutomaticHistoryLoadCompleted(SESSION_A);clearSessionScroll(SESSION_A);expect(readSessionScroll(SESSION_A)).toBeUndefined();diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex c43aceb471..863c5a708d 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -65,7 +65,6 @@ import { createLogger } from '@/lib/logger';import { stopAllMedia } from '@/lib/mediaPlaybackBus';import { cn } from '@/lib/utils';import {- markSessionAutomaticHistoryLoadStarted,readSessionScroll,restoreSessionAutomaticHistoryLoadAttempts,saveSessionScroll,@@ -261,8 +260,8 @@ interface MessageStreamProps {continuationTurnClientId?: string | null;/** 旧被控端缺省该字段时才启用兼容兜底;unknown 在首个投影前 fail closed。 */continuationInFlightProjectionCapability?: ContinuationInFlightProjectionCapability;- /** F-SYNC-2: callback to load older messages */- onLoadMore?: () => void;+ /** F-SYNC-2: callback to load older messages; true marks this as an automatic fill. */+ onLoadMore?: (automatic?: boolean) => Promise<boolean>;isLoadingMore?: boolean;hasMoreMessages?: boolean;/** Dynamic bottom padding (px) to reserve space for the input overlay */@@ -3258,7 +3257,7 @@ export function MessageStream({// 3. attemptCount >= MAX_AUTO_LOAD_ATTEMPTS → 退化保护 (只数 IPC, 不数 expand)//// attemptCount 用 ref 持有,让同一次 mount 内仍可按原预算连续补页。第一次真的- // 发起自动补载时同时在 sessionScrollStore 记 started;切走再切回的新 mount+ // 成功推进缓存窗口后同时在 sessionScrollStore 记 completed;切走再切回的新 mount// 直接从耗尽态开始,避免 leaveView 裁掉已补前缀后把同一页重新拉一遍。// 用户明确向上滚动 / 翻页走 decideUserIntentFillAction,不读取这份自动预算。// useLayoutEffect 而不是 useEffect — 在 commit 同步阶段读 scrollH/clientH,@@ -3301,8 +3300,7 @@ export function MessageStream({autoLoadAttemptCountRef.current += 1;prevScrollHeightRef.current = el.scrollHeight;prevScrollTopAtLoadRef.current = el.scrollTop;- if (sessionId) markSessionAutomaticHistoryLoadStarted(sessionId);- onLoadMore();+ void onLoadMore(true);return;}case 'none':@@ -4096,8 +4094,7 @@ export function MessageStream({navRailBackfillRoundsRef.current += 1;prevScrollHeightRef.current = el.scrollHeight;prevScrollTopAtLoadRef.current = el.scrollTop;- if (sessionId) markSessionAutomaticHistoryLoadStarted(sessionId);- onLoadMore();+ void onLoadMore(true);};// 空闲期执行,别跟首屏渲染 / 两段式扩窗抢主线程;测试等无 ric 环境退化。if (typeof window.requestIdleCallback === 'function') {diff --git a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts b/apps/desktop/src/renderer/hooks/useCCAgentChat.tsindex 7907097f24..db442f6581 100644--- a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts+++ b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts@@ -194,8 +194,8 @@ interface UseCCAgentChatReturn {continuationTurnClientId: string | null;/** 续跑边界投影能力;legacy 时保留旧被控端的兼容兜底。 */continuationInFlightProjectionCapability: ContinuationInFlightProjectionCapability;- /** F-SYNC-2: Load older messages (prepend to top) */- loadOlderMessages: () => void;+ /** F-SYNC-2: Load older messages; automatic=true remembers a successful auto-fill. */+ loadOlderMessages: (automatic?: boolean) => Promise<boolean>;isLoadingMore: boolean;hasMoreMessages: boolean;historyWindowHasIsland: boolean;@@ -549,9 +549,9 @@ export function useCCAgentChat([sessionId],);- const loadOlderMessages = useCallback(() => {- if (!sessionId) return;- makerChatStore.loadOlderMessages(sessionId);+ const loadOlderMessages = useCallback((automatic = false): Promise<boolean> => {+ if (!sessionId) return Promise.resolve(false);+ return makerChatStore.loadOlderMessages(sessionId, automatic);}, [sessionId]);const respondToPermission = useCallback(diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 47f0da3b70..816d063fe4 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -120,6 +120,10 @@ import type { AgentKind } from '@/hooks/useAgentCapabilities';import type { Effort } from '@/lib/userPreferences.types';import { emitAutoTitlePreview, emitAutoTitlePreviewCleared, emitPatch } from '@/lib/sessionsBus';import { createLogger } from '@/lib/logger';+import {+ markSessionAutomaticHistoryLoadCompleted,+ resetSessionAutomaticHistoryLoadCompletion,+} from '@/lib/sessionScrollStore';import { extractIpcError } from '@/utils/ipcError';import { tryBeginAgentSendDispatch } from '@/lib/agentSwitchCoordinator';import { getUserPrompt } from '@/lib/userPromptStore';@@ -3174,6 +3178,7 @@ function _purgeSession(sessionId: string): void {// 交接中的迟到 continuation,且不写入 /clear 的历史时间边界。bumpRendererClearGeneration(sessionId);cancelRemoteOptimisticSendsForSessionPurge(sessionId);+ resetSessionAutomaticHistoryLoadCompletion(sessionId);sessions.delete(sessionId);localSentUserMessageIds.delete(sessionId);pendingLocalRetryIntents.delete(sessionId);@@ -3387,6 +3392,7 @@ function _demoteIdleSessions(): void {// 分页锁。漏 bump 的后果是 in-flight 那一页按 demote 前的游标提交,把一段脱离上下文// 的旧历史 merge 进空切片(或重开后的新切片),最近的消息反而缺席(#676 review)。bumpMessagesEpoch(sessionId);+ resetSessionAutomaticHistoryLoadCompletion(sessionId);setState(sessionId, (s) => ({...s,messages: [],@@ -9602,6 +9608,7 @@ function ensureInitialMessages(sessionId: string): void {*/function reloadMessages(sessionId: string, opts?: { allowCacheHydrate?: boolean }): void {discardPendingTextDelta(sessionId);+ resetSessionAutomaticHistoryLoadCompletion(sessionId);// 代际递增:作废 in-flight 的 loadOlderMessages 追页窗口(见 _messagesEpoch 注释)。bumpMessagesEpoch(sessionId);invalidateHistoryFetch(sessionId);@@ -10094,7 +10101,10 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): PromhistoryWindowHasIsland: hasDetachedArrival,};});- if (didRebuild) bumpMessagesEpoch(sessionId);+ if (didRebuild) {+ resetSessionAutomaticHistoryLoadCompletion(sessionId);+ bumpMessagesEpoch(sessionId);+ }} finally {// 消息路径的早返 / 异常都要等交互重建落定;交互失败会让 run reject(替换原结果),// 语义正确:本代不完成。@@ -10147,21 +10157,26 @@ function finalizeStuckRemoteTurn(sessionId: string): void {*/const MAX_LOAD_OLDER_PAGES = 10;-function loadOlderMessages(sessionId: string): void {+/**+ * 加载并提交更早的历史。返回 true 仅表示当前缓存窗口确实向前推进;+ * 行首守卫、空页、全程失败、代际作废和提交异常都返回 false。+ * automatic=true 时只在推进成功后耗尽该缓存窗口的跨 mount 自动补载预算。+ */+function loadOlderMessages(sessionId: string, automatic = false): Promise<boolean> {const state = getOrCreateState(sessionId);- if (state.isLoadingMore || !state.hasMoreMessages) return;+ if (state.isLoadingMore || !state.hasMoreMessages) return Promise.resolve(false);let firstPageOpts: { limit: number; before?: string; beforeTs?: number };if (state.oldestMessageId) {firstPageOpts = { limit: 50, before: state.oldestMessageId };} else if (state.messages.length > 0) {const oldest = state.messages[0];- if (!oldest.createdAt) return;+ if (!oldest.createdAt) return Promise.resolve(false);const ts = new Date(oldest.createdAt).getTime();- if (!Number.isFinite(ts)) return;+ if (!Number.isFinite(ts)) return Promise.resolve(false);firstPageOpts = { limit: 50, beforeTs: ts };} else {- return;+ return Promise.resolve(false);}setState(sessionId, (s) => ({ ...s, isLoadingMore: true }));@@ -10173,7 +10188,7 @@ function loadOlderMessages(sessionId: string): void {// 远程会话(device-link)往上翻页加载更多历史:会话与消息只在被控端,必须走 origin-aware// 的 listMessagesFor(本地会话回落 messageService.list),否则查控制端空库 → 旧历史加载为空。// 与初始加载 / backfill(本文件其余处)保持一致。- void (async () => {+ return (async () => {try {const collected: Message[] = [];// 跨页按 clientId 去重:mergeMessages 只对"新批 vs 已有"去重,不去重批内@@ -10220,7 +10235,7 @@ function loadOlderMessages(sessionId: string): void {// 重置之后,新代际很可能已经开始自己的分页并重新置了锁 —— 这里再无条件清一次,// 就是把别人的锁放掉,让后续滚动 / 跳转并发去抢同一个游标,重新制造游标回退与// 重复分页(#676 review)。谁重置谁释放,被作废的请求一律不碰。- if ((_messagesEpoch.get(sessionId) ?? 0) !== epochAtStart) return;+ if ((_messagesEpoch.get(sessionId) ?? 0) !== epochAtStart) return false;if (collected.length === 0) {setState(sessionId, (s) => ({@@ -10229,17 +10244,28 @@ function loadOlderMessages(sessionId: string): void {hasMoreMessages: hasMore ? s.hasMoreMessages : false,isLoadingMore: false,}));- return;+ return false;}const mapped = mapServerMessages(collected);- setState(sessionId, (s) => ({- ...s,- messages: mergeMessages(mapped, s.messages, {}, 'newest-first'),- oldestMessageId: oldestId ?? s.oldestMessageId,- hasMoreMessages: hasMore,- isLoadingMore: false,- }));+ let didAdvanceWindow = false;+ setState(sessionId, (s) => {+ const messages = mergeMessages(mapped, s.messages, {}, 'newest-first');+ const nextOldestMessageId = oldestId ?? s.oldestMessageId;+ didAdvanceWindow =+ messages.length > s.messages.length || nextOldestMessageId !== s.oldestMessageId;+ return {+ ...s,+ messages,+ oldestMessageId: nextOldestMessageId,+ hasMoreMessages: hasMore,+ isLoadingMore: false,+ };+ });+ if (didAdvanceWindow && automatic) {+ markSessionAutomaticHistoryLoadCompleted(sessionId);+ }+ return didAdvanceWindow;} catch (err) {// map/merge/commit 阶段兜底(subagent review P1):任何异常都必须复位// isLoadingMore,否则行首守卫会让该会话永久无法再翻页(spinner 卡死)。@@ -10252,6 +10278,7 @@ function loadOlderMessages(sessionId: string): void {if ((_messagesEpoch.get(sessionId) ?? 0) === epochAtStart) {setState(sessionId, (s) => ({ ...s, isLoadingMore: false }));}+ return false;}})();}@@ -12551,6 +12578,7 @@ async function clearSessionAfterGuardImpl(sessionId: string, clearedAt: string):// The clear guard itself must be the new authority generation, otherwise an// older projection can win the race and reinsert pre-clear queue state.bumpMessagesEpoch(sessionId);+ resetSessionAutomaticHistoryLoadCompletion(sessionId);bumpInteractionReconcileEpoch(sessionId);supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });if (remoteDeviceId) {diff --git a/apps/desktop/src/renderer/lib/sessionScrollStore.ts b/apps/desktop/src/renderer/lib/sessionScrollStore.tsindex 62be6b267a..6d4e10518c 100644--- a/apps/desktop/src/renderer/lib/sessionScrollStore.ts+++ b/apps/desktop/src/renderer/lib/sessionScrollStore.ts@@ -36,14 +36,15 @@ export interface SessionScrollSnapshot {interface SessionViewMemory {scroll?: SessionScrollSnapshot;/**- * 本次 app 运行期内,该会话是否已经启动过一轮自动历史补载。+ * 当前缓存消息窗口是否已经成功完成过一轮自动历史补载。*- * 这里只记 started,不记精确轮数:一次 mount 可能只拉 1 页就撑满视口,+ * 这里只记 completed,不记精确轮数:一次 mount 可能只拉 1 页就撑满视口,* 离开时消息缓存又会裁掉刚补进来的前缀。若下次 mount 从 1/5 继续算,* 仍会把同一页历史重新拉一遍。重挂载时应把自动预算整体视作已用完;- * 用户明确上滑 / 翻页的加载路径不读取这个标记,仍可继续加载。+ * 用户明确上滑 / 翻页的加载路径不读取这个标记,仍可继续加载。缓存窗口被+ * 整体丢弃时清除此标记,让新窗口重新获得一次自动补载预算。*/- automaticHistoryLoadStarted?: true;+ automaticHistoryLoadCompleted?: true;}const store = new Map<string, SessionViewMemory>();@@ -57,22 +58,32 @@ export function readSessionScroll(sessionId: string): SessionScrollSnapshot | unreturn store.get(sessionId)?.scroll;}-/** 记录该会话在当前 app 运行期已经启动过自动历史补载。 */-export function markSessionAutomaticHistoryLoadStarted(sessionId: string): void {+/** 记录当前缓存消息窗口已经成功推进过一次自动历史补载。 */+export function markSessionAutomaticHistoryLoadCompleted(sessionId: string): void {const previous = store.get(sessionId);- store.set(sessionId, { ...previous, automaticHistoryLoadStarted: true });+ store.set(sessionId, { ...previous, automaticHistoryLoadCompleted: true });+}++/** 缓存消息窗口被整体重建时,恢复该会话的自动补载预算并保留滚动快照。 */+export function resetSessionAutomaticHistoryLoadCompletion(sessionId: string): void {+ const previous = store.get(sessionId);+ if (!previous?.automaticHistoryLoadCompleted) return;+ const next = { ...previous };+ delete next.automaticHistoryLoadCompleted;+ if (next.scroll) store.set(sessionId, next);+ else store.delete(sessionId);}/*** 为一次新的 MessageStream mount 恢复自动补载计数。- * 旧 mount 已经启动过补载时直接返回上限,避免切走再切回后重启同一轮补载。+ * 当前缓存窗口已经完成过补载时直接返回上限,避免切走再切回后重启同一轮补载。*/export function restoreSessionAutomaticHistoryLoadAttempts(sessionId: string | null | undefined,maxAttempts: number,): number {if (!sessionId) return 0;- return store.get(sessionId)?.automaticHistoryLoadStarted ? maxAttempts : 0;+ return store.get(sessionId)?.automaticHistoryLoadCompleted ? maxAttempts : 0;}export function clearSessionScroll(sessionId: string): void {