Files
PaperClipAI/ui/src/pages/PluginSettings.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

600 lines
21 KiB
TypeScript

// @vitest-environment jsdom
import { act } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ApiError } from "@/api/client";
import { queryKeys } from "../lib/queryKeys";
import { PluginSettings } from "./PluginSettings";
const mockPluginsApi = vi.hoisted(() => ({
get: vi.fn(),
health: vi.fn(),
dashboard: vi.fn(),
logs: vi.fn(),
getConfig: vi.fn(),
saveConfig: vi.fn(),
listLocalFolders: vi.fn(),
configureLocalFolder: vi.fn(),
}));
const mockSetBreadcrumbs = vi.hoisted(() => vi.fn());
const mockRoute = vi.hoisted(() => ({ pluginId: "plugin-1" }));
const mockSlots = vi.hoisted(() => ({ slots: [] as Array<Record<string, unknown>> }));
vi.mock("@/api/plugins", () => ({
pluginsApi: mockPluginsApi,
}));
vi.mock("@/context/BreadcrumbContext", () => ({
useBreadcrumbs: () => ({
setBreadcrumbs: mockSetBreadcrumbs,
}),
}));
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 }) => <a href={to}>{children}</a>,
Navigate: () => null,
useParams: () => ({ companyPrefix: "PAP", pluginId: mockRoute.pluginId }),
}));
vi.mock("@/plugins/slots", () => ({
PluginSlotMount: ({ slot }: { slot: { id: string } }) => <div data-testid="settings-slot">{slot.id}</div>,
usePluginSlots: () => ({ slots: mockSlots.slots }),
}));
vi.mock("@/components/PageTabBar", () => ({
PageTabBar: () => null,
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
async function flushReact() {
await act(async () => {
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
});
}
function basePlugin(overrides: Record<string, unknown> = {}) {
return {
id: "plugin-1",
pluginKey: "paperclip.e2b-sandbox-provider",
packageName: "@paperclipai/plugin-e2b",
version: "0.1.0",
status: "error",
categories: ["automation"],
manifestJson: {
displayName: "E2B Sandbox Provider",
version: "0.1.0",
description: "E2B environments for Paperclip.",
author: "Paperclip",
capabilities: ["environment.drivers.register"],
environmentDrivers: [
{
driverKey: "e2b",
kind: "sandbox_provider",
displayName: "E2B Cloud Sandbox",
},
],
},
lastError: null,
...overrides,
};
}
function wikiFolderDeclaration() {
return {
folderKey: "wiki-root",
displayName: "Wiki root",
description: "Company-scoped local folder that stores wiki files.",
access: "readWrite" as const,
requiredDirectories: ["raw", "wiki"],
requiredFiles: ["WIKI.md", "index.md"],
};
}
function folderStatus(overrides: Record<string, unknown> = {}) {
return {
folderKey: "wiki-root",
configured: false,
path: null,
realPath: null,
access: "readWrite",
readable: false,
writable: false,
requiredDirectories: ["raw", "wiki"],
requiredFiles: ["WIKI.md", "index.md"],
missingDirectories: ["raw", "wiki"],
missingFiles: ["WIKI.md", "index.md"],
healthy: false,
problems: [{ code: "not_configured", message: "No local folder path is configured." }],
checkedAt: "2026-05-02T16:00:00.000Z",
...overrides,
};
}
async function renderSettings(
container: HTMLDivElement,
experimentalSettings: Record<string, unknown> = {},
) {
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
// The local-folders section is a host-path surface, so it stays hidden until
// the managed-sandbox-only policy is known. Seed the policy as off; the tests
// below are about folder rendering, not about the gate.
queryClient.setQueryData(queryKeys.instance.experimentalSettings, experimentalSettings);
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<PluginSettings />
</QueryClientProvider>,
);
});
await flushReact();
await flushReact();
return root;
}
describe("PluginSettings", () => {
let container: HTMLDivElement;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
mockPluginsApi.get.mockResolvedValue(basePlugin());
mockPluginsApi.dashboard.mockResolvedValue(null);
mockPluginsApi.health.mockResolvedValue({ pluginId: "plugin-1", status: "ready", healthy: true, checks: [] });
mockPluginsApi.logs.mockResolvedValue([]);
mockPluginsApi.listLocalFolders.mockResolvedValue({
pluginId: "plugin-1",
companyId: "company-1",
declarations: [],
folders: [],
});
});
afterEach(() => {
container.remove();
document.body.innerHTML = "";
vi.clearAllMocks();
mockRoute.pluginId = "plugin-1";
mockSlots.slots = [];
});
it("shows a plugin's custom settings page when the route names the plugin by key", async () => {
mockRoute.pluginId = "acme.website-preview";
mockSlots.slots = [
{ id: "settings", type: "settingsPage", pluginId: "plugin-1", pluginKey: "acme.website-preview" },
{ id: "other-settings", type: "settingsPage", pluginId: "plugin-2", pluginKey: "acme.other" },
];
mockPluginsApi.get.mockResolvedValue(basePlugin({
pluginKey: "acme.website-preview",
status: "ready",
manifestJson: { displayName: "Website Preview", version: "0.1.0", capabilities: [] },
}));
const root = await renderSettings(container);
const mounted = [...container.querySelectorAll('[data-testid="settings-slot"]')].map((node) => node.textContent);
expect(mounted).toEqual(["settings"]);
expect(container.textContent).not.toContain("This plugin does not require any settings.");
await act(async () => {
root.unmount();
});
});
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);
expect(container.textContent).toContain("Configure this plugin from Settings → Environments.");
expect(container.textContent).toContain("secret bindings still resolve through the selected organization context");
const link = container.querySelector('a[href="/company/settings/instance/environments"]');
expect(link?.textContent).toContain("Open Environments");
await act(async () => {
root.unmount();
});
});
it("renders unconfigured manifest local folders with required paths", async () => {
const declaration = wikiFolderDeclaration();
mockPluginsApi.get.mockResolvedValue(basePlugin({
pluginKey: "paperclipai.plugin-llm-wiki",
packageName: "@paperclipai/plugin-llm-wiki",
status: "ready",
manifestJson: {
displayName: "LLM Wiki",
version: "0.1.0",
description: "Local-file LLM Wiki plugin.",
author: "Paperclip",
capabilities: ["local.folders"],
localFolders: [declaration],
},
}));
mockPluginsApi.listLocalFolders.mockResolvedValue({
pluginId: "plugin-1",
companyId: "company-1",
declarations: [declaration],
folders: [folderStatus()],
});
const root = await renderSettings(container);
expect(container.textContent).toContain("Local folders");
expect(container.textContent).toContain("Wiki root");
expect(container.textContent).toContain("Needs attention");
expect(container.textContent).toContain("No local folder path is configured.");
expect(container.textContent).toContain("Missing directories: raw, wiki");
expect(container.textContent).toContain("Missing files: WIKI.md, index.md");
await act(async () => {
root.unmount();
});
});
it("keeps loaded local folder statuses on screen when their refetch fails transiently", async () => {
const declaration = wikiFolderDeclaration();
mockPluginsApi.get.mockResolvedValue(basePlugin({
pluginKey: "paperclipai.plugin-llm-wiki",
packageName: "@paperclipai/plugin-llm-wiki",
status: "ready",
manifestJson: {
displayName: "LLM Wiki",
version: "0.1.0",
description: "Local-file LLM Wiki plugin.",
author: "Paperclip",
capabilities: ["local.folders"],
localFolders: [declaration],
},
}));
mockPluginsApi.listLocalFolders.mockResolvedValue({
pluginId: "plugin-1",
companyId: "company-1",
declarations: [declaration],
folders: [folderStatus()],
});
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
queryClient.setQueryData(queryKeys.instance.experimentalSettings, {});
const root = createRoot(container);
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<PluginSettings />
</QueryClientProvider>,
);
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("No local folder path is configured.");
mockPluginsApi.listLocalFolders.mockRejectedValue(
new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }),
);
await act(async () => {
await queryClient.invalidateQueries({ queryKey: queryKeys.plugins.localFolders("plugin-1", "company-1") });
});
await flushReact();
expect(mockPluginsApi.listLocalFolders).toHaveBeenCalledTimes(2);
expect(container.textContent).toContain("Wiki root");
expect(container.textContent).toContain("No local folder path is configured.");
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
expect(container.textContent).not.toContain("Paperclip is restarting.");
expect(container.textContent).not.toContain("tenant_app_unavailable");
await act(async () => {
root.unmount();
});
});
it("shows readable copy with Retry instead of leaving the page when the plugin fails to load", async () => {
mockPluginsApi.get
.mockRejectedValueOnce(new ApiError("Boom", 500, { error: "Boom" }))
.mockResolvedValue(basePlugin());
const root = await renderSettings(container);
expect(container.querySelector('[data-query-view="error"]')).not.toBeNull();
expect(container.textContent).toContain("Couldn't load this plugin");
expect(container.textContent).not.toContain("E2B Sandbox Provider");
const retryButton = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent === "Retry",
);
expect(retryButton, "Retry button").toBeTruthy();
await act(async () => {
retryButton!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
await flushReact();
expect(container.textContent).toContain("E2B Sandbox Provider");
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
await act(async () => {
root.unmount();
});
});
it("hides local folders when the instance runs agents only in the platform-managed environment", async () => {
const declaration = wikiFolderDeclaration();
mockPluginsApi.get.mockResolvedValue(basePlugin({
pluginKey: "paperclipai.plugin-llm-wiki",
packageName: "@paperclipai/plugin-llm-wiki",
status: "ready",
manifestJson: {
displayName: "LLM Wiki",
version: "0.1.0",
description: "Local-file LLM Wiki plugin.",
author: "Paperclip",
capabilities: ["local.folders"],
localFolders: [declaration],
},
}));
mockPluginsApi.listLocalFolders.mockResolvedValue({
pluginId: "plugin-1",
companyId: "company-1",
declarations: [declaration],
folders: [folderStatus()],
});
const root = await renderSettings(container, { enableManagedSandboxOnly: true });
// The platform-managed environment owns the filesystem, so the whole
// section disappears rather than showing paths nobody can act on.
expect(container.textContent).not.toContain("Local folders");
await act(async () => {
root.unmount();
});
});
it("renders invalid configured folders with validation problems", async () => {
const declaration = wikiFolderDeclaration();
mockPluginsApi.get.mockResolvedValue(basePlugin({
manifestJson: {
displayName: "LLM Wiki",
version: "0.1.0",
description: "Local-file LLM Wiki plugin.",
author: "Paperclip",
capabilities: ["local.folders"],
localFolders: [declaration],
},
}));
mockPluginsApi.listLocalFolders.mockResolvedValue({
pluginId: "plugin-1",
companyId: "company-1",
declarations: [declaration],
folders: [folderStatus({
configured: true,
path: "/tmp/wiki",
realPath: "/tmp/wiki",
readable: true,
writable: true,
missingDirectories: [],
missingFiles: ["WIKI.md"],
problems: [{ code: "missing_file", message: "Required file is missing.", path: "WIKI.md" }],
})],
});
const root = await renderSettings(container);
expect(container.textContent).toContain("/tmp/wiki");
expect(container.textContent).toContain("ReadableYes");
expect(container.textContent).toContain("WritableYes");
expect(container.textContent).toContain("Validation problems");
expect(container.textContent).toContain("Required file is missing.");
expect(container.textContent).toContain("Missing files: WIKI.md");
await act(async () => {
root.unmount();
});
});
it("does not render required paths as present when the configured root cannot be inspected", async () => {
const declaration = wikiFolderDeclaration();
mockPluginsApi.get.mockResolvedValue(basePlugin({
manifestJson: {
displayName: "LLM Wiki",
version: "0.1.0",
description: "Local-file LLM Wiki plugin.",
author: "Paperclip",
capabilities: ["local.folders"],
localFolders: [declaration],
},
}));
mockPluginsApi.listLocalFolders.mockResolvedValue({
pluginId: "plugin-1",
companyId: "company-1",
declarations: [declaration],
folders: [folderStatus({
configured: true,
path: "/tmp/wiki-missing",
readable: false,
writable: false,
missingDirectories: [],
missingFiles: [],
problems: [{ code: "missing", message: "Configured local folder cannot be inspected.", path: "/tmp/wiki-missing" }],
})],
});
const root = await renderSettings(container);
expect(container.textContent).toContain("Configured local folder cannot be inspected.");
expect(container.textContent).toContain("Not inspected");
expect(container.textContent).toContain("Configured root was not inspected.");
expect(container.textContent).not.toContain("Present");
await act(async () => {
root.unmount();
});
});
it("renders healthy folders without validation problems", async () => {
const declaration = wikiFolderDeclaration();
mockPluginsApi.get.mockResolvedValue(basePlugin({
manifestJson: {
displayName: "LLM Wiki",
version: "0.1.0",
description: "Local-file LLM Wiki plugin.",
author: "Paperclip",
capabilities: ["local.folders"],
localFolders: [declaration],
},
}));
mockPluginsApi.listLocalFolders.mockResolvedValue({
pluginId: "plugin-1",
companyId: "company-1",
declarations: [declaration],
folders: [folderStatus({
configured: true,
path: "/tmp/wiki",
realPath: "/private/tmp/wiki",
readable: true,
writable: true,
missingDirectories: [],
missingFiles: [],
healthy: true,
problems: [],
})],
});
const root = await renderSettings(container);
expect(container.textContent).toContain("Healthy");
expect(container.textContent).toContain("Configured path");
expect(container.textContent).toContain("/tmp/wiki");
expect(container.textContent).toContain("ReadableYes");
expect(container.textContent).toContain("WritableYes");
expect(container.textContent).toContain("Present");
expect(container.textContent).not.toContain("Validation problems");
await act(async () => {
root.unmount();
});
});
});