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(desktop): reset worker history budgets on rebuild

Dash4caf07bf64e6
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts
index 79f8c346cc..8fdc3afeee 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts
@@ -1077,6 +1077,7 @@ describe('makerChatStore active view tracking', () => {
it('keeps legacy single-row removal compatible with an in-flight paging window', async () => {
const sessionId = sid('older-backfill-single-delete-compat');
await seedSession(sessionId);
+ markSessionAutomaticHistoryLoadCompleted(sessionId);
let resolveOlderPage!: (rows: Message[]) => void;
vi.mocked(messageService.list).mockReturnValueOnce(
@@ -1094,11 +1095,13 @@ describe('makerChatStore active view tracking', () => {
expect(snapshot.messages).toHaveLength(10);
expect(snapshot.messages.some((message) => message.clientId === 'client-current')).toBe(false);
expect(snapshot.isLoadingMore).toBe(false);
+ expect(restoreSessionAutomaticHistoryLoadAttempts(sessionId, 5)).toBe(5);
});
it('discards an in-flight paging window after grouped deletion', async () => {
const sessionId = sid('older-backfill-group-delete-race');
await seedSession(sessionId);
+ markSessionAutomaticHistoryLoadCompleted(sessionId);
let resolveOlderPage!: (rows: Message[]) => void;
vi.mocked(messageService.list).mockReturnValueOnce(
@@ -1115,6 +1118,7 @@ describe('makerChatStore active view tracking', () => {
const snapshot = makerChatStore.getSnapshot(sessionId);
expect(snapshot.messages).toHaveLength(0);
expect(snapshot.isLoadingMore).toBe(false);
+ expect(restoreSessionAutomaticHistoryLoadAttempts(sessionId, 5)).toBe(0);
});
});
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts
index cd709d05f5..b345b06c01 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts
@@ -355,6 +355,7 @@ describe('跳转补齐 — 窗口连续,不留历史空洞', () => {
createdAt: '2026-07-20T00:00:00.000Z',
});
vi.mocked(aroundMessagesByClientIdFor).mockResolvedValueOnce([target]);
+ markSessionAutomaticHistoryLoadCompleted(SID);
vi.mocked(listMessagesFor).mockImplementationOnce(async () => {
const page = fullPageNewestFirst();
// 补齐 await 期间发生 edit-last 截断。
@@ -367,6 +368,7 @@ describe('跳转补齐 — 窗口连续,不留历史空洞', () => {
// 跳转整体作废:不返回目标,也不把 around 行 merge 回窗口。
expect(result).toBeNull();
expect(makerChatStore.getSnapshot(SID).messages.map((m) => m.clientId)).not.toContain('rewound');
+ expect(restoreSessionAutomaticHistoryLoadAttempts(SID, 5)).toBe(0);
});
it('J. 纯文本会话在预算内停手,不会无限翻到几千行', async () => {
diff --git a/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts b/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts
index 386e7573cf..bcf2b840c4 100644
--- a/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts
+++ b/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts
@@ -514,6 +514,14 @@ describe('makerChatStore.reconcileRemoteMessages', () => {
dbMessage(s, 'cached-future', 'controller clock ahead text', '2026-06-16T00:00:00.000Z'),
]);
markSessionAutomaticHistoryLoadCompleted(s);
+ const completionAttemptsAtRebuildNotification: number[] = [];
+ const unsubscribe = makerChatStore.subscribe(s, () => {
+ if (makerChatStore.getSnapshot(s).messages[0]?.clientId === 'client-new-50') {
+ completionAttemptsAtRebuildNotification.push(
+ restoreSessionAutomaticHistoryLoadAttempts(s, 5),
+ );
+ }
+ });
const remoteHistory = Array.from({ length: 550 }, (_, index) =>
dbMessage(
@@ -527,6 +535,7 @@ describe('makerChatStore.reconcileRemoteMessages', () => {
makerChatStore.reconcileRemoteMessages(s);
await flushMany(REMOTE_RECONCILE_FLUSH_TICKS);
+ unsubscribe();
const snapshot = makerChatStore.getSnapshot(s);
expect(snapshot.messages).toHaveLength(500);
@@ -537,6 +546,7 @@ describe('makerChatStore.reconcileRemoteMessages', () => {
expect(snapshot.oldestMessageId).toBe('new-50');
expect(snapshot.hasMoreMessages).toBe(true);
expect(restoreSessionAutomaticHistoryLoadAttempts(s, 5)).toBe(0);
+ expect(completionAttemptsAtRebuildNotification).toContain(0);
});
it('远程会话:无重叠对账保留分页期间新到的 remote push', async () => {
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 863c5a708d..dd69c25903 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -66,7 +66,6 @@ import { stopAllMedia } from '@/lib/mediaPlaybackBus';
import { cn } from '@/lib/utils';
import {
readSessionScroll,
- restoreSessionAutomaticHistoryLoadAttempts,
saveSessionScroll,
type SessionScrollSnapshot,
} from '@/lib/sessionScrollStore';
@@ -226,6 +225,7 @@ import {
import { countUnreadAdded } from './unreadCount';
import { useNavigationKeyListener } from './useNavigationKeyListener';
import { suppressScrollbarActivation } from '@/lib/scrollbarAutoHide';
+import { useAutomaticHistoryLoadBudget } from './useAutomaticHistoryLoadBudget';
import { collectAssistantTurnUsageDetails } from '@/lib/userTurnUsage';
import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';
import { hasReviewableTurnChanges, type TurnChangeSetSummary } from '../../../shared/turnChangeSet';
@@ -250,6 +250,7 @@ interface MessageStreamProps {
* triggers extra re-renders mid-session. */
workingDir: string;
messages: ChatMessage[];
+ historyLoaded: boolean;
taskUpdates?: ReadonlyMap<string, AgentTaskUpdate>;
/** Kept for API compatibility. v2 — no longer threaded into render items
* (AgentActionsBlock + ThinkingCard manage their own per-block expand
@@ -2526,6 +2527,7 @@ export function MessageStream({
remoteHostId,
workingDir,
messages,
+ historyLoaded,
taskUpdates,
isSessionStreaming = false,
continuationTurnClientId = null,
@@ -3268,9 +3270,23 @@ 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>(
- restoreSessionAutomaticHistoryLoadAttempts(sessionId, MAX_AUTO_LOAD_ATTEMPTS),
+ const {
+ viewportAttemptsRef: autoLoadAttemptCountRef,
+ navRailRoundsRef: navRailBackfillRoundsRef,
+ runAutomaticLoad,
+ } = useAutomaticHistoryLoadBudget(
+ sessionId,
+ MAX_AUTO_LOAD_ATTEMPTS,
+ NAV_RAIL_BACKFILL_MAX_ROUNDS,
+ {
+ historyLoaded,
+ messageCount: messages.length,
+ firstMessageClientId: messages[0]?.clientId ?? null,
+ },
);
+ // MessageStream 只按 sessionId remount。逻辑窗口在同一 mount 内被 reload / reconcile /
+ // truncate 时,hook 会同步归零两套本地预算;不能只用 messages identity,正常
+ // push/prepend 同样会换引用。
useLayoutEffect(() => {
const el = scrollRef.current;
if (!el) return;
@@ -3300,7 +3316,7 @@ export function MessageStream({
autoLoadAttemptCountRef.current += 1;
prevScrollHeightRef.current = el.scrollHeight;
prevScrollTopAtLoadRef.current = el.scrollTop;
- void onLoadMore(true);
+ void runAutomaticLoad(onLoadMore);
return;
}
case 'none':
@@ -3323,6 +3339,7 @@ export function MessageStream({
hasMoreMessages,
isLoadingMore,
onLoadMore,
+ runAutomaticLoad,
sessionId,
windowAtTop,
expandWindow,
@@ -4072,9 +4089,6 @@ export function MessageStream({
// 取消旧会话待发的空闲回调。轮数预算只在 mount 时按会话记忆恢复一次;
// 不能在 passive effect 再读,否则同一 mount 的 viewport-fill 先 mark 后会
// 提前封死导航条自己的本轮预算。
- const navRailBackfillRoundsRef = useRef(
- restoreSessionAutomaticHistoryLoadAttempts(sessionId, NAV_RAIL_BACKFILL_MAX_ROUNDS),
- );
useEffect(() => {
if (!navRailEnabled) return;
if (!onLoadMore) return;
@@ -4094,7 +4108,7 @@ export function MessageStream({
navRailBackfillRoundsRef.current += 1;
prevScrollHeightRef.current = el.scrollHeight;
prevScrollTopAtLoadRef.current = el.scrollTop;
- void onLoadMore(true);
+ void runAutomaticLoad(onLoadMore);
};
// 空闲期执行,别跟首屏渲染 / 两段式扩窗抢主线程;测试等无 ric 环境退化。
if (typeof window.requestIdleCallback === 'function') {
@@ -4110,6 +4124,7 @@ export function MessageStream({
hasMoreMessages,
isLoadingMore,
onLoadMore,
+ runAutomaticLoad,
]);
const railJumpSeqRef = useRef(0);
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/useAutomaticHistoryLoadBudget.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/useAutomaticHistoryLoadBudget.test.tsx
new file mode 100644
index 0000000000..710f40fd17
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/__tests__/useAutomaticHistoryLoadBudget.test.tsx
@@ -0,0 +1,139 @@
+// @vitest-environment jsdom
+
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ clearSessionScroll,
+ markSessionAutomaticHistoryLoadCompleted,
+ resetSessionAutomaticHistoryLoadCompletion,
+} from '@/lib/sessionScrollStore';
+import { useAutomaticHistoryLoadBudget } from '../useAutomaticHistoryLoadBudget';
+
+const SESSION_ID = 'worker-mounted-budget';
+const LOADED_WINDOW = {
+ historyLoaded: true,
+ messageCount: 10,
+ firstMessageClientId: 'oldest-a',
+};
+
+afterEach(() => clearSessionScroll(SESSION_ID));
+
+describe('useAutomaticHistoryLoadBudget', () => {
+ it('resets both mounted budgets when the completed window is invalidated', () => {
+ markSessionAutomaticHistoryLoadCompleted(SESSION_ID);
+ const view = renderHook(() => useAutomaticHistoryLoadBudget(SESSION_ID, 5, 3, LOADED_WINDOW));
+
+ expect(view.result.current.viewportAttemptsRef.current).toBe(5);
+ expect(view.result.current.navRailRoundsRef.current).toBe(3);
+
+ act(() => {
+ resetSessionAutomaticHistoryLoadCompletion(SESSION_ID);
+ view.rerender();
+ });
+
+ expect(view.result.current.viewportAttemptsRef.current).toBe(0);
+ expect(view.result.current.navRailRoundsRef.current).toBe(0);
+ });
+
+ it('does not reset failed-load budgets while completion remains false', () => {
+ const view = renderHook(() => useAutomaticHistoryLoadBudget(SESSION_ID, 5, 3, LOADED_WINDOW));
+ view.result.current.viewportAttemptsRef.current = 5;
+ view.result.current.navRailRoundsRef.current = 3;
+
+ act(() => view.rerender());
+
+ expect(view.result.current.viewportAttemptsRef.current).toBe(5);
+ expect(view.result.current.navRailRoundsRef.current).toBe(3);
+ });
+
+ it('resets exhausted failed-load budgets when the mounted window reloads', () => {
+ const view = renderHook(
+ ({ historyLoaded }) =>
+ useAutomaticHistoryLoadBudget(SESSION_ID, 5, 3, {
+ ...LOADED_WINDOW,
+ historyLoaded,
+ }),
+ { initialProps: { historyLoaded: true } },
+ );
+ view.result.current.viewportAttemptsRef.current = 5;
+ view.result.current.navRailRoundsRef.current = 3;
+
+ act(() => view.rerender({ historyLoaded: false }));
+
+ expect(view.result.current.viewportAttemptsRef.current).toBe(0);
+ expect(view.result.current.navRailRoundsRef.current).toBe(0);
+ });
+
+ it('resets exhausted budgets when reconciliation replaces the mounted window head', () => {
+ const view = renderHook(
+ ({ firstMessageClientId }) =>
+ useAutomaticHistoryLoadBudget(SESSION_ID, 5, 3, {
+ ...LOADED_WINDOW,
+ firstMessageClientId,
+ }),
+ { initialProps: { firstMessageClientId: 'oldest-a' } },
+ );
+ view.result.current.viewportAttemptsRef.current = 5;
+ view.result.current.navRailRoundsRef.current = 3;
+
+ act(() => view.rerender({ firstMessageClientId: 'oldest-rebuilt' }));
+
+ expect(view.result.current.viewportAttemptsRef.current).toBe(0);
+ expect(view.result.current.navRailRoundsRef.current).toBe(0);
+ });
+
+ it('does not mistake an in-flight automatic prepend for a window rebuild', async () => {
+ const view = renderHook(
+ ({ firstMessageClientId }) =>
+ useAutomaticHistoryLoadBudget(SESSION_ID, 5, 3, {
+ ...LOADED_WINDOW,
+ firstMessageClientId,
+ }),
+ { initialProps: { firstMessageClientId: 'oldest-a' } },
+ );
+ view.result.current.viewportAttemptsRef.current = 4;
+ view.result.current.navRailRoundsRef.current = 2;
+ let finishLoad!: (advanced: boolean) => void;
+ const load = () =>
+ new Promise<boolean>((resolve) => {
+ finishLoad = resolve;
+ });
+
+ const pending = view.result.current.runAutomaticLoad(load);
+ act(() => view.rerender({ firstMessageClientId: 'older-page' }));
+
+ expect(view.result.current.viewportAttemptsRef.current).toBe(4);
+ expect(view.result.current.navRailRoundsRef.current).toBe(2);
+
+ finishLoad(true);
+ await pending;
+ });
+
+ it('resets budgets after an in-flight automatic load is invalidated by a replacement', async () => {
+ const view = renderHook(
+ ({ firstMessageClientId }) =>
+ useAutomaticHistoryLoadBudget(SESSION_ID, 5, 3, {
+ ...LOADED_WINDOW,
+ firstMessageClientId,
+ }),
+ { initialProps: { firstMessageClientId: 'oldest-a' } },
+ );
+ view.result.current.viewportAttemptsRef.current = 5;
+ view.result.current.navRailRoundsRef.current = 3;
+ let finishLoad!: (advanced: boolean) => void;
+ const load = () =>
+ new Promise<boolean>((resolve) => {
+ finishLoad = resolve;
+ });
+
+ const pending = view.result.current.runAutomaticLoad(load);
+ act(() => view.rerender({ firstMessageClientId: 'authoritative-head' }));
+
+ finishLoad(false);
+ await pending;
+
+ expect(view.result.current.viewportAttemptsRef.current).toBe(0);
+ expect(view.result.current.navRailRoundsRef.current).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts b/apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts
new file mode 100644
index 0000000000..a25b8f8faa
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts
@@ -0,0 +1,85 @@
+import { useCallback, useLayoutEffect, useRef } from 'react';
+
+import { restoreSessionAutomaticHistoryLoadAttempts } from '@/lib/sessionScrollStore';
+
+export function useAutomaticHistoryLoadBudget(
+ sessionId: string | undefined,
+ viewportMaxAttempts: number,
+ navRailMaxRounds: number,
+ windowSnapshot: {
+ historyLoaded: boolean;
+ messageCount: number;
+ firstMessageClientId: string | null;
+ },
+) {
+ const viewportAttemptsRef = useRef(
+ restoreSessionAutomaticHistoryLoadAttempts(sessionId, viewportMaxAttempts),
+ );
+ const navRailRoundsRef = useRef(
+ restoreSessionAutomaticHistoryLoadAttempts(sessionId, navRailMaxRounds),
+ );
+ const completionSeenRef = useRef(restoreSessionAutomaticHistoryLoadAttempts(sessionId, 1) > 0);
+ const previousWindowSnapshotRef = useRef(windowSnapshot);
+ const automaticLoadInFlightCountRef = useRef(0);
+ const windowInvalidatedDuringAutomaticLoadRef = useRef(false);
+
+ const resetMountedBudgets = useCallback(() => {
+ viewportAttemptsRef.current = 0;
+ navRailRoundsRef.current = 0;
+ }, []);
+
+ // 消费当前窗口失效的既有响应式事实。只看 completed 的 true → false 不够:预算也可能
+ // 因连续失败耗尽,那时 marker 始终是 false。反过来,不能在普通 false → false rerender
+ // 上归零,否则会绕过两套退化上限。
+ useLayoutEffect(() => {
+ const completedNow = restoreSessionAutomaticHistoryLoadAttempts(sessionId, 1) > 0;
+ const previous = previousWindowSnapshotRef.current;
+ const reloadStarted = previous.historyLoaded && !windowSnapshot.historyLoaded;
+ const visibleWindowWasTruncated = windowSnapshot.messageCount < previous.messageCount;
+ const windowHeadChanged =
+ previous.firstMessageClientId !== null &&
+ windowSnapshot.firstMessageClientId !== previous.firstMessageClientId;
+ const invalidatedWindowShape =
+ !completedNow && (visibleWindowWasTruncated || windowHeadChanged);
+
+ if ((completionSeenRef.current && !completedNow) || reloadStarted) {
+ resetMountedBudgets();
+ } else if (invalidatedWindowShape) {
+ if (visibleWindowWasTruncated || automaticLoadInFlightCountRef.current === 0) {
+ resetMountedBudgets();
+ } else {
+ // 正常自动 prepend 与同大小的权威换窗都表现成“首行变化”。请求返回前无法区分,
+ // 先记下边沿;成功推进说明是 prepend,false 则说明请求被 epoch 作废,届时复位。
+ windowInvalidatedDuringAutomaticLoadRef.current = true;
+ }
+ }
+ completionSeenRef.current = completedNow;
+ previousWindowSnapshotRef.current = windowSnapshot;
+ });
+
+ const runAutomaticLoad = useCallback(
+ async (loadMore: (automatic?: boolean) => Promise<boolean>): Promise<boolean> => {
+ automaticLoadInFlightCountRef.current += 1;
+ try {
+ const advanced = await loadMore(true);
+ if (advanced) {
+ completionSeenRef.current = true;
+ windowInvalidatedDuringAutomaticLoadRef.current = false;
+ }
+ return advanced;
+ } finally {
+ automaticLoadInFlightCountRef.current -= 1;
+ if (
+ automaticLoadInFlightCountRef.current === 0 &&
+ windowInvalidatedDuringAutomaticLoadRef.current
+ ) {
+ windowInvalidatedDuringAutomaticLoadRef.current = false;
+ resetMountedBudgets();
+ }
+ }
+ },
+ [resetMountedBudgets],
+ );
+
+ return { viewportAttemptsRef, navRailRoundsRef, runAutomaticLoad };
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 92f27565ac..4a5f2459d0 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -3686,6 +3686,7 @@ export function CCAgentSessionView({
// a TS-narrowing fallback, never expected to fire at runtime.
workingDir={session?.workingDir ?? ''}
messages={messages}
+ historyLoaded={historyLoaded}
taskUpdates={taskUpdates}
isSessionStreaming={isStreaming}
continuationTurnClientId={continuationTurnClientId}
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 816d063fe4..eab461f07e 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -2064,6 +2064,8 @@ function cancelRemoteOptimisticSendsForRemoteClear(
clearBoundaryMs: number,
opts: { historicalHydration?: boolean } = {},
): void {
+ // 历史 hydration 也会走到这里,但它只清理旧 optimistic 状态,并没有替换当前消息窗口;
+ // 因此只作废在途请求,不能把已经完成的自动补载误判成新窗口。
bumpMessagesEpoch(sessionId);
bumpInteractionReconcileEpoch(sessionId);
invalidateInputProjectionRequests(sessionId);
@@ -3172,13 +3174,12 @@ function _purgeSession(sessionId: string): void {
clearIssueConfirmDraftsForSession(sessionId);
// 代际递增(bump 而非 delete,原因见 _messagesEpoch 注释):作废 in-flight 翻页,
// 避免其提交把旧窗口 merge 进 purge 后重建的空 slice。
- bumpMessagesEpoch(sessionId);
+ invalidateMessageHistoryWindow(sessionId);
invalidateInputProjectionRequests(sessionId);
// 删除 / 归档 / LRU 都是 renderer owner 边界。作废仍在附件物化或 composer
// 交接中的迟到 continuation,且不写入 /clear 的历史时间边界。
bumpRendererClearGeneration(sessionId);
cancelRemoteOptimisticSendsForSessionPurge(sessionId);
- resetSessionAutomaticHistoryLoadCompletion(sessionId);
sessions.delete(sessionId);
localSentUserMessageIds.delete(sessionId);
pendingLocalRetryIntents.delete(sessionId);
@@ -3391,8 +3392,7 @@ function _demoteIdleSessions(): void {
// 等于代际重置,必须 bump epoch 作废 in-flight 的翻页 / 跳转补齐,并由本次重置释放
// 分页锁。漏 bump 的后果是 in-flight 那一页按 demote 前的游标提交,把一段脱离上下文
// 的旧历史 merge 进空切片(或重开后的新切片),最近的消息反而缺席(#676 review)。
- bumpMessagesEpoch(sessionId);
- resetSessionAutomaticHistoryLoadCompletion(sessionId);
+ invalidateMessageHistoryWindow(sessionId);
setState(sessionId, (s) => ({
...s,
messages: [],
@@ -8997,6 +8997,17 @@ function bumpMessagesEpoch(sessionId: string): void {
_messagesEpoch.set(sessionId, (_messagesEpoch.get(sessionId) ?? 0) + 1);
}
+/**
+ * 作废当前逻辑历史窗口:既让在途分页不能提交回旧窗口,也让下一次挂载重新获得自动
+ * 补载预算。在真正替换当前窗口的路径中,纯内存 trim 是唯一例外——它正是要保留
+ * “这个窗口已经自动补过”的事实,避免切回会话后重复拉同一段历史,所以仍只调用
+ * bumpMessagesEpoch。
+ */
+function invalidateMessageHistoryWindow(sessionId: string): void {
+ bumpMessagesEpoch(sessionId);
+ resetSessionAutomaticHistoryLoadCompletion(sessionId);
+}
+
function isCurrentHistoryFetch(
sessionId: string,
token: number,
@@ -9608,9 +9619,8 @@ function ensureInitialMessages(sessionId: string): void {
*/
function reloadMessages(sessionId: string, opts?: { allowCacheHydrate?: boolean }): void {
discardPendingTextDelta(sessionId);
- resetSessionAutomaticHistoryLoadCompletion(sessionId);
// 代际递增:作废 in-flight 的 loadOlderMessages 追页窗口(见 _messagesEpoch 注释)。
- bumpMessagesEpoch(sessionId);
+ invalidateMessageHistoryWindow(sessionId);
invalidateHistoryFetch(sessionId);
// Drop the in-flight guard so ensureInitialMessages can run again.
_historyFetchInFlight.delete(sessionId);
@@ -9681,7 +9691,7 @@ function removeMessagesByClientIds(
invalidateRemoteMessageCache(sessionId);
discardPendingTextDelta(sessionId);
// 作废删除提交前发起的历史分页,避免旧页响应把已经清除的行重新 merge 回来。
- if (options.invalidateHistory !== false) bumpMessagesEpoch(sessionId);
+ if (options.invalidateHistory !== false) invalidateMessageHistoryWindow(sessionId);
setState(sessionId, (s) => {
const removedMessages = s.messages.filter((message) => deletedClientIds.has(message.clientId));
const messages = s.messages.filter((message) => !deletedClientIds.has(message.clientId));
@@ -9751,7 +9761,7 @@ function dropMessagesFromClientId(sessionId: string, clientId: string): void {
// 路径,同样必须作废 in-flight 的分页 / 跳转补齐。漏 bump 的后果是它们把 rewind
// 刚软删掉的行当作有效响应 merge 回渲染层(#676 review)。clientId 不在列表时
// 也照 bump:代价只是让 in-flight 分页重新取一次,比漏作废安全。
- bumpMessagesEpoch(sessionId);
+ invalidateMessageHistoryWindow(sessionId);
setState(sessionId, (s) => {
const idx = s.messages.findIndex((m) => m.clientId === clientId);
// 目标已经不在切片里(reload / 重开把它清掉了)也必须放锁:上面 bump 过 epoch,
@@ -10004,12 +10014,10 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Prom
//
// historyWindowHasIsland 按"是否保留了晚到的本地行"决定清不清,见下方 lateArrivals。
const isContiguous = reachedKnownWindow;
- // 代际 bump 与分页锁释放都**只在重建真正提交后**才做。原先在 setState 之前先 bump:
- // 一旦更新器里的 isStreaming 守卫(分页期间开始了新 turn)否掉这次重建,窗口没换、
- // 却已经作废掉一个无关的 in-flight 跳转 / 翻页、还替它放了锁;更晚启动的对账也会
- // 因为这个白 bump 被当成陈旧丢掉(#676 review codex P1)。setState 是同步的,
- // 把 bump 挪到它之后不引入任何可观察的中间态。
- let didRebuild = false;
+ // 代际 bump 与分页锁释放都**只在重建确定提交时**做。不能放在 setState 外面提前 bump:
+ // 更新器里的 isStreaming 守卫可能否掉重建。也不能等 setState 通知完成后才 bump:
+ // MessageStream 要在同一次通知里观察到窗口已失效、重置已挂载的自动补载预算。
+ // updater 同步执行且下面所有早退都已经结束,在 return 新 state 前失效正好满足两边。
setState(sessionId, (s) => {
// promise 期间可能已开始新 turn(streaming)→ 放弃本次合并,turn 结束会再触发。
// force 时(stall 看门狗已确认被控端 not-running)放行:此处 isStreaming 是卡死残留。
@@ -10043,7 +10051,7 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Prom
// 无缺失且无权威字段变化 → 不换引用(视同已应用)。
if (messages === s.messages) return s;
if (isContiguous) return { ...s, messages };
- didRebuild = true;
+ invalidateMessageHistoryWindow(sessionId);
const oldestRow = oldestMessageRow(collected, 'newest-first');
// 保留下来的晚到行是否**可证明**与新窗口连续:
// - 比权威窗口最新一行还新 → 就是分页期间的 live push,接在尾部,连续;
@@ -10101,10 +10109,6 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Prom
historyWindowHasIsland: hasDetachedArrival,
};
});
- if (didRebuild) {
- resetSessionAutomaticHistoryLoadCompletion(sessionId);
- bumpMessagesEpoch(sessionId);
- }
} finally {
// 消息路径的早返 / 异常都要等交互重建落定;交互失败会让 run reject(替换原结果),
// 语义正确:本代不完成。
@@ -12577,8 +12581,7 @@ async function clearSessionAfterGuardImpl(sessionId: string, clearedAt: string):
// Invalidate old history/projection operations before the first network await.
// 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);
+ invalidateMessageHistoryWindow(sessionId);
bumpInteractionReconcileEpoch(sessionId);
supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });
if (remoteDeviceId) {