Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(webui): preserve sidebar state after failed initial fetch (#6009)
Willow Lopezd2aaa8e54ba2
diff --git a/webui/src/App.tsx b/webui/src/App.tsxindex 0176955ab..4569277cf 100644--- a/webui/src/App.tsx+++ b/webui/src/App.tsx@@ -1199,18 +1199,21 @@ function Shell({const {sessions,loading,+ error: sessionsError,refresh,createChat,forkChat,deleteChat,getSessionAutomations,} = useSessions();+ // Failed reads retain an empty list or partial reload cache, not proof of deletion.+ const sessionsLoaded = !loading && sessionsError === null;const {state: sidebarState,loading: sidebarStateLoading,update: updateSidebarState,} =- useSidebarState(sessions, !loading);+ useSidebarState(sessions, sessionsLoaded);const initialRouteRef = useRef<ShellRoute | null>(null);if (!initialRouteRef.current) initialRouteRef.current = readShellRoute();const [activeKey, setActiveKey] = useState<string | null>(@@ -1599,7 +1602,7 @@ function Shell({}, [refreshWorkspaces]);useEffect(() => {- if (loading) return;+ if (!sessionsLoaded) return;const knownChatIds = new Set(sessions.map((session) => session.chatId));setUpdatedChatIds((current) => {const next = new Set(@@ -1611,16 +1614,16 @@ function Shell({const entries = Object.entries(current).filter(([chatId]) => knownChatIds.has(chatId));return entries.length === Object.keys(current).length ? current : Object.fromEntries(entries);});- }, [loading, sessions]);+ }, [sessionsLoaded, sessions]);useEffect(() => {- if (loading || sidebarStateLoading) return;+ if (!sessionsLoaded || sidebarStateLoading) return;const validKeys = new Set(sessions.map((session) => session.key));updateWorkbenchState((current) => {return reconcileWorkbench(current, validKeys);});}, [- loading,+ sessionsLoaded,sidebarStateLoading,sessions,updateWorkbenchState,@@ -2780,12 +2783,12 @@ function Shell({: activeKey;const sidebarProps = {- sessions: sidebarTopicSessions,- temporarySessions: temporarySessionList,+ sessions: sidebarStateLoading ? [] : sidebarTopicSessions,+ temporarySessions: sidebarStateLoading ? [] : temporarySessionList,activeKey: !managingConnections && view === "chat"? (temporaryChatActive ? activeKey : activeSidebarKey): null,- loading,+ loading: loading || sidebarStateLoading,newChatActive: !managingConnections && view === "chat" && activeKey === null,onNewChat,onSelect: onSelectSidebarItem,diff --git a/webui/src/hooks/useSidebarState.ts b/webui/src/hooks/useSidebarState.tsindex e615d07d6..051b6965a 100644--- a/webui/src/hooks/useSidebarState.ts+++ b/webui/src/hooks/useSidebarState.ts@@ -143,6 +143,7 @@ export function useSidebarState(const { client, token } = useClient();const tokenRef = useRef(token);const stateRef = useRef(DEFAULT_SIDEBAR_STATE);+ const loadedRef = useRef(false);const connectionOpenRef = useRef(client.status === "open");const pendingPersistenceRef = useRef<SidebarStatePayload | null>(null);const persistenceInFlightRef = useRef(false);@@ -154,29 +155,35 @@ export function useSidebarState(useEffect(() => {let cancelled = false;+ let retryTimer: ReturnType<typeof setTimeout> | undefined;setLoading(true);- (async () => {+ const load = async () => {+ if (cancelled || loadedRef.current) return;try {const loaded = normalizeSidebarState(await fetchSidebarState(tokenRef.current));- if (cancelled) return;+ if (cancelled || loadedRef.current) return;stateRef.current = loaded;+ loadedRef.current = true;setState(loaded);+ setLoading(false);} catch {- if (cancelled) return;- stateRef.current = DEFAULT_SIDEBAR_STATE;- setState(DEFAULT_SIDEBAR_STATE);- } finally {- if (!cancelled) setLoading(false);+ if (cancelled || loadedRef.current) return;+ // A failed read is not an empty store. Keep writes blocked until a+ // retry can load the saved state, including after gateway restarts.+ retryTimer = setTimeout(() => void load(), 3_000);}- })();+ };+ void load();return () => {cancelled = true;+ clearTimeout(retryTimer);};}, []);const flushPersistence = useCallback(() => {if (- persistenceInFlightRef.current+ !loadedRef.current+ || persistenceInFlightRef.current|| !connectionOpenRef.current|| pendingPersistenceRef.current === null) return;@@ -220,11 +227,14 @@ export function useSidebarState() return;const loaded = normalizeSidebarState(incoming);stateRef.current = loaded;+ loadedRef.current = true;setState(loaded);+ setLoading(false);}), [client]);const update = useCallback(async (updater: (current: SidebarStatePayload) => SidebarStatePayload) => {+ if (!loadedRef.current) return;const next = normalizeSidebarState(updater(stateRef.current));if (sameState(next, stateRef.current)) return;stateRef.current = next;diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsxindex 9d0a3990e..b817fd432 100644--- a/webui/src/tests/app-layout.test.tsx+++ b/webui/src/tests/app-layout.test.tsx@@ -4,6 +4,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Window as HappyWindow } from "happy-dom";import i18n from "@/i18n";+import { useSessions } from "@/hooks/useSessions";+import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";import type {ChatSummary,ConnectionStatus,@@ -61,6 +63,7 @@ function mockFetchRoutes(routes: Record<string, unknown>): void {"fetch",vi.fn(async (input: RequestInfo | URL) => {const route = routes[String(input)]+ ?? (String(input) === "/api/webui/sidebar-state" ? {} : undefined)?? (/^\/api\/sessions\/[^/]+\/subagents$/.test(String(input)) ? { tasks: [] } : undefined);const body =typeof route === "function"@@ -169,7 +172,7 @@ vi.mock("@/hooks/useSessions", async (importOriginal) => {const actual = await importOriginal<typeof import("@/hooks/useSessions")>();return {...actual,- useSessions: () => {+ useSessions: vi.fn(function useMockSessions() {const [sessions, setSessions] = React.useState(mockSessions);return {sessions,@@ -203,7 +206,7 @@ vi.mock("@/hooks/useSessions", async (importOriginal) => {return { deleted: true };},};- },+ }),};});@@ -303,11 +306,15 @@ import {import App from "@/App";import { mockBrowserFocus } from "./browser-focus";+const defaultUseSessions = vi.mocked(useSessions).getMockImplementation()!;+describe("App layout", () => {let restoreBrowserFocus: (() => void) | undefined;beforeEach(async () => {await i18n.changeLanguage("en");mockSessions = [];+ vi.mocked(useSessions).mockImplementation(defaultUseSessions);+ clearReloadCache();connectSpy.mockClear();updateUrlSpy.mockClear();refreshSpy.mockReset();@@ -2568,7 +2575,7 @@ describe("App layout", () => {);}, 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 = [{key: "websocket:chat-a",@@ -2601,11 +2608,13 @@ describe("App layout", () => {},updated_at: null,};+ let sidebarReads = 0;vi.stubGlobal("fetch",vi.fn().mockImplementation(async (url: string | URL | Request) => {const href = String(url);if (href === "/api/webui/sidebar-state") {+ if (++sidebarReads === 1) throw new Error("Gateway restarting");return { ok: true, json: async () => initialState };}return { ok: false, status: 404 };@@ -2619,8 +2628,11 @@ describe("App layout", () => {statusHandlers.forEach((handler) => handler("open"));});const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });+ expect(within(sidebar).getByText("Loading…")).toBeInTheDocument();+ expect(setSidebarStateSpy).not.toHaveBeenCalled();await waitFor(() =>expect(within(sidebar).getByText("Pinned")).toBeInTheDocument(),+ { timeout: 5_000 },);expect(within(sidebar).getByRole("button", { name: /^Roadmap$/ })).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(setSidebarStateSpy).toHaveBeenCalledWith(expect.objectContaining({+ pinned_keys: initialState.pinned_keys,+ archived_keys: initialState.archived_keys,+ title_overrides: initialState.title_overrides,view: expect.objectContaining({ show_archived: true }),}),);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 () => {mockSessions = [diff --git a/webui/src/tests/temporary-chat-navigation.test.tsx b/webui/src/tests/temporary-chat-navigation.test.tsxindex d2f34d8af..03f8f8dc5 100644--- a/webui/src/tests/temporary-chat-navigation.test.tsx+++ b/webui/src/tests/temporary-chat-navigation.test.tsx@@ -115,7 +115,8 @@ describe("temporary chat navigation", () => {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: {"tab:websocket:regular": {explicit: true, title: "Regular topic",diff --git a/webui/src/tests/useSidebarState.test.tsx b/webui/src/tests/useSidebarState.test.tsxindex ffe0233de..afdef2c0d 100644--- a/webui/src/tests/useSidebarState.test.tsx+++ b/webui/src/tests/useSidebarState.test.tsx@@ -8,6 +8,136 @@ import type { SidebarStatePayload } from "@/lib/types";import { ClientProvider } from "@/providers/ClientProvider";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 () => {let resolveFirstWrite: (() => void) | null = null;let sidebarStateUpdateHandler: ((state: SidebarStatePayload) => void) | null = null;