diff --git a/ui/src/pages/PluginSettings.save-refetch.test.tsx b/ui/src/pages/PluginSettings.save-refetch.test.tsx new file mode 100644 index 00000000000..6df8ee29833 --- /dev/null +++ b/ui/src/pages/PluginSettings.save-refetch.test.tsx @@ -0,0 +1,102 @@ +// @vitest-environment jsdom + +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { expect, it, vi } from "vitest"; +import { queryKeys } from "../lib/queryKeys"; +import { PluginSettings } from "./PluginSettings"; + +const api = vi.hoisted(() => ({ + get: vi.fn(), + dashboard: vi.fn(), + getConfig: vi.fn(), + saveConfig: vi.fn(), +})); +const setBreadcrumbs = vi.hoisted(() => vi.fn()); + +vi.mock("@/api/plugins", () => ({ pluginsApi: api })); +vi.mock("@/context/BreadcrumbContext", () => ({ + useBreadcrumbs: () => ({ setBreadcrumbs }), +})); +vi.mock("@/context/CompanyContext", () => ({ + useCompany: () => ({ + selectedCompany: { id: "company-1", name: "Paperclip", issuePrefix: "PAP" }, + selectedCompanyId: "company-1", + }), +})); +vi.mock("@/lib/router", () => ({ + Link: ({ to, children }: { to: string; children: React.ReactNode }) => {children}, + Navigate: () => null, + useParams: () => ({ companyPrefix: "PAP", pluginId: "plugin-1" }), +})); +vi.mock("@/plugins/slots", () => ({ + PluginSlotMount: () => null, + usePluginSlots: () => ({ slots: [] }), +})); +vi.mock("@/components/PageTabBar", () => ({ PageTabBar: () => null })); + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +async function flushReact() { + await act(async () => { + await Promise.resolve(); + await new Promise((resolve) => window.setTimeout(resolve, 0)); + }); +} + +it("keeps unchanged defaults unsaveable after persistence while config refetch is pending", async () => { + const saved = { configJson: { label: "Default" } }; + let finishRefetch!: (value: typeof saved) => void; + api.get.mockResolvedValue({ + id: "plugin-1", + packageName: "default-plugin", + status: "error", + categories: [], + manifestJson: { + displayName: "Default configuration", + instanceConfigSchema: { + type: "object", + properties: { label: { type: "string", default: "Default" } }, + }, + }, + }); + api.dashboard.mockResolvedValue(null); + api.getConfig.mockResolvedValueOnce(null).mockImplementation( + () => new Promise((resolve) => { finishRefetch = resolve; }), + ); + api.saveConfig.mockResolvedValue(saved); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + client.setQueryData(queryKeys.instance.experimentalSettings, {}); + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + try { + await act(async () => { + root.render(); + }); + await flushReact(); + await flushReact(); + const button = Array.from(container.querySelectorAll("button")).find( + (item) => item.textContent === "Save Configuration", + )!; + expect(button).toBeDefined(); + expect(button.disabled).toBe(false); + await act(async () => { button.click(); }); + await flushReact(); + await flushReact(); + expect(api.saveConfig).toHaveBeenCalledExactlyOnceWith("plugin-1", "company-1", { label: "Default" }); + expect(api.getConfig).toHaveBeenCalledTimes(2); + expect(client.getQueryState(queryKeys.plugins.config("plugin-1", "company-1"))?.fetchStatus).toBe("fetching"); + expect(container.textContent).toContain("Configuration saved."); + expect(button.disabled, "Persisted unchanged defaults must stay disabled during refetch").toBe(true); + } finally { + await act(async () => { + finishRefetch?.(saved); + root.unmount(); + }); + client.clear(); + container.remove(); + vi.clearAllMocks(); + } +}); diff --git a/ui/src/pages/PluginSettings.save-scope.test.tsx b/ui/src/pages/PluginSettings.save-scope.test.tsx new file mode 100644 index 00000000000..a2153376eaf --- /dev/null +++ b/ui/src/pages/PluginSettings.save-scope.test.tsx @@ -0,0 +1,83 @@ +// @vitest-environment jsdom + +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { expect, it, vi } from "vitest"; +import { queryKeys } from "../lib/queryKeys"; +import { PluginSettings } from "./PluginSettings"; + +const state = vi.hoisted(() => ({ companyId: "company-1", pluginId: "plugin-1" })); +const api = vi.hoisted(() => ({ get: vi.fn(), dashboard: vi.fn(), getConfig: vi.fn(), saveConfig: vi.fn() })); +const setBreadcrumbs = vi.hoisted(() => vi.fn()); +vi.mock("@/api/plugins", () => ({ pluginsApi: api })); +vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs }) })); +vi.mock("@/context/CompanyContext", () => ({ + useCompany: () => ({ + selectedCompany: { id: state.companyId, name: "Paperclip", issuePrefix: "PAP" }, + selectedCompanyId: state.companyId, + }), +})); +vi.mock("@/lib/router", () => ({ + Link: ({ to, children }: { to: string; children: React.ReactNode }) => {children}, + Navigate: () => null, + useParams: () => ({ companyPrefix: "PAP", pluginId: state.pluginId }), +})); +vi.mock("@/plugins/slots", () => ({ PluginSlotMount: () => null, usePluginSlots: () => ({ slots: [] }) })); +vi.mock("@/components/PageTabBar", () => ({ PageTabBar: () => null })); +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +async function flushReact() { + await act(async () => { + await Promise.resolve(); + await new Promise((resolve) => window.setTimeout(resolve, 0)); + }); +} + +it.each(["company", "plugin"])("keeps a pending save scoped to its original %s", async (selection) => { + state.companyId = "company-1"; + state.pluginId = "plugin-1"; + const manifestJson = { + displayName: "Defaults", + instanceConfigSchema: { type: "object", properties: { label: { type: "string", default: "Default" } } }, + }; + api.get.mockImplementation(async (id: string) => ({ id, packageName: "defaults", status: "error", categories: [], manifestJson })); + api.dashboard.mockResolvedValue(null); + api.getConfig.mockResolvedValue(null); + const saved = { configJson: { label: "Default" } }; + let finishSave!: (value: typeof saved) => void; + api.saveConfig.mockImplementation(() => new Promise((resolve) => { finishSave = resolve; })); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + client.setQueryData(queryKeys.instance.experimentalSettings, {}); + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + const render = async () => { + await act(async () => { root.render(); }); + await flushReact(); + await flushReact(); + }; + const saveButton = () => Array.from(container.querySelectorAll("button")).find((button) => button.textContent === "Save Configuration")!; + try { + await render(); + expect(saveButton().disabled).toBe(false); + await act(async () => { saveButton().click(); }); + expect(api.saveConfig).toHaveBeenCalledExactlyOnceWith("plugin-1", "company-1", { label: "Default" }); + if (selection === "company") state.companyId = "company-2"; + else state.pluginId = "plugin-2"; + await render(); + api.getConfig.mockImplementation(() => new Promise(() => {})); + await act(async () => { finishSave(saved); }); + await flushReact(); + await flushReact(); + expect(client.getQueryData(queryKeys.plugins.config(state.pluginId, state.companyId))).toBeNull(); + expect(client.getQueryData(queryKeys.plugins.config("plugin-1", "company-1"))).toEqual(saved); + expect(saveButton().disabled).toBe(false); + expect(container.querySelector("input")?.value).toBe("Default"); + } finally { + await act(async () => { root.unmount(); }); + client.clear(); + container.remove(); + vi.clearAllMocks(); + } +}); diff --git a/ui/src/pages/PluginSettings.test.tsx b/ui/src/pages/PluginSettings.test.tsx index d129f093637..0eae8e730ed 100644 --- a/ui/src/pages/PluginSettings.test.tsx +++ b/ui/src/pages/PluginSettings.test.tsx @@ -14,6 +14,7 @@ const mockPluginsApi = vi.hoisted(() => ({ dashboard: vi.fn(), logs: vi.fn(), getConfig: vi.fn(), + saveConfig: vi.fn(), listLocalFolders: vi.fn(), configureLocalFolder: vi.fn(), })); @@ -197,6 +198,114 @@ describe("PluginSettings", () => { }); }); + describe("generated configuration saves", () => { + beforeEach(() => { + mockPluginsApi.get.mockResolvedValue(basePlugin({ + manifestJson: { + displayName: "Default configuration", + instanceConfigSchema: { + type: "object", + properties: { label: { type: "string", default: "Default" } }, + }, + }, + })); + }); + + it("saves defaults without edits and disables saving after the row exists", async () => { + const saved = { configJson: { label: "Default" } }; + mockPluginsApi.getConfig.mockResolvedValue(null); + let finishSave!: (value: typeof saved) => void; + mockPluginsApi.saveConfig.mockImplementation(() => new Promise((resolve) => { finishSave = resolve; })); + const root = await renderSettings(container); + const button = Array.from(container.querySelectorAll("button")).find( + (item) => item.textContent === "Save Configuration", + )!; + + expect(button.disabled).toBe(false); + await act(async () => { button.click(); }); + expect(mockPluginsApi.saveConfig).toHaveBeenCalledWith("plugin-1", "company-1", { label: "Default" }); + expect(button.disabled).toBe(true); + + mockPluginsApi.getConfig.mockResolvedValue(saved); + await act(async () => { finishSave(saved); }); + await flushReact(); + await flushReact(); + expect(button.disabled).toBe(true); + await act(async () => { root.unmount(); }); + }); + + it.each([{}, { label: "Default" }])("keeps unchanged saved values disabled: %j", async (configJson) => { + mockPluginsApi.getConfig.mockResolvedValue({ configJson }); + const root = await renderSettings(container); + const button = Array.from(container.querySelectorAll("button")).find( + (item) => item.textContent === "Save Configuration", + )!; + expect(button.disabled).toBe(true); + const input = container.querySelector("input")!; + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "Changed"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + expect(button.disabled).toBe(false); + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "Default"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + expect(button.disabled).toBe(true); + await act(async () => { root.unmount(); }); + }); + + it("does not allow an initial save when configuration loading fails", async () => { + mockPluginsApi.getConfig.mockRejectedValue(new Error("Unavailable")); + const root = await renderSettings(container); + const button = Array.from(container.querySelectorAll("button")).find( + (item) => item.textContent === "Save Configuration", + )!; + expect(button.disabled).toBe(true); + await act(async () => { button.click(); }); + expect(mockPluginsApi.saveConfig).not.toHaveBeenCalled(); + await act(async () => { root.unmount(); }); + }); + + it("waits for configuration loading before offering an initial save", async () => { + let finishLoad!: (value: null) => void; + mockPluginsApi.getConfig.mockImplementation(() => new Promise((resolve) => { finishLoad = resolve; })); + const root = await renderSettings(container); + expect(Array.from(container.querySelectorAll("button")).some( + (item) => item.textContent === "Save Configuration", + )).toBe(false); + await act(async () => { finishLoad(null); }); + await flushReact(); + const button = Array.from(container.querySelectorAll("button")).find( + (item) => item.textContent === "Save Configuration", + )!; + expect(button.disabled).toBe(false); + await act(async () => { root.unmount(); }); + }); + + it("validates required fields before saving a missing configuration", async () => { + mockPluginsApi.get.mockResolvedValue(basePlugin({ + manifestJson: { + displayName: "Required configuration", + instanceConfigSchema: { + type: "object", + properties: { label: { type: "string" } }, + required: ["label"], + }, + }, + })); + mockPluginsApi.getConfig.mockResolvedValue(null); + const root = await renderSettings(container); + const button = Array.from(container.querySelectorAll("button")).find( + (item) => item.textContent === "Save Configuration", + )!; + expect(button.disabled).toBe(false); + await act(async () => { button.click(); }); + expect(mockPluginsApi.saveConfig).not.toHaveBeenCalled(); + await act(async () => { root.unmount(); }); + }); + }); + it("routes environment-provider plugins to instance environments when they have no instance config", async () => { const root = await renderSettings(container); diff --git a/ui/src/pages/PluginSettings.tsx b/ui/src/pages/PluginSettings.tsx index 86202461bca..5b4ed5ad3c0 100644 --- a/ui/src/pages/PluginSettings.tsx +++ b/ui/src/pages/PluginSettings.tsx @@ -106,7 +106,7 @@ export function PluginSettings() { ? queryKeys.plugins.config(pluginId, selectedCompanyId) : ["plugins", pluginId ?? "__missing_plugin__", "companies", "__missing_company__", "config"] as const; - const { data: configData, isLoading: configLoading } = useQuery({ + const { data: configData, isLoading: configLoading, isSuccess: configLoaded } = useQuery({ queryKey: configQueryKey, queryFn: () => pluginsApi.getConfig(pluginId!, selectedCompanyId!), enabled: !!pluginId && !!hasConfigSchema && !!selectedCompanyId, @@ -280,6 +280,7 @@ export function PluginSettings() { companyId={selectedCompanyId} schema={configSchema!} initialValues={configData?.configJson} + needsInitialSave={configLoaded && configData === null} isLoading={configLoading} pluginStatus={plugin.status} supportsConfigTest={(plugin as unknown as { supportsConfigTest?: boolean }).supportsConfigTest === true} @@ -958,6 +959,7 @@ interface PluginConfigFormProps { companyId: string | null; schema: JsonSchemaNode; initialValues?: Record; + needsInitialSave: boolean; isLoading?: boolean; /** Current plugin lifecycle status — "Test Configuration" only available when `ready`. */ pluginStatus?: string; @@ -972,7 +974,7 @@ interface PluginConfigFormProps { * Separated from PluginSettings to isolate re-render scope — only the form * re-renders on field changes, not the entire page. */ -function PluginConfigForm({ pluginId, companyId, schema, initialValues, isLoading, pluginStatus, supportsConfigTest }: PluginConfigFormProps) { +function PluginConfigForm({ pluginId, companyId, schema, initialValues, needsInitialSave, isLoading, pluginStatus, supportsConfigTest }: PluginConfigFormProps) { const queryClient = useQueryClient(); // Form values: start with saved values, fall back to schema defaults @@ -1012,14 +1014,15 @@ function PluginConfigForm({ pluginId, companyId, schema, initialValues, isLoadin // Save mutation const saveMutation = useMutation({ - mutationFn: (configJson: Record) => { + mutationFn: ({ pluginId, companyId, configJson }: { pluginId: string; companyId: string | null; configJson: Record }) => { if (!companyId) throw new Error("Select an organization before saving plugin configuration."); return pluginsApi.saveConfig(pluginId, companyId, configJson); }, - onSuccess: () => { + onSuccess: (savedConfig, { pluginId, companyId }) => { setSaveMessage({ type: "success", text: "Configuration saved." }); setTestResult(null); if (companyId) { + queryClient.setQueryData(queryKeys.plugins.config(pluginId, companyId), savedConfig); queryClient.invalidateQueries({ queryKey: queryKeys.plugins.config(pluginId, companyId) }); } // Clear success message after 3s @@ -1063,8 +1066,8 @@ function PluginConfigForm({ pluginId, companyId, schema, initialValues, isLoadin return; } setErrors({}); - saveMutation.mutate(values); - }, [schema, values, saveMutation]); + saveMutation.mutate({ pluginId, companyId, configJson: values }); + }, [schema, values, saveMutation, pluginId, companyId]); const handleTestConnection = useCallback(() => { // Validate before testing @@ -1126,7 +1129,7 @@ function PluginConfigForm({ pluginId, companyId, schema, initialValues, isLoadin