fix(web): preserve the visible chat window during rewind (#1766)

* fix(web): preserve chat window during rewind

* fix(web): scope rewind invalidation preservation

* fix(web): clear unknown rewind boundaries

* fix(web): deduplicate rewind invalidations

* fix(web): retain rewind dedupe history
This commit is contained in:
Ananovo
2026-09-09 09:23:31 +08:00
committed by GitHub
parent fa1caf7d71
commit 17ee052d9a
9 changed files with 208 additions and 12 deletions
+92
View File
@@ -11,9 +11,11 @@ import {
getMessageWindowState,
getQueuedReconcileCandidateLocalIds,
ingestIncomingMessages,
invalidateMessageWindow,
markMessagesConsumed,
reconcileQueuedLocalIds,
removeOptimisticMessage,
rewindMessageWindow,
setMessageViewMode,
syncTailMessages,
updateMessageStatus,
@@ -247,6 +249,96 @@ afterEach(() => {
})
describe('message tail synchronization', () => {
it('removes the rewound suffix immediately and applies duplicate invalidations once', async () => {
const id = sessionId('rewind-suffix')
const prefix = makeAgentMessage({ id: 'prefix', seq: 1, at: 1_000 })
const target = makeUserMessage({
id: 'target',
seq: 2,
localId: 'target-local-id',
createdAt: 2_000,
invokedAt: 2_000
})
const suffix = makeAgentMessage({ id: 'suffix', seq: 3, at: 3_000 })
const getMessages = vi.fn(async () => latestResponse([prefix, target, suffix], { epoch: 1 }))
await syncTailMessages(createApi(getMessages), id)
rewindMessageWindow(id, 'target-local-id')
rewindMessageWindow(id, 'target-local-id')
expect(getMessageWindowState(id).messages.map((message) => message.id)).toEqual(['prefix'])
expect(getMessageWindowState(id).isSyncingTail).toBe(true)
})
it('clears the window when the rewind boundary is outside the loaded page', async () => {
const id = sessionId('rewind-boundary-not-loaded')
const current = makeAgentMessage({ id: 'current', seq: 40, at: 40_000 })
const getMessages = vi.fn(async () => latestResponse([current], { epoch: 1 }))
await syncTailMessages(createApi(getMessages), id)
rewindMessageWindow(id, 'boundary-not-loaded')
expect(getMessageWindowState(id).messages).toEqual([])
})
it('deduplicates delayed rewind events across consecutive boundaries', async () => {
const id = sessionId('rewind-delayed-event')
const prefix = makeAgentMessage({ id: 'prefix', seq: 1, at: 1_000 })
const firstBoundary = makeUserMessage({
id: 'first-boundary',
seq: 2,
localId: 'first-boundary-local-id',
createdAt: 2_000,
invokedAt: 2_000
})
const secondBoundary = makeUserMessage({
id: 'second-boundary',
seq: 3,
localId: 'second-boundary-local-id',
createdAt: 3_000,
invokedAt: 3_000
})
const suffix = makeAgentMessage({ id: 'suffix', seq: 4, at: 4_000 })
const getMessages = vi.fn(async () => latestResponse(
[prefix, firstBoundary, secondBoundary, suffix],
{ epoch: 1 }
))
await syncTailMessages(createApi(getMessages), id)
rewindMessageWindow(id, 'second-boundary-local-id')
rewindMessageWindow(id, 'first-boundary-local-id')
rewindMessageWindow(id, 'second-boundary-local-id')
expect(getMessageWindowState(id).messages.map((message) => message.id)).toEqual(['prefix'])
})
it('retains the current window while a latest reset is in flight', async () => {
const id = sessionId('invalidation-preserves-window')
const current = makeAgentMessage({ id: 'current', seq: 10, at: 10_000 })
const latest = makeAgentMessage({ id: 'latest', seq: 20, at: 20_000 })
const response = deferred<MessagesResponse>()
const getMessages = vi.fn()
.mockResolvedValueOnce(latestResponse([current], { epoch: 1 }))
.mockImplementationOnce(async () => await response.promise)
const api = createApi(getMessages)
await syncTailMessages(api, id)
invalidateMessageWindow(id)
expect(getMessageWindowState(id).messages.map((message) => message.id)).toEqual(['current'])
expect(getMessageWindowState(id).isSyncingTail).toBe(true)
const syncing = syncTailMessages(api, id)
await vi.waitFor(() => expect(getMessages).toHaveBeenCalledTimes(2))
expect(getMessages.mock.calls[1]?.[1]).toEqual({ limit: 200 })
response.resolve(latestResponse([latest], { epoch: 2 }))
await syncing
expect(getMessageWindowState(id).messages.map((message) => message.id)).toEqual(['latest'])
expect(getMessageWindowState(id).isSyncingTail).toBe(false)
})
it('renders a persisted window immediately, then requests the latest tail on re-entry', async () => {
const id = sessionId('reentry')
const cached = makeAgentMessage({ id: 'cached', seq: 40, at: 40_000 })
+73 -1
View File
@@ -80,6 +80,7 @@ type TailSyncController = {
const states = new Map<string, InternalState>()
const listeners = new Map<string, Set<() => void>>()
const tailSyncControllers = new Map<string, TailSyncController>()
const appliedRewindLocalIds = new Map<string, Set<string>>()
const NOTIFY_THROTTLE_MS = 150
const PERSIST_THROTTLE_MS = 200
@@ -312,7 +313,14 @@ function notifyImmediate(sessionId: string): void {
function setState(sessionId: string, next: InternalState, immediate = false): void {
states.set(sessionId, next)
schedulePersist(sessionId)
// A latest-reset state still contains the previous server snapshot. Do not
// persist that stale window while the authoritative replacement is in
// flight; a reload during the reset must not resurrect removed messages.
if (next.requiresLatestReset) {
pendingPersistSessionIds.delete(sessionId)
} else {
schedulePersist(sessionId)
}
if (immediate) {
notifyImmediate(sessionId)
} else {
@@ -1091,6 +1099,70 @@ export function clearMessageWindow(sessionId: string): void {
}, true)
}
function markMessageWindowForLatestReset(sessionId: string, messages: DecryptedMessage[]): void {
const previous = states.get(sessionId)
if (!previous) return
tailSyncControllers.delete(sessionId)
clearPersistedState(sessionId)
setState(sessionId, buildState(previous, {
messages,
epoch: null,
oldestPositionAt: null,
oldestPositionSeq: null,
newestPositionAt: null,
newestPositionSeq: null,
requiresLatestReset: true,
preferLatestOnActivation: false,
isSyncingTail: true,
isLoadingMore: false,
warning: null,
syncGeneration: previous.syncGeneration + 1,
olderGeneration: previous.olderGeneration + 1
}), true)
}
/**
* Mark the current window stale without exposing an empty transcript while a
* latest snapshot is fetched. The next tail sync sees `requiresLatestReset`
* and replaces server rows atomically with the authoritative response.
*/
export function invalidateMessageWindow(sessionId: string): void {
const previous = states.get(sessionId)
if (!previous) return
markMessageWindowForLatestReset(sessionId, previous.messages)
}
/**
* Apply the known local effect of a successful Rewind before the server
* snapshot arrives. Rewind removes the boundary message and every later row;
* retaining the earlier prefix keeps the chat usable and lets the current
* bottom position clamp directly to the new tail.
*/
export function rewindMessageWindow(sessionId: string, messageLocalId: string): void {
const previous = states.get(sessionId)
if (!previous) return
const applied = appliedRewindLocalIds.get(sessionId) ?? new Set<string>()
if (applied.has(messageLocalId)) return
applied.add(messageLocalId)
appliedRewindLocalIds.set(sessionId, applied)
const boundaryIndex = previous.messages.findIndex((message) => message.localId === messageLocalId)
if (boundaryIndex < 0) {
// The boundary may be outside the current latest window. Without a
// local boundary, retaining rows could show messages removed by the
// rewind until the authoritative tail sync completes.
clearMessageWindow(sessionId)
return
}
const messages = previous.messages.slice(0, boundaryIndex)
markMessageWindowForLatestReset(sessionId, messages)
}
export function seedMessageWindowFromSession(fromSessionId: string, toSessionId: string): void {
if (!fromSessionId || !toSessionId || fromSessionId === toSessionId) return
const source = getState(fromSessionId)