fix(webui): separate page routes from chat return state

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-25 00:47:30 +08:00
1 parent 0d1d2e82c2
commit f57cc3aad2
2 files changed
+102 -27

No files matched your search

+53 -27
View File
@@ -254,26 +254,33 @@ function readShellRoute(): ShellRoute {
const settingsSection = isSettingsSectionKey(rawSettingsSection) const settingsSection = isSettingsSectionKey(rawSettingsSection)
? rawSettingsSection ? rawSettingsSection
: "overview"; : "overview";
const activeKey = params.get("chat")?.trim() || null; const saved: unknown = window.history.state?.nanobotReturnChat;
const returnChat = saved && typeof saved === "object" && "hash" in saved
&& saved.hash === window.location.hash ? saved : null;
const activeKey = params.get("chat")?.trim()
|| (returnChat && "key" in returnChat && typeof returnChat.key === "string"
? returnChat.key : null);
const temporary = Boolean(returnChat && "temporary" in returnChat && returnChat.temporary === true);
if (path === "/settings") { if (path === "/settings") {
return { return {
view: shellViewForSettingsSection(settingsSection), view: shellViewForSettingsSection(settingsSection),
activeKey, activeKey,
temporary,
settingsSection, settingsSection,
}; };
} }
if (path === "/apps") { if (path === "/apps") {
return { view: "apps", activeKey, settingsSection: "apps" }; return { view: "apps", activeKey, temporary, settingsSection: "apps" };
} }
if (path === "/automations") { if (path === "/automations") {
return { view: "automations", activeKey, settingsSection: "automations" }; return { view: "automations", activeKey, temporary, settingsSection: "automations" };
} }
if (path === "/channels") { if (path === "/channels") {
return { view: "channels", activeKey, settingsSection: "channels" }; return { view: "channels", activeKey, temporary, settingsSection: "channels" };
} }
if (path === "/skills") { if (path === "/skills") {
return { view: "skills", activeKey, settingsSection: "skills" }; return { view: "skills", activeKey, temporary, settingsSection: "skills" };
} }
if (path.startsWith("/temporary/")) { if (path.startsWith("/temporary/")) {
const encoded = path.slice("/temporary/".length); const encoded = path.slice("/temporary/".length);
@@ -316,7 +323,6 @@ function shellRouteHash(route: ShellRoute): string {
: "#/new"; : "#/new";
} }
const params = new URLSearchParams(); const params = new URLSearchParams();
if (route.activeKey) params.set("chat", route.activeKey);
if (route.view === "settings" && route.settingsSection !== "overview") { if (route.view === "settings" && route.settingsSection !== "overview") {
params.set("section", route.settingsSection); params.set("section", route.settingsSection);
} }
@@ -327,20 +333,20 @@ function shellRouteHash(route: ShellRoute): string {
function writeShellRoute(route: ShellRoute, replace = false): void { function writeShellRoute(route: ShellRoute, replace = false): void {
if (typeof window === "undefined") return; if (typeof window === "undefined") return;
const nextHash = shellRouteHash(route); const nextHash = shellRouteHash(route);
if (window.location.hash === nextHash) return; const state = {
if (replace) { ...window.history.state,
window.history.replaceState( nanobotReturnChat: route.view === "chat" ? null : {
null, hash: nextHash,
"", key: route.activeKey,
`${window.location.pathname}${window.location.search}${nextHash}`, temporary: route.temporary === true,
); },
return; };
const url = `${window.location.pathname}${window.location.search}${nextHash}`;
if (replace || window.location.hash === nextHash) {
window.history.replaceState(state, "", url);
} else {
window.history.pushState(state, "", url);
} }
window.history.pushState(
null,
"",
`${window.location.pathname}${window.location.search}${nextHash}`,
);
} }
function bootstrapTokenExpiresAt(expiresInSeconds: number): number { function bootstrapTokenExpiresAt(expiresInSeconds: number): number {
@@ -1119,6 +1125,16 @@ function Shell({
initialRouteRef.current.activeKey, initialRouteRef.current.activeKey,
); );
const [view, setView] = useState<ShellView>(initialRouteRef.current.view); const [view, setView] = useState<ShellView>(initialRouteRef.current.view);
const [chatVisited, setChatVisited] = useState(initialRouteRef.current.view === "chat");
useEffect(() => {
if (view === "chat") setChatVisited(true);
}, [view]);
useEffect(() => {
// Normalize legacy links while retaining their return destination in history.
if (new URLSearchParams(window.location.hash.split("?")[1]).has("chat")) {
writeShellRoute(initialRouteRef.current!, true);
}
}, []);
const [temporarySessions, setTemporarySessions] = useState<Record<string, ChatSummary>>({}); const [temporarySessions, setTemporarySessions] = useState<Record<string, ChatSummary>>({});
const [temporaryChatEnabled, setTemporaryChatEnabled] = useState(false); const [temporaryChatEnabled, setTemporaryChatEnabled] = useState(false);
const [settingsInitialSection, setSettingsInitialSection] = const [settingsInitialSection, setSettingsInitialSection] =
@@ -1186,7 +1202,10 @@ function Shell({
} | null>(null); } | null>(null);
const settingsExitGuardRef = useRef<SettingsExitGuard | null>(null); const settingsExitGuardRef = useRef<SettingsExitGuard | null>(null);
const currentShellRouteRef = useRef<ShellRoute>({ view, activeKey, settingsSection: settingsInitialSection }); const currentShellRouteRef = useRef<ShellRoute>({ view, activeKey, settingsSection: settingsInitialSection });
currentShellRouteRef.current = { view, activeKey, settingsSection: settingsInitialSection }; currentShellRouteRef.current = {
view, activeKey, settingsSection: settingsInitialSection,
temporary: Boolean(activeKey && temporarySessions[activeKey]),
};
const registerSettingsExitGuard = useCallback((guard: SettingsExitGuard | null) => { const registerSettingsExitGuard = useCallback((guard: SettingsExitGuard | null) => {
settingsExitGuardRef.current = guard; settingsExitGuardRef.current = guard;
}, []); }, []);
@@ -1205,7 +1224,7 @@ function Shell({
const showMainSidebar = view !== "settings"; const showMainSidebar = view !== "settings";
const activeTemporarySession = activeKey ? temporarySessions[activeKey] ?? null : null; const activeTemporarySession = activeKey ? temporarySessions[activeKey] ?? null : null;
const temporaryChatId = activeTemporarySession?.chatId ?? null; const temporaryChatId = activeTemporarySession?.chatId ?? null;
const temporaryChatActive = view === "chat" && temporaryChatId !== null; const temporaryChatActive = temporaryChatId !== null;
const temporaryChatRequested = temporaryChatActive || temporaryChatEnabled; const temporaryChatRequested = temporaryChatActive || temporaryChatEnabled;
const temporarySessionList = useMemo( const temporarySessionList = useMemo(
() => Object.values(temporarySessions).sort((a, b) => ( () => Object.values(temporarySessions).sort((a, b) => (
@@ -1241,7 +1260,10 @@ function Shell({
setActiveKey(route.activeKey); setActiveKey(route.activeKey);
setView(route.view); setView(route.view);
setSettingsInitialSection(route.settingsSection); setSettingsInitialSection(route.settingsSection);
writeShellRoute(route, options?.replace); writeShellRoute({
...route,
temporary: route.temporary || Boolean(route.activeKey && temporarySessionsRef.current[route.activeKey]),
}, options?.replace);
}; };
if (currentShellRouteRef.current.view === "settings" && route.view !== "settings" && settingsExitGuardRef.current) { if (currentShellRouteRef.current.view === "settings" && route.view !== "settings" && settingsExitGuardRef.current) {
settingsExitGuardRef.current(leave); settingsExitGuardRef.current(leave);
@@ -1504,9 +1526,11 @@ function Shell({
} }
if (!activeKey) return; if (!activeKey) return;
const currentRoute = readShellRoute(); const currentRoute = readShellRoute();
if (temporarySessions[activeKey]) return;
if (currentRoute.temporary) { if (currentRoute.temporary) {
if (temporarySessions[activeKey]) return; navigate(currentRoute.view === "chat" ? defaultShellRoute() : {
navigate(defaultShellRoute(), { replace: true }); ...currentRoute, activeKey: null, temporary: false,
}, { replace: true });
return; return;
} }
if (sessions.some((session) => session.key === activeKey)) return; if (sessions.some((session) => session.key === activeKey)) return;
@@ -2129,12 +2153,14 @@ function Shell({
setMobileSidebarOpen(false); setMobileSidebarOpen(false);
const nextKey = (() => { const nextKey = (() => {
if (!activeKey) return null; if (!activeKey) return null;
if (temporarySessionsRef.current[activeKey]) return activeKey;
if (topicSessions.some((session) => session.key === activeKey)) return activeKey; if (topicSessions.some((session) => session.key === activeKey)) return activeKey;
return topicSessions[0]?.key ?? null; return null;
})(); })();
navigate({ navigate({
view: "chat", view: "chat",
activeKey: nextKey, activeKey: nextKey,
temporary: Boolean(nextKey && temporarySessionsRef.current[nextKey]),
settingsSection: "overview", settingsSection: "overview",
}); });
}, [activeKey, navigate, topicSessions]); }, [activeKey, navigate, topicSessions]);
@@ -2835,7 +2861,7 @@ function Shell({
"relative flex h-full min-w-0 flex-1 flex-col overflow-hidden bg-background", "relative flex h-full min-w-0 flex-1 flex-col overflow-hidden bg-background",
)} )}
> >
<div {(view === "chat" || chatVisited) && <div
className={cn( className={cn(
"absolute inset-0 flex flex-col", "absolute inset-0 flex flex-col",
view !== "chat" && "hidden", view !== "chat" && "hidden",
@@ -2983,7 +3009,7 @@ function Shell({
/> />
</Suspense> </Suspense>
</ThreadVisibilityContext.Provider> </ThreadVisibilityContext.Provider>
</div> </div>}
{view !== "chat" && ( {view !== "chat" && (
<div className="absolute inset-0 flex flex-col"> <div className="absolute inset-0 flex flex-col">
<Suspense fallback={<SurfaceLoadingFallback />}> <Suspense fallback={<SurfaceLoadingFallback />}>
@@ -147,6 +147,55 @@ describe("temporary chat navigation", () => {
vi.unstubAllGlobals(); vi.unstubAllGlobals();
}); });
it.each(["settings", "apps", "automations", "skills", "channels"])(
"opens %s directly without mounting chat or retaining a chat query",
async (view) => {
window.history.replaceState(null, "", `/#/${view}?chat=websocket%3Aregular`);
render(<App />);
await screen.findByRole("button", { name: "Back to chat" });
act(() => TestSocket.current.open());
await waitFor(() => expect(window.location.hash).toBe(`#/${view}`));
expect(window.history.state.nanobotReturnChat.key).toBe("websocket:regular");
expect(screen.queryByTestId("thread-message-region")).not.toBeInTheDocument();
const requests = vi.mocked(fetch).mock.calls.map(([url]) => String(url));
expect(requests.filter((url) => url.includes("/webui-thread") || url === "/api/commands")).toEqual([]);
},
);
it("restores the return destination after refreshing a clean settings URL", async () => {
const first = render(<App />);
await screen.findByRole("button", { name: "Temporary chat" });
act(() => TestSocket.current.open());
await selectTopic("Regular topic");
fireEvent.click(screen.getByRole("button", { name: "Settings", exact: true }));
await screen.findByRole("button", { name: "Back to chat" });
expect(window.location.hash).toBe("#/settings");
first.unmount();
vi.mocked(fetch).mockClear();
render(<App />);
await screen.findByRole("button", { name: "Back to chat" });
act(() => TestSocket.current.open());
expect(vi.mocked(fetch).mock.calls.filter(([url]) => String(url).includes("/webui-thread"))).toEqual([]);
fireEvent.click(screen.getByRole("button", { name: "Back to chat" }));
await waitFor(() => expect(window.location.hash).toBe("#/chat/websocket%3Aregular"));
await waitFor(() => expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("/webui-thread"))).toBe(true));
});
it("returns from settings to the same temporary chat and keeps its live messages", async () => {
render(<App />);
await screen.findByRole("button", { name: "Temporary chat" });
act(() => TestSocket.current.open());
const chatId = await startTemporaryChat("Temporary navigation check");
fireEvent.click(screen.getByRole("button", { name: "Settings", exact: true }));
await screen.findByRole("button", { name: "Back to chat" });
expect(window.location.hash).toBe("#/settings");
act(() => TestSocket.current.receive({ event: "message", chat_id: chatId, text: "Reply while in settings" }));
fireEvent.click(screen.getByRole("button", { name: "Back to chat" }));
await waitFor(() => expect(window.location.hash).toBe(`#/temporary/${chatId}`));
await screen.findByText("Reply while in settings");
expect(vi.mocked(fetch).mock.calls.filter(([url]) => String(url).includes(chatId))).toEqual([]);
});
it("keeps the preview resource stable across bootstrap token refresh", async () => { it("keeps the preview resource stable across bootstrap token refresh", async () => {
withFiles = true; withFiles = true;
vi.useFakeTimers({ shouldAdvanceTime: true }); vi.useFakeTimers({ shouldAdvanceTime: true });