perf(webui): restore cached threads and load mention catalogs on demand
This commit is contained in:
1 parent
c370e2a5a5
commit
1a78ae2b99
13 files changed
+316
-65
No files matched your search
+20
-40
@@ -57,45 +57,21 @@
|
||||
color: #fafafa;
|
||||
}
|
||||
|
||||
.boot-splash {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
.startup-shell { position: relative; height: 100%; }
|
||||
.startup-header { display: flex; justify-content: space-between; padding: 5px 13px; }
|
||||
.startup-control-shadow {
|
||||
width: 28px; height: 28px; border-radius: 8px; background: rgba(0,0,0,0.025);
|
||||
}
|
||||
|
||||
.boot-splash-inner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
color: rgba(255, 255, 255, 0.74);
|
||||
font-size: 14px;
|
||||
.startup-composer {
|
||||
position: absolute; inset-inline: 16px; bottom: max(24px, env(safe-area-inset-bottom));
|
||||
box-sizing: border-box; max-width: 768px; margin-inline: auto;
|
||||
height: 96px; border-radius: 24px; background: rgba(0,0,0,0.025);
|
||||
}
|
||||
|
||||
html:not(.dark) .boot-splash-inner {
|
||||
color: rgba(10, 10, 10, 0.64);
|
||||
}
|
||||
|
||||
.boot-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 9999px;
|
||||
background: currentColor;
|
||||
opacity: 0.75;
|
||||
animation: boot-pulse 1s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes boot-pulse {
|
||||
0%,
|
||||
100% {
|
||||
transform: scale(0.9);
|
||||
opacity: 0.45;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1);
|
||||
opacity: 0.85;
|
||||
}
|
||||
.startup-status {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0;
|
||||
}
|
||||
html.dark :is(.startup-control-shadow, .startup-composer) { background: rgba(255,255,255,0.035); }
|
||||
</style>
|
||||
<script>
|
||||
(function () {
|
||||
@@ -124,12 +100,16 @@
|
||||
</head>
|
||||
<body class="bg-background text-foreground antialiased">
|
||||
<div id="root">
|
||||
<div class="boot-splash">
|
||||
<div class="boot-splash-inner">
|
||||
<span class="boot-dot" aria-hidden="true"></span>
|
||||
<main class="startup-shell" aria-busy="true">
|
||||
<div class="startup-header" aria-hidden="true">
|
||||
<span class="startup-control-shadow"></span>
|
||||
<span class="startup-control-shadow"></span>
|
||||
</div>
|
||||
<div class="startup-composer" aria-hidden="true"></div>
|
||||
<div class="startup-status" role="status">
|
||||
<span data-boot-copy>Loading nanobot…</span>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
|
||||
+15
-15
@@ -18,6 +18,9 @@ import { SidebarResizeHandle, SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH } from "@/com
|
||||
import { matchSidebarShortcut } from "@/lib/sidebar-shortcuts";
|
||||
import type { SidebarDeleteItem } from "@/components/ChatList";
|
||||
import type { SettingsSectionKey } from "@/components/settings/SettingsView";
|
||||
import { StartupShell } from "@/components/StartupShell";
|
||||
import { activateReloadCache, clearReloadCache } from "@/lib/reload-cache";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
|
||||
import type { SettingsExitGuard } from "@/components/settings/contracts";
|
||||
import { PaneWorkbench } from "@/components/workbench/PaneWorkbench";
|
||||
@@ -133,7 +136,8 @@ type ShellRoute = {
|
||||
settingsSection: SettingsSectionKey;
|
||||
temporary?: boolean;
|
||||
};
|
||||
const ThreadShell = lazy(() => import("@/components/thread/ThreadShell").then(
|
||||
const loadThreadShell = () => import("@/components/thread/ThreadShell");
|
||||
const ThreadShell = lazy(() => loadThreadShell().then(
|
||||
(module) => ({ default: module.ThreadShell }),
|
||||
));
|
||||
const loadSettingsView = () => import("@/components/settings/SettingsView");
|
||||
@@ -917,6 +921,7 @@ export default function App() {
|
||||
const bootstrapWithSecret = useCallback(
|
||||
(secret: string) => {
|
||||
let cancelled = false;
|
||||
if (readShellRoute().view === "chat") void loadThreadShell().catch(() => {});
|
||||
(async () => {
|
||||
setState({ status: "loading" });
|
||||
try {
|
||||
@@ -924,6 +929,7 @@ export default function App() {
|
||||
if (cancelled) return;
|
||||
if (secret) saveSecret(secret);
|
||||
const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url);
|
||||
activateReloadCache(url);
|
||||
const runtimeSurface = resolveRuntimeSurface(boot.runtime_surface, "browser");
|
||||
const runtimeHost = createRuntimeHost(runtimeSurface, boot.runtime_capabilities);
|
||||
const client = new NanobotClient({
|
||||
@@ -955,6 +961,8 @@ export default function App() {
|
||||
} catch (e) {
|
||||
if (cancelled) return;
|
||||
if (isBootstrapAuthRequired(e)) {
|
||||
clearReloadCache();
|
||||
webuiThreadCache.clear();
|
||||
setState({ status: "auth", failed: !!secret });
|
||||
} else {
|
||||
setState({
|
||||
@@ -979,6 +987,8 @@ export default function App() {
|
||||
await refreshReadyClient(client, state.runtimeSurface);
|
||||
} catch (e) {
|
||||
if (isBootstrapAuthRequired(e)) {
|
||||
clearReloadCache();
|
||||
webuiThreadCache.clear();
|
||||
setState({ status: "auth", failed: !!bootstrapSecretRef.current });
|
||||
}
|
||||
}
|
||||
@@ -992,19 +1002,7 @@ export default function App() {
|
||||
}, [bootstrapWithSecret]);
|
||||
|
||||
if (state.status === "loading") {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<div className="flex flex-col items-center gap-3 animate-in fade-in-0 duration-300">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span className="relative flex h-2 w-2">
|
||||
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-foreground/40" />
|
||||
<span className="relative inline-flex h-2 w-2 rounded-full bg-foreground/60" />
|
||||
</span>
|
||||
{t("app.loading.connecting")}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return <StartupShell />;
|
||||
}
|
||||
if (state.status === "auth") {
|
||||
return (
|
||||
@@ -1039,6 +1037,8 @@ export default function App() {
|
||||
state.client.close();
|
||||
}
|
||||
clearSavedSecret();
|
||||
clearReloadCache();
|
||||
webuiThreadCache.clear();
|
||||
setState({ status: "auth" });
|
||||
};
|
||||
|
||||
@@ -2842,7 +2842,7 @@ function Shell({
|
||||
)}
|
||||
>
|
||||
<ThreadVisibilityContext.Provider value={view === "chat"}>
|
||||
<Suspense fallback={<SurfaceLoadingFallback label={t("chat.loading")} />}>
|
||||
<Suspense fallback={<StartupShell embedded />}>
|
||||
<PaneWorkbench
|
||||
panes={renderedWorkbenchPanes}
|
||||
activePaneKey={renderedActivePaneKey}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
/** Quiet layout placeholders while the authenticated application starts. */
|
||||
export function StartupShell({ embedded = false }: { embedded?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const Root = embedded ? "section" : "main";
|
||||
return (
|
||||
<Root className="startup-shell" aria-busy="true">
|
||||
<div className="startup-header" aria-hidden="true">
|
||||
<span className="startup-control-shadow" />
|
||||
<span className="startup-control-shadow" />
|
||||
</div>
|
||||
<div className="startup-composer" aria-hidden="true" />
|
||||
<span className="startup-status" role="status">{t("app.loading.connecting")}</span>
|
||||
</Root>
|
||||
);
|
||||
}
|
||||
@@ -211,6 +211,7 @@ interface ThreadComposerProps {
|
||||
recentRoundUsage?: readonly ComposerRoundUsage[];
|
||||
variant?: "thread" | "hero";
|
||||
slashCommands?: SlashCommand[];
|
||||
onMentionSearch?: () => void;
|
||||
cliApps?: CliAppInfo[];
|
||||
mcpPresets?: McpPresetInfo[];
|
||||
sessions?: ChatSummary[];
|
||||
@@ -912,6 +913,7 @@ export function ThreadComposer({
|
||||
recentRoundUsage = [],
|
||||
variant = "thread",
|
||||
slashCommands = [],
|
||||
onMentionSearch,
|
||||
cliApps = [],
|
||||
mcpPresets = [],
|
||||
sessions = [],
|
||||
@@ -1301,6 +1303,11 @@ export function ThreadComposer({
|
||||
};
|
||||
}, [cliAppMenuDismissed, cursorPosition, interactionDisabled, value]);
|
||||
|
||||
const mentionSearchActive = cliAppMention !== null;
|
||||
useEffect(() => {
|
||||
if (mentionSearchActive) onMentionSearch?.();
|
||||
}, [mentionSearchActive, onMentionSearch]);
|
||||
|
||||
const availableSessionMentions = useMemo(
|
||||
() => sessionMentionOptions(sessions),
|
||||
[sessions],
|
||||
|
||||
@@ -541,6 +541,7 @@ interface PendingFirstMessage {
|
||||
}
|
||||
|
||||
interface InstalledSettingItemsOptions<Payload, Item> {
|
||||
enabled: boolean;
|
||||
getToken: () => string;
|
||||
eventName: string;
|
||||
fetchPayload: (token: string) => Promise<Payload>;
|
||||
@@ -549,6 +550,7 @@ interface InstalledSettingItemsOptions<Payload, Item> {
|
||||
}
|
||||
|
||||
function useInstalledSettingItems<Payload, Item>({
|
||||
enabled,
|
||||
getToken,
|
||||
eventName,
|
||||
fetchPayload,
|
||||
@@ -583,14 +585,14 @@ function useInstalledSettingItems<Payload, Item>({
|
||||
}
|
||||
};
|
||||
const queueRefresh = () => {
|
||||
if (document.visibilityState === "hidden" || refreshQueued) return;
|
||||
if (!enabled || document.visibilityState === "hidden" || refreshQueued) return;
|
||||
refreshQueued = true;
|
||||
queueMicrotask(() => {
|
||||
refreshQueued = false;
|
||||
if (!cancelled) void refresh();
|
||||
});
|
||||
};
|
||||
void refresh();
|
||||
if (enabled) void refresh();
|
||||
|
||||
const refreshOnChanged = (event: Event) => {
|
||||
const payload = (event as CustomEvent<unknown>).detail;
|
||||
@@ -606,16 +608,12 @@ function useInstalledSettingItems<Payload, Item>({
|
||||
queueRefresh();
|
||||
};
|
||||
|
||||
window.addEventListener("focus", queueRefresh);
|
||||
document.addEventListener("visibilitychange", queueRefresh);
|
||||
window.addEventListener(eventName, refreshOnChanged);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.removeEventListener("focus", queueRefresh);
|
||||
document.removeEventListener("visibilitychange", queueRefresh);
|
||||
window.removeEventListener(eventName, refreshOnChanged);
|
||||
};
|
||||
}, [eventName, fetchPayload, getToken, isPayload, selectItems]);
|
||||
}, [enabled, eventName, fetchPayload, getToken, isPayload, selectItems]);
|
||||
|
||||
return items;
|
||||
}
|
||||
@@ -698,7 +696,10 @@ export function ThreadShell({
|
||||
}, [client]);
|
||||
const [booting, setBooting] = useState(false);
|
||||
const [slashCommands, setSlashCommands] = useState<SlashCommand[]>([]);
|
||||
const [mentionCatalogsRequested, setMentionCatalogsRequested] = useState(false);
|
||||
const requestMentionCatalogs = useCallback(() => setMentionCatalogsRequested(true), []);
|
||||
const cliApps = useInstalledSettingItems({
|
||||
enabled: mentionCatalogsRequested,
|
||||
getToken,
|
||||
eventName: CLI_APPS_CHANGED_EVENT,
|
||||
fetchPayload: fetchInstalledCliApps,
|
||||
@@ -706,6 +707,7 @@ export function ThreadShell({
|
||||
selectItems: installedCliAppsFromPayload,
|
||||
});
|
||||
const mcpPresets = useInstalledSettingItems({
|
||||
enabled: mentionCatalogsRequested,
|
||||
getToken,
|
||||
eventName: MCP_PRESETS_CHANGED_EVENT,
|
||||
fetchPayload: fetchMcpPresets,
|
||||
@@ -899,6 +901,11 @@ export function ThreadShell({
|
||||
}, []);
|
||||
|
||||
const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]);
|
||||
useEffect(() => {
|
||||
if (displayMessages.some((message) => message.cliApps?.length || message.mcpPresets?.length)) {
|
||||
requestMentionCatalogs();
|
||||
}
|
||||
}, [displayMessages, requestMentionCatalogs]);
|
||||
const composerContextUsage = useMemo(
|
||||
() => latestComposerContextUsage(displayMessages),
|
||||
[displayMessages],
|
||||
@@ -1725,6 +1732,7 @@ export function ThreadShell({
|
||||
recentRoundUsage={composerRoundUsage}
|
||||
variant={composerVariant}
|
||||
slashCommands={availableSlashCommands}
|
||||
onMentionSearch={requestMentionCatalogs}
|
||||
cliApps={cliApps}
|
||||
mcpPresets={mcpPresets}
|
||||
sessions={mentionSessions}
|
||||
@@ -1774,6 +1782,7 @@ export function ThreadShell({
|
||||
recentRoundUsage={composerRoundUsage}
|
||||
variant="hero"
|
||||
slashCommands={availableSlashCommands}
|
||||
onMentionSearch={requestMentionCatalogs}
|
||||
cliApps={cliApps}
|
||||
mcpPresets={mcpPresets}
|
||||
sessions={mentionSessions}
|
||||
|
||||
@@ -13,6 +13,7 @@ import { hasPendingAgentActivity } from "@/lib/activity-timeline";
|
||||
import { deriveTitle } from "@/lib/format";
|
||||
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import { readReloadSessions, writeReloadCache } from "@/lib/reload-cache";
|
||||
import type {
|
||||
ChatSummary,
|
||||
SessionAutomationJob,
|
||||
@@ -214,7 +215,7 @@ export function useSessions(): {
|
||||
getSessionAutomations: (key: string) => Promise<SessionAutomationJob[]>;
|
||||
} {
|
||||
const { client, token } = useClient();
|
||||
const [sessions, setSessions] = useState<ChatSummary[]>([]);
|
||||
const [sessions, setSessions] = useState<ChatSummary[]>(readReloadSessions);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const tokenRef = useRef(token);
|
||||
@@ -223,6 +224,10 @@ export function useSessions(): {
|
||||
const refreshInFlightRef = useRef<Promise<void> | null>(null);
|
||||
tokenRef.current = token;
|
||||
|
||||
useEffect(() => {
|
||||
if (sessions.length || !loading) writeReloadCache("sessions", sessions.slice(0, 200));
|
||||
}, [sessions, loading]);
|
||||
|
||||
const refresh = useCallback((): Promise<void> => {
|
||||
refreshPendingRef.current = true;
|
||||
if (refreshInFlightRef.current) return refreshInFlightRef.current;
|
||||
|
||||
@@ -369,7 +369,7 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
|
||||
throw new Error(`Invalid WebUI thread projection event: ${value.event}`);
|
||||
}
|
||||
|
||||
function parseWebuiThreadPayload(value: unknown): WebuiThreadPersistedPayload {
|
||||
export function parseWebuiThreadPayload(value: unknown): WebuiThreadPersistedPayload {
|
||||
if (!isRecord(value) || typeof value.schemaVersion !== "number") {
|
||||
throw new Error("Invalid WebUI thread response");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { ChatSummary, WorkspaceScopePayload } from "./types";
|
||||
|
||||
const PREFIX = "nanobot.reload.v1.";
|
||||
const MAX_CHARS = 512 * 1024;
|
||||
let scope: string | null = null;
|
||||
|
||||
/** Enable tab-local replay only after bootstrap authenticates the gateway. */
|
||||
export function activateReloadCache(wsUrl: string): void {
|
||||
const url = new URL(wsUrl, window.location.href);
|
||||
scope = `${url.origin}${url.pathname}`;
|
||||
}
|
||||
|
||||
export function readReloadCache(name: string): unknown {
|
||||
if (!scope) return undefined;
|
||||
try {
|
||||
const raw = sessionStorage.getItem(PREFIX + name);
|
||||
if (!raw || raw.length > MAX_CHARS) return undefined;
|
||||
const stored: unknown = JSON.parse(raw);
|
||||
return isRecord(stored) && stored.scope === scope ? stored.value : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeReloadCache(name: string, value: unknown): void {
|
||||
if (!scope) return;
|
||||
try {
|
||||
const raw = JSON.stringify({ scope, value });
|
||||
if (raw.length <= MAX_CHARS) sessionStorage.setItem(PREFIX + name, raw);
|
||||
else sessionStorage.removeItem(PREFIX + name);
|
||||
} catch {
|
||||
// Storage can be unavailable or full; in-memory replay remains usable.
|
||||
}
|
||||
}
|
||||
|
||||
export function removeReloadCache(name: string): void {
|
||||
try { sessionStorage.removeItem(PREFIX + name); } catch { /* Storage is optional. */ }
|
||||
}
|
||||
|
||||
export function clearReloadCache(): void {
|
||||
scope = null;
|
||||
removeReloadCache("sessions");
|
||||
removeReloadCache("thread");
|
||||
}
|
||||
|
||||
export function readReloadSessions(): ChatSummary[] {
|
||||
const value = readReloadCache("sessions");
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.flatMap((row): ChatSummary[] => {
|
||||
if (!isRecord(row) || typeof row.key !== "string" || typeof row.channel !== "string"
|
||||
|| typeof row.chatId !== "string" || typeof row.preview !== "string") return [];
|
||||
const workspaceScope = readWorkspaceScope(row.workspaceScope);
|
||||
return [{
|
||||
key: row.key, channel: row.channel, chatId: row.chatId, preview: row.preview,
|
||||
title: typeof row.title === "string" ? row.title : undefined,
|
||||
createdAt: typeof row.createdAt === "string" ? row.createdAt : null,
|
||||
updatedAt: typeof row.updatedAt === "string" ? row.updatedAt : null,
|
||||
...(typeof row.modelPreset === "string" ? { modelPreset: row.modelPreset } : {}),
|
||||
...(typeof row.runStartedAt === "number" ? { runStartedAt: row.runStartedAt } : {}),
|
||||
...(workspaceScope ? { workspaceScope } : {}),
|
||||
}];
|
||||
});
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readWorkspaceScope(value: unknown): WorkspaceScopePayload | undefined {
|
||||
if (!isRecord(value) || typeof value.project_path !== "string"
|
||||
|| (value.access_mode !== "full" && value.access_mode !== "restricted")
|
||||
|| typeof value.restrict_to_workspace !== "boolean") return undefined;
|
||||
return {
|
||||
project_path: value.project_path,
|
||||
access_mode: value.access_mode,
|
||||
restrict_to_workspace: value.restrict_to_workspace,
|
||||
...(typeof value.project_name === "string" ? { project_name: value.project_name } : {}),
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { MemoryLruCache } from "./memory-lru-cache";
|
||||
import { parseWebuiThreadPayload } from "./api";
|
||||
import { readReloadCache, removeReloadCache, writeReloadCache } from "./reload-cache";
|
||||
import type { WebuiThreadPersistedPayload } from "./types";
|
||||
|
||||
/** Process-local canonical replay cache used for stale-while-revalidate session entry. */
|
||||
/** Bounded canonical replay cache; the most recent snapshot also survives tab reloads. */
|
||||
export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload> {
|
||||
constructor(
|
||||
maxBytes = 16 * 1024 * 1024,
|
||||
@@ -9,6 +11,40 @@ export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload
|
||||
) {
|
||||
super(maxBytes, maxEntries);
|
||||
}
|
||||
|
||||
override get(key: string): WebuiThreadPersistedPayload | undefined {
|
||||
const cached = super.get(key);
|
||||
if (cached) return cached;
|
||||
const stored = readReloadCache("thread");
|
||||
if (!stored || typeof stored !== "object" || !("key" in stored)
|
||||
|| stored.key !== key || !("body" in stored)) return undefined;
|
||||
try {
|
||||
const body = parseWebuiThreadPayload(stored.body);
|
||||
this.set(key, body);
|
||||
return super.get(key);
|
||||
} catch {
|
||||
removeReloadCache("thread");
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
override set(key: string, body: WebuiThreadPersistedPayload): void {
|
||||
super.set(key, body);
|
||||
if (super.get(key)) writeReloadCache("thread", { key, body });
|
||||
}
|
||||
|
||||
override delete(key: string): void {
|
||||
super.delete(key);
|
||||
const stored = readReloadCache("thread");
|
||||
if (stored && typeof stored === "object" && "key" in stored && stored.key === key) {
|
||||
removeReloadCache("thread");
|
||||
}
|
||||
}
|
||||
|
||||
override clear(): void {
|
||||
super.clear();
|
||||
removeReloadCache("thread");
|
||||
}
|
||||
}
|
||||
|
||||
export const webuiThreadCache = new WebuiThreadCache();
|
||||
@@ -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"),
|
||||
|
||||
@@ -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,
|
||||
}]);
|
||||
});
|
||||
});
|
||||
@@ -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(),
|
||||
|
||||
@@ -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" };
|
||||
|
||||
Reference in new issue
Block a user