fix(webui): cache and defer thread history

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-12 17:09:51 +08:00
1 parent 7ba60c2ef0
commit a490cd629b
30 files changed
+1306 -145

No files matched your search

+24 -1
View File
@@ -41,6 +41,7 @@ import type {
WebSearchSettingsUpdate,
WorkspacesPayload,
WebuiThreadPersistedPayload,
WebuiThreadTraceDetailPayload,
WorkspaceScopePayload,
} from "./types";
import { fetchWithTimeout } from "./http";
@@ -226,6 +227,8 @@ export interface FetchWebuiThreadOptions {
direction?: "latest";
before?: string | null;
signal?: AbortSignal;
revision?: string;
cached?: WebuiThreadPersistedPayload;
}
export async function fetchWebuiThread(
@@ -243,17 +246,37 @@ export async function fetchWebuiThread(
const query = params.toString();
const suffix = query ? `?${query}` : "";
const url = `${resolvedBase}/api/sessions/${encodeURIComponent(key)}/webui-thread${suffix}`;
const headers: Record<string, string> = { Authorization: `Bearer ${token}` };
if (options?.revision) headers["If-None-Match"] = `"${options.revision}"`;
const res = await fetchWithTimeout(url, {
headers: { Authorization: `Bearer ${token}` },
headers,
credentials: "same-origin",
cache: "no-store",
signal: options?.signal,
});
if (res.status === 304 && options?.cached) return options.cached;
if (res.status === 404) return null;
if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`);
return (await res.json()) as WebuiThreadPersistedPayload;
}
export async function fetchWebuiThreadTraceDetail(
token: string,
key: string,
ref: string,
base: string = "",
): Promise<WebuiThreadTraceDetailPayload> {
const query = new URLSearchParams({ ref });
const url = `${base}/api/sessions/${encodeURIComponent(key)}/webui-thread/trace-detail?${query}`;
const res = await fetchWithTimeout(url, {
headers: { Authorization: `Bearer ${token}` },
credentials: "same-origin",
cache: "no-store",
});
if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`);
return (await res.json()) as WebuiThreadTraceDetailPayload;
}
export async function fetchFilePreview(
token: string,
key: string,
+56
View File
@@ -0,0 +1,56 @@
/** Byte- and entry-bounded in-memory LRU for JSON-shaped WebUI state. */
export class MemoryLruCache<T> {
private entries = new Map<string, { value: T; bytes: number }>();
private sizes = new WeakMap<object, number>();
private bytes = 0;
constructor(
private maxBytes: number,
private maxEntries: number,
private canEvict: (key: string) => boolean = () => true,
) {}
get(key: string): T | undefined {
const entry = this.entries.get(key);
if (!entry) return undefined;
this.entries.delete(key);
this.entries.set(key, entry);
return entry.value;
}
set(key: string, value: T): void {
this.delete(key);
const bytes = this.estimate(value);
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);
}
}
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<object, number>();
this.bytes = 0;
}
private estimate(value: unknown): 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 size = 32 + Object.values(value).reduce<number>(
(total, item) => total + this.estimate(item),
0,
);
this.sizes.set(value, size);
return size;
}
}
+7 -42
View File
@@ -1,49 +1,14 @@
import type { UIMessage } from "./types";
import { MemoryLruCache } from "./memory-lru-cache";
/** Bounded replay cache; temporary chats remain pinned because they have no disk history. */
export class ThreadMessageCache {
private entries = new Map<string, { messages: UIMessage[]; bytes: number }>();
private sizes = new WeakMap<object, number>();
private bytes = 0;
export class ThreadMessageCache extends MemoryLruCache<UIMessage[]> {
constructor(
private isPinned: (key: string) => boolean,
private maxBytes = 16 * 1024 * 1024,
private maxEntries = 12,
) {}
get(key: string): UIMessage[] | undefined {
const entry = this.entries.get(key);
if (!entry) return undefined;
this.entries.delete(key);
this.entries.set(key, entry);
return entry.messages;
}
set(key: string, messages: UIMessage[]): void {
this.delete(key);
const bytes = this.estimate(messages);
this.entries.set(key, { messages, bytes });
this.bytes += bytes;
for (const candidate of this.entries.keys()) {
if (this.bytes <= this.maxBytes && this.entries.size <= this.maxEntries) break;
if (!this.isPinned(candidate)) this.delete(candidate);
}
}
delete(key: string): void {
const entry = this.entries.get(key);
if (entry) this.bytes -= entry.bytes;
this.entries.delete(key);
}
private estimate(value: unknown): 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 size = 32 + Object.values(value).reduce<number>((total, item) => total + this.estimate(item), 0);
this.sizes.set(value, size);
return size;
isPinned: (key: string) => boolean,
maxBytes = 16 * 1024 * 1024,
maxEntries = 12,
) {
super(maxBytes, maxEntries, (key) => !isPinned(key));
}
}
+15
View File
@@ -81,6 +81,12 @@ export interface UIMessage {
/** Structured tool events behind trace rows. Kept so activity cards can
* distinguish running, completed, and failed tool phases. */
toolEvents?: ToolProgressEvent[];
/** Oversized persisted trace content that can be fetched when activity is expanded. */
traceDetail?: {
ref: string;
bytes: number;
traceCount: number;
};
/** Activity rows: explicit file edits emitted by edit tools. */
fileEdits?: UIFileEdit[];
/** Activity rows created during the same agent phase share one collapsible block. */
@@ -1542,6 +1548,8 @@ export interface WebuiThreadPersistedPayload {
schemaVersion: number;
sessionKey?: string;
savedAt?: string;
/** Cheap server revision used for application-managed conditional revalidation. */
revision?: string;
messages: UIMessage[];
fork_boundary_message_count?: number;
/** Turn ids backed by an explicit persisted ``turn_end`` event. */
@@ -1553,6 +1561,13 @@ export interface WebuiThreadPersistedPayload {
workspace_scope?: WorkspaceScopePayload;
}
export interface WebuiThreadTraceDetailPayload {
message_id: string;
content: string;
traces?: string[];
toolEvents?: ToolProgressEvent[];
}
export interface FilePreviewPayload {
path: string;
display_path: string;
+14
View File
@@ -0,0 +1,14 @@
import { MemoryLruCache } from "./memory-lru-cache";
import type { WebuiThreadPersistedPayload } from "./types";
/** Process-local canonical replay cache used for stale-while-revalidate session entry. */
export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload> {
constructor(
maxBytes = 16 * 1024 * 1024,
maxEntries = 12,
) {
super(maxBytes, maxEntries);
}
}
export const webuiThreadCache = new WebuiThreadCache();