Merge pull request #2120 from herjarsa/fix/chat-anchor-save-race
fix(chat): save previous-session anchor in microtask with bail check
This commit is contained in:
@@ -996,7 +996,16 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
|||||||
// skeleton to render and reads messages which can be expensive.
|
// skeleton to render and reads messages which can be expensive.
|
||||||
if (previousSessionId && previousSessionId !== id) {
|
if (previousSessionId && previousSessionId !== id) {
|
||||||
const prevId = previousSessionId
|
const prevId = previousSessionId
|
||||||
setTimeout(() => {
|
const newId = id
|
||||||
|
// queueMicrotask runs after the current synchronous call stack (and
|
||||||
|
// before the next macrotask / setTimeout(0) / paint), so the previous
|
||||||
|
// session's anchor is saved before the new session's restoreSnapshot
|
||||||
|
// effect fires. This eliminates the race where save and restore
|
||||||
|
// interleave against the same viewport store entry.
|
||||||
|
queueMicrotask(() => {
|
||||||
|
// Bail if the user already switched again — save is now stale.
|
||||||
|
const current = get().currentSessionId
|
||||||
|
if (current !== newId) return
|
||||||
const memState = getViewportSessionMemory(prevId)
|
const memState = getViewportSessionMemory(prevId)
|
||||||
if (!memState?.isStreaming) {
|
if (!memState?.isStreaming) {
|
||||||
const prevMessages = getSyncMessages(prevId)
|
const prevMessages = getSyncMessages(prevId)
|
||||||
@@ -1004,7 +1013,7 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
|||||||
useViewportStore.getState().updateViewportAnchor(prevId, prevMessages.length - 1)
|
useViewportStore.getState().updateViewportAnchor(prevId, prevMessages.length - 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, 0)
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mark session viewed in notification store + update active session ref
|
// Mark session viewed in notification store + update active session ref
|
||||||
|
|||||||
Reference in New Issue
Block a user