From 0ce10533d364607f1e75bb061577272e4ba80a11 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:08:48 +0800 Subject: [PATCH] fix(webui): preserve session caches during history revalidation (#6636) --- webui/src/hooks/useNanobotStream.ts | 8 +-- webui/src/lib/memory-lru-cache.ts | 55 ++++++++++++-------- webui/src/lib/thread-message-cache.ts | 2 +- webui/src/lib/webui-thread-cache.ts | 2 +- webui/src/tests/memory-lru-cache.test.ts | 14 +++-- webui/src/tests/thread-message-cache.test.ts | 24 ++++++--- webui/src/tests/thread-shell.test.tsx | 6 +-- 7 files changed, 68 insertions(+), 43 deletions(-) diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index 2e3fb60ed..3bfaed96e 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -520,7 +520,6 @@ export function useNanobotStream( pending.owner.finishRead(pending.read); if (transcriptRef.current === pending.owner) publishHistory(); }, [publishHistory]); - const latestReadOwnerRef = useRef(); const detailRequestsRef = useRef(new Map>()); const reconcileCanonical = useCallback((generation: number, canonical: ReturnType, accepted: boolean) => { if (!chatId) return; @@ -542,9 +541,6 @@ export function useNanobotStream( const owner = transcriptRef.current; const controller = new AbortController(); const generation = chatId ? client.getRunGeneration(chatId) : 0; - const read = owner.begin(latestReadOwnerRef.current === owner ? "latest" : "initial"); - latestReadOwnerRef.current = owner; - publishHistory(); let disposed = false; let superseded = false; let publishing = false; @@ -573,6 +569,10 @@ export function useNanobotStream( }; const cached = webuiThreadCache.get(historyKey); if (cached && owner.paging.version === 0) install(cached, false, true); + // A restored projection or cached seed already has history. Revalidate it + // as latest so a safe disjoint window can replace its durable baseline. + const read = owner.begin(owner.paging.version > 0 ? "latest" : "initial"); + publishHistory(); const unsubscribe = webuiThreadCache.subscribe(historyKey, (body) => { if (publishing) return; superseded = true; diff --git a/webui/src/lib/memory-lru-cache.ts b/webui/src/lib/memory-lru-cache.ts index 81086a84b..9d146f31b 100644 --- a/webui/src/lib/memory-lru-cache.ts +++ b/webui/src/lib/memory-lru-cache.ts @@ -1,8 +1,6 @@ -/** Byte- and entry-bounded in-memory LRU for WebUI state. */ +/** Byte- and entry-bounded LRU; non-evictable working state is outside that budget. */ export class MemoryLruCache { private entries = new Map(); - private sizes = new WeakMap(); - private bytes = 0; constructor( private maxBytes: number, @@ -24,40 +22,51 @@ export class MemoryLruCache { } set(key: string, value: T): void { - this.delete(key); const bytes = this.estimate(value); + // A rejected replacement must not leave a stale snapshot under this key. + this.delete(key); + if (this.canEvict(key) && (bytes > this.maxBytes || this.maxEntries < 1)) return; this.entries.set(key, { value, bytes }); - this.bytes += bytes; - for (const candidate of this.entries.keys()) { - if (this.bytes <= this.maxBytes && this.entries.size <= this.maxEntries) break; - if (this.canEvict(candidate)) this.delete(candidate); + + let reclaimableBytes = 0; + let reclaimableEntries = 0; + for (const [candidate, entry] of this.entries) { + if (!this.canEvict(candidate)) continue; + reclaimableBytes += entry.bytes; + reclaimableEntries++; + } + for (const [candidate, entry] of this.entries) { + if (reclaimableBytes <= this.maxBytes && reclaimableEntries <= this.maxEntries) break; + if (!this.canEvict(candidate)) continue; + this.delete(candidate); + reclaimableBytes -= entry.bytes; + reclaimableEntries--; } } delete(key: string): void { - const entry = this.entries.get(key); - if (entry) this.bytes -= entry.bytes; this.entries.delete(key); } clear(): void { this.entries.clear(); - this.sizes = new WeakMap(); - this.bytes = 0; } - private estimate(value: unknown): number { + private estimate(value: unknown, seen = new WeakSet()): number { if (typeof value === "string") return value.length * 2; if (!value || typeof value !== "object") return 8; - const cached = this.sizes.get(value); - if (cached !== undefined) return cached; - const values = value instanceof Map ? Array.from(value.entries()) - : value instanceof Set ? Array.from(value) : Object.values(value); - const size = 32 + values.reduce( - (total, item) => total + this.estimate(item), - 0, - ); - this.sizes.set(value, size); - return size; + if (seen.has(value)) return 0; + seen.add(value); + let bytes = 32; + if (value instanceof Map) { + for (const [key, item] of value) { + bytes += this.estimate(key, seen) + this.estimate(item, seen); + } + } else { + for (const item of value instanceof Set ? value : Object.values(value)) { + bytes += this.estimate(item, seen); + } + } + return bytes; } } diff --git a/webui/src/lib/thread-message-cache.ts b/webui/src/lib/thread-message-cache.ts index a39572d66..b95a125bd 100644 --- a/webui/src/lib/thread-message-cache.ts +++ b/webui/src/lib/thread-message-cache.ts @@ -13,7 +13,7 @@ export class ThreadMessageCache extends MemoryLruCache constructor( isPinned: (key: string) => boolean, - maxBytes = 16 * 1024 * 1024, + maxBytes = 32 * 1024 * 1024, maxEntries = 12, ) { super(maxBytes, maxEntries, (key) => !isPinned(key)); diff --git a/webui/src/lib/webui-thread-cache.ts b/webui/src/lib/webui-thread-cache.ts index 2e4a5e631..42033346c 100644 --- a/webui/src/lib/webui-thread-cache.ts +++ b/webui/src/lib/webui-thread-cache.ts @@ -60,7 +60,7 @@ export class WebuiThreadCache extends MemoryLruCache void>>(); constructor( - maxBytes = 16 * 1024 * 1024, + maxBytes = 32 * 1024 * 1024, maxEntries = 12, ) { super(maxBytes, maxEntries); diff --git a/webui/src/tests/memory-lru-cache.test.ts b/webui/src/tests/memory-lru-cache.test.ts index 10b8c27b6..8ae6ea89d 100644 --- a/webui/src/tests/memory-lru-cache.test.ts +++ b/webui/src/tests/memory-lru-cache.test.ts @@ -6,15 +6,19 @@ it.each([ { collection: "Map keys", small: new Map([["turn", "source"]]), large: new Map([["x".repeat(64), "source"]]) }, { collection: "Map values", small: new Map([["turn", "source"]]), large: new Map([["turn", "x".repeat(64)]]) }, { collection: "Set members", small: new Set(["turn"]), large: new Set(["x".repeat(64)]) }, -])("counts nested $collection toward the byte budget", ({ small, large }) => { - const cache = new MemoryLruCache<{ members: typeof large }>(160, 2); - const snapshot = { members: small }; +])("counts shared nested $collection once and re-estimates changed snapshots", ({ small, large }) => { + const cache = new MemoryLruCache<{ members: typeof large }>(110, 2); + const snapshot = { members: small, alias: small }; cache.set("small", snapshot); expect(cache.get("small")).toBe(snapshot); cache.set("large", { members: large }); expect(cache.get("large")).toBeUndefined(); - - cache.set("small", snapshot); expect(cache.get("small")).toBe(snapshot); + + // A saved transcript can share mutable collections with its next snapshot. + if (small instanceof Map) small.set("turn", "x".repeat(64)); + else small.add("x".repeat(64)); + cache.set("small", snapshot); + expect(cache.get("small")).toBeUndefined(); }); diff --git a/webui/src/tests/thread-message-cache.test.ts b/webui/src/tests/thread-message-cache.test.ts index de03952c6..e31260628 100644 --- a/webui/src/tests/thread-message-cache.test.ts +++ b/webui/src/tests/thread-message-cache.test.ts @@ -15,13 +15,25 @@ it("keeps recently visited chats within the entry budget", () => { .toEqual([rows, undefined, rows]); }); -it("bounds large replay snapshots while retaining temporary chats", () => { +it("bounds large replay snapshots without charging temporary chats to the reusable budget", () => { const cache = new ThreadMessageCache((key) => key === "temporary", 4096, 2); - cache.set("temporary", snapshot); - cache.set("large", new ThreadTranscript([{ ...rows[0], content: "x".repeat(4096) }]).save()); + cache.set("ordinary-a", snapshot); + cache.set("ordinary-b", snapshot); + const large = new ThreadTranscript([{ ...rows[0], content: "x".repeat(4096) }]).save(); + cache.set("large", large); expect(cache.get("large")).toBeUndefined(); - expect(cache.get("temporary")?.projection.messages).toBe(rows); - cache.delete("temporary"); + expect(cache.peek("ordinary-a")).toBe(snapshot); + expect(cache.peek("ordinary-b")).toBe(snapshot); + + cache.set("temporary", large); + expect(cache.get("temporary")).toBe(large); + expect(cache.get("ordinary-a")).toBe(snapshot); + expect(cache.peek("ordinary-b")).toBe(snapshot); + cache.set("small", snapshot); - expect(cache.get("small")?.projection.messages).toBe(rows); + expect(cache.peek("ordinary-a")).toBe(snapshot); + expect(cache.peek("ordinary-b")).toBeUndefined(); + expect(cache.get("small")).toBe(snapshot); + cache.delete("temporary"); + expect(cache.get("small")).toBe(snapshot); }); diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index 3f4b58892..0d498bd6a 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -3263,7 +3263,7 @@ describe("ThreadShell", () => { ); }); - it("recovers an uncommitted reset lineage on the next canonical hydrate", async () => { + it("adopts a disjoint latest window immediately when returning to a cached session", async () => { const client = makeClient(); let chatACalls = 0; vi.stubGlobal( @@ -3309,8 +3309,8 @@ describe("ThreadShell", () => { rerender(view("lineage-chat-a")); await waitFor(() => expect(chatACalls).toBe(2)); - expect(screen.getByText("committed old lineage")).toBeInTheDocument(); - expect(screen.queryByText("disjoint new lineage")).not.toBeInTheDocument(); + expect(await screen.findByText("disjoint new lineage")).toBeInTheDocument(); + expect(screen.queryByText("committed old lineage")).not.toBeInTheDocument(); act(() => client._emitSessionUpdate("lineage-chat-a", "thread"));