diff --git a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx index 02be7a010..26934daa7 100644 --- a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx +++ b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx @@ -107,7 +107,7 @@ describe("Linear channel UI", () => { mockFeature(linearFeature); renderSettingsView({ initialSection: "channels" }); fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" })); - const createApp = await screen.findByRole("button", { name: "Create Linear app" }); + const createApp = await screen.findByRole("button", { name: "Create Linear app" }, { timeout: 5000 }); expect(createApp).toBeEnabled(); fireEvent.click(createApp); const prompt = await screen.findByRole("alertdialog", { name: "Public HTTPS URL" }); @@ -151,7 +151,7 @@ describe("Linear channel UI", () => { expect(screen.queryByRole("dialog", { name: "Linear" })).not.toBeInTheDocument(); }); - it("automatically saves a public URL before OAuth credentials and reveals the app button", async () => { + it("commits a public URL on blur before OAuth credentials and reveals the app button", async () => { vi.stubGlobal( "fetch", vi.fn(async (input: RequestInfo | URL) => { @@ -197,6 +197,7 @@ describe("Linear channel UI", () => { fireEvent.change(await screen.findByPlaceholderText("https://nanobot.example.com"), { target: { value: "https://nanobot.example.com" }, }); + fireEvent.blur(screen.getByPlaceholderText("https://nanobot.example.com")); expect(screen.queryByRole("button", { name: /^Save/ })).not.toBeInTheDocument(); await waitFor(() => @@ -242,6 +243,7 @@ describe("Linear channel UI", () => { target: { value: "3980" }, }); expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled(); + fireEvent.blur(screen.getByRole("spinbutton", { name: "Listen port" })); await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled()); const params = actionCalls()[0][1] as { values: Record }; expect(params.values["channels.linear.port"]).toBe("3980"); @@ -450,7 +452,7 @@ describe("Linear channel UI", () => { }); const dialog = screen.getByRole("dialog"); fireEvent.click(within(dialog).getByRole("button", { name: "Close" })); - expect(actionCalls()).toHaveLength(1); + await waitFor(() => expect(actionCalls()).toHaveLength(1)); expect(dialog).toBeVisible(); fireEvent.click(within(dialog).getByRole("button", { name: "Close" })); expect(actionCalls()).toHaveLength(1); diff --git a/nanobot/channels/linear/webui/LinearPanel.tsx b/nanobot/channels/linear/webui/LinearPanel.tsx index f1d37cefb..11148b8ae 100644 --- a/nanobot/channels/linear/webui/LinearPanel.tsx +++ b/nanobot/channels/linear/webui/LinearPanel.tsx @@ -5,7 +5,7 @@ import { channelTranslator } from "@/channel-plugins/i18n"; import type { ChannelPluginPanelProps } from "@/channel-plugins/types"; import { channelValuesForSubmit, defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm"; import { channelSetup } from "@/components/settings/channels/ChannelIdentity"; -import { useAutoSave } from "@/components/settings/shared/useAutoSave"; +import { useEditCompletion } from "@/components/settings/shared/useEditCompletion"; import { configureChannel, disableNanobotFeature, fetchNanobotFeatures } from "@/lib/api"; import { useClient } from "@/providers/ClientProvider"; @@ -71,17 +71,21 @@ export function LinearPanel({ setTouchedFields(new Set()); setVisibleSecrets({}); setClearedSecrets(new Set()); - }, [savedValuesKey, feature.name]); + }, [feature.name]); + + useEffect(() => { + const savedValues = defaultChannelFieldValues(editableFields, feature.config_values); + setFieldValues((current) => ({ + ...savedValues, + ...Object.fromEntries(Object.entries(current).filter(([key]) => touchedFields.has(key))), + })); + }, [savedValuesKey]); const busy = saving || resetting || Boolean(actionKey); const savedValues = defaultChannelFieldValues(editableFields, feature.config_values); const dirty = clearedSecrets.size > 0 || editableFields.some( (field) => fieldValues[field.key] !== savedValues[field.key], ); - const secretFields = editableFields.filter((field) => field.secret); - const touchedSecret = secretFields.some((field) => - touchedFields.has(field.key) && Boolean(fieldValues[field.key]?.trim()), - ); const memberConfigScope = JSON.stringify([ feature.config_values?.["channels.linear.clientId"], feature.config_values?.["channels.linear.allowFrom"], @@ -155,8 +159,7 @@ export function LinearPanel({ const saveSettings = useCallback(async (): Promise => { if (savePromiseRef.current) return savePromiseRef.current; - if (!dirty) return true; - if (busy || connecting) return false; + if (resetting || actionKey || connecting) return false; const save = (async () => { setSaving(true); setSaved(false); @@ -167,10 +170,10 @@ export function LinearPanel({ feature.name, channelValuesForSubmit(editableFields, fieldValues, touchedFields, clearedSecrets), ); - setTouchedFields(new Set()); - setClearedSecrets(new Set()); + setTouchedFields((current) => current === touchedFields ? new Set() : current); + setClearedSecrets((current) => current === clearedSecrets ? new Set() : current); setVisibleSecrets({}); - setFieldValues((current) => Object.fromEntries( + setFieldValues((current) => current !== fieldValues ? current : Object.fromEntries( editableFields.map((field) => [field.key, field.secret ? "" : current[field.key] ?? ""]), )); if (payload.nanobot_features) onFeaturesUpdate(payload.nanobot_features); @@ -187,15 +190,11 @@ export function LinearPanel({ const result = await save; if (savePromiseRef.current === save) savePromiseRef.current = null; return result; - }, [busy, connecting, dirty, client, feature.name, editableFields, fieldValues, + }, [resetting, actionKey, connecting, client, feature.name, editableFields, fieldValues, touchedFields, clearedSecrets, onFeaturesUpdate]); - useAutoSave( - { fieldValues, clearedSecrets: [...clearedSecrets] }, - dirty, - busy || connecting, - () => void saveSettings(), - !touchedSecret && !notice, + const edits = useEditCompletion( + { fieldValues, clearedSecrets: [...clearedSecrets] }, dirty, saveSettings, true, feature.name, ); useEffect(() => { @@ -203,10 +202,10 @@ export function LinearPanel({ if (secretSavePromiseRef.current) { try { await secretSavePromiseRef.current; } catch { return false; } } - return saveSettings(); + return edits.commit(); } : null); return () => onBeforeCloseChange?.(null); - }, [dirty, saving, saveSettings, onBeforeCloseChange]); + }, [dirty, saving, edits.commit, onBeforeCloseChange]); const saveSecret = async (key: string, value: string) => { if (busy || dirty || connecting || savePromiseRef.current || secretSavePromiseRef.current) { @@ -235,20 +234,19 @@ export function LinearPanel({ visibleSecrets, clearedSecrets, onChange: setFieldValue, - onFieldBlur: () => { void saveSettings(); }, onToggleSecret: (key: string) => { setVisibleSecrets((current) => ({ ...current, [key]: !current[key] })); }, - disabled: busy || connecting, + disabled: resetting || Boolean(actionKey) || connecting, compact: true, }; - return setWorkspaceError(null)} onRequestConnection={() => setConnectRequestId(id => id + 1)} onConfigureMcp={onConfigureMcp} renderMemberAccess={(organizationId, disabled) => { onFeaturesUpdate(payload); void workspaceStore.load(true); - }} onActiveChange={setConnecting} renderActions={renderActions} />} />; + }} onActiveChange={setConnecting} renderActions={renderActions} />} />; } diff --git a/nanobot/channels/linear/webui/LinearPanelView.tsx b/nanobot/channels/linear/webui/LinearPanelView.tsx index 06d897f7e..22dc6eafd 100644 --- a/nanobot/channels/linear/webui/LinearPanelView.tsx +++ b/nanobot/channels/linear/webui/LinearPanelView.tsx @@ -120,7 +120,10 @@ export function LinearPanelView({ feature, showBrandLogos, fields, advancedField + + ; +} + +describe("settings edit completion", () => { + it("does not restore a closing picker over a newer focused input", async () => { + vi.useFakeTimers(); + try { + render(Model + {}} /> + + ); + 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(); + const save = vi.fn(() => pending.promise); + render(); + 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(); + const save = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(true); + render(); + 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(); + const save = vi.fn().mockResolvedValueOnce(true).mockReturnValueOnce(pending.promise).mockResolvedValue(true); + render(); + 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(); + const save = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(true); + const view = render(); + 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(); + const save = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(true); + render(); + 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
+ +
; + } + render(); + 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( { 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(); + const save = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(true); + render(); + 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(); + const save = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(true); + let edits!: EditCompletion; + const view = render( { edits = current; }} />); + fireEvent.focus(screen.getByRole("textbox")); + fireEvent.change(screen.getByRole("textbox"), { target: { value: "object-a" } }); + fireEvent.blur(screen.getByRole("textbox")); + view.rerender( { 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>(); + 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>(); + 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(); + }); +}); diff --git a/webui/src/tests/settings-models.test.tsx b/webui/src/tests/settings-models.test.tsx index bb3b70746..12eab0b47 100644 --- a/webui/src/tests/settings-models.test.tsx +++ b/webui/src/tests/settings-models.test.tsx @@ -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(() => {}))); - 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, + ); }); }); }); diff --git a/webui/src/tests/settings-runtime-config.test.tsx b/webui/src/tests/settings-runtime-config.test.tsx index e2a8d8a18..5dbcd9572 100644 --- a/webui/src/tests/settings-runtime-config.test.tsx +++ b/webui/src/tests/settings-runtime-config.test.tsx @@ -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(); diff --git a/webui/src/tests/temporary-chat-navigation.test.tsx b/webui/src/tests/temporary-chat-navigation.test.tsx index ef747a227..b3ebce5df 100644 --- a/webui/src/tests/temporary-chat-navigation.test.tsx +++ b/webui/src/tests/temporary-chat-navigation.test.tsx @@ -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;