perf(webui): restore cached threads and load mention catalogs on demand

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-24 23:32:22 +08:00
1 parent c370e2a5a5
commit 1a78ae2b99
13 files changed
+316 -65

No files matched your search

+10
View File
@@ -351,6 +351,16 @@ describe("App layout", () => {
vi.unstubAllGlobals();
});
it("shows only layout shadows while bootstrap is pending", () => {
vi.mocked(fetchBootstrap).mockReturnValueOnce(new Promise(() => {}));
render(<App />);
expect(screen.getByRole("main")).toHaveAttribute("aria-busy", "true");
expect(screen.queryByRole("button")).not.toBeInTheDocument();
expect(screen.queryByRole("link")).not.toBeInTheDocument();
expect(screen.getByRole("status")).toHaveClass("startup-status");
expect(screen.queryByText("Loading nanobot…")).not.toBeInTheDocument();
});
it("shows the auth form without an invalid-password error on first load", async () => {
vi.mocked(fetchBootstrap).mockRejectedValueOnce(
new Error("bootstrap failed: HTTP 401"),
+62
View File
@@ -0,0 +1,62 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { activateReloadCache, clearReloadCache, readReloadSessions, writeReloadCache } from "@/lib/reload-cache";
import { WebuiThreadCache } from "@/lib/webui-thread-cache";
import { canonicalThreadPayload } from "./thread-test-payload";
afterEach(() => { clearReloadCache(); vi.restoreAllMocks(); });
const thread = canonicalThreadPayload({ schemaVersion: 3, revision: "rev-1", messages: [
{ id: "a", role: "assistant", content: "Saved answer", createdAt: 1 },
] })!;
describe("tab reload cache", () => {
it("restores authenticated replay into a fresh cache and retains it for another reload", () => {
activateReloadCache("ws://localhost:8765/?token=old");
new WebuiThreadCache().set("websocket:a", thread);
activateReloadCache("ws://localhost:8765/?token=renewed");
expect(new WebuiThreadCache().get("websocket:a")).toEqual(thread);
expect(new WebuiThreadCache().get("websocket:a")).toEqual(thread);
expect(new WebuiThreadCache().get("websocket:b")).toBeUndefined();
});
it("does not restore another gateway's data or data after logout", () => {
activateReloadCache("ws://localhost:8765/");
new WebuiThreadCache().set("websocket:a", thread);
activateReloadCache("ws://localhost:8888/");
expect(new WebuiThreadCache().get("websocket:a")).toBeUndefined();
clearReloadCache();
activateReloadCache("ws://localhost:8765/");
expect(new WebuiThreadCache().get("websocket:a")).toBeUndefined();
});
it("removes deleted sessions and ignores malformed replay", () => {
activateReloadCache("ws://localhost:8765/");
const cache = new WebuiThreadCache();
cache.set("websocket:a", thread);
cache.delete("websocket:a");
expect(new WebuiThreadCache().get("websocket:a")).toBeUndefined();
writeReloadCache("thread", { key: "websocket:a", body: { projection: "events", events: [{}] } });
expect(new WebuiThreadCache().get("websocket:a")).toBeUndefined();
});
it("keeps memory caching working when storage fails", () => {
activateReloadCache("ws://localhost:8765/");
vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("quota"); });
const cache = new WebuiThreadCache();
cache.set("websocket:a", thread);
expect(cache.get("websocket:a")).toEqual(thread);
});
it("does not persist oversized replay and validates session summaries", () => {
activateReloadCache("ws://localhost:8765/");
writeReloadCache("thread", { key: "large", body: "x".repeat(600_000) });
expect(sessionStorage.getItem("nanobot.reload.v1.thread")).toBeNull();
writeReloadCache("sessions", [{ key: "bad" }, {
key: "websocket:a", channel: "websocket", chatId: "a", preview: "Answer", title: "Topic",
}]);
expect(readReloadSessions()).toEqual([{
key: "websocket:a", channel: "websocket", chatId: "a", preview: "Answer", title: "Topic",
createdAt: null, updatedAt: null,
}]);
});
});
+24
View File
@@ -4475,6 +4475,29 @@ describe("ThreadShell", () => {
expect(screen.queryByText("from chat a")).not.toBeInTheDocument();
});
it("loads mention catalogs only on demand and ignores window focus", async () => {
render(wrap(makeClient(), <ThreadShell
session={session("lazy-mentions")}
title="Lazy mentions"
onToggleSidebar={() => {}}
onGoHome={() => {}}
onNewChat={() => {}}
/>));
const input = await screen.findByLabelText("Message input");
const catalogCalls = () => vi.mocked(fetch).mock.calls.filter(([url]) =>
/cli-apps|mcp-presets/.test(String(url)));
fireEvent.change(input, { target: { value: "hello", selectionStart: 5 } });
fireEvent(window, new Event("focus"));
expect(catalogCalls()).toHaveLength(0);
fireEvent.change(input, { target: { value: "@", selectionStart: 1 } });
await waitFor(() => expect(catalogCalls()).toHaveLength(2));
fireEvent(window, new Event("focus"));
fireEvent.change(input, { target: { value: "@app", selectionStart: 4 } });
fireEvent.change(input, { target: { value: "", selectionStart: 0 } });
fireEvent.change(input, { target: { value: "@", selectionStart: 1 } });
expect(catalogCalls()).toHaveLength(2);
});
it("updates @ CLI app suggestions when settings broadcasts an install", async () => {
const client = makeClient();
render(wrap(
@@ -4549,6 +4572,7 @@ describe("ThreadShell", () => {
));
const input = await screen.findByLabelText("Message input");
fireEvent.change(input, { target: { value: "@", selectionStart: 1 } });
await waitFor(() => expect(fetch).toHaveBeenCalledWith(
"/api/settings/cli-apps?installed_only=1",
expect.anything(),
+22
View File
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { sessionTitle, useSessionHistory, useSessions } from "@/hooks/useSessions";
import * as api from "@/lib/api";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";
import { ClientProvider } from "@/providers/ClientProvider";
import { canonicalThreadPayload } from "./thread-test-payload";
@@ -72,6 +73,27 @@ function wrap(
}
describe("useSessions", () => {
it("shows tab-cached sessions while revalidating and removes server-deleted rows", async () => {
activateReloadCache("ws://localhost:8765/");
writeReloadCache("sessions", [{
key: "websocket:cached", channel: "websocket", chatId: "cached", preview: "Saved answer",
createdAt: null, updatedAt: null,
}]);
let finish!: (rows: Awaited<ReturnType<typeof api.listSessions>>) => void;
vi.mocked(api.listSessions).mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
const { result, unmount } = renderHook(() => useSessions(), { wrapper: wrap(fakeClient()) });
try {
expect(result.current.sessions[0]?.key).toBe("websocket:cached");
expect(result.current.loading).toBe(true);
await act(async () => finish([]));
expect(result.current.sessions).toEqual([]);
expect(result.current.loading).toBe(false);
} finally {
unmount();
clearReloadCache();
}
});
it("coalesces a burst across tasks and preserves unchanged session identities", async () => {
const row = { key: "websocket:burst", channel: "websocket", chatId: "burst",
createdAt: "2026-09-08", updatedAt: "2026-09-08", preview: "Stable" };