Files
PaperClipAI/ui/src/pages/PluginSettings.save-scope.test.tsx
T
commitperclip[bot] 633c8076c0 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

<!-- prospector:issue-fix v1 issue=17637 base=d1ee25d0f722
report=44fc7d94342a1efd -->

Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-11-13 12:57:38 -06:00

84 lines
3.8 KiB
TypeScript

// @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 }) => <a href={to}>{children}</a>,
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(<QueryClientProvider client={client}><PluginSettings /></QueryClientProvider>); });
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();
}
});