refactor(webui): separate gateway mutations and UI state (#6727)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-19 22:22:51 +08:00
1 parent ce12bfdd0d
commit 5537bdabd3
70 files changed
+4058 -3650

No files matched your search

+22
View File
@@ -4812,6 +4812,28 @@ describe("App layout", () => {
unmount();
});
it("does not apply a timed credential refresh after signing out", async () => {
vi.mocked(fetchBootstrap).mockResolvedValueOnce({
token: "old", api_token: "old-api", ws_path: "/", expires_in: 0.001,
});
let complete!: (boot: Awaited<ReturnType<typeof fetchBootstrap>>) => void;
vi.mocked(fetchBootstrap).mockImplementationOnce(() => new Promise((resolve) => { complete = resolve; }));
vi.mocked(deriveWsUrl).mockImplementation((_path, token) => `ws://test?token=${token}`);
mockFetchRoutes({ "/api/settings": baseSettingsPayload() });
window.history.replaceState(null, "", "/#/settings");
await import("@/components/settings/SettingsView");
render(<App />);
const signOut = await screen.findByRole("button", { name: "Sign out" }, { timeout: 4_000 });
await waitFor(() => expect(fetchBootstrap).toHaveBeenCalledTimes(2), { timeout: 8_000 });
fireEvent.click(signOut);
await screen.findByLabelText("WebUI password");
await act(async () => complete({ token: "late", api_token: "late-api", ws_path: "/" }));
expect(updateUrlSpy).not.toHaveBeenCalled();
expect(screen.getByLabelText("WebUI password")).toBeInTheDocument();
}, 10_000);
it("refreshes the bootstrap token before REST settings auth expires", async () => {
vi.useFakeTimers();
vi.mocked(fetchBootstrap)
+11 -4
View File
@@ -341,7 +341,7 @@ describe("NanobotClient", () => {
expect(notice).toHaveBeenCalledWith({ event, temporary: false });
client.close();
});
it("bounds regular replay tails but retains temporary events until discard", async () => {
it("retains a larger replay tail for temporary chats and clears it on discard", async () => {
const client = new NanobotClient({
url: "ws://test", reconnect: false,
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
@@ -357,13 +357,20 @@ describe("NanobotClient", () => {
socket.fakeMessage({ event: "delta", chat_id: chatId, text: String(index) });
}
}
for (let index = 2_010; index < 20_010; index++) {
socket.fakeMessage({ event: "delta", chat_id: "temporary", text: String(index) });
}
const regular = vi.fn();
const temporary = vi.fn();
const temporary: string[] = [];
client.onTranscript("regular", regular);
const unsubscribe = client.onTranscript("temporary", temporary);
const unsubscribe = client.onTranscript("temporary", (event) => {
if (event.event === "delta") temporary.push(event.text);
});
expect(regular).toHaveBeenCalledTimes(2_000);
expect(regular.mock.calls[0][0].text).toBe("10");
expect(temporary.mock.calls.filter(([event]) => event.event === "delta")).toHaveLength(2_010);
expect(temporary).toHaveLength(20_000);
expect(temporary[0]).toBe("10");
expect(temporary.at(-1)).toBe("20009");
unsubscribe();
socket.fakeMessage({ event: "delta", chat_id: "temporary", text: "discard me" });
client.discardTemporaryChat("temporary");
+24
View File
@@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { PromptNavigator } from "@/components/thread/PromptNavigator";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { mockBrowserFocus } from "./browser-focus";
let restoreBrowserFocus: () => void;
@@ -80,6 +81,29 @@ it("keeps an unknown recovered time blank while the prompt remains navigable", a
expect(onJumpToPrompt).toHaveBeenCalledWith("undated");
});
it("defers Ctrl+F to an open popover but not to its exit animation", async () => {
render(<>
<style>{`.test-popover[data-state="open"] { animation-name: enter; }
.test-popover[data-state="closed"] { animation-name: exit; }`}</style>
<Popover>
<PopoverTrigger>Model options</PopoverTrigger>
<PopoverContent aria-label="Model options" className="test-popover"><button>Choose model</button></PopoverContent>
</Popover>
<PromptNavigator messages={[{ id: "one", role: "user", content: "alpha", createdAt: 1 }]} onJumpToPrompt={vi.fn()} />
</>);
fireEvent.click(screen.getByRole("button", { name: "Model options" }));
const popover = screen.getByRole("dialog", { name: "Model options" });
const option = screen.getByRole("button", { name: "Choose model" });
fireEvent.keyDown(option, { key: "f", ctrlKey: true });
expect(screen.queryByRole("textbox", { name: "Search messages" })).not.toBeInTheDocument();
fireEvent.keyDown(option, { key: "Escape" });
expect(popover).toHaveAttribute("data-state", "closed");
expect(popover).toBeInTheDocument();
fireEvent.keyDown(screen.getByRole("button", { name: "Model options" }), { key: "f", ctrlKey: true });
expect(screen.getByRole("textbox", { name: "Search messages" })).toBeInTheDocument();
});
it("returns shortcut-opened search to the interrupted editor", async () => {
const user = userEvent.setup();
render(<><input aria-label="Draft" /><PromptNavigator messages={[
@@ -10,6 +10,7 @@ import { canonicalThreadPayload } from "./thread-test-payload";
let groupedTopics = false;
let withFiles = false;
let withPairing = false;
const previewFile = (path: string) => ({
path: `/workspace/${path}`, display_path: path, project_path: "/workspace",
language: "text", content: `Preview of ${path}`, size: 20, truncated: false,
@@ -105,12 +106,16 @@ describe("temporary chat navigation", () => {
vi.mocked(fetchBootstrap).mockReset().mockResolvedValue({ token: "test", api_token: "test", ws_path: "/" });
groupedTopics = false;
withFiles = false;
withPairing = false;
localStorage.clear();
sessionStorage.clear();
window.history.replaceState(null, "", "/");
vi.stubGlobal("WebSocket", TestSocket);
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
const path = String(input);
if (path === "/api/settings/pairing") {
return Response.json({ requests: withPairing ? [{ code: "ABCD-EFGH", channel: "telegram", sender_id: "1" }] : [] });
}
if (path === "/api/sessions") {
return Response.json({ sessions: ["regular", ...(groupedTopics ? ["child"] : [])].map((id) => ({
key: `websocket:${id}`,
@@ -345,16 +350,49 @@ describe("temporary chat navigation", () => {
expect(screen.getAllByRole("tab")).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
await screen.findByText("Preview of notes.txt");
const dialog = document.createElement("div");
dialog.setAttribute("role", "dialog");
document.body.append(dialog);
fireEvent.keyDown(window, { key: "Escape" });
withPairing = true;
act(() => TestSocket.current.receive({ event: "pairing_changed" }));
const dialog = await screen.findByRole("dialog", { name: "Pair account" });
// This popup does not intercept Escape itself; the preview must still yield.
fireEvent.keyDown(within(dialog).getByRole("textbox", { name: "Pairing code" }), { key: "Escape" });
expect(screen.getByTestId("file-preview-panel")).toBeInTheDocument();
dialog.remove();
fireEvent.keyDown(window, { key: "Escape" });
fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
await waitFor(() => expect(dialog).not.toBeInTheDocument());
fireEvent.keyDown(screen.getByRole("button", { name: "notes.txt" }), { key: "Escape" });
await waitFor(() => expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument());
});
it("commits a file preview drag and restores the page when closing mid-drag", async () => {
withFiles = true;
render(<App />);
await screen.findByRole("button", { name: "Temporary chat" });
act(() => TestSocket.current.open());
await selectTopic("Regular topic");
fireEvent.click(await screen.findByRole("button", { name: "notes.txt" }));
await screen.findByText("Preview of notes.txt");
const panel = screen.getByTestId("preview-pane");
vi.spyOn(panel.parentElement!, "getBoundingClientRect")
.mockReturnValue(DOMRect.fromRect({ width: 1_200 }));
fireEvent(window, new Event("resize"));
const handle = screen.getByRole("button", { name: "Resize file preview" });
const { cursor, userSelect } = document.body.style;
fireEvent.pointerDown(handle, { clientX: 700 });
expect(document.body.style.cursor).toBe("col-resize");
fireEvent.pointerMove(window, { clientX: 570 });
fireEvent.pointerUp(window);
expect(panel.style.getPropertyValue("--file-preview-width")).toBe("630px");
expect(document.body.style.cursor).toBe(cursor);
fireEvent.pointerDown(handle, { clientX: 600 });
fireEvent.click(screen.getByRole("button", { name: "Close notes.txt" }));
expect(document.body.style.cursor).toBe(cursor);
expect(document.body.style.userSelect).toBe(userSelect);
await waitFor(() => expect(panel).not.toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
expect(screen.getByTestId("preview-pane").style.getPropertyValue("--file-preview-width")).toBe("630px");
});
it("forgets preview paths on temporary close and disconnect", async () => {
const update = vi.spyOn(FilePreviewStore.prototype, "open");
render(<App />);
+2 -12
View File
@@ -1272,18 +1272,9 @@ describe("ThreadViewport", () => {
});
expect(hitTest.mock).toHaveBeenCalled();
const replacement = anchor.cloneNode(true) as HTMLElement;
anchor.replaceWith(replacement);
// Deferred content grows above the existing row wrapper.
anchorDocumentTop += 180;
scrollHeight += 180;
Object.defineProperty(replacement, "getBoundingClientRect", {
configurable: true,
value: () => DOMRect.fromRect({
y: anchorDocumentTop - scroller.scrollTop,
width: 800,
height: 40,
}),
});
const content = screen.getByTestId("thread-message-region").firstElementChild;
const observer = resizeObserver.observers.find((candidate) =>
content ? candidate.elements.includes(content) : false,
@@ -1294,10 +1285,9 @@ describe("ThreadViewport", () => {
});
expect(scroller.scrollTop).toBe(260);
expect(replacement.getBoundingClientRect().top).toBe(120);
expect(anchor.getBoundingClientRect().top).toBe(120);
// ResizeObserver may arrive before the next native scroll event.
hitTarget = replacement;
scroller.scrollTop = 240;
anchorDocumentTop += 60;
scrollHeight += 60;