fix(webui): save settings when editing completes (NAN-323) (#6384)

* fix(webui): save settings when editing completes (NAN-323)

* fix(webui): close settings completion and verification gaps

* refactor(webui): simplify settings edit ownership
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-22 13:39:46 +08:00
1 parent 26e1f41a00
commit c6babb20e8
34 files changed
+1363 -388

No files matched your search

+101
View File
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
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 { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";
import type {
@@ -3149,6 +3150,106 @@ describe("App layout", () => {
expect(screen.getByRole("button", { name: "Check again" })).toBeInTheDocument();
});
it.each([true, false])("completes focused settings edits before history changes section (saved=%s)", async (saved) => {
const payload = { ...baseSettingsPayload(), transcription: { ...DEFAULT_TRANSCRIPTION_SETTINGS, language: "en" } };
mockFetchRoutes({ "/api/settings": payload });
let resolveSave!: (value: unknown) => void;
let rejectSave!: (error: Error) => void;
requestMutationSpy.mockImplementationOnce(() => new Promise((resolve, reject) => { resolveSave = resolve; rejectSave = reject; }));
window.history.replaceState(null, "", "/#/settings?section=voice");
render(<App />);
await act(async () => { await import("@/components/settings/SettingsView"); });
const language = await screen.findByPlaceholderText("Auto");
fireEvent.focus(language);
fireEvent.change(language, { target: { value: "ja" } });
expect(requestMutationSpy).not.toHaveBeenCalled();
act(() => {
window.history.replaceState(null, "", "/#/settings?section=models");
window.dispatchEvent(new PopStateEvent("popstate"));
});
await waitFor(() => expect(requestMutationSpy).toHaveBeenCalledWith(
"settings.transcription.update", expect.objectContaining({ language: "ja" }), 20_000,
));
expect(window.location.hash).toBe("#/settings?section=voice");
expect(language).toHaveValue("ja");
await act(async () => {
if (saved) resolveSave({ ...payload, transcription: { ...payload.transcription, language: "ja" } });
else rejectSave(new Error("Save failed"));
});
if (saved) {
await waitFor(() => expect(window.location.hash).toBe("#/settings?section=models"));
expect(await screen.findByText("Model presets")).toBeInTheDocument();
} else {
expect(window.location.hash).toBe("#/settings?section=voice");
expect(language).toHaveValue("ja");
expect(await screen.findByText("Save failed")).toBeVisible();
}
});
it("retains a capability draft while opening provider configuration", async () => {
const payload = { ...baseSettingsPayload(), transcription: { ...DEFAULT_TRANSCRIPTION_SETTINGS, language: "en" } };
mockFetchRoutes({ "/api/settings": payload });
window.history.replaceState(null, "", "/#/settings?section=voice");
render(<App />);
await act(async () => { await import("@/components/settings/SettingsView"); });
const language = await screen.findByPlaceholderText("Auto");
fireEvent.focus(language);
fireEvent.change(language, { target: { value: "ja" } });
fireEvent.click(screen.getByRole("button", { name: "Configure provider" }));
expect(await screen.findByText("Model presets")).toBeInTheDocument();
expect(window.location.hash).toBe("#/settings?section=models");
expect(requestMutationSpy).not.toHaveBeenCalled();
fireEvent.click(within(screen.getByRole("navigation", { name: "Settings sections" })).getByRole("button", { name: "Capabilities" }));
fireEvent.click(within(screen.getByRole("region", { name: "Transcription" })).getByRole("button", { name: "Configure" }));
expect(screen.getByPlaceholderText("Auto")).toHaveValue("ja");
});
it.each([true, false])("completes standalone channel drafts before leaving by history (saved=%s)", async (saved) => {
const feature = {
name: "email", display_name: "Email", type: "channel", webui: "webui/index.ts", enabled: false,
configured: true, installed: true, requires_dependencies: false, ready: false, status: "not_enabled",
install_supported: true, requires_restart: false, configured_fields: ["channels.email.imapHost"],
config_values: { "channels.email.imapHost": "imap.example.test" },
setup: { fields: [{ key: "channels.email.imapHost", field: "imapHost", kind: "string", required: true, choices: [] }], requirements: [] },
};
mockFetchRoutes({ "/api/settings": baseSettingsPayload(),
"/api/settings/nanobot-features": { features: [feature], enabled_count: 0 } });
let resolveSave!: (value: unknown) => void;
let rejectSave!: (error: Error) => void;
requestMutationSpy.mockImplementationOnce(() => new Promise((resolve, reject) => { resolveSave = resolve; rejectSave = reject; }));
window.history.replaceState(null, "", "/#/channels");
render(<App />);
await act(async () => {
await import("@/components/settings/SettingsView");
await import("@/components/settings/channels/ChannelSetupPanel");
});
fireEvent.click(await screen.findByRole("button", { name: "View Email settings" }));
const host = await screen.findByLabelText("IMAP host");
fireEvent.focus(host);
fireEvent.change(host, { target: { value: "imap.changed.test" } });
act(() => {
window.history.replaceState(null, "", "/#/new");
window.dispatchEvent(new PopStateEvent("popstate"));
});
await waitFor(() => expect(requestMutationSpy).toHaveBeenCalledWith(
"settings.channel.configure", expect.objectContaining({ name: "email", values: { "channels.email.imapHost": "imap.changed.test" } }), 150_000,
));
expect(window.location.hash).toBe("#/channels");
expect(host).toHaveValue("imap.changed.test");
await act(async () => {
if (saved) resolveSave({ name: "email", saved: true, saved_keys: ["channels.email.imapHost"] });
else rejectSave(new Error("Save failed"));
});
if (saved) {
await waitFor(() => expect(window.location.hash).toBe("#/new"));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
} else {
expect(window.location.hash).toBe("#/channels");
expect(host).toHaveValue("imap.changed.test");
expect(await screen.findByText("Save failed")).toBeVisible();
}
});
it("restores the settings section from the URL hash after a page reload", async () => {
mockFetchRoutes({ "/api/settings": baseSettingsPayload() });
window.history.replaceState(null, "", "/#/settings?section=voice");
+4 -1
View File
@@ -1,7 +1,8 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
import { preloadMarkdownText } from "@/components/MarkdownText";
import { CodeBlock } from "@/components/CodeBlock";
import { PreviewPane } from "@/components/PreviewPane";
import { FilePreviewStore, useFilePreviewState } from "@/hooks/useFilePreviewState";
@@ -38,6 +39,8 @@ vi.mock("@/lib/api", async (importOriginal) => {
});
describe("FilePreviewPanel", () => {
beforeAll(preloadMarkdownText);
beforeEach(async () => {
await setAppLanguage("en");
vi.mocked(fetchFilePreview).mockReset();
+4 -2
View File
@@ -1,11 +1,13 @@
import { render, waitFor } from "@testing-library/react";
import { expect, it } from "vitest";
import { beforeAll, expect, it } from "vitest";
import { MarkdownText } from "@/components/MarkdownText";
import { MarkdownText, preloadMarkdownText } from "@/components/MarkdownText";
import mixedMathFixture from "@/tests/fixtures/markdown-math-mixed.md?raw";
const mixedMath = mixedMathFixture.replaceAll("\r\n", "\n");
beforeAll(preloadMarkdownText);
it("retains a rendered TeX formula when an assistant response completes in streaming layout", async () => {
const source = String.raw`Before
+103 -5
View File
@@ -1,4 +1,7 @@
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { useState } from "react";
import { SettingsView } from "@/components/settings/SettingsView";
import { ClientProvider } from "@/providers/ClientProvider";
import { expect, it, vi } from "vitest";
import type { SettingsPayload } from "@/lib/types";
import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings";
@@ -111,7 +114,17 @@ describe("Settings capabilities", () => {
expect(screen.getAllByRole("alert")).toHaveLength(1);
});
it("keeps a rejected image save attached to the feature when its editor is collapsed", async () => {
it("retains an invalid capability draft while navigating to repair its provider", () => {
renderSettingsView({ initialSection: "capabilities", initialSettings: settingsPayload() });
fireEvent.click(screen.getByRole("switch", { name: "Image generation" }));
fireEvent.click(within(screen.getByRole("dialog", { name: "Image generation" })).getByRole("button", { name: "Configure provider" }));
expect(screen.getByRole("button", { name: "Models" })).toHaveAttribute("aria-current", "page");
fireEvent.click(screen.getByRole("button", { name: "Capabilities" }));
expect(screen.getByRole("switch", { name: "Image generation" })).toBeChecked();
expect(requestMutationMock).not.toHaveBeenCalled();
});
it("keeps a rejected image draft in its editor until retry succeeds", async () => {
const payload = settingsPayload();
payload.image_generation.providers = [{ name: "openrouter", label: "OpenRouter", configured: true }];
requestMutationMock.mockRejectedValue(new Error("image generation provider is not configured"));
@@ -120,8 +133,11 @@ describe("Settings capabilities", () => {
const image = within(screen.getByRole("dialog", { name: "Image generation" }));
await waitFor(() => expect(image.getByRole("alert")).toHaveTextContent("Configure this provider before enabling image generation."));
fireEvent.click(image.getByRole("button", { name: "Close" }));
expect(screen.getByRole("region", { name: "Image generation" })).toContainElement(screen.getByRole("alert"));
expect(screen.getAllByRole("alert")).toHaveLength(1);
await act(async () => {});
expect(screen.getByRole("dialog", { name: "Image generation" })).toContainElement(screen.getByRole("alert"));
requestMutationMock.mockResolvedValue({ ...payload, image_generation: { ...payload.image_generation, enabled: true } });
fireEvent.click(image.getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
it("keeps capabilities together and separates expanding settings from enabling a feature", () => {
@@ -228,6 +244,10 @@ describe("Settings capabilities", () => {
},
};
requestMutationMock.mockImplementation(async (_action, args) => {
payload.image_generation = { ...payload.image_generation, provider: args.provider, model: args.model };
return { ...payload };
});
renderSettingsView({ initialSection: "image", initialSettings: payload });
fireEvent.keyDown(screen.getByRole("combobox", { name: "OpenRouter" }), { key: "ArrowDown" });
@@ -392,7 +412,9 @@ describe("Settings capabilities", () => {
fireEvent.click(await screen.findByRole("option", { name: "DeepSeek" }));
expect(await screen.findByText("Add the required credential before saving.")).toBeVisible();
expect(requestMutationMock).not.toHaveBeenCalled();
fireEvent.change(screen.getByPlaceholderText("Enter API key"), { target: { value: "sk-deepseek-search-key" } });
const key = screen.getByPlaceholderText("Enter API key");
fireEvent.change(key, { target: { value: "sk-deepseek-search-key" } });
fireEvent.blur(key);
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.web_search.update",
{ provider: "deepseek", api_key: "sk-deepseek-search-key", max_results: 5, timeout: 30, use_jina_reader: true },
@@ -403,6 +425,7 @@ describe("Settings capabilities", () => {
fireEvent.click(screen.getByRole("button", { name: "Advanced options" }));
const timeout = screen.getAllByRole("spinbutton").find((input) => (input as HTMLInputElement).value === "30")!;
fireEvent.change(timeout, { target: { value: "45" } });
fireEvent.blur(timeout);
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.web_search.update",
{ provider: "deepseek", max_results: 5, timeout: 45, use_jina_reader: true },
@@ -410,6 +433,33 @@ describe("Settings capabilities", () => {
));
});
it("keeps a newer credential draft visible when an older save response arrives", async () => {
const payload = settingsPayload();
payload.web_search = { ...payload.web_search, provider: "deepseek", api_key_hint: "old-key",
providers: [...payload.web_search.providers, { name: "deepseek", label: "DeepSeek", credential: "api_key" }] };
let finish!: (value: SettingsPayload) => void;
requestMutationMock.mockImplementationOnce(() => new Promise<SettingsPayload>((resolve) => { finish = resolve; }))
.mockResolvedValue({ ...payload, web_search: { ...payload.web_search, api_key_hint: "latest-key" } });
renderSettingsView({ initialSection: "browser", initialSettings: payload });
const credential = screen.getByText("old-key").parentElement!;
fireEvent.click(within(credential).getByRole("button", { name: "Edit" }));
const key = credential.querySelector("input")!;
fireEvent.focus(key);
fireEvent.change(key, { target: { value: "first-key" } });
fireEvent.blur(key);
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(1));
fireEvent.focus(key);
fireEvent.change(key, { target: { value: "latest-key" } });
await act(async () => finish({ ...payload, web_search: { ...payload.web_search, api_key_hint: "first-key" } }));
expect(key).toBeVisible();
expect(key).toHaveValue("latest-key");
expect(requestMutationMock).toHaveBeenCalledTimes(1);
fireEvent.blur(key);
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.web_search.update", expect.objectContaining({ api_key: "latest-key" }), 20_000,
));
});
it("uses native host safety copy on the native surface", async () => {
const payload = {
...settingsPayload(),
@@ -434,6 +484,54 @@ describe("Settings capabilities", () => {
expect(await screen.findByRole("tooltip")).toHaveTextContent("Allow Full Access shell commands to reach services on this Mac.");
});
it("keeps a newer focused transcription draft through automatic native restart", async () => {
const payload = {
...settingsPayload(), surface: "native" as const, runtime_surface: "native" as const,
runtime_capabilities: { can_restart_engine: true, can_open_logs: true, can_export_diagnostics: true },
transcription: { ...DEFAULT_TRANSCRIPTION_SETTINGS, enabled: true, language: "en" },
};
const saved = { ...payload, requires_restart: true, transcription: { ...payload.transcription, language: "zh" } };
let finishRestart!: (token: string) => void;
const restart = vi.fn(() => new Promise<string>((resolve) => { finishRestart = resolve; }));
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
if (String(input) === "/api/settings") return jsonResponse(
(init?.headers as Record<string, string> | undefined)?.Authorization === "Bearer fresh-token"
? { ...saved, requires_restart: false } : payload,
);
return jsonResponse({ apps: [], presets: [], installed_count: 0 });
}));
requestMutationMock.mockResolvedValueOnce(saved);
let refreshParent!: (snapshot: SettingsPayload) => void;
let parentSnapshot: SettingsPayload = payload;
function Parent() {
const [snapshot, setSnapshot] = useState<SettingsPayload>(payload);
parentSnapshot = snapshot;
refreshParent = setSnapshot;
return <ClientProvider client={{ requestMutation: requestMutationMock, status: "open",
onStatus: (handler: (status: "open") => void) => { handler("open"); return () => {}; },
} as never} token="tok">
<SettingsView theme="light" initialSection="voice" initialSettings={snapshot}
onSettingsChange={setSnapshot} onNativeEngineRestart={restart}
onToggleTheme={() => {}} onBackToChat={() => {}} onModelNameChange={() => {}} />
</ClientProvider>;
}
render(<Parent />);
await act(async () => {});
const language = screen.getByPlaceholderText("Auto");
fireEvent.focus(language);
fireEvent.change(language, { target: { value: "zh" } });
fireEvent.blur(language);
await waitFor(() => expect(restart).toHaveBeenCalledTimes(1));
fireEvent.focus(language);
fireEvent.change(language, { target: { value: "ja" } });
expect(parentSnapshot.requires_restart).toBe(true);
await act(async () => refreshParent({ ...saved, requires_restart: false }));
expect(language).toHaveValue("ja");
await act(async () => finishRestart("fresh-token"));
expect(language).toHaveValue("ja");
expect(requestMutationMock).toHaveBeenCalledTimes(1);
});
it("refreshes settings with a fresh token after native engine restart", async () => {
const payload = {
...settingsPayload(),
+101 -36
View File
@@ -216,6 +216,32 @@ function catalogFeature(
};
}
function configuredEmailFeature(overrides: Partial<NanobotFeatureInfo> = {}): NanobotFeatureInfo {
return {
...catalogFeature("email", true),
display_name: "Email",
webui: "webui/index.ts",
config_values: {
"channels.email.consentGranted": "true",
"channels.email.imapHost": "imap.example.com",
"channels.email.imapUsername": "bot@example.com",
"channels.email.smtpHost": "smtp.example.com",
"channels.email.smtpUsername": "bot@example.com",
},
configured_fields: [
"channels.email.consentGranted",
"channels.email.imapHost",
"channels.email.imapUsername",
"channels.email.imapPassword",
"channels.email.smtpHost",
"channels.email.smtpUsername",
"channels.email.smtpPassword",
],
setup: channelSetupContract("email"),
...overrides,
};
}
describe("Settings channels", () => {
installSettingsViewTestHooks();
@@ -1411,7 +1437,7 @@ describe("Settings channels", () => {
expect(within(behavior).getByRole("radio", { name: "All messages" })).toBeChecked();
fireEvent.click(advanced);
expect(advanced).toHaveAttribute("aria-expanded", "false");
await waitFor(() => expect(advanced).toHaveAttribute("aria-expanded", "false"));
expect(behavior).not.toBeVisible();
advanced.focus();
await userEvent.setup().keyboard("[Space]");
@@ -1689,8 +1715,8 @@ describe("Settings channels", () => {
expect(notGranted).toHaveAttribute("aria-invalid", "true");
expect(granted).toHaveAttribute("aria-invalid", "true");
expect(screen.getByText("Required to complete setup.")).toBeInTheDocument();
expect(requestMutationMock.mock.calls.some(([action]) => (
action === "settings.channel.validate" || action === "settings.channel.configure"
expect(requestMutationMock.mock.calls.some(([action, args]) => (
action === "settings.channel.validate" || (action === "settings.channel.configure" && args.enable === true)
))).toBe(false);
fireEvent.click(granted);
@@ -1723,7 +1749,7 @@ describe("Settings channels", () => {
);
});
it("autosaves Email edits and waits for the save before closing", async () => {
it("commits Email edits on blur and waits for the save before closing", async () => {
let resolveConfigure: ((value: Record<string, unknown>) => void) | undefined;
const configureResult = new Promise<Record<string, unknown>>((resolve) => {
resolveConfigure = resolve;
@@ -1737,38 +1763,7 @@ describe("Settings channels", () => {
if (url === "/api/settings/mcp-presets") return jsonResponse({ presets: [], installed_count: 0 });
if (url === "/api/settings/nanobot-features") {
return jsonResponse({
features: [{
name: "email",
display_name: "Email",
webui: "webui/index.ts",
type: "channel",
enabled: true,
configured: true,
installed: true,
ready: true,
running: true,
runtime_status: "running",
status: "enabled",
install_supported: true,
requires_restart: false,
config_values: {
"channels.email.consentGranted": "true",
"channels.email.imapHost": "imap.example.com",
"channels.email.imapUsername": "bot@example.com",
"channels.email.smtpHost": "smtp.example.com",
"channels.email.smtpUsername": "bot@example.com",
},
configured_fields: [
"channels.email.consentGranted",
"channels.email.imapHost",
"channels.email.imapUsername",
"channels.email.imapPassword",
"channels.email.smtpHost",
"channels.email.smtpUsername",
"channels.email.smtpPassword",
],
setup: channelSetupContract("email"),
}],
features: [configuredEmailFeature({ running: true, runtime_status: "running" })],
enabled_count: 1,
});
}
@@ -1790,6 +1785,7 @@ describe("Settings channels", () => {
fireEvent.change(screen.getByLabelText("IMAP host"), {
target: { value: "imap.changed.example.com" },
});
fireEvent.blur(screen.getByLabelText("IMAP host"));
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.channel.configure",
@@ -1813,6 +1809,75 @@ describe("Settings channels", () => {
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
it("keeps focused Email advanced edits unsaved when an earlier blur save completes", async () => {
const user = userEvent.setup();
let resolveConfigure: ((value: Record<string, unknown>) => void) | undefined;
const configureResult = new Promise<Record<string, unknown>>((resolve) => {
resolveConfigure = resolve;
});
const emailFeature = configuredEmailFeature();
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url === "/api/settings") return jsonResponse(settingsPayload());
if (url === "/api/settings/nanobot-features") {
return jsonResponse({ features: [emailFeature], enabled_count: 1 });
}
return jsonResponse({});
}));
requestMutationMock
.mockResolvedValue({ name: "email", saved: true, saved_keys: ["channels.email.trustedAuthservIds"] })
.mockReturnValueOnce(configureResult);
renderSettingsView({ initialSection: "channels" });
await user.click(await screen.findByRole("button", { name: "View Email settings" }));
await user.click(screen.getByRole("button", { name: "Advanced" }));
const fromAddress = screen.getByRole("textbox", { name: "From address" });
const trustedServices = screen.getByRole("textbox", { name: "Trusted authentication services" });
await user.type(fromAddress, "changed@example.com");
expect(requestMutationMock).not.toHaveBeenCalled();
await user.click(trustedServices);
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(1));
expect(requestMutationMock).toHaveBeenNthCalledWith(
1,
"settings.channel.configure",
{
name: "email",
values: expect.objectContaining({ "channels.email.fromAddress": "changed@example.com" }),
},
150_000,
);
expect(requestMutationMock.mock.calls[0][1].values).not.toHaveProperty("channels.email.trustedAuthservIds");
expect(screen.getByText("Saving")).toBeVisible();
await user.type(trustedServices, "mx.receiver.example");
expect(trustedServices).toHaveFocus();
expect(requestMutationMock).toHaveBeenCalledTimes(1);
await act(async () => {
resolveConfigure?.({ name: "email", saved: true, saved_keys: ["channels.email.fromAddress"] });
await configureResult;
});
expect(trustedServices).toHaveFocus();
expect(trustedServices).toHaveValue("mx.receiver.example");
expect(requestMutationMock).toHaveBeenCalledTimes(1);
await user.tab();
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(2));
expect(requestMutationMock).toHaveBeenNthCalledWith(
2,
"settings.channel.configure",
{
name: "email",
values: expect.objectContaining({
"channels.email.fromAddress": "changed@example.com",
"channels.email.trustedAuthservIds": "mx.receiver.example",
}),
},
150_000,
);
});
it("prefills saved channel config without exposing secrets", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
@@ -0,0 +1,326 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { useState } from "react";
import { installSettingsViewTestHooks, renderSettingsView, requestMutationMock, settingsPayload } from "@/tests/settings-test-utils";
import { describe, expect, it, vi } from "vitest";
import { useEditCompletion, type EditCompletion } from "@/components/settings/shared/useEditCompletion";
import { NumberInput } from "@/components/settings/shared/SettingsControls";
import { ReasoningEffortPicker } from "@/components/settings/models/ReasoningEffortPicker";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => { resolve = done; });
return { promise, resolve };
}
function Editor({ save, identity = "a", expose }: {
save: (identity: string, value: string) => Promise<boolean>;
identity?: string;
expose?: (edits: EditCompletion) => void;
}) {
const [value, setValue] = useState("");
const edits = useEditCompletion(value, value !== "", () => save(identity, value), value !== "invalid", identity);
expose?.(edits);
return <div onChangeCapture={edits.onChangeCapture} onFocusCapture={edits.onFocusCapture} onBlurCapture={edits.onBlurCapture}>
<input aria-label="Draft" value={value} onChange={(event) => setValue(event.target.value)} />
<button onClick={() => setValue("selected")}>Select</button>
<button onClick={() => void edits.commit()}>Close</button>
</div>;
}
describe("settings edit completion", () => {
it("does not restore a closing picker over a newer focused input", async () => {
vi.useFakeTimers();
try {
render(<Dialog open><DialogContent aria-describedby={undefined}><DialogTitle>Model</DialogTitle>
<ReasoningEffortPicker token="test" provider={undefined} model="test" value="" onChange={() => {}} />
<input aria-label="Next field" />
</DialogContent></Dialog>);
const effort = screen.getByRole("combobox", { name: "Reasoning effort" });
effort.focus();
fireEvent.click(effort);
const option = screen.getByRole("option", { name: "Default" });
option.focus();
fireEvent.click(option);
// The enclosing Radix focus scope recovers here after the option is removed.
screen.getByRole("dialog").focus();
await act(async () => { vi.runOnlyPendingTimers(); });
expect(effort).toHaveFocus();
fireEvent.click(effort);
const selected = screen.getByRole("option", { name: "Default" });
selected.focus();
fireEvent.click(selected);
const next = screen.getByRole("textbox", { name: "Next field" });
next.focus();
await act(async () => { vi.runOnlyPendingTimers(); });
expect(next).toHaveFocus();
} finally {
vi.useRealTimers();
}
});
it("keeps text draft through pauses, then deduplicates blur and close", async () => {
const pending = deferred<boolean>();
const save = vi.fn(() => pending.promise);
render(<Editor save={save} />);
const input = screen.getByRole("textbox");
fireEvent.focus(input);
fireEvent.change(input, { target: { value: "first" } });
await act(async () => { await new Promise((done) => setTimeout(done, 700)); });
expect(save).not.toHaveBeenCalled();
fireEvent.change(input, { target: { value: "latest" } });
fireEvent.blur(input);
fireEvent.click(screen.getByRole("button", { name: "Close" }));
await waitFor(() => expect(save).toHaveBeenCalledWith("a", "latest"));
expect(save).toHaveBeenCalledTimes(1);
await act(async () => pending.resolve(true));
});
it("saves discrete edits immediately and serializes later completed drafts", async () => {
const first = deferred<boolean>();
const save = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(true);
render(<Editor save={save} />);
fireEvent.click(screen.getByRole("button", { name: "Select" }));
await waitFor(() => expect(save).toHaveBeenCalledWith("a", "selected"));
expect(save).toHaveBeenCalledTimes(1);
const input = screen.getByRole("textbox");
fireEvent.focus(input);
fireEvent.change(input, { target: { value: "second" } });
fireEvent.blur(input);
await act(async () => {});
expect(save).toHaveBeenCalledTimes(1);
await act(async () => first.resolve(true));
await waitFor(() => expect(save).toHaveBeenLastCalledWith("a", "second"));
});
it("does not confuse a later edit with an earlier successful draft containing the same text", async () => {
const pending = deferred<boolean>();
const save = vi.fn().mockResolvedValueOnce(true).mockReturnValueOnce(pending.promise).mockResolvedValue(true);
render(<Editor save={save} />);
fireEvent.click(screen.getByRole("button", { name: "Select" }));
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
const input = screen.getByRole("textbox");
fireEvent.change(input, { target: { value: "different" } });
fireEvent.blur(input);
await waitFor(() => expect(save).toHaveBeenCalledTimes(2));
fireEvent.change(input, { target: { value: "selected" } });
fireEvent.blur(input);
await act(async () => pending.resolve(true));
await waitFor(() => expect(save).toHaveBeenCalledTimes(3));
expect(save).toHaveBeenLastCalledWith("a", "selected");
});
it("flushes the focused version on unmount, including after a request already in flight", async () => {
const first = deferred<boolean>();
const save = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(true);
const view = render(<Editor save={save} />);
fireEvent.click(screen.getByRole("button", { name: "Select" }));
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
fireEvent.focus(screen.getByRole("textbox"));
fireEvent.change(screen.getByRole("textbox"), { target: { value: "unmounted" } });
view.unmount();
await act(async () => first.resolve(true));
await waitFor(() => expect(save).toHaveBeenLastCalledWith("a", "unmounted"));
});
it("persists a revert to the old baseline when an earlier save is still pending", async () => {
const first = deferred<boolean>();
const save = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(true);
render(<Editor save={save} />);
fireEvent.click(screen.getByRole("button", { name: "Select" }));
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
fireEvent.change(screen.getByRole("textbox"), { target: { value: "" } });
fireEvent.click(screen.getByRole("button", { name: "Close" }));
await act(async () => first.resolve(true));
await waitFor(() => expect(save).toHaveBeenLastCalledWith("a", ""));
});
it("retains an empty numeric draft instead of committing it as zero", async () => {
const save = vi.fn().mockResolvedValue(true);
function NumericEditor() {
const [value, setValue] = useState(1);
const edits = useEditCompletion(value, value !== 1, () => save(value), Number.isFinite(value));
return <div onChangeCapture={edits.onChangeCapture} onFocusCapture={edits.onFocusCapture} onBlurCapture={edits.onBlurCapture}>
<NumberInput value={value} min={0} max={2} onChange={setValue} />
</div>;
}
render(<NumericEditor />);
const input = screen.getByRole("spinbutton");
fireEvent.focus(input);
fireEvent.change(input, { target: { value: "" } });
fireEvent.blur(input);
await act(async () => {});
expect(input).toHaveValue(null);
expect(save).not.toHaveBeenCalled();
fireEvent.change(input, { target: { value: "0" } });
fireEvent.blur(input);
await waitFor(() => expect(save).toHaveBeenCalledWith(0));
});
it("blocks completion for invalid or rejected drafts and permits retry", async () => {
const save = vi.fn().mockResolvedValueOnce(false).mockResolvedValue(true);
let edits!: EditCompletion;
render(<Editor save={save} expose={(current) => { edits = current; }} />);
fireEvent.focus(screen.getByRole("textbox"));
fireEvent.change(screen.getByRole("textbox"), { target: { value: "invalid" } });
expect(await edits.commit()).toBe(false);
expect(save).not.toHaveBeenCalled();
fireEvent.change(screen.getByRole("textbox"), { target: { value: "valid" } });
expect(await edits.commit()).toBe(false);
expect(screen.getByRole("textbox")).toHaveValue("valid");
expect(await edits.commit()).toBe(true);
expect(save).toHaveBeenCalledTimes(2);
});
it("does not flush a newer focused text draft when a discrete save finishes", async () => {
const first = deferred<boolean>();
const save = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(true);
render(<Editor save={save} />);
fireEvent.click(screen.getByRole("button", { name: "Select" }));
await waitFor(() => expect(save).toHaveBeenCalledWith("a", "selected"));
fireEvent.focus(screen.getByRole("textbox"));
fireEvent.change(screen.getByRole("textbox"), { target: { value: "still typing" } });
await act(async () => first.resolve(true));
expect(save).toHaveBeenCalledTimes(1);
fireEvent.blur(screen.getByRole("textbox"));
await waitFor(() => expect(save).toHaveBeenLastCalledWith("a", "still typing"));
});
it("retains each source object when blur and an object switch share a turn", async () => {
const first = deferred<boolean>();
const save = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(true);
let edits!: EditCompletion;
const view = render(<Editor save={save} expose={(current) => { edits = current; }} />);
fireEvent.focus(screen.getByRole("textbox"));
fireEvent.change(screen.getByRole("textbox"), { target: { value: "object-a" } });
fireEvent.blur(screen.getByRole("textbox"));
view.rerender(<Editor save={save} identity="b" expose={(current) => { edits = current; }} />);
fireEvent.focus(screen.getByRole("textbox"));
fireEvent.change(screen.getByRole("textbox"), { target: { value: "object-b" } });
const completion = edits.commit();
await waitFor(() => expect(save).toHaveBeenCalledWith("a", "object-a"));
await act(async () => first.resolve(true));
expect(await completion).toBe(true);
expect(save).toHaveBeenLastCalledWith("b", "object-b");
});
});
// Exercise the real controller and portaled editor, not only the completion primitive.
describe("model editor completion boundaries", () => {
installSettingsViewTestHooks();
it("retains a focused draft through a pause and a failed close, then retries without losing it", async () => {
const payload = settingsPayload();
const saved = {
...payload,
model_presets: payload.model_presets.map((preset) => ({ ...preset, name: "Renamed", label: "Renamed" })),
model_call_order: ["Renamed"],
};
requestMutationMock.mockRejectedValueOnce(new Error("Save failed")).mockResolvedValueOnce(saved);
renderSettingsView({ initialSection: "models", initialSettings: payload });
fireEvent.click(within(screen.getByTestId("model-call-order-row-primary")).getAllByRole("button")[0]);
const name = screen.getByRole("textbox", { name: "Preset name" });
fireEvent.focus(name);
fireEvent.change(name, { target: { value: "Renamed" } });
await act(async () => { await new Promise((done) => setTimeout(done, 700)); });
expect(requestMutationMock).not.toHaveBeenCalled();
fireEvent.blur(name);
fireEvent.click(screen.getByRole("button", { name: "Close" }));
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(1));
await act(async () => {});
expect(screen.getByRole("textbox", { name: "Preset name" })).toHaveValue("Renamed");
expect(within(screen.getByRole("dialog")).getByRole("alert")).toHaveTextContent("Save failed");
fireEvent.click(screen.getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(requestMutationMock).toHaveBeenCalledTimes(2);
});
it("keeps a failed context-window save visible in the advanced dialog", async () => {
const payload = settingsPayload();
requestMutationMock.mockRejectedValueOnce(new Error("Save failed"));
renderSettingsView({ initialSection: "models", initialSettings: payload });
fireEvent.click(within(screen.getByTestId("model-call-order-row-primary")).getAllByRole("button")[0]);
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
const context = screen.getByRole("textbox", { name: "Context window" });
fireEvent.focus(context);
fireEvent.change(context, { target: { value: "500k" } });
fireEvent.click(screen.getByRole("button", { name: "Close" }));
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(1));
expect(within(screen.getByRole("dialog", { name: "Advanced options" })).getByRole("alert")).toHaveTextContent("Save failed");
expect(context).toHaveValue("500k");
});
it("does not let an unchanged reasoning selection complete subsequent typing", async () => {
renderSettingsView({ initialSection: "models", initialSettings: settingsPayload() });
fireEvent.click(within(screen.getByTestId("model-call-order-row-primary")).getAllByRole("button")[0]);
const effort = screen.getByRole("combobox", { name: "Reasoning effort" });
fireEvent.click(effort);
fireEvent.click(await screen.findByRole("option", { name: "Default" }));
fireEvent.focus(effort);
fireEvent.change(effort, { target: { value: "m" } });
await act(async () => {});
expect(effort).toHaveValue("m");
expect(requestMutationMock).not.toHaveBeenCalled();
fireEvent.blur(effort);
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.model_configuration.update", { name: "primary", reasoning_effort: "m" }, 20_000,
));
});
it("queues a rename back to its original name using the latest catalog", async () => {
const payload = settingsPayload();
const first = deferred<ReturnType<typeof settingsPayload>>();
requestMutationMock.mockReturnValueOnce(first.promise).mockResolvedValueOnce(payload);
renderSettingsView({ initialSection: "models", initialSettings: payload });
fireEvent.click(within(screen.getByTestId("model-call-order-row-primary")).getAllByRole("button")[0]);
const name = screen.getByRole("textbox", { name: "Preset name" });
fireEvent.focus(name);
fireEvent.change(name, { target: { value: "First" } });
fireEvent.blur(name);
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(1));
fireEvent.focus(name);
fireEvent.change(name, { target: { value: "primary" } });
fireEvent.blur(name);
fireEvent.click(screen.getByRole("button", { name: "Close" }));
await act(async () => first.resolve({
...payload, model_presets: payload.model_presets.map((preset) => ({ ...preset, name: "First", label: "First" })),
model_call_order: ["First"],
}));
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.model_configuration.update", { name: "First", new_name: "primary" }, 20_000,
));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(screen.getByTestId("model-call-order-row-primary")).toBeInTheDocument();
expect(requestMutationMock).toHaveBeenCalledTimes(2);
});
it("preserves and queues a later rename while the previous rename response is pending", async () => {
const payload = settingsPayload();
const first = deferred<ReturnType<typeof settingsPayload>>();
requestMutationMock.mockReturnValueOnce(first.promise).mockImplementationOnce(async (_action, args) => ({
...payload,
model_presets: payload.model_presets.map((preset) => ({ ...preset, name: args.new_name, label: args.new_name })),
model_call_order: [args.new_name],
}));
renderSettingsView({ initialSection: "models", initialSettings: payload });
fireEvent.click(within(screen.getByTestId("model-call-order-row-primary")).getAllByRole("button")[0]);
const name = screen.getByRole("textbox", { name: "Preset name" });
fireEvent.focus(name);
fireEvent.change(name, { target: { value: "First" } });
fireEvent.blur(name);
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(1));
fireEvent.click(screen.getByRole("button", { name: "Close" }));
fireEvent.focus(name);
fireEvent.change(name, { target: { value: "Latest" } });
await act(async () => first.resolve({
...payload,
model_presets: payload.model_presets.map((preset) => ({ ...preset, name: "First", label: "First" })),
model_call_order: ["First"],
}));
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.model_configuration.update", { name: "First", new_name: "Latest" }, 20_000,
));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(screen.getByTestId("model-call-order-row-Latest")).toBeInTheDocument();
});
});
+70 -44
View File
@@ -99,9 +99,12 @@ async function openModelPicker() {
return input;
}
function returnToPresetEditor() {
async function returnToPresetEditor() {
const advanced = screen.queryByRole("dialog", { name: "Advanced options" });
if (advanced) fireEvent.click(within(advanced).getByRole("button", { name: "Close" }));
if (advanced) {
fireEvent.click(within(advanced).getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Advanced options" })).not.toBeInTheDocument());
}
}
function presetSaveButton() {
@@ -175,7 +178,7 @@ describe("Settings models", () => {
expect(screen.getAllByRole("option")).toHaveLength(3);
fireEvent.click(screen.getByRole("option", { name: "Responses" }));
expect(screen.getByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).not.toBeChecked();
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.model_configuration.update",
@@ -187,7 +190,7 @@ describe("Settings models", () => {
await openPresetAdvancedOptions();
expect(screen.getByLabelText("API connection")).toHaveTextContent("Responses");
fireEvent.click(screen.getByRole("switch", { name: "Try Chat Completions if Responses is unsupported" }));
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.model_configuration.update",
@@ -205,7 +208,7 @@ describe("Settings models", () => {
await openPopover(screen.getByLabelText("API connection"));
fireEvent.click(screen.getByRole("option", { name: "Auto" }));
expect(screen.queryByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).not.toBeInTheDocument();
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.model_configuration.update", { name: "primary", api: null }, 20_000,
@@ -236,7 +239,7 @@ describe("Settings models", () => {
expect(screen.getAllByRole("option")).toHaveLength(4);
fireEvent.click(screen.getByRole("option", { name: "Anthropic Messages" }));
expect(screen.queryByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).not.toBeInTheDocument();
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.model_configuration.update",
@@ -271,10 +274,15 @@ describe("Settings models", () => {
? { provider: "openai", api: "chat_completions" }
: { provider: "anthropic", api: "anthropic_messages" });
}));
requestMutationMock.mockResolvedValue(payload);
requestMutationMock.mockImplementation(async (_action, args) => {
payload.model_presets = payload.model_presets.map((preset) => preset.name !== args.name ? preset : {
...preset, model: args.model ?? preset.model, api: args.api ?? preset.api,
});
return { ...payload };
});
renderSettingsView({ initialSection: "models", initialSettings: payload });
await openPresetAdvancedOptions();
returnToPresetEditor();
await returnToPresetEditor();
const search = await openModelPicker();
fireEvent.change(search, { target: { value: "gpt-4o" } });
fireEvent.keyDown(search, { key: "Enter" });
@@ -282,11 +290,11 @@ describe("Settings models", () => {
await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)"));
await openPopover(screen.getByLabelText("API connection"));
fireEvent.click(screen.getByRole("option", { name: "Responses" }));
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.model_configuration.update", {
name: "primary", model: "gpt-4o",
name: "primary",
api: { supported_apis: ["responses"], preferred_api: "responses" },
}, 20_000,
));
@@ -309,6 +317,12 @@ describe("Settings models", () => {
return jsonResponse({ provider: "openai", api: "chat_completions" });
});
vi.stubGlobal("fetch", fetchMock);
requestMutationMock.mockImplementation(async (_action, args) => {
payload.model_presets = payload.model_presets.map((preset) => ({
...preset, reasoning_effort: args.reasoning_effort ?? preset.reasoning_effort,
}));
return { ...payload };
});
renderSettingsView({ initialSection: "models" });
await openPresetAdvancedOptions();
await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)"));
@@ -316,18 +330,20 @@ describe("Settings models", () => {
await openPopover(screen.getByLabelText("API connection"));
expect(screen.getByRole("option", { name: "Auto (Chat Completions)" })).toHaveAttribute("aria-selected", "true");
fireEvent.click(screen.getByRole("option", { name: "Auto (Chat Completions)" }));
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.change(screen.getByLabelText("Reasoning effort"), { target: { value: "high" } });
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
await waitFor(() => expect(fetchMock.mock.calls.some(([url]) => String(url).includes("reasoning_effort=high"))).toBe(true));
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.change(screen.getByLabelText("Reasoning effort"), { target: { value: "none" } });
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
await waitFor(() => expect(fetchMock.mock.calls.some(([url]) => String(url).includes("reasoning_effort=none"))).toBe(true));
await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)"));
await act(async () => { finishHigh(jsonResponse({ provider: "openai", api: "responses" })); });
expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)");
expect(requestMutationMock).not.toHaveBeenCalled();
expect(requestMutationMock).toHaveBeenCalledWith(
"settings.model_configuration.update", { name: "primary", reasoning_effort: "high" }, 20_000,
);
});
it("updates the Auto label from a valid host result without changing the preset declaration", async () => {
@@ -348,11 +364,11 @@ describe("Settings models", () => {
renderSettingsView({ initialSection: "models" });
await openPresetAdvancedOptions();
await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)"));
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.change(screen.getByLabelText("Reasoning effort"), { target: { value: "high" } });
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Responses)"));
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.model_configuration.update", { name: "primary", reasoning_effort: "high" }, 20_000,
@@ -405,7 +421,7 @@ describe("Settings models", () => {
expect(screen.getByRole("button", { name: /Advanced options/ })).toHaveAttribute("aria-expanded", "false");
expect(presetSaveButton()).toBeDisabled();
fireEvent.change(screen.getByLabelText("Preset name"), { target: { value: "Renamed" } });
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.model_configuration.update", { name: "primary", new_name: "Renamed" }, 20_000,
@@ -536,7 +552,7 @@ describe("Settings models", () => {
fireEvent.change(screen.getByLabelText("Temperature"), {
target: { value: "0.4" },
});
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => {
@@ -568,7 +584,8 @@ describe("Settings models", () => {
const nameInput = screen.getByRole("textbox", { name: "Preset name" });
fireEvent.change(nameInput, { target: { value: "Codex" } });
returnToPresetEditor();
fireEvent.blur(nameInput);
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => {
@@ -592,7 +609,8 @@ describe("Settings models", () => {
const nameInput = screen.getByRole("textbox", { name: "Preset name" });
fireEvent.change(nameInput, { target: { value: "Codex" } });
returnToPresetEditor();
fireEvent.blur(nameInput);
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
expect(await screen.findByRole("alert")).toHaveTextContent(
@@ -628,7 +646,7 @@ describe("Settings models", () => {
expect(within(screen.getByRole("dialog", { name: "Advanced options" })).getByText("Context window")).toBeInTheDocument();
expect(screen.getByText("Temperature")).toBeInTheDocument();
expect(screen.getByRole("textbox", { name: "Context window" })).toHaveValue("200k");
returnToPresetEditor();
await returnToPresetEditor();
const reasoningEffort = screen.getByLabelText("Reasoning effort");
expect(reasoningEffort).toHaveProperty("type", "text");
fireEvent.change(reasoningEffort, { target: { value: "provider-native-mode" } });
@@ -648,7 +666,7 @@ describe("Settings models", () => {
fireEvent.change(screen.getByRole("textbox", { name: "Context window" }), {
target: { value: input },
});
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.model_configuration.update", expect.objectContaining({ context_window_tokens: tokens }), expect.any(Number),
@@ -671,7 +689,9 @@ describe("Settings models", () => {
vi.useRealTimers();
expect(requestMutationMock).not.toHaveBeenCalled();
expect(input).toHaveValue(value);
returnToPresetEditor();
fireEvent.click(screen.getByRole("button", { name: "Close" }));
await act(async () => {});
expect(screen.getByRole("dialog", { name: "Advanced options" })).toContainElement(input);
expect(presetSaveButton()).toBeDisabled();
});
@@ -689,7 +709,7 @@ describe("Settings models", () => {
await openPresetAdvancedOptions();
let input = screen.getByRole("textbox", { name: "Max output tokens" });
fireEvent.change(input, { target: { value: "32K" } });
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.model_configuration.update", expect.objectContaining({ max_tokens: 32000 }), expect.any(Number),
@@ -707,7 +727,7 @@ describe("Settings models", () => {
vi.useRealTimers();
expect(requestMutationMock).not.toHaveBeenCalled();
fireEvent.change(input, { target: { value: "8.192k" } });
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.model_configuration.update", expect.objectContaining({ max_tokens: 8192 }), expect.any(Number),
@@ -758,15 +778,19 @@ describe("Settings models", () => {
it("opens advanced options in a separate dialog and preserves the preset draft", async () => {
vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>(() => {})));
renderSettingsView({ initialSection: "models", initialSettings: settingsPayload() });
const payload = settingsPayload();
requestMutationMock.mockResolvedValue({
...payload, model_presets: payload.model_presets.map((preset) => ({ ...preset, context_window_tokens: 128000 })),
});
renderSettingsView({ initialSection: "models", initialSettings: payload });
await togglePresetEditor();
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
const advanced = screen.getByRole("dialog", { name: "Advanced options" });
fireEvent.change(within(advanced).getByLabelText("Context window"), { target: { value: "128k" } });
fireEvent.click(within(advanced).getByRole("button", { name: "Close" }));
expect(screen.queryByRole("dialog", { name: "Advanced options" })).not.toBeInTheDocument();
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Advanced options" })).not.toBeInTheDocument());
expect(screen.getByTestId("model-preset-editor")).toBeVisible();
expect(requestMutationMock).not.toHaveBeenCalled();
expect(requestMutationMock).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
expect(within(screen.getByRole("dialog", { name: "Advanced options" })).getByLabelText("Context window")).toHaveValue("128k");
});
@@ -832,6 +856,7 @@ describe("Settings models", () => {
model_presets: payload.model_presets.map((preset) => ({
...preset,
active: preset.name === backupPreset.name,
temperature: preset.name === "primary" ? 0.4 : preset.temperature,
})),
model_call_order: ["backup", "primary"],
};
@@ -847,7 +872,9 @@ describe("Settings models", () => {
return { ok: false, status: 404, json: async () => ({}) } as Response;
});
vi.stubGlobal("fetch", fetchMock);
requestMutationMock.mockResolvedValueOnce(updatedPayload);
requestMutationMock.mockResolvedValueOnce({
...payload, model_presets: payload.model_presets.map((preset) => preset.name === "primary" ? { ...preset, temperature: 0.4 } : preset),
}).mockResolvedValueOnce(updatedPayload);
renderSettingsView({ initialSection: "models", initialSettings: payload });
@@ -864,8 +891,10 @@ describe("Settings models", () => {
fireEvent.change(screen.getByLabelText("Temperature"), {
target: { value: "0.4" },
});
await returnToPresetEditor();
fireEvent.click(screen.getByRole("button", { name: "Close" }));
fireEvent.click(screen.getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
requestMutationMock.mockClear();
const centers = mockPresetRowLayout();
const draggedRow = screen.getByTestId(`model-call-order-row-${name}`);
fireEvent.pointerDown(draggedRow, { button: 0, clientY: centers[from], pointerId: 1 });
@@ -889,7 +918,7 @@ describe("Settings models", () => {
fireEvent.click(within(screen.getByTestId("model-call-order-row-primary")).getByRole("button", { name: "Configure" }));
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
expect(screen.getByLabelText("Temperature")).toHaveValue(0.4);
expect(presetSaveButton()).toBeEnabled();
expect(presetSaveButton()).toBeDisabled();
});
it("allows the next switch click when a drag ends without a click event", async () => {
@@ -1200,7 +1229,7 @@ describe("Settings models", () => {
const modelSearch = await openModelPicker();
fireEvent.change(modelSearch, { target: { value: "openai/gpt-4o-mini" } });
fireEvent.keyDown(modelSearch, { key: "Enter" });
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
expect(requestMutationMock).not.toHaveBeenCalled();
@@ -1972,7 +2001,7 @@ describe("Settings models", () => {
expect(screen.getByRole("textbox", { name: "Preset name" })).toHaveValue("");
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
expect(screen.getByText("Temperature")).toBeInTheDocument();
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(document.body.style.pointerEvents).toBe(previousPointerEvents));
@@ -2020,12 +2049,12 @@ describe("Settings models", () => {
fireEvent.click(screen.getByRole("button", { name: "New preset" }));
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
if (manual) fireEvent.change(screen.getByRole("textbox", { name: "Context window" }), { target: { value: manual } });
returnToPresetEditor();
await returnToPresetEditor();
await openModelPicker();
fireEvent.click(await screen.findByRole("option", { name: /catalog-model/ }));
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
await waitFor(() => expect(screen.getByRole("textbox", { name: "Context window" })).toHaveValue(expected));
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.model_configuration.create", expect.objectContaining({ context_window_tokens: manual ? 256000 : context ?? 200000 }), expect.any(Number),
@@ -2071,7 +2100,7 @@ describe("Settings models", () => {
fireEvent.click(input);
fireEvent.change(input, { target: { value: "provider-native-mode" } });
fireEvent.keyDown(input, { key: "Enter" });
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.click(presetSaveButton());
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.model_configuration.update", expect.objectContaining({ reasoning_effort: "provider-native-mode" }), expect.any(Number),
@@ -2161,12 +2190,11 @@ describe("Settings models", () => {
fireEvent.change(screen.getByLabelText("Temperature"), {
target: { value: "0.4" },
});
returnToPresetEditor();
await returnToPresetEditor();
fireEvent.change(screen.getByLabelText("Reasoning effort"), {
target: { value: "provider-native-mode" },
});
returnToPresetEditor();
fireEvent.click(presetSaveButton());
fireEvent.blur(screen.getByLabelText("Reasoning effort"));
await waitFor(() =>
expect(fetchMock).toHaveBeenCalledWith(
@@ -2181,12 +2209,10 @@ describe("Settings models", () => {
action === "settings.model_configuration.update",
);
expect(saveCall).toBeDefined();
expect(saveCall?.[1]).toEqual({
name: "primary",
model: "deepseek-reasoner",
reasoning_effort: "provider-native-mode",
temperature: 0.4,
});
expect(saveCall?.[1]).toEqual({ name: "primary", model: "deepseek-reasoner" });
expect(requestMutationMock).toHaveBeenCalledWith(
"settings.model_configuration.update", expect.objectContaining({ reasoning_effort: "provider-native-mode" }), 20_000,
);
});
});
});
@@ -59,12 +59,14 @@ describe("Runtime configuration settings", () => {
});
it("places common settings in their feature pages and reserves advanced for low-frequency controls", () => {
renderSettingsView({ initialSection: "runtime", initialSettings: runtimeSettings() });
const payload = runtimeSettings();
payload.image_generation.enabled = true;
renderSettingsView({ initialSection: "runtime", initialSettings: payload });
expect(document.getElementById("runtime-tools.exec.enable")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Advanced" }));
expect(document.getElementById("runtime-tools.exec.sandbox")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Capabilities" }));
fireEvent.click(screen.getByRole("switch", { name: "Image generation" }));
fireEvent.click(within(screen.getByRole("region", { name: "Image generation" })).getByRole("button", { name: "Configure" }));
expect(document.getElementById("runtime-tools.image_generation.save_dir")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close" }));
expect(screen.getByRole("switch", { name: "Web access" })).toBeInTheDocument();
@@ -1,6 +1,6 @@
// @vitest-environment-options {"settings":{"disableIframePageLoading":true}}
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import App from "@/App";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
@@ -97,6 +97,13 @@ async function selectTopic(name: string) {
}
describe("temporary chat navigation", () => {
beforeAll(async () => {
await Promise.all([
import("@/components/settings/SettingsView"),
import("@/components/thread/ThreadShell"),
]);
});
beforeEach(() => {
vi.mocked(fetchBootstrap).mockReset().mockResolvedValue({ token: "test", api_token: "test", ws_path: "/" });
groupedTopics = false;