fix(webui): preserve session caches during history revalidation (#6636)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-12 16:08:48 +08:00
1 parent 1046a37be1
commit 0ce10533d3
7 files changed
+68 -43

No files matched your search

+4 -4
View File
@@ -520,7 +520,6 @@ export function useNanobotStream(
pending.owner.finishRead(pending.read); pending.owner.finishRead(pending.read);
if (transcriptRef.current === pending.owner) publishHistory(); if (transcriptRef.current === pending.owner) publishHistory();
}, [publishHistory]); }, [publishHistory]);
const latestReadOwnerRef = useRef<ThreadTranscript>();
const detailRequestsRef = useRef(new Map<string, Promise<{ ref: string; events: ThreadProjectionEvent[] } | null>>()); const detailRequestsRef = useRef(new Map<string, Promise<{ ref: string; events: ThreadProjectionEvent[] } | null>>());
const reconcileCanonical = useCallback((generation: number, canonical: ReturnType<typeof persistedCanonicalRunState>, accepted: boolean) => { const reconcileCanonical = useCallback((generation: number, canonical: ReturnType<typeof persistedCanonicalRunState>, accepted: boolean) => {
if (!chatId) return; if (!chatId) return;
@@ -542,9 +541,6 @@ export function useNanobotStream(
const owner = transcriptRef.current; const owner = transcriptRef.current;
const controller = new AbortController(); const controller = new AbortController();
const generation = chatId ? client.getRunGeneration(chatId) : 0; const generation = chatId ? client.getRunGeneration(chatId) : 0;
const read = owner.begin(latestReadOwnerRef.current === owner ? "latest" : "initial");
latestReadOwnerRef.current = owner;
publishHistory();
let disposed = false; let disposed = false;
let superseded = false; let superseded = false;
let publishing = false; let publishing = false;
@@ -573,6 +569,10 @@ export function useNanobotStream(
}; };
const cached = webuiThreadCache.get(historyKey); const cached = webuiThreadCache.get(historyKey);
if (cached && owner.paging.version === 0) install(cached, false, true); 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) => { const unsubscribe = webuiThreadCache.subscribe(historyKey, (body) => {
if (publishing) return; if (publishing) return;
superseded = true; superseded = true;
+32 -23
View File
@@ -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<T> { export class MemoryLruCache<T> {
private entries = new Map<string, { value: T; bytes: number }>(); private entries = new Map<string, { value: T; bytes: number }>();
private sizes = new WeakMap<object, number>();
private bytes = 0;
constructor( constructor(
private maxBytes: number, private maxBytes: number,
@@ -24,40 +22,51 @@ export class MemoryLruCache<T> {
} }
set(key: string, value: T): void { set(key: string, value: T): void {
this.delete(key);
const bytes = this.estimate(value); 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.entries.set(key, { value, bytes });
this.bytes += bytes;
for (const candidate of this.entries.keys()) { let reclaimableBytes = 0;
if (this.bytes <= this.maxBytes && this.entries.size <= this.maxEntries) break; let reclaimableEntries = 0;
if (this.canEvict(candidate)) this.delete(candidate); 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 { delete(key: string): void {
const entry = this.entries.get(key);
if (entry) this.bytes -= entry.bytes;
this.entries.delete(key); this.entries.delete(key);
} }
clear(): void { clear(): void {
this.entries.clear(); this.entries.clear();
this.sizes = new WeakMap<object, number>();
this.bytes = 0;
} }
private estimate(value: unknown): number { private estimate(value: unknown, seen = new WeakSet<object>()): number {
if (typeof value === "string") return value.length * 2; if (typeof value === "string") return value.length * 2;
if (!value || typeof value !== "object") return 8; if (!value || typeof value !== "object") return 8;
const cached = this.sizes.get(value); if (seen.has(value)) return 0;
if (cached !== undefined) return cached; seen.add(value);
const values = value instanceof Map ? Array.from(value.entries()) let bytes = 32;
: value instanceof Set ? Array.from(value) : Object.values(value); if (value instanceof Map) {
const size = 32 + values.reduce<number>( for (const [key, item] of value) {
(total, item) => total + this.estimate(item), bytes += this.estimate(key, seen) + this.estimate(item, seen);
0, }
); } else {
this.sizes.set(value, size); for (const item of value instanceof Set ? value : Object.values(value)) {
return size; bytes += this.estimate(item, seen);
}
}
return bytes;
} }
} }
+1 -1
View File
@@ -13,7 +13,7 @@ export class ThreadMessageCache extends MemoryLruCache<ThreadTranscriptSnapshot>
constructor( constructor(
isPinned: (key: string) => boolean, isPinned: (key: string) => boolean,
maxBytes = 16 * 1024 * 1024, maxBytes = 32 * 1024 * 1024,
maxEntries = 12, maxEntries = 12,
) { ) {
super(maxBytes, maxEntries, (key) => !isPinned(key)); super(maxBytes, maxEntries, (key) => !isPinned(key));
+1 -1
View File
@@ -60,7 +60,7 @@ export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload
private readonly listeners = new Map<string, Set<(body: WebuiThreadPersistedPayload) => void>>(); private readonly listeners = new Map<string, Set<(body: WebuiThreadPersistedPayload) => void>>();
constructor( constructor(
maxBytes = 16 * 1024 * 1024, maxBytes = 32 * 1024 * 1024,
maxEntries = 12, maxEntries = 12,
) { ) {
super(maxBytes, maxEntries); super(maxBytes, maxEntries);
+9 -5
View File
@@ -6,15 +6,19 @@ it.each([
{ collection: "Map keys", small: new Map([["turn", "source"]]), large: new Map([["x".repeat(64), "source"]]) }, { 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: "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)]) }, { collection: "Set members", small: new Set(["turn"]), large: new Set(["x".repeat(64)]) },
])("counts nested $collection toward the byte budget", ({ small, large }) => { ])("counts shared nested $collection once and re-estimates changed snapshots", ({ small, large }) => {
const cache = new MemoryLruCache<{ members: typeof large }>(160, 2); const cache = new MemoryLruCache<{ members: typeof large }>(110, 2);
const snapshot = { members: small }; const snapshot = { members: small, alias: small };
cache.set("small", snapshot); cache.set("small", snapshot);
expect(cache.get("small")).toBe(snapshot); expect(cache.get("small")).toBe(snapshot);
cache.set("large", { members: large }); cache.set("large", { members: large });
expect(cache.get("large")).toBeUndefined(); expect(cache.get("large")).toBeUndefined();
cache.set("small", snapshot);
expect(cache.get("small")).toBe(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();
}); });
+18 -6
View File
@@ -15,13 +15,25 @@ it("keeps recently visited chats within the entry budget", () => {
.toEqual([rows, undefined, rows]); .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); const cache = new ThreadMessageCache((key) => key === "temporary", 4096, 2);
cache.set("temporary", snapshot); cache.set("ordinary-a", snapshot);
cache.set("large", new ThreadTranscript([{ ...rows[0], content: "x".repeat(4096) }]).save()); 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("large")).toBeUndefined();
expect(cache.get("temporary")?.projection.messages).toBe(rows); expect(cache.peek("ordinary-a")).toBe(snapshot);
cache.delete("temporary"); 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); 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);
}); });
+3 -3
View File
@@ -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(); const client = makeClient();
let chatACalls = 0; let chatACalls = 0;
vi.stubGlobal( vi.stubGlobal(
@@ -3309,8 +3309,8 @@ describe("ThreadShell", () => {
rerender(view("lineage-chat-a")); rerender(view("lineage-chat-a"));
await waitFor(() => expect(chatACalls).toBe(2)); await waitFor(() => expect(chatACalls).toBe(2));
expect(screen.getByText("committed old lineage")).toBeInTheDocument(); expect(await screen.findByText("disjoint new lineage")).toBeInTheDocument();
expect(screen.queryByText("disjoint new lineage")).not.toBeInTheDocument(); expect(screen.queryByText("committed old lineage")).not.toBeInTheDocument();
act(() => client._emitSessionUpdate("lineage-chat-a", "thread")); act(() => client._emitSessionUpdate("lineage-chat-a", "thread"));