fix(webui): make action feedback easier to notice (#6702)
* fix(webui): make action feedback easier to notice * fix(webui): preserve undo and report confirmed action results * refactor(webui): trim toast preview and redundant coverage * test(webui): advance the undo window for the last topic deletion
This commit is contained in:
1 parent
0f45d74fec
commit
9ccf3b6214
59 files changed
+1621
-508
No files matched your search
@@ -6,6 +6,7 @@ import type { Window as HappyWindow } from "happy-dom";
|
||||
import i18n from "@/i18n";
|
||||
import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings";
|
||||
import { useSessions } from "@/hooks/useSessions";
|
||||
import { TOAST_ACTION_MS } from "@/components/ui/toast";
|
||||
import type { NanobotClientOptions, RunState } from "@/lib/nanobot-client";
|
||||
import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";
|
||||
import type {
|
||||
@@ -49,6 +50,13 @@ const pairingChangeHandlers = new Set<() => void>();
|
||||
const readyHandlers = new Set<() => void>();
|
||||
let mockSessions: ChatSummary[] = [];
|
||||
|
||||
async function confirmTopicDeletion(button: HTMLElement) {
|
||||
fireEvent.click(button);
|
||||
// Happy DOM delivers the modal's aria-hidden removal on a timer. Start
|
||||
// measuring the Undo window after the observer makes the toast reachable.
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(0); });
|
||||
}
|
||||
|
||||
function setNavigatorPlatform(platform: string): void {
|
||||
Object.defineProperty(window.navigator, "platform", {
|
||||
configurable: true,
|
||||
@@ -205,8 +213,8 @@ vi.mock("@/hooks/useSessions", async (importOriginal) => {
|
||||
forkChat: async () => "fork-chat",
|
||||
getSessionAutomations: getSessionAutomationsSpy,
|
||||
deleteChat: async (key: string, options?: { deleteAutomations?: boolean }) => {
|
||||
if (options === undefined) await deleteChatSpy(key);
|
||||
else await deleteChatSpy(key, options);
|
||||
const result = options === undefined ? await deleteChatSpy(key) : await deleteChatSpy(key, options);
|
||||
if (result && !result.deleted) return result;
|
||||
setSessions((prev: ChatSummary[]) => prev.filter((s) => s.key !== key));
|
||||
return { deleted: true };
|
||||
},
|
||||
@@ -321,6 +329,7 @@ import {
|
||||
BootstrapAuthRequiredError,
|
||||
deriveWsUrl,
|
||||
fetchBootstrap,
|
||||
loadSavedSecret,
|
||||
} from "@/lib/bootstrap";
|
||||
import App from "@/App";
|
||||
import { mockBrowserFocus } from "./browser-focus";
|
||||
@@ -437,9 +446,10 @@ describe("App layout", () => {
|
||||
expect(requestMutationSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows the auth form without an invalid-password error on first load", async () => {
|
||||
it.each(["", "stale-password"])("shows a clean auth form when the initial automatic sign-in fails (saved password: %j)", async (savedPassword) => {
|
||||
vi.mocked(loadSavedSecret).mockReturnValueOnce(savedPassword);
|
||||
vi.mocked(fetchBootstrap).mockRejectedValueOnce(
|
||||
new Error("bootstrap failed: HTTP 401"),
|
||||
new BootstrapAuthRequiredError("bootstrap failed: HTTP 401"),
|
||||
);
|
||||
|
||||
render(<App />);
|
||||
@@ -452,8 +462,10 @@ describe("App layout", () => {
|
||||
"autocomplete",
|
||||
"current-password",
|
||||
);
|
||||
expect(password).not.toHaveAttribute("placeholder");
|
||||
expect(password).toHaveValue("");
|
||||
expect(password).toHaveFocus();
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
expect(fetchBootstrap).toHaveBeenCalledWith("", savedPassword);
|
||||
expect(connectSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -467,6 +479,7 @@ describe("App layout", () => {
|
||||
|
||||
await user.type(await screen.findByLabelText("WebUI password"), "draft-password");
|
||||
await user.tab({ shift: true });
|
||||
await user.tab({ shift: true });
|
||||
expect(screen.getByRole("combobox", { name: "Change language" })).toHaveFocus();
|
||||
await user.keyboard("{Enter}");
|
||||
await screen.findByRole("listbox");
|
||||
@@ -474,7 +487,9 @@ describe("App layout", () => {
|
||||
|
||||
expect(await screen.findByRole("heading", { name: "连接到 nanobot" }))
|
||||
.toBeInTheDocument();
|
||||
expect(screen.getByLabelText("WebUI 密码")).toHaveValue("draft-password");
|
||||
const password = screen.getByLabelText("WebUI 密码");
|
||||
expect(password).toHaveValue("draft-password");
|
||||
expect(password).toHaveAttribute("placeholder", "WebUI 密码");
|
||||
expect(screen.getByRole("button", { name: "连接" })).toBeEnabled();
|
||||
expect(document.documentElement.lang).toBe("zh-CN");
|
||||
expect(localStorage.getItem("nanobot.locale")).toBe("zh-CN");
|
||||
@@ -482,7 +497,7 @@ describe("App layout", () => {
|
||||
expect(connectSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reveals password setup help with the keyboard without submitting the form", async () => {
|
||||
it("opens password help as a dialog without submitting or clearing the password draft", async () => {
|
||||
vi.mocked(fetchBootstrap).mockRejectedValueOnce(
|
||||
new Error("bootstrap failed: HTTP 401"),
|
||||
);
|
||||
@@ -492,26 +507,25 @@ describe("App layout", () => {
|
||||
|
||||
const password = await screen.findByLabelText("WebUI password");
|
||||
await user.type(password, "draft-password");
|
||||
await user.tab();
|
||||
await user.tab();
|
||||
await user.tab();
|
||||
const help = screen.getByRole("button", { name: "Where can I find the password?" });
|
||||
await user.tab({ shift: true });
|
||||
const helpTitle = "Where can I find the password?";
|
||||
const help = screen.getByRole("button", { name: helpTitle });
|
||||
expect(help).toHaveFocus();
|
||||
expect(help).toHaveAttribute("aria-expanded", "false");
|
||||
const content = document.getElementById(help.getAttribute("aria-controls")!);
|
||||
expect(content).toHaveAttribute("aria-hidden", "true");
|
||||
expect(await screen.findByRole("tooltip")).toHaveTextContent(helpTitle);
|
||||
|
||||
await user.keyboard("{Enter}");
|
||||
|
||||
expect(help).toHaveAttribute("aria-expanded", "true");
|
||||
expect(content).not.toHaveAttribute("aria-hidden");
|
||||
expect(content).toHaveTextContent("~/.nanobot/config.json");
|
||||
expect(content).toHaveTextContent("channels.websocket.tokenIssueSecret");
|
||||
expect(content).toHaveTextContent("If that value is empty, use channels.websocket.token.");
|
||||
const dialog = await screen.findByRole("dialog", { name: helpTitle });
|
||||
expect(dialog).toHaveFocus();
|
||||
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
|
||||
expect(dialog).toHaveTextContent("~/.nanobot/config.json");
|
||||
expect(dialog).toHaveTextContent("channels.websocket.tokenIssueSecret");
|
||||
expect(dialog).toHaveTextContent("If that value is empty, use channels.websocket.token.");
|
||||
|
||||
await user.keyboard(" ");
|
||||
await user.keyboard("{Escape}");
|
||||
|
||||
expect(help).toHaveAttribute("aria-expanded", "false");
|
||||
await waitFor(() => expect(help).toHaveFocus());
|
||||
expect(dialog).not.toBeInTheDocument();
|
||||
expect(password).toHaveValue("draft-password");
|
||||
expect(fetchBootstrap).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
@@ -557,17 +571,13 @@ describe("App layout", () => {
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(
|
||||
"Enter password",
|
||||
);
|
||||
expect(password).toHaveAttribute("placeholder", "Enter password");
|
||||
expect(password).toHaveAttribute("aria-invalid", "true");
|
||||
expect(password).toHaveAttribute(
|
||||
"aria-describedby",
|
||||
"webui-auth-error",
|
||||
);
|
||||
expect(password).toHaveAccessibleDescription("Enter password");
|
||||
expect(password).toHaveFocus();
|
||||
fireEvent.change(password, { target: { value: " " } });
|
||||
fireEvent.click(connect);
|
||||
expect(password).toHaveValue("");
|
||||
expect(password).toHaveAttribute("placeholder", "Enter password");
|
||||
expect(password).toHaveAccessibleDescription("Enter password");
|
||||
expect(fetchBootstrap).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -586,34 +596,47 @@ describe("App layout", () => {
|
||||
expect(connectSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows an invalid-password error after a submitted password is rejected", async () => {
|
||||
vi.mocked(fetchBootstrap).mockRejectedValue(
|
||||
new Error("bootstrap failed: HTTP 401"),
|
||||
);
|
||||
it("keeps the sign-in form mounted during submission and refocuses it on rejection", async () => {
|
||||
let rejectAttempt!: (error: Error) => void;
|
||||
vi.mocked(fetchBootstrap)
|
||||
.mockRejectedValueOnce(new Error("bootstrap failed: HTTP 401"))
|
||||
.mockReturnValueOnce(new Promise((_, reject) => { rejectAttempt = reject; }));
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<App />);
|
||||
|
||||
const password = await screen.findByLabelText("WebUI password");
|
||||
fireEvent.change(password, { target: { value: "wrong-password" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
|
||||
const submit = screen.getByRole("button", { name: "Connect" });
|
||||
await user.type(password, "wrong-password");
|
||||
await user.click(screen.getByRole("button", { name: "Show password" }));
|
||||
await user.click(submit);
|
||||
|
||||
const retryPassword = await screen.findByLabelText("WebUI password");
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(
|
||||
"Incorrect password",
|
||||
);
|
||||
expect(retryPassword).toHaveAttribute("placeholder", "Incorrect password");
|
||||
expect(retryPassword).toHaveValue("");
|
||||
expect(retryPassword).toHaveAttribute("aria-invalid", "true");
|
||||
expect(retryPassword).toHaveFocus();
|
||||
expect(screen.getByLabelText("WebUI password")).toBe(password);
|
||||
expect(submit).toBeDisabled();
|
||||
expect(submit).toHaveAttribute("aria-busy", "true");
|
||||
expect(password).toHaveAttribute("readonly");
|
||||
expect(fetchBootstrap).toHaveBeenCalledTimes(2);
|
||||
expect(fetchBootstrap).toHaveBeenLastCalledWith("", "wrong-password");
|
||||
|
||||
await act(async () => rejectAttempt(new Error("bootstrap failed: HTTP 401")));
|
||||
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Incorrect password");
|
||||
expect(screen.getByLabelText("WebUI password")).toBe(password);
|
||||
expect(submit).toBeEnabled();
|
||||
expect(password).toHaveAccessibleDescription("Incorrect password");
|
||||
expect(password).toHaveValue("");
|
||||
expect(password).toHaveAttribute("type", "password");
|
||||
expect(password).toHaveAttribute("aria-invalid", "true");
|
||||
expect(password).toHaveFocus();
|
||||
expect(connectSpy).not.toHaveBeenCalled();
|
||||
fireEvent.change(retryPassword, { target: { value: "retry-password" } });
|
||||
expect(retryPassword).not.toHaveAttribute("placeholder");
|
||||
expect(retryPassword).not.toHaveAttribute("aria-invalid");
|
||||
await user.type(password, "retry-password");
|
||||
expect(password).toHaveValue("retry-password");
|
||||
expect(password).not.toHaveAccessibleDescription();
|
||||
expect(password).not.toHaveAttribute("aria-invalid");
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("clears auth feedback after three seconds without moving focus", async () => {
|
||||
it("keeps auth errors on the password field while the user waits", async () => {
|
||||
vi.mocked(fetchBootstrap).mockRejectedValue(
|
||||
new Error("bootstrap failed: HTTP 401"),
|
||||
);
|
||||
@@ -622,9 +645,9 @@ describe("App layout", () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
|
||||
expect(password).toHaveAttribute("placeholder", "Enter password");
|
||||
act(() => vi.advanceTimersByTime(3_000));
|
||||
expect(password).not.toHaveAttribute("placeholder");
|
||||
act(() => vi.advanceTimersByTime(5_000));
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Enter password");
|
||||
expect(password).toHaveAccessibleDescription("Enter password");
|
||||
expect(password).toHaveFocus();
|
||||
|
||||
await act(async () => {
|
||||
@@ -632,13 +655,10 @@ describe("App layout", () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
|
||||
});
|
||||
const retryPassword = screen.getByLabelText("WebUI password");
|
||||
expect(retryPassword).toHaveAttribute("placeholder", "Incorrect password");
|
||||
act(() => vi.advanceTimersByTime(2_999));
|
||||
expect(retryPassword).toHaveAttribute("placeholder", "Incorrect password");
|
||||
act(() => vi.advanceTimersByTime(1));
|
||||
expect(retryPassword).not.toHaveAttribute("placeholder");
|
||||
expect(retryPassword).not.toHaveAttribute("aria-invalid");
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
act(() => vi.advanceTimersByTime(5_000));
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Incorrect password");
|
||||
expect(retryPassword).toHaveAccessibleDescription("Incorrect password");
|
||||
expect(retryPassword).toHaveAttribute("aria-invalid", "true");
|
||||
expect(retryPassword).toHaveFocus();
|
||||
});
|
||||
|
||||
@@ -2468,23 +2488,27 @@ describe("App layout", () => {
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText("Delete this topic?")).toBeInTheDocument(),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-a"),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
within(sidebar).getByRole("button", { name: /^Second chat$/ }),
|
||||
).toBeInTheDocument(),
|
||||
);
|
||||
vi.useFakeTimers();
|
||||
await confirmTopicDeletion(screen.getByRole("button", { name: "Delete" }));
|
||||
expect(screen.getByText("Topic will be deleted")).toBeVisible();
|
||||
expect(within(sidebar).queryByRole("button", { name: /^First chat$/ })).not.toBeInTheDocument();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS - 1); });
|
||||
expect(deleteChatSpy).not.toHaveBeenCalled();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
|
||||
vi.useRealTimers();
|
||||
expect(deleteChatSpy).toHaveBeenCalledTimes(1);
|
||||
expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-a");
|
||||
expect(within(sidebar).getByRole("button", { name: /^Second chat$/ })).toBeInTheDocument();
|
||||
expect(screen.queryByText("Delete this topic?")).not.toBeInTheDocument();
|
||||
expect(document.body.style.pointerEvents).not.toBe("none");
|
||||
|
||||
fireEvent.pointerDown(screen.getByLabelText("Topic actions for Second chat"), { button: 0 });
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" }));
|
||||
fireEvent.click(within(await screen.findByRole("alertdialog")).getByRole("button", { name: "Delete" }));
|
||||
await waitFor(() => expect(screen.getByTestId("host-sidebar-flow")).toHaveStyle({ width: "56px" }));
|
||||
const lastDelete = await screen.findByRole("alertdialog", { name: "Delete this topic?" });
|
||||
vi.useFakeTimers();
|
||||
await confirmTopicDeletion(within(lastDelete).getByRole("button", { name: "Delete" }));
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
|
||||
expect(screen.getByTestId("host-sidebar-flow")).toHaveStyle({ width: "56px" });
|
||||
}, 15_000);
|
||||
|
||||
it.each([false, true])("archives only persisted selected topics in one sidebar update (draft=%s)", async (includeDraft) => {
|
||||
@@ -2523,9 +2547,68 @@ describe("App layout", () => {
|
||||
if (includeDraft) expect(within(sidebar).getByRole("button", { name: "Topic a" })).toBeInTheDocument();
|
||||
else expect(within(sidebar).queryByRole("button", { name: "Topic a" })).not.toBeInTheDocument();
|
||||
expect(within(sidebar).queryByRole("button", { name: "Topic b" })).not.toBeInTheDocument();
|
||||
const fallback = window.location.hash;
|
||||
const undo = await screen.findByRole("button", { name: "Undo" });
|
||||
expect(screen.getByText(includeDraft ? "Topic archived" : "2 topics archived")).toBeVisible();
|
||||
fireEvent.click(undo);
|
||||
await waitFor(() => expect(setSidebarStateSpy).toHaveBeenCalledTimes(2));
|
||||
expect(setSidebarStateSpy).toHaveBeenLastCalledWith(expect.objectContaining({
|
||||
archived_keys: [], pinned_keys: ["websocket:chat-a", "websocket:chat-b"],
|
||||
}));
|
||||
expect(within(sidebar).getByRole("button", { name: "Topic b" })).toBeInTheDocument();
|
||||
expect(window.location.hash).toBe(fallback);
|
||||
expect(deleteChatSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the topic and reports archive failure instead of retrying it silently", async () => {
|
||||
const key = "websocket:chat-a";
|
||||
mockSessions = [{
|
||||
key, channel: "websocket", chatId: "chat-a", title: "Review notes", preview: "",
|
||||
createdAt: "2026-04-16T10:00:00Z", updatedAt: "2026-04-16T10:00:00Z",
|
||||
}];
|
||||
mockFetchRoutes({ "/api/webui/sidebar-state": { pinned_keys: [key] } });
|
||||
let rejectSave!: (error: Error) => void;
|
||||
setSidebarStateSpy.mockImplementationOnce(() => new Promise((_resolve, reject) => { rejectSave = reject; }));
|
||||
render(<App />);
|
||||
const sidebar = await screen.findByRole("navigation", { name: "Sidebar navigation" });
|
||||
act(() => statusHandlers.forEach((handler) => handler("open")));
|
||||
fireEvent.pointerDown(await within(sidebar).findByLabelText("Topic actions for Review notes"), { button: 0 });
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Archive" }));
|
||||
await waitFor(() => expect(setSidebarStateSpy).toHaveBeenCalledTimes(1));
|
||||
expect(within(sidebar).getByRole("button", { name: "Review notes" })).toBeVisible();
|
||||
expect(screen.queryByText("Topic archived")).not.toBeInTheDocument();
|
||||
await act(async () => rejectSave(new Error("Disk full")));
|
||||
expect(await screen.findByText("Could not change archive status.")).toBeVisible();
|
||||
expect(within(sidebar).getByRole("button", { name: "Review notes" })).toBeVisible();
|
||||
expect(screen.queryByRole("button", { name: "Undo" })).not.toBeInTheDocument();
|
||||
act(() => statusHandlers.forEach((handler) => { handler("reconnecting"); handler("open"); }));
|
||||
expect(setSidebarStateSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([["a", "b"], ["b", "a"]])("restores pin order when undoing archives in %s, %s order", async (first, second) => {
|
||||
const keys = ["a", "b", "c"].map((id) => `websocket:chat-${id}`);
|
||||
mockSessions = ["a", "b", "c"].map((id, index) => ({
|
||||
key: keys[index], channel: "websocket", chatId: `chat-${id}`, title: `Topic ${id}`, preview: "",
|
||||
createdAt: "2026-04-16T10:00:00Z", updatedAt: "2026-04-16T10:00:00Z",
|
||||
}));
|
||||
mockFetchRoutes({ "/api/webui/sidebar-state": { pinned_keys: keys } });
|
||||
render(<App />);
|
||||
const sidebar = await screen.findByRole("navigation", { name: "Sidebar navigation" });
|
||||
act(() => statusHandlers.forEach((handler) => handler("open")));
|
||||
for (const id of ["a", "b"]) {
|
||||
fireEvent.pointerDown(await within(sidebar).findByLabelText(`Topic actions for Topic ${id}`), { button: 0 });
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Archive" }));
|
||||
await waitFor(() => expect(within(sidebar).queryByRole("button", { name: `Topic ${id}` })).not.toBeInTheDocument());
|
||||
}
|
||||
for (const id of [first, second]) {
|
||||
const card = screen.getByText(`Topic ${id}`, { selector: '[role="status"] span' }).closest<HTMLElement>("[data-toast-tone]")!;
|
||||
fireEvent.click(within(card).getByRole("button", { name: "Undo" }));
|
||||
await within(sidebar).findByRole("button", { name: `Topic ${id}` });
|
||||
}
|
||||
expect(setSidebarStateSpy).toHaveBeenCalledTimes(4);
|
||||
expect(setSidebarStateSpy).toHaveBeenLastCalledWith(expect.objectContaining({ pinned_keys: keys, archived_keys: [] }));
|
||||
});
|
||||
|
||||
it("deletes multiple selected topics through one confirmation", async () => {
|
||||
mockSessions = [
|
||||
{
|
||||
@@ -2580,10 +2663,14 @@ describe("App layout", () => {
|
||||
getSessionAutomationsSpy.mockResolvedValue([]);
|
||||
fireEvent.click(within(sidebar).getByRole("button", { name: "Delete" }));
|
||||
expect(await screen.findByText("Delete 2 conversations?")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
|
||||
vi.useFakeTimers();
|
||||
await confirmTopicDeletion(screen.getByRole("button", { name: "Delete" }));
|
||||
expect(screen.queryByTestId("delete-selection-bar")).not.toBeInTheDocument();
|
||||
|
||||
await waitFor(() => expect(deleteChatSpy).toHaveBeenCalledTimes(2));
|
||||
expect(screen.getByText("2 topics will be deleted")).toBeVisible();
|
||||
expect(screen.getAllByRole("button", { name: "Undo" })).toHaveLength(1);
|
||||
expect(deleteChatSpy).not.toHaveBeenCalled();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
|
||||
expect(deleteChatSpy).toHaveBeenCalledTimes(2);
|
||||
expect(deleteChatSpy.mock.calls.map(([key]) => key)).toEqual([
|
||||
"websocket:chat-a",
|
||||
"websocket:chat-b",
|
||||
@@ -2594,6 +2681,73 @@ describe("App layout", () => {
|
||||
.toBeInTheDocument();
|
||||
}, 15_000);
|
||||
|
||||
it.each(["undo", "failure", "unmount"] as const)("handles pending topic deletion on %s", async (outcome) => {
|
||||
mockSessions = ["Review notes", "Release notes"].map((title, index) => ({
|
||||
key: `websocket:chat-${index}`,
|
||||
channel: "websocket",
|
||||
chatId: `chat-${index}`,
|
||||
createdAt: "2026-04-16T10:00:00Z",
|
||||
updatedAt: "2026-04-16T10:00:00Z",
|
||||
title,
|
||||
preview: "",
|
||||
}));
|
||||
if (outcome === "failure") deleteChatSpy.mockRejectedValueOnce(new Error("Offline"));
|
||||
const { unmount } = render(<App />);
|
||||
const sidebar = await screen.findByRole("navigation", { name: "Sidebar navigation" });
|
||||
fireEvent.pointerDown(await within(sidebar).findByLabelText("Topic actions for Review notes"), { button: 0 });
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" }));
|
||||
expect(await screen.findByRole("alertdialog", { name: "Delete this topic?" })).toBeVisible();
|
||||
vi.useFakeTimers();
|
||||
await confirmTopicDeletion(screen.getByRole("button", { name: "Delete" }));
|
||||
expect(within(sidebar).queryByRole("button", { name: "Review notes" })).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Topic will be deleted").closest('[role="status"]')).toHaveTextContent("Review notes");
|
||||
expect(deleteChatSpy).not.toHaveBeenCalled();
|
||||
|
||||
if (outcome === "undo") fireEvent.click(screen.getByRole("button", { name: "Undo" }));
|
||||
if (outcome === "unmount") unmount();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
|
||||
|
||||
if (outcome === "failure") {
|
||||
expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-0");
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Could not delete the topic");
|
||||
} else {
|
||||
expect(deleteChatSpy).not.toHaveBeenCalled();
|
||||
}
|
||||
if (outcome !== "unmount") {
|
||||
expect(within(sidebar).getByRole("button", { name: "Review notes" })).toBeVisible();
|
||||
}
|
||||
});
|
||||
|
||||
it("asks again only for the topic whose automations appeared during the delete window", async () => {
|
||||
mockSessions = ["a", "b"].map((id) => ({
|
||||
key: `websocket:chat-${id}`, channel: "websocket", chatId: `chat-${id}`, title: `Topic ${id}`, preview: "",
|
||||
createdAt: "2026-04-16T10:00:00Z", updatedAt: "2026-04-16T10:00:00Z",
|
||||
}));
|
||||
const job: SessionAutomationJob = {
|
||||
id: "late-job", name: "Added during undo", enabled: true,
|
||||
schedule: { kind: "every", every_ms: 86_400_000 }, payload: { message: "Check the repo" }, state: {},
|
||||
};
|
||||
deleteChatSpy.mockResolvedValueOnce({ deleted: true })
|
||||
.mockResolvedValueOnce({ deleted: false, blocked_by_automations: true, automations: [job] });
|
||||
render(<App />);
|
||||
const sidebar = await screen.findByRole("navigation", { name: "Sidebar navigation" });
|
||||
fireEvent.pointerDown(await within(sidebar).findByLabelText("Topic actions for Topic a"), { button: 0 });
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Select" }));
|
||||
fireEvent.click(within(sidebar).getByRole("button", { name: "Topic b" }));
|
||||
fireEvent.click(within(sidebar).getByRole("button", { name: "Delete" }));
|
||||
const initial = await screen.findByRole("alertdialog", { name: "Delete 2 conversations?" });
|
||||
vi.useFakeTimers();
|
||||
await confirmTopicDeletion(within(initial).getByRole("button", { name: "Delete" }));
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
|
||||
expect(deleteChatSpy.mock.calls).toEqual([["websocket:chat-a"], ["websocket:chat-b"]]);
|
||||
const retry = screen.getByRole("alertdialog", { name: "Delete this topic?" });
|
||||
expect(within(retry).getByText("Added during undo")).toBeVisible();
|
||||
await confirmTopicDeletion(within(retry).getByRole("button", { name: "Delete" }));
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
|
||||
expect(deleteChatSpy).toHaveBeenCalledTimes(3);
|
||||
expect(deleteChatSpy).toHaveBeenLastCalledWith("websocket:chat-b", { deleteAutomations: true });
|
||||
}, 15_000);
|
||||
|
||||
it("shows localized bound automations in the first delete confirmation", async () => {
|
||||
mockSessions = [
|
||||
{
|
||||
@@ -2651,13 +2805,11 @@ describe("App layout", () => {
|
||||
screen.queryByText("Deleting this topic also deletes its linked automations."),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "删除" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-a", {
|
||||
deleteAutomations: true,
|
||||
}),
|
||||
);
|
||||
vi.useFakeTimers();
|
||||
await confirmTopicDeletion(screen.getByRole("button", { name: "删除" }));
|
||||
expect(deleteChatSpy).not.toHaveBeenCalled();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
|
||||
expect(deleteChatSpy).toHaveBeenCalledWith("websocket:chat-a", { deleteAutomations: true });
|
||||
expect(deleteChatSpy).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByText("Daily repo check")).not.toBeInTheDocument();
|
||||
}, 15_000);
|
||||
@@ -4427,15 +4579,18 @@ describe("App layout", () => {
|
||||
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
|
||||
expect(await within(sidebar).findByRole("button", { name: "Group: Research" }))
|
||||
.toBeInTheDocument();
|
||||
expect((await screen.findByTestId("pane-grid")).children).toHaveLength(2);
|
||||
fireEvent.pointerDown(within(sidebar).getByRole("button", {
|
||||
name: "New topic pane actions",
|
||||
}), { button: 0, ctrlKey: false });
|
||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" }));
|
||||
expect(await screen.findByText("Delete this topic?")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
|
||||
vi.useFakeTimers();
|
||||
await confirmTopicDeletion(screen.getByRole("button", { name: "Delete" }));
|
||||
|
||||
await waitFor(() => expect(deleteChatSpy).toHaveBeenCalledWith("websocket:new-pane"));
|
||||
await waitFor(() => expect(window.location.hash).toBe("#/chat/websocket%3Aalpha"));
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(TOAST_ACTION_MS); });
|
||||
expect(deleteChatSpy).toHaveBeenCalledWith("websocket:new-pane");
|
||||
expect(window.location.hash).toBe("#/chat/websocket%3Aalpha");
|
||||
expect(within(sidebar).getByRole("button", { name: "Group: Research" }))
|
||||
.toBeInTheDocument();
|
||||
expect(screen.getByTestId("pane-grid").children).toHaveLength(1);
|
||||
|
||||
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { FileActions, FileActionsProvider } from "@/components/FileActions";
|
||||
import { FileReferenceChip } from "@/components/FileReferenceChip";
|
||||
import { ToastProvider } from "@/components/ui/toast";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import type { FileReferenceMetadata } from "@/lib/types";
|
||||
|
||||
@@ -84,6 +85,25 @@ describe("File actions", () => {
|
||||
expect(await screen.findByText("Could not copy. Please try again.")).toBeVisible();
|
||||
});
|
||||
|
||||
it("coalesces repeated file copy success into one toast and makes the failure alert accessible", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<ToastProvider><FileActions path="notes.md" metadata={details}><button>notes.md</button></FileActions></ToastProvider>);
|
||||
const reference = screen.getByRole("button", { name: "notes.md" });
|
||||
for (let i = 0; i < 2; i++) {
|
||||
fireEvent.contextMenu(reference);
|
||||
await user.click(screen.getByRole("menuitem", { name: "Copy absolute path" }));
|
||||
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
||||
expect(screen.getAllByRole("status")).toHaveLength(1);
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Copied");
|
||||
}
|
||||
vi.mocked(copyTextToClipboard).mockResolvedValueOnce(false);
|
||||
fireEvent.contextMenu(reference);
|
||||
await user.click(screen.getByRole("menuitem", { name: "Copy absolute path" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not copy. Please try again.");
|
||||
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
|
||||
expect(reference).toHaveFocus();
|
||||
});
|
||||
|
||||
it("ignores late metadata from a previous session", async () => {
|
||||
const user = userEvent.setup();
|
||||
let resolveOld!: (value: FileReferenceMetadata) => void;
|
||||
|
||||
@@ -4,6 +4,7 @@ import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { MessageBlockMenuActions, MessageBubble } from "@/components/MessageBubble";
|
||||
import { preloadMarkdownText } from "@/components/MarkdownText";
|
||||
import { ThreadMessages } from "@/components/thread/ThreadMessages";
|
||||
import { ToastProvider } from "@/components/ui/toast";
|
||||
import { setAppLanguage } from "@/i18n";
|
||||
import { parseWebuiThreadPayload } from "@/lib/api";
|
||||
import * as clipboard from "@/lib/clipboard";
|
||||
@@ -995,6 +996,22 @@ describe("MessageBubble", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("announces clipboard failure and leaves Copy available for another attempt", async () => {
|
||||
const copy = vi.spyOn(clipboard, "copyTextToClipboard").mockResolvedValue(false);
|
||||
try {
|
||||
const message: UIMessage = { id: "copy-failed", role: "assistant", content: "A reply", createdAt: 1 };
|
||||
const { container } = render(<MessageBlockMenuActions message={message} />, { wrapper: ToastProvider });
|
||||
menuActions(container);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Copy" }));
|
||||
const alert = await screen.findByRole("alert");
|
||||
expect(alert.closest("[data-toast-tone=error]")).not.toBeNull();
|
||||
expect(alert).toHaveTextContent("Could not copy. Please try again.");
|
||||
expect(screen.getByRole("button", { name: "Copy" })).toBeEnabled();
|
||||
} finally {
|
||||
copy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("copies completed assistant replies with the textarea fallback", async () => {
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
configurable: true,
|
||||
|
||||
@@ -4,6 +4,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { RemoteInstances } from "@/components/remote/RemoteInstances";
|
||||
import { useRemoteConnections } from "@/components/remote/remote-context";
|
||||
import { RemoteConnectionsPage } from "@/components/remote/RemoteConnectionsPage";
|
||||
import { PairingCodePopup } from "@/components/pairing/PairingCodePopup";
|
||||
import { ToastProvider } from "@/components/ui/toast";
|
||||
import { Sidebar } from "@/components/Sidebar";
|
||||
import { HOST_BRIDGE } from "@/components/remote/host-bridge";
|
||||
import { readSelectedRemote, readRecentRemotes, rememberSelectedRemote, validateRemoteConnection, type RemoteConnection } from "@/lib/remote-instances";
|
||||
@@ -157,6 +159,28 @@ describe("remote instance UX", () => {
|
||||
expect(mocks.request).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(["toast", "no provider", "pairing popup"])("reports an attempt to open the local gateway (%s)", async (surface) => {
|
||||
mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, paired: true }] });
|
||||
mocks.request.mockRejectedValueOnce(new Error("same_instance"));
|
||||
const shell = <>
|
||||
<LocalShell initialRemote />
|
||||
{surface === "pairing popup" && <PairingCodePopup
|
||||
requests={[{ code: "ABCD-EFGH", channel: "telegram", sender_id: "alice" }]}
|
||||
total={1} busyCode={null} error={null} onApprove={noop} onDismiss={noop} />}
|
||||
</>;
|
||||
render(<RemoteInstances>{surface === "no provider" ? shell : <ToastProvider>{shell}</ToastProvider>}</RemoteInstances>);
|
||||
|
||||
const directory = await screen.findByRole("region", { name: i18n.t("remote.title") });
|
||||
const server = await within(directory).findByRole("button", { name: "Team server ubuntu@example.test" });
|
||||
fireEvent.click(server);
|
||||
const alert = await screen.findByRole("alert");
|
||||
expect(alert).toHaveTextContent(i18n.t("remote.errors.same_instance"));
|
||||
if (surface === "toast") expect(alert.closest("[data-toast-tone]")).toHaveAttribute("data-toast-tone", "error");
|
||||
else expect(within(directory).getByRole("alert")).toBe(alert);
|
||||
expect(server).toBeEnabled();
|
||||
expect(readSelectedRemote()).toBeNull();
|
||||
});
|
||||
|
||||
it.each([false, true])("renames an open server without reloading its view (paired: %s)", async (paired) => {
|
||||
let saved = { ...profile, paired, connected: true };
|
||||
mocks.read.mockImplementation(async () => ({ available: true, profiles: [saved] }));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { act, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -156,7 +156,9 @@ describe("SessionInfoPopover", () => {
|
||||
expect(within(detail).getByRole("button", { name: "More actions" })).toHaveFocus();
|
||||
});
|
||||
|
||||
it("returns from the shared editor to the same task detail", async () => {
|
||||
it("blocks Escape and outside clicks while saving, then keeps the error and draft in the editor", async () => {
|
||||
let failSave!: (error: Error) => void;
|
||||
requestMutation.mockImplementationOnce(() => new Promise((_, reject) => { failSave = reject; }));
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<SessionInfoPopover
|
||||
@@ -171,12 +173,54 @@ describe("SessionInfoPopover", () => {
|
||||
await user.click(await screen.findByRole("button", { name: "Edit" }));
|
||||
const editor = await screen.findByRole("dialog", { name: "Edit task" });
|
||||
expect(screen.getAllByRole("dialog")).toHaveLength(1);
|
||||
const name = within(editor).getByRole("textbox", { name: "Name" });
|
||||
await user.clear(name);
|
||||
await user.type(name, "Edited task name");
|
||||
const save = within(editor).getByRole("button", { name: "Save" });
|
||||
await user.click(save);
|
||||
expect(save).toBeDisabled();
|
||||
await user.keyboard("{Escape}");
|
||||
expect(editor).toBeVisible();
|
||||
fireEvent.pointerDown(editor.closest("[data-dialog-backdrop]")!);
|
||||
expect(editor).toBeVisible();
|
||||
|
||||
await act(async () => failSave(new Error("Could not save schedule")));
|
||||
expect(await within(editor).findByRole("alert")).toHaveTextContent("Could not save schedule");
|
||||
expect(save).toBeEnabled();
|
||||
expect(name).toHaveValue("Edited task name");
|
||||
await user.click(within(editor).getByRole("button", { name: "Cancel" }));
|
||||
|
||||
expect(await screen.findByRole("dialog", { name: "Morning check" })).toBeVisible();
|
||||
expect(screen.getAllByRole("dialog")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps the delete confirmation open until the request settles so failures can be retried", async () => {
|
||||
let failDelete!: (error: Error) => void;
|
||||
requestMutation.mockImplementationOnce(() => new Promise((_, reject) => { failDelete = reject; }));
|
||||
const user = userEvent.setup();
|
||||
render(<SessionInfoPopover client={client} sessionKey="websocket:chat-1" token="tok" />);
|
||||
await user.click(screen.getByRole("button", { name: "Session details" }));
|
||||
await user.click(await screen.findByRole("button", { name: /Morning check/ }));
|
||||
const detail = await screen.findByRole("dialog", { name: "Morning check" });
|
||||
await user.click(within(detail).getByRole("button", { name: "More actions" }));
|
||||
await user.click(screen.getByRole("menuitem", { name: "Delete" }));
|
||||
const confirmation = await screen.findByRole("dialog", { name: "Delete automation" });
|
||||
const remove = within(confirmation).getByRole("button", { name: "Delete" });
|
||||
await user.click(remove);
|
||||
expect(remove).toBeDisabled();
|
||||
fireEvent.pointerDown(confirmation.closest("[data-dialog-backdrop]")!);
|
||||
expect(confirmation).toBeVisible();
|
||||
await user.keyboard("{Escape}");
|
||||
expect(confirmation).toBeVisible();
|
||||
|
||||
await act(async () => failDelete(new Error("Could not delete schedule")));
|
||||
expect(within(confirmation).getByRole("alert")).toHaveTextContent("Could not delete schedule");
|
||||
expect(remove).toBeEnabled();
|
||||
requestMutation.mockResolvedValueOnce({ jobs: [] });
|
||||
await user.click(remove);
|
||||
await waitFor(() => expect(confirmation).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("localizes the panel chrome in Simplified Chinese", async () => {
|
||||
await setAppLanguage("zh-CN");
|
||||
const user = userEvent.setup();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { act, cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { ApiError } from "@/lib/api";
|
||||
import type { ProviderModelsPayload, SettingsPayload } from "@/lib/types";
|
||||
import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView as renderSettingsViewBase, openPopover, installSettingsViewTestHooks } from "@/tests/settings-test-utils";
|
||||
|
||||
@@ -827,12 +828,12 @@ describe("Settings models", () => {
|
||||
it.each([true, false])("closes the preset editor only after deletion succeeds (success: %s)", async (success) => {
|
||||
const { payload } = settingsPayloadWithBackup();
|
||||
vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>(() => {})));
|
||||
if (success) requestMutationMock.mockResolvedValueOnce({
|
||||
...payload,
|
||||
model_presets: payload.model_presets.filter((preset) => preset.name !== "backup"),
|
||||
model_call_order: ["primary"],
|
||||
});
|
||||
else requestMutationMock.mockRejectedValueOnce(new Error("Delete failed"));
|
||||
let finishDelete!: (value: SettingsPayload) => void;
|
||||
let failDelete!: (error: Error) => void;
|
||||
requestMutationMock.mockImplementationOnce(() => new Promise<SettingsPayload>((resolve, reject) => {
|
||||
finishDelete = resolve;
|
||||
failDelete = reject;
|
||||
}));
|
||||
renderSettingsView({ initialSection: "models", initialSettings: payload });
|
||||
fireEvent.click(within(screen.getByTestId("model-call-order-row-backup")).getByRole("button", { name: "Configure" }));
|
||||
fireEvent.click(within(screen.getByTestId("model-preset-editor")).getByRole("button", { name: "Delete" }));
|
||||
@@ -841,11 +842,23 @@ describe("Settings models", () => {
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.delete", { name: "backup" }, 20_000,
|
||||
));
|
||||
expect(within(confirmation).getByRole("button", { name: /Deleting/ })).toBeDisabled();
|
||||
fireEvent.keyDown(confirmation, { key: "Escape" });
|
||||
expect(confirmation).toBeVisible();
|
||||
fireEvent.pointerDown(confirmation.closest("[data-dialog-backdrop]")!);
|
||||
expect(confirmation).toBeVisible();
|
||||
if (success) {
|
||||
await act(async () => finishDelete({
|
||||
...payload,
|
||||
model_presets: payload.model_presets.filter((preset) => preset.name !== "backup"),
|
||||
model_call_order: ["primary"],
|
||||
}));
|
||||
await waitFor(() => expect(screen.queryByTestId("model-preset-editor")).not.toBeInTheDocument());
|
||||
expect(screen.queryByTestId("model-call-order-row-backup")).not.toBeInTheDocument();
|
||||
} else {
|
||||
await waitFor(() => expect(within(confirmation).getByRole("button", { name: "Delete" })).toBeEnabled());
|
||||
await act(async () => failDelete(new Error("Delete failed")));
|
||||
expect(await within(confirmation).findByRole("alert")).toHaveTextContent("Delete failed");
|
||||
expect(within(confirmation).getByRole("button", { name: "Delete" })).toBeEnabled();
|
||||
expect(screen.getByTestId("model-preset-editor")).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
@@ -1098,7 +1111,7 @@ describe("Settings models", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("restores the model call order when immediate persistence fails", async () => {
|
||||
it("restores the model call order and announces a transient save failure", async () => {
|
||||
const { payload } = settingsPayloadWithBackup();
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
@@ -1112,7 +1125,7 @@ describe("Settings models", () => {
|
||||
return { ok: false, status: 404, json: async () => ({}) } as Response;
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
requestMutationMock.mockRejectedValueOnce(new Error("Order update failed"));
|
||||
requestMutationMock.mockRejectedValueOnce(new ApiError(503, "WebUI connection is not open"));
|
||||
|
||||
renderSettingsView({ initialSection: "models", initialSettings: payload });
|
||||
|
||||
@@ -1128,7 +1141,7 @@ describe("Settings models", () => {
|
||||
key: "ArrowUp",
|
||||
});
|
||||
|
||||
expect(await screen.findByText("Order update failed")).toBeInTheDocument();
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not update agent settings");
|
||||
expect(
|
||||
screen
|
||||
.getAllByTestId(/^model-call-order-row-/)
|
||||
|
||||
@@ -80,6 +80,35 @@ describe("Settings system domains", () => {
|
||||
expect(restart).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("announces transient desktop utility failures once per action and keeps the exported path", async () => {
|
||||
const openLogs = vi.fn().mockRejectedValue(new Error("Host could not open the folder"));
|
||||
const exportDiagnostics = vi.fn().mockRejectedValueOnce(new Error("Host could not export"))
|
||||
.mockResolvedValueOnce("/diagnostics/report.zip");
|
||||
vi.stubGlobal("nanobotHost", { openLogs, exportDiagnostics });
|
||||
renderSettingsView({ initialSection: "runtime", initialSettings: {
|
||||
...settingsPayload(), surface: "native",
|
||||
runtime_capabilities: { can_restart_engine: false, can_open_logs: true, can_export_diagnostics: true },
|
||||
} });
|
||||
|
||||
const open = screen.getByRole("button", { name: "Open" });
|
||||
for (const attempts of [1, 2]) {
|
||||
fireEvent.click(open);
|
||||
await waitFor(() => expect(open).toBeEnabled());
|
||||
expect(openLogs).toHaveBeenCalledTimes(attempts);
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Could not open logs folder.");
|
||||
expect(screen.getAllByText("Could not open logs folder.")).toHaveLength(1);
|
||||
}
|
||||
|
||||
const exportButton = screen.getByRole("button", { name: "Export" });
|
||||
fireEvent.click(exportButton);
|
||||
await waitFor(() => expect(exportButton).toBeEnabled());
|
||||
expect(screen.getAllByRole("alert").map((alert) => alert.textContent)).toContain("Could not export diagnostics.");
|
||||
expect(screen.getAllByText("Could not export diagnostics.")).toHaveLength(1);
|
||||
fireEvent.click(exportButton);
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Diagnostics" }));
|
||||
expect(await screen.findByRole("tooltip")).toHaveTextContent("Diagnostics exported to /diagnostics/report.zip.");
|
||||
});
|
||||
|
||||
it("leaves directly when no restart is pending", () => {
|
||||
const leave = vi.fn();
|
||||
renderSettingsView({ initialSection: "runtime", initialSettings: settingsPayload(), onBackToChat: leave });
|
||||
@@ -574,6 +603,28 @@ describe("Settings system domains", () => {
|
||||
expect(fetchMock.mock.calls.filter(([url]) => String(url) === "/api/settings/cli-apps")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("announces when copying an installed app's example prompt fails", async () => {
|
||||
const writeText = vi.fn().mockRejectedValue(new Error("Clipboard blocked"));
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
|
||||
try {
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (String(input) === "/api/settings/cli-apps") {
|
||||
return jsonResponse({ apps: [{ ...installedAnyGen, installed: false }], installed_count: 0 });
|
||||
}
|
||||
if (String(input) === "/api/settings/mcp-presets") return jsonResponse({ presets: [], installed_count: 0 });
|
||||
return jsonResponse(settingsPayload());
|
||||
}));
|
||||
requestMutationMock.mockResolvedValue({ apps: [installedAnyGen], installed_count: 1 });
|
||||
renderSettingsView({ initialSection: "apps" });
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Install app" }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Try @anygen" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Could not copy. Please try again.");
|
||||
expect(writeText).toHaveBeenCalledWith("Ask nanobot to use @anygen for this task.");
|
||||
} finally {
|
||||
Reflect.deleteProperty(navigator, "clipboard");
|
||||
}
|
||||
});
|
||||
|
||||
it("shows a visible uninstall button for installed CLI apps and calls uninstall", async () => {
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { cleanup, render, screen, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, beforeEach, vi } from "vitest";
|
||||
import { SettingsView } from "@/components/settings/SettingsView";
|
||||
import { ToastProvider } from "@/components/ui/toast";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
import type { SettingsPayload } from "@/lib/types";
|
||||
import type { NanobotClient } from "@/lib/nanobot-client";
|
||||
@@ -164,6 +165,7 @@ export function renderSettingsView(options: SettingsViewTestOptions = {}) {
|
||||
onRestart={options.onRestart}
|
||||
/>
|
||||
</ClientProvider>,
|
||||
{ wrapper: ToastProvider },
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import userEvent from "@testing-library/user-event";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ThreadComposer } from "@/components/thread/ThreadComposer";
|
||||
import { ToastProvider } from "@/components/ui/toast";
|
||||
import { ComposerDraftStore } from "@/lib/composer-draft";
|
||||
import type { EncodeResponse } from "@/lib/imageEncode";
|
||||
import type { WebUIIngressLimits } from "@/lib/types";
|
||||
@@ -216,7 +217,7 @@ describe("ThreadComposer — attachments", () => {
|
||||
const file = new File([], "empty.csv", { type: "application/vnd.ms-excel" });
|
||||
const onSend = vi.fn();
|
||||
|
||||
render(<ThreadComposer onSend={onSend} />);
|
||||
render(<ThreadComposer onSend={onSend} />, { wrapper: ToastProvider });
|
||||
|
||||
const input = screen
|
||||
.getByLabelText(/message input/i)
|
||||
@@ -227,7 +228,9 @@ describe("ThreadComposer — attachments", () => {
|
||||
fireEvent.change(input, { target: { files: [file] } });
|
||||
});
|
||||
|
||||
expect(screen.getByText("Empty files cannot be attached")).toBeInTheDocument();
|
||||
const alert = screen.getByRole("alert");
|
||||
expect(alert.closest("[data-toast-tone=error]")).not.toBeNull();
|
||||
expect(alert).toHaveTextContent("Empty files cannot be attached");
|
||||
expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
|
||||
expect(encodeImage).not.toHaveBeenCalled();
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
|
||||
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ThreadComposer } from "@/components/thread/ThreadComposer";
|
||||
import { ComposerUsagePopover } from "@/components/thread/ComposerUsagePopover";
|
||||
import { ToastProvider } from "@/components/ui/toast";
|
||||
import { ComposerDraftStore } from "@/lib/composer-draft";
|
||||
import { encodeImage } from "@/lib/imageEncode";
|
||||
import { SESSION_DRAG_TYPE } from "@/lib/session-drag";
|
||||
@@ -889,7 +890,10 @@ describe("ThreadComposer", () => {
|
||||
+ "Open this WebUI over HTTPS to use voice input.",
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole("alert")).toHaveClass("max-h-24");
|
||||
const input = screen.getByRole("textbox", { name: "Message input" });
|
||||
fireEvent.change(input, { target: { value: "Continue by typing" } });
|
||||
expect(screen.getByRole("alert").closest("form")).toBe(input.closest("form"));
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Open this WebUI over HTTPS");
|
||||
expect(getUserMedia).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -898,11 +902,8 @@ describe("ThreadComposer", () => {
|
||||
vi.stubGlobal("isSecureContext", true);
|
||||
vi.stubGlobal("MediaRecorder", undefined);
|
||||
render(
|
||||
<ThreadComposer
|
||||
onSend={vi.fn()}
|
||||
onTranscribeAudio={vi.fn(async () => "unused")}
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
<ThreadComposer onSend={vi.fn()} onTranscribeAudio={vi.fn(async () => "unused")} />,
|
||||
{ wrapper: ToastProvider },
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Voice input" }));
|
||||
@@ -988,24 +989,23 @@ describe("ThreadComposer", () => {
|
||||
await waitFor(() => expect(screen.getByLabelText("Message input")).toHaveValue("one recording"));
|
||||
});
|
||||
|
||||
it("distinguishes a missing microphone from a blocked permission", async () => {
|
||||
it("shows microphone-not-found as one toast across repeated attempts", async () => {
|
||||
const { getUserMedia } = mockVoiceRecorder();
|
||||
getUserMedia.mockRejectedValue(Object.assign(new Error("no microphone"), {
|
||||
name: "NotFoundError",
|
||||
}));
|
||||
getUserMedia.mockRejectedValue(new DOMException("No microphone", "NotFoundError"));
|
||||
render(
|
||||
<ThreadComposer
|
||||
onSend={vi.fn()}
|
||||
onTranscribeAudio={vi.fn(async () => "unused")}
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
<ThreadComposer onSend={vi.fn()} onTranscribeAudio={vi.fn(async () => "unused")} />,
|
||||
{ wrapper: ToastProvider },
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Voice input" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("No microphone was found. Connect a microphone and try again.")).toBeInTheDocument();
|
||||
});
|
||||
const retry = screen.getByRole("button", { name: "Voice input" });
|
||||
fireEvent.click(retry);
|
||||
const first = await screen.findByRole("alert");
|
||||
expect(first.closest("[data-toast-tone=error]")).not.toBeNull();
|
||||
expect(first).toHaveTextContent("Connect a microphone to record.");
|
||||
fireEvent.click(retry);
|
||||
await waitFor(() => expect(first).not.toBeInTheDocument());
|
||||
expect(getUserMedia).toHaveBeenCalledTimes(2);
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Connect a microphone to record.");
|
||||
});
|
||||
|
||||
it("clears a previous voice error when retrying microphone access", async () => {
|
||||
@@ -1022,7 +1022,9 @@ describe("ThreadComposer", () => {
|
||||
|
||||
const voiceButton = screen.getByRole("button", { name: "Voice input" });
|
||||
fireEvent.click(voiceButton);
|
||||
await waitFor(() => expect(screen.getByText("Allow microphone access in the address bar, then retry.")).toBeInTheDocument());
|
||||
const permission = await screen.findByRole("alert");
|
||||
expect(permission).toHaveTextContent("Allow microphone access in the address bar, then retry.");
|
||||
expect(permission.closest("form")).not.toBeNull();
|
||||
|
||||
fireEvent.click(voiceButton);
|
||||
|
||||
@@ -1152,11 +1154,8 @@ describe("ThreadComposer", () => {
|
||||
mockVoiceRecorder();
|
||||
const onTranscribeAudio = vi.fn(async () => "should not appear");
|
||||
render(
|
||||
<ThreadComposer
|
||||
onSend={vi.fn()}
|
||||
onTranscribeAudio={onTranscribeAudio}
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
<ThreadComposer onSend={vi.fn()} onTranscribeAudio={onTranscribeAudio} />,
|
||||
{ wrapper: ToastProvider },
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Voice input" }));
|
||||
|
||||
@@ -6,6 +6,7 @@ import { preloadMarkdownText } from "@/components/MarkdownText";
|
||||
import { ThreadCameraController } from "@/components/thread/thread-camera";
|
||||
import { ThreadShell } from "@/components/thread/ThreadShell";
|
||||
import { SessionSearchDialog } from "@/components/SessionSearchDialog";
|
||||
import { ToastProvider } from "@/components/ui/toast";
|
||||
import i18n from "@/i18n";
|
||||
import { ComposerDraftStore, clearStoredComposerDrafts } from "@/lib/composer-draft";
|
||||
import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events";
|
||||
@@ -5598,7 +5599,7 @@ describe("ThreadShell", () => {
|
||||
it("disables offline goal cancellation and treats an unchanged goal after a control reply as a retryable failure", async () => {
|
||||
const client = makeClient();
|
||||
const chatId = "cancel-failure";
|
||||
render(wrap(client, <ThreadShell session={session(chatId)} title="Goal" onToggleSidebar={() => {}} />));
|
||||
render(<ToastProvider>{wrap(client, <ThreadShell session={session(chatId)} title="Goal" onToggleSidebar={() => {}} />)}</ToastProvider>);
|
||||
await act(async () => {});
|
||||
act(() => {
|
||||
client._emitChat(chatId, { event: "goal_state", chat_id: chatId, goal_state: { active: false, status: "blocked", objective: "Ship the release" } });
|
||||
|
||||
Reference in new issue
Block a user