fix(webui): preserve sidebar state after failed initial fetch (#6009)
* fix(webui): wait for sidebar state before persisting edits * test(webui): load sidebar state in temporary chat fixtures * fix(webui): preserve sidebar pushes during initial reads * fix(webui): require successful session reads before pruning Treat sidebar initialization and session-list completeness as separate permissions. Retain sidebar metadata, workbench panes, activity markers, and workspace overrides when the session list fails or only a partial reload cache is available. Add integration coverage for recovery with and without cached sessions, successful deletion reconciliation, and successful empty session lists. * test(webui): align sidebar recovery fixture with current schema Remove obsolete preview and timestamp settings from the raw API fixture. Assert supported view preferences while retaining exact metadata and workbench comparisons. --------- Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
1 parent
f101a24571
commit
d2aaa8e54b
5 files changed
+286
-22
No files matched your search
+11
-8
@@ -1199,18 +1199,21 @@ function Shell({
|
|||||||
const {
|
const {
|
||||||
sessions,
|
sessions,
|
||||||
loading,
|
loading,
|
||||||
|
error: sessionsError,
|
||||||
refresh,
|
refresh,
|
||||||
createChat,
|
createChat,
|
||||||
forkChat,
|
forkChat,
|
||||||
deleteChat,
|
deleteChat,
|
||||||
getSessionAutomations,
|
getSessionAutomations,
|
||||||
} = useSessions();
|
} = useSessions();
|
||||||
|
// Failed reads retain an empty list or partial reload cache, not proof of deletion.
|
||||||
|
const sessionsLoaded = !loading && sessionsError === null;
|
||||||
const {
|
const {
|
||||||
state: sidebarState,
|
state: sidebarState,
|
||||||
loading: sidebarStateLoading,
|
loading: sidebarStateLoading,
|
||||||
update: updateSidebarState,
|
update: updateSidebarState,
|
||||||
} =
|
} =
|
||||||
useSidebarState(sessions, !loading);
|
useSidebarState(sessions, sessionsLoaded);
|
||||||
const initialRouteRef = useRef<ShellRoute | null>(null);
|
const initialRouteRef = useRef<ShellRoute | null>(null);
|
||||||
if (!initialRouteRef.current) initialRouteRef.current = readShellRoute();
|
if (!initialRouteRef.current) initialRouteRef.current = readShellRoute();
|
||||||
const [activeKey, setActiveKey] = useState<string | null>(
|
const [activeKey, setActiveKey] = useState<string | null>(
|
||||||
@@ -1599,7 +1602,7 @@ function Shell({
|
|||||||
}, [refreshWorkspaces]);
|
}, [refreshWorkspaces]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (loading) return;
|
if (!sessionsLoaded) return;
|
||||||
const knownChatIds = new Set(sessions.map((session) => session.chatId));
|
const knownChatIds = new Set(sessions.map((session) => session.chatId));
|
||||||
setUpdatedChatIds((current) => {
|
setUpdatedChatIds((current) => {
|
||||||
const next = new Set(
|
const next = new Set(
|
||||||
@@ -1611,16 +1614,16 @@ function Shell({
|
|||||||
const entries = Object.entries(current).filter(([chatId]) => knownChatIds.has(chatId));
|
const entries = Object.entries(current).filter(([chatId]) => knownChatIds.has(chatId));
|
||||||
return entries.length === Object.keys(current).length ? current : Object.fromEntries(entries);
|
return entries.length === Object.keys(current).length ? current : Object.fromEntries(entries);
|
||||||
});
|
});
|
||||||
}, [loading, sessions]);
|
}, [sessionsLoaded, sessions]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (loading || sidebarStateLoading) return;
|
if (!sessionsLoaded || sidebarStateLoading) return;
|
||||||
const validKeys = new Set(sessions.map((session) => session.key));
|
const validKeys = new Set(sessions.map((session) => session.key));
|
||||||
updateWorkbenchState((current) => {
|
updateWorkbenchState((current) => {
|
||||||
return reconcileWorkbench(current, validKeys);
|
return reconcileWorkbench(current, validKeys);
|
||||||
});
|
});
|
||||||
}, [
|
}, [
|
||||||
loading,
|
sessionsLoaded,
|
||||||
sidebarStateLoading,
|
sidebarStateLoading,
|
||||||
sessions,
|
sessions,
|
||||||
updateWorkbenchState,
|
updateWorkbenchState,
|
||||||
@@ -2780,12 +2783,12 @@ function Shell({
|
|||||||
: activeKey;
|
: activeKey;
|
||||||
|
|
||||||
const sidebarProps = {
|
const sidebarProps = {
|
||||||
sessions: sidebarTopicSessions,
|
sessions: sidebarStateLoading ? [] : sidebarTopicSessions,
|
||||||
temporarySessions: temporarySessionList,
|
temporarySessions: sidebarStateLoading ? [] : temporarySessionList,
|
||||||
activeKey: !managingConnections && view === "chat"
|
activeKey: !managingConnections && view === "chat"
|
||||||
? (temporaryChatActive ? activeKey : activeSidebarKey)
|
? (temporaryChatActive ? activeKey : activeSidebarKey)
|
||||||
: null,
|
: null,
|
||||||
loading,
|
loading: loading || sidebarStateLoading,
|
||||||
newChatActive: !managingConnections && view === "chat" && activeKey === null,
|
newChatActive: !managingConnections && view === "chat" && activeKey === null,
|
||||||
onNewChat,
|
onNewChat,
|
||||||
onSelect: onSelectSidebarItem,
|
onSelect: onSelectSidebarItem,
|
||||||
|
|||||||
@@ -143,6 +143,7 @@ export function useSidebarState(
|
|||||||
const { client, token } = useClient();
|
const { client, token } = useClient();
|
||||||
const tokenRef = useRef(token);
|
const tokenRef = useRef(token);
|
||||||
const stateRef = useRef(DEFAULT_SIDEBAR_STATE);
|
const stateRef = useRef(DEFAULT_SIDEBAR_STATE);
|
||||||
|
const loadedRef = useRef(false);
|
||||||
const connectionOpenRef = useRef(client.status === "open");
|
const connectionOpenRef = useRef(client.status === "open");
|
||||||
const pendingPersistenceRef = useRef<SidebarStatePayload | null>(null);
|
const pendingPersistenceRef = useRef<SidebarStatePayload | null>(null);
|
||||||
const persistenceInFlightRef = useRef(false);
|
const persistenceInFlightRef = useRef(false);
|
||||||
@@ -154,29 +155,35 @@ export function useSidebarState(
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
let retryTimer: ReturnType<typeof setTimeout> | undefined;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
(async () => {
|
const load = async () => {
|
||||||
|
if (cancelled || loadedRef.current) return;
|
||||||
try {
|
try {
|
||||||
const loaded = normalizeSidebarState(await fetchSidebarState(tokenRef.current));
|
const loaded = normalizeSidebarState(await fetchSidebarState(tokenRef.current));
|
||||||
if (cancelled) return;
|
if (cancelled || loadedRef.current) return;
|
||||||
stateRef.current = loaded;
|
stateRef.current = loaded;
|
||||||
|
loadedRef.current = true;
|
||||||
setState(loaded);
|
setState(loaded);
|
||||||
|
setLoading(false);
|
||||||
} catch {
|
} catch {
|
||||||
if (cancelled) return;
|
if (cancelled || loadedRef.current) return;
|
||||||
stateRef.current = DEFAULT_SIDEBAR_STATE;
|
// A failed read is not an empty store. Keep writes blocked until a
|
||||||
setState(DEFAULT_SIDEBAR_STATE);
|
// retry can load the saved state, including after gateway restarts.
|
||||||
} finally {
|
retryTimer = setTimeout(() => void load(), 3_000);
|
||||||
if (!cancelled) setLoading(false);
|
|
||||||
}
|
}
|
||||||
})();
|
};
|
||||||
|
void load();
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
|
clearTimeout(retryTimer);
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const flushPersistence = useCallback(() => {
|
const flushPersistence = useCallback(() => {
|
||||||
if (
|
if (
|
||||||
persistenceInFlightRef.current
|
!loadedRef.current
|
||||||
|
|| persistenceInFlightRef.current
|
||||||
|| !connectionOpenRef.current
|
|| !connectionOpenRef.current
|
||||||
|| pendingPersistenceRef.current === null
|
|| pendingPersistenceRef.current === null
|
||||||
) return;
|
) return;
|
||||||
@@ -220,11 +227,14 @@ export function useSidebarState(
|
|||||||
) return;
|
) return;
|
||||||
const loaded = normalizeSidebarState(incoming);
|
const loaded = normalizeSidebarState(incoming);
|
||||||
stateRef.current = loaded;
|
stateRef.current = loaded;
|
||||||
|
loadedRef.current = true;
|
||||||
setState(loaded);
|
setState(loaded);
|
||||||
|
setLoading(false);
|
||||||
}), [client]);
|
}), [client]);
|
||||||
|
|
||||||
const update = useCallback(
|
const update = useCallback(
|
||||||
async (updater: (current: SidebarStatePayload) => SidebarStatePayload) => {
|
async (updater: (current: SidebarStatePayload) => SidebarStatePayload) => {
|
||||||
|
if (!loadedRef.current) return;
|
||||||
const next = normalizeSidebarState(updater(stateRef.current));
|
const next = normalizeSidebarState(updater(stateRef.current));
|
||||||
if (sameState(next, stateRef.current)) return;
|
if (sameState(next, stateRef.current)) return;
|
||||||
stateRef.current = next;
|
stateRef.current = next;
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|||||||
import type { Window as HappyWindow } from "happy-dom";
|
import type { Window as HappyWindow } from "happy-dom";
|
||||||
|
|
||||||
import i18n from "@/i18n";
|
import i18n from "@/i18n";
|
||||||
|
import { useSessions } from "@/hooks/useSessions";
|
||||||
|
import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";
|
||||||
import type {
|
import type {
|
||||||
ChatSummary,
|
ChatSummary,
|
||||||
ConnectionStatus,
|
ConnectionStatus,
|
||||||
@@ -61,6 +63,7 @@ function mockFetchRoutes(routes: Record<string, unknown>): void {
|
|||||||
"fetch",
|
"fetch",
|
||||||
vi.fn(async (input: RequestInfo | URL) => {
|
vi.fn(async (input: RequestInfo | URL) => {
|
||||||
const route = routes[String(input)]
|
const route = routes[String(input)]
|
||||||
|
?? (String(input) === "/api/webui/sidebar-state" ? {} : undefined)
|
||||||
?? (/^\/api\/sessions\/[^/]+\/subagents$/.test(String(input)) ? { tasks: [] } : undefined);
|
?? (/^\/api\/sessions\/[^/]+\/subagents$/.test(String(input)) ? { tasks: [] } : undefined);
|
||||||
const body =
|
const body =
|
||||||
typeof route === "function"
|
typeof route === "function"
|
||||||
@@ -169,7 +172,7 @@ vi.mock("@/hooks/useSessions", async (importOriginal) => {
|
|||||||
const actual = await importOriginal<typeof import("@/hooks/useSessions")>();
|
const actual = await importOriginal<typeof import("@/hooks/useSessions")>();
|
||||||
return {
|
return {
|
||||||
...actual,
|
...actual,
|
||||||
useSessions: () => {
|
useSessions: vi.fn(function useMockSessions() {
|
||||||
const [sessions, setSessions] = React.useState(mockSessions);
|
const [sessions, setSessions] = React.useState(mockSessions);
|
||||||
return {
|
return {
|
||||||
sessions,
|
sessions,
|
||||||
@@ -203,7 +206,7 @@ vi.mock("@/hooks/useSessions", async (importOriginal) => {
|
|||||||
return { deleted: true };
|
return { deleted: true };
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
}),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -303,11 +306,15 @@ import {
|
|||||||
import App from "@/App";
|
import App from "@/App";
|
||||||
import { mockBrowserFocus } from "./browser-focus";
|
import { mockBrowserFocus } from "./browser-focus";
|
||||||
|
|
||||||
|
const defaultUseSessions = vi.mocked(useSessions).getMockImplementation()!;
|
||||||
|
|
||||||
describe("App layout", () => {
|
describe("App layout", () => {
|
||||||
let restoreBrowserFocus: (() => void) | undefined;
|
let restoreBrowserFocus: (() => void) | undefined;
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
await i18n.changeLanguage("en");
|
await i18n.changeLanguage("en");
|
||||||
mockSessions = [];
|
mockSessions = [];
|
||||||
|
vi.mocked(useSessions).mockImplementation(defaultUseSessions);
|
||||||
|
clearReloadCache();
|
||||||
connectSpy.mockClear();
|
connectSpy.mockClear();
|
||||||
updateUrlSpy.mockClear();
|
updateUrlSpy.mockClear();
|
||||||
refreshSpy.mockReset();
|
refreshSpy.mockReset();
|
||||||
@@ -2568,7 +2575,7 @@ describe("App layout", () => {
|
|||||||
);
|
);
|
||||||
}, 15_000);
|
}, 15_000);
|
||||||
|
|
||||||
it("applies persisted sidebar workspace state from the gateway", async () => {
|
it("retries a failed sidebar read before enabling edits without losing saved state", async () => {
|
||||||
mockSessions = [
|
mockSessions = [
|
||||||
{
|
{
|
||||||
key: "websocket:chat-a",
|
key: "websocket:chat-a",
|
||||||
@@ -2601,11 +2608,13 @@ describe("App layout", () => {
|
|||||||
},
|
},
|
||||||
updated_at: null,
|
updated_at: null,
|
||||||
};
|
};
|
||||||
|
let sidebarReads = 0;
|
||||||
vi.stubGlobal(
|
vi.stubGlobal(
|
||||||
"fetch",
|
"fetch",
|
||||||
vi.fn().mockImplementation(async (url: string | URL | Request) => {
|
vi.fn().mockImplementation(async (url: string | URL | Request) => {
|
||||||
const href = String(url);
|
const href = String(url);
|
||||||
if (href === "/api/webui/sidebar-state") {
|
if (href === "/api/webui/sidebar-state") {
|
||||||
|
if (++sidebarReads === 1) throw new Error("Gateway restarting");
|
||||||
return { ok: true, json: async () => initialState };
|
return { ok: true, json: async () => initialState };
|
||||||
}
|
}
|
||||||
return { ok: false, status: 404 };
|
return { ok: false, status: 404 };
|
||||||
@@ -2619,8 +2628,11 @@ describe("App layout", () => {
|
|||||||
statusHandlers.forEach((handler) => handler("open"));
|
statusHandlers.forEach((handler) => handler("open"));
|
||||||
});
|
});
|
||||||
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
|
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
|
||||||
|
expect(within(sidebar).getByText("Loading…")).toBeInTheDocument();
|
||||||
|
expect(setSidebarStateSpy).not.toHaveBeenCalled();
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(within(sidebar).getByText("Pinned")).toBeInTheDocument(),
|
expect(within(sidebar).getByText("Pinned")).toBeInTheDocument(),
|
||||||
|
{ timeout: 5_000 },
|
||||||
);
|
);
|
||||||
expect(within(sidebar).getByRole("button", { name: /^Roadmap$/ })).toBeInTheDocument();
|
expect(within(sidebar).getByRole("button", { name: /^Roadmap$/ })).toBeInTheDocument();
|
||||||
expect(within(sidebar).queryByRole("button", { name: /^First chat$/ })).not.toBeInTheDocument();
|
expect(within(sidebar).queryByRole("button", { name: /^First chat$/ })).not.toBeInTheDocument();
|
||||||
@@ -2632,12 +2644,120 @@ describe("App layout", () => {
|
|||||||
expect(within(sidebar).getByRole("button", { name: /^First chat$/ })).toBeInTheDocument();
|
expect(within(sidebar).getByRole("button", { name: /^First chat$/ })).toBeInTheDocument();
|
||||||
expect(setSidebarStateSpy).toHaveBeenCalledWith(
|
expect(setSidebarStateSpy).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
|
pinned_keys: initialState.pinned_keys,
|
||||||
|
archived_keys: initialState.archived_keys,
|
||||||
|
title_overrides: initialState.title_overrides,
|
||||||
view: expect.objectContaining({ show_archived: true }),
|
view: expect.objectContaining({ show_archived: true }),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(within(sidebar).queryByRole("button", { name: "View" })).not.toBeInTheDocument();
|
expect(within(sidebar).queryByRole("button", { name: "View" })).not.toBeInTheDocument();
|
||||||
});
|
}, 10_000);
|
||||||
|
|
||||||
|
it.each([false, true])("preserves sidebar metadata and panes after both reads fail with partial cache: %s", async (cached) => {
|
||||||
|
const actual = await vi.importActual<typeof import("@/hooks/useSessions")>("@/hooks/useSessions");
|
||||||
|
vi.mocked(useSessions).mockImplementation(actual.useSessions);
|
||||||
|
const sessions: ChatSummary[] = ["a", "b"].map((id) => ({
|
||||||
|
key: `websocket:chat-${id}`, channel: "websocket", chatId: `chat-${id}`,
|
||||||
|
createdAt: null, updatedAt: null, preview: "",
|
||||||
|
}));
|
||||||
|
if (cached) {
|
||||||
|
activateReloadCache("ws://test");
|
||||||
|
writeReloadCache("sessions", sessions.slice(0, 1));
|
||||||
|
}
|
||||||
|
const saved = {
|
||||||
|
schema_version: 1,
|
||||||
|
pinned_keys: ["websocket:chat-b", "websocket:deleted"],
|
||||||
|
archived_keys: ["websocket:deleted"],
|
||||||
|
session_order: ["websocket:chat-a", "websocket:chat-b", "websocket:deleted"],
|
||||||
|
title_overrides: {
|
||||||
|
"websocket:chat-a": "Saved A", "websocket:chat-b": "Saved B", "websocket:deleted": "Old topic",
|
||||||
|
},
|
||||||
|
project_name_overrides: {},
|
||||||
|
tags_by_key: { "websocket:chat-b": ["important"], "websocket:deleted": ["old"] },
|
||||||
|
collapsed_groups: {},
|
||||||
|
workbench: {
|
||||||
|
version: 1,
|
||||||
|
tabs: {
|
||||||
|
"tab:saved": {
|
||||||
|
explicit: true, title: "Saved group",
|
||||||
|
paneKeys: ["websocket:chat-a", "websocket:chat-b", "websocket:deleted"],
|
||||||
|
layoutPaneKeys: ["websocket:chat-b", "websocket:chat-a", "websocket:deleted"],
|
||||||
|
layout: "columns", splitRatios: [0.4, 0.6],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
view: {
|
||||||
|
density: "comfortable", show_archived: false, sort: "updated_desc",
|
||||||
|
},
|
||||||
|
updated_at: null,
|
||||||
|
};
|
||||||
|
let sidebarReads = 0;
|
||||||
|
let sessionsFail = true;
|
||||||
|
let serverSessions = sessions;
|
||||||
|
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||||
|
if (String(input) === "/api/sessions") {
|
||||||
|
return sessionsFail
|
||||||
|
? Response.json({}, { status: 503 })
|
||||||
|
: jsonResponse({ sessions: serverSessions });
|
||||||
|
}
|
||||||
|
if (String(input) === "/api/webui/sidebar-state") {
|
||||||
|
return ++sidebarReads === 1
|
||||||
|
? Response.json({}, { status: 503 })
|
||||||
|
: jsonResponse(saved);
|
||||||
|
}
|
||||||
|
return Response.json({}, { status: 404 });
|
||||||
|
}));
|
||||||
|
|
||||||
|
const markersKey = "nanobot-webui.sidebar.session-updates.v1";
|
||||||
|
localStorage.setItem(markersKey, JSON.stringify(["chat-b", "deleted"]));
|
||||||
|
render(<App />);
|
||||||
|
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
|
||||||
|
act(() => statusHandlers.forEach((handler) => handler("open")));
|
||||||
|
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
|
||||||
|
expect(within(sidebar).getByText("Loading…")).toBeInTheDocument();
|
||||||
|
await waitFor(() => expect(sidebarReads).toBe(2), { timeout: 5_000 });
|
||||||
|
await act(async () => {});
|
||||||
|
expect(within(sidebar).queryByText("Loading…")).not.toBeInTheDocument();
|
||||||
|
expect(setSidebarStateSpy).not.toHaveBeenCalled();
|
||||||
|
expect(JSON.parse(localStorage.getItem(markersKey)!)).toEqual(["chat-b", "deleted"]);
|
||||||
|
|
||||||
|
// A successful full list can authorize removal; the failed read and cache cannot.
|
||||||
|
sessionsFail = false;
|
||||||
|
act(() => sessionUpdateHandlers.forEach((handler) => handler("chat-a")));
|
||||||
|
await within(sidebar).findByRole("button", { name: "Group: Saved group" });
|
||||||
|
expect(await within(sidebar).findByRole("button", { name: "Saved B", exact: true })).toBeInTheDocument();
|
||||||
|
await waitFor(() => expect(setSidebarStateSpy).toHaveBeenLastCalledWith({
|
||||||
|
...saved,
|
||||||
|
view: expect.objectContaining(saved.view),
|
||||||
|
pinned_keys: ["websocket:chat-b"],
|
||||||
|
archived_keys: [],
|
||||||
|
session_order: ["websocket:chat-a", "websocket:chat-b"],
|
||||||
|
title_overrides: { "websocket:chat-a": "Saved A", "websocket:chat-b": "Saved B" },
|
||||||
|
tags_by_key: { "websocket:chat-b": ["important"] },
|
||||||
|
workbench: {
|
||||||
|
version: 1,
|
||||||
|
tabs: {
|
||||||
|
"tab:saved": {
|
||||||
|
...saved.workbench.tabs["tab:saved"],
|
||||||
|
paneKeys: ["websocket:chat-a", "websocket:chat-b"],
|
||||||
|
layoutPaneKeys: ["websocket:chat-b", "websocket:chat-a"],
|
||||||
|
splitRatios: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(JSON.parse(localStorage.getItem(markersKey)!)).toEqual(["chat-b"]);
|
||||||
|
serverSessions = [];
|
||||||
|
act(() => sessionUpdateHandlers.forEach((handler) => handler("chat-a")));
|
||||||
|
await waitFor(() => expect(setSidebarStateSpy).toHaveBeenLastCalledWith({
|
||||||
|
...saved, view: expect.objectContaining(saved.view),
|
||||||
|
pinned_keys: [], archived_keys: [], session_order: [],
|
||||||
|
title_overrides: {}, tags_by_key: {}, workbench: { version: 1, tabs: {} },
|
||||||
|
}));
|
||||||
|
expect(JSON.parse(localStorage.getItem(markersKey)!)).toEqual([]);
|
||||||
|
}, 10_000);
|
||||||
|
|
||||||
it("sorts chats by displayed title when A-Z is persisted", async () => {
|
it("sorts chats by displayed title when A-Z is persisted", async () => {
|
||||||
mockSessions = [
|
mockSessions = [
|
||||||
|
|||||||
@@ -115,7 +115,8 @@ describe("temporary chat navigation", () => {
|
|||||||
updated_at: "2026-09-01T00:00:00Z",
|
updated_at: "2026-09-01T00:00:00Z",
|
||||||
})) });
|
})) });
|
||||||
}
|
}
|
||||||
if (path === "/api/webui/sidebar-state" && groupedTopics) {
|
if (path === "/api/webui/sidebar-state") {
|
||||||
|
if (!groupedTopics) return Response.json({});
|
||||||
return Response.json({ workbench: { version: 1, tabs: {
|
return Response.json({ workbench: { version: 1, tabs: {
|
||||||
"tab:websocket:regular": {
|
"tab:websocket:regular": {
|
||||||
explicit: true, title: "Regular topic",
|
explicit: true, title: "Regular topic",
|
||||||
|
|||||||
@@ -8,6 +8,136 @@ import type { SidebarStatePayload } from "@/lib/types";
|
|||||||
import { ClientProvider } from "@/providers/ClientProvider";
|
import { ClientProvider } from "@/providers/ClientProvider";
|
||||||
|
|
||||||
describe("useSidebarState", () => {
|
describe("useSidebarState", () => {
|
||||||
|
it("blocks writes after a failed read and retries before allowing edits", async () => {
|
||||||
|
const setSidebarState = vi.fn(async (state: SidebarStatePayload) => state);
|
||||||
|
const client = {
|
||||||
|
status: "open",
|
||||||
|
onStatus: () => () => {},
|
||||||
|
onSidebarStateUpdate: () => () => {},
|
||||||
|
setSidebarState,
|
||||||
|
} as unknown as NanobotClient;
|
||||||
|
const saved = {
|
||||||
|
pinned_keys: ["websocket:old"],
|
||||||
|
archived_keys: ["websocket:archived"],
|
||||||
|
title_overrides: { "websocket:old": "Saved title" },
|
||||||
|
tags_by_key: { "websocket:old": ["important"] },
|
||||||
|
session_order: ["websocket:old", "websocket:archived"],
|
||||||
|
};
|
||||||
|
const fetch = vi.fn()
|
||||||
|
.mockRejectedValueOnce(new Error("Gateway restarting"))
|
||||||
|
.mockResolvedValue({ ok: true, json: async () => saved });
|
||||||
|
vi.stubGlobal("fetch", fetch);
|
||||||
|
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||||
|
<ClientProvider client={client} token="token">{children}</ClientProvider>
|
||||||
|
);
|
||||||
|
const { result, unmount } = renderHook(() => useSidebarState([], false), { wrapper });
|
||||||
|
await act(async () => {});
|
||||||
|
expect(fetch).toHaveBeenCalled();
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.update((current) => ({ ...current, pinned_keys: ["websocket:new"] }));
|
||||||
|
});
|
||||||
|
expect(setSidebarState).not.toHaveBeenCalled();
|
||||||
|
expect(result.current.loading).toBe(true);
|
||||||
|
await waitFor(() => expect(result.current.loading).toBe(false), { timeout: 5_000 });
|
||||||
|
expect(result.current.state).toEqual(expect.objectContaining(saved));
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.update((current) => ({
|
||||||
|
...current, pinned_keys: [...current.pinned_keys, "websocket:new"],
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
expect(setSidebarState).toHaveBeenCalledTimes(1);
|
||||||
|
expect(setSidebarState).toHaveBeenCalledWith(expect.objectContaining({
|
||||||
|
...saved, pinned_keys: ["websocket:old", "websocket:new"],
|
||||||
|
}));
|
||||||
|
unmount();
|
||||||
|
}, 10_000);
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{ outcome: "fails", status: 503 },
|
||||||
|
{ outcome: "returns an older snapshot", status: 200 },
|
||||||
|
])("preserves pushed state when the initial fetch $outcome", async ({ status }) => {
|
||||||
|
let resolveInitialFetch!: (response: Response) => void;
|
||||||
|
const initialFetch = new Promise<Response>((resolve) => { resolveInitialFetch = resolve; });
|
||||||
|
let receive: ((state: SidebarStatePayload) => void) | undefined;
|
||||||
|
const setSidebarState = vi.fn(async (state: SidebarStatePayload) => state);
|
||||||
|
const client = {
|
||||||
|
status: "open",
|
||||||
|
onStatus: () => () => {},
|
||||||
|
onSidebarStateUpdate: (handler: (state: SidebarStatePayload) => void) => {
|
||||||
|
receive = handler;
|
||||||
|
return () => { receive = undefined; };
|
||||||
|
},
|
||||||
|
setSidebarState,
|
||||||
|
} as unknown as NanobotClient;
|
||||||
|
vi.stubGlobal("fetch", vi.fn().mockReturnValue(initialFetch));
|
||||||
|
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||||
|
<ClientProvider client={client} token="token">{children}</ClientProvider>
|
||||||
|
);
|
||||||
|
const { result } = renderHook(() => useSidebarState([], false), { wrapper });
|
||||||
|
const pushed: SidebarStatePayload = {
|
||||||
|
...result.current.state,
|
||||||
|
pinned_keys: ["websocket:saved"],
|
||||||
|
archived_keys: ["websocket:archived"],
|
||||||
|
session_order: ["websocket:saved", "websocket:archived"],
|
||||||
|
title_overrides: { "websocket:saved": "Saved title" },
|
||||||
|
tags_by_key: { "websocket:saved": ["saved-tag"] },
|
||||||
|
};
|
||||||
|
|
||||||
|
act(() => receive?.(pushed));
|
||||||
|
expect(result.current.loading).toBe(false);
|
||||||
|
await act(async () => { resolveInitialFetch(Response.json({}, { status })); });
|
||||||
|
expect(result.current.state).toEqual(pushed);
|
||||||
|
expect(setSidebarState).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.update((current) => ({
|
||||||
|
...current, pinned_keys: [...current.pinned_keys, "websocket:new"],
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
expect(setSidebarState).toHaveBeenCalledWith({
|
||||||
|
...pushed, pinned_keys: ["websocket:saved", "websocket:new"],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stops a scheduled read retry once a server push supplies state", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
let unmount: (() => void) | undefined;
|
||||||
|
try {
|
||||||
|
let receive: ((state: SidebarStatePayload) => void) | undefined;
|
||||||
|
const client = {
|
||||||
|
status: "open",
|
||||||
|
onStatus: () => () => {},
|
||||||
|
onSidebarStateUpdate: (handler: (state: SidebarStatePayload) => void) => {
|
||||||
|
receive = handler;
|
||||||
|
return () => { receive = undefined; };
|
||||||
|
},
|
||||||
|
setSidebarState: vi.fn(async (state: SidebarStatePayload) => state),
|
||||||
|
} as unknown as NanobotClient;
|
||||||
|
const fetch = vi.fn()
|
||||||
|
.mockResolvedValueOnce(Response.json({}, { status: 503 }))
|
||||||
|
.mockResolvedValue(Response.json({}));
|
||||||
|
vi.stubGlobal("fetch", fetch);
|
||||||
|
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||||
|
<ClientProvider client={client} token="token">{children}</ClientProvider>
|
||||||
|
);
|
||||||
|
const hook = renderHook(() => useSidebarState([], false), { wrapper });
|
||||||
|
unmount = hook.unmount;
|
||||||
|
await act(async () => {});
|
||||||
|
expect(hook.result.current.loading).toBe(true);
|
||||||
|
const pushed: SidebarStatePayload = {
|
||||||
|
...hook.result.current.state, pinned_keys: ["websocket:saved"],
|
||||||
|
};
|
||||||
|
act(() => receive?.(pushed));
|
||||||
|
await act(async () => { await vi.advanceTimersByTimeAsync(3_000); });
|
||||||
|
expect(hook.result.current.loading).toBe(false);
|
||||||
|
expect(hook.result.current.state).toEqual(pushed);
|
||||||
|
expect(fetch).toHaveBeenCalledTimes(1);
|
||||||
|
} finally {
|
||||||
|
unmount?.();
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it("serializes full-state writes so an older request cannot overwrite a newer update", async () => {
|
it("serializes full-state writes so an older request cannot overwrite a newer update", async () => {
|
||||||
let resolveFirstWrite: (() => void) | null = null;
|
let resolveFirstWrite: (() => void) | null = null;
|
||||||
let sidebarStateUpdateHandler: ((state: SidebarStatePayload) => void) | null = null;
|
let sidebarStateUpdateHandler: ((state: SidebarStatePayload) => void) | null = null;
|
||||||
|
|||||||
Reference in new issue
Block a user