From 633c8076c0927c354ccae2ba1654f08711eeddec Mon Sep 17 00:00:00 2001 From: "commitperclip[bot]" <284812584+commitperclip[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:57:38 -0600 Subject: [PATCH] fix: Allow initial plugin configuration saves and scope completed saves to their original company and plugin (#19847) > [!NOTE] > Opened by Prospector's automated issue-fix pipeline. A maintainer reviews and decides; nothing here merges on its own. > [!WARNING] > This change crosses a trust boundary. See Risks. ## Thinking Path - Issue #17637 reports a defect in paperclipai/paperclip. - Root cause, as the fixing agent read it: Dirty tracking did not distinguish missing configuration records from saved defaults. The earlier attempt also updated the cache using the current selection rather than the identifiers captured when saving. - This pull request: Allow initial plugin configuration saves and scope completed saves to their original company and plugin ## What Changed - `ui/src/pages/PluginSettings.tsx`: Preserve initial saves after successful loading, validation, and pending guards. Capture pluginId and companyId in mutation variables and use them for persistence, cache updates, and invalidation. - `ui/src/pages/PluginSettings.test.tsx`: Retain coverage for initial defaults, saved values, loading failures, and validation. - `ui/src/pages/PluginSettings.save-refetch.test.tsx`: Retain coverage preventing duplicate unchanged saves during refetch. - `ui/src/pages/PluginSettings.save-scope.test.tsx`: Add company and plugin selection coverage during pending saves. The company case failed before the revision; all 17 relevant tests and the sandbox typecheck now pass. ## Verification - Reproducing test(s), added in this PR: `ui/src/pages/PluginSettings.save-scope.test.tsx`, `ui/src/pages/PluginSettings.test.tsx`, `ui/src/pages/PluginSettings.save-refetch.test.tsx` - They fail on the base commit and pass with the fix, each twice in a fresh sandbox. - 3 independent attempts wrote 3 reproductions; this fix passes every one of them. - The repository's compile command passes with the fix applied. - The full test suite passes except for the 15 file(s) that already fail on the base commit. - Revised in 1 round(s) of automated code review; 1 reviewer claim(s) were first shown by a failing test. ## Risks - Written by an automated pipeline, not a person: review it as you would an outside contribution. - Risk tier of the touched paths: 3. - The scope reviewer found it also changes, beyond the report: Config query is loading, errored, or disabled (no company selected) - The scope reviewer found it also changes, beyond the report: saveMutation.mutate call signature (internal) - It crosses a trust boundary. Check each crossing against what the issue asked for, and against who asked: - validation (ui/src/pages/PluginSettings.tsx:1131): The Save button's disable check is loosened from '!isDirty' to '!isDirty && !needsInitialSave', so an unchanged form can now be submitted when the company has no saved plugin_config row. ## Model Used - codex:gpt-6.1-sol, opus, sonnet (Anthropic Claude, via Claude Code; OpenAI, via the Codex CLI), writing and checking the change in an isolated sandbox. - opus (Anthropic Claude, via Claude Code), reviewing it independently. ## Linked Issues Fixes #17637 #17637 also mentions, without asking this fix for it: - Proactive company set / job-scope hole (#12109, #12655) (Report: "This is not a request to change proactive scope. That discussion belongs on #12109 and #12655.") Other pull requests that name #17637: - #17654 (open): fix(ui): allow saving default plugin configuration ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with 'Fixes: #' / 'Closes #' / 'Refs #' OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub '#NNN' / 'github.com/paperclipai/paperclip' URLs) - [ ] My branch name describes the change (e.g. 'docs/...', 'fix/...') and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com> --- .../PluginSettings.save-refetch.test.tsx | 102 ++++++++++++++++ .../pages/PluginSettings.save-scope.test.tsx | 83 +++++++++++++ ui/src/pages/PluginSettings.test.tsx | 109 ++++++++++++++++++ ui/src/pages/PluginSettings.tsx | 17 +-- 4 files changed, 304 insertions(+), 7 deletions(-) create mode 100644 ui/src/pages/PluginSettings.save-refetch.test.tsx create mode 100644 ui/src/pages/PluginSettings.save-scope.test.tsx 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