Files
PaperClipAI/ui/src/components/InboxAgentPolicyControl.test.tsx
T
DottaandPaperclip e826188e82 refactor(settings): unify settings and speed up exports (#11789)
## Thinking Path

> - Paperclip is the open source app that people use to manage AI agents
for work.
> - Operators use the settings area to control a company and its
Paperclip instance.
> - The current navigation separates related settings and uses duplicate
instance pages.
> - Company exports also do independent reads in sequence and do extra
work for previews.
> - Hardened workspace commands can differ from their saved command
after loopback binding.
> - This pull request makes these related operator workflows consistent
and faster.
> - The benefit is one clear settings area, faster exports, and stable
runtime command matching.

## Linked Issues or Issue Description

Refs #338

Related: #9834

**What existing behavior does this improve?**

This improves the company settings UI, company export preparation, and
workspace runtime command matching.

**Current behavior**

Company and instance settings use separate navigation and duplicate
pages. Export preparation reads many independent records in sequence.
Preview generation can also build an unused organization image. A
command with a forced loopback bind can fail to match its saved runtime
command.

**Proposed behavior**

Use one settings navigation and put general instance controls on the
company General page. Load independent export data with bounded
concurrency, skip unused preview image work, and load the export page
only when it is needed. Treat the loopback-bound form of a command as
the same runtime command.

**Reason and benefit**

Operators get one clear settings area. Large company exports need fewer
serialized reads. Export previews and initial UI loads do less work.
Hardened runtime services remain linked to their saved command
definitions.

**Breaking changes**

The obsolete instance General URL redirects to the unified settings
page. Access and Heartbeats remain available, and legacy bookmarks keep
their destinations. No API response shape or database schema changes.

## What Changed

- Unified company and instance settings navigation and removed duplicate
instance settings pages.
- Embedded general instance controls in the company General page and
kept access-sensitive navigation behavior.
- Preserved instance Access and Heartbeats controls in the unified
navigation and normalized old bookmarks to those destinations.
- Improved environment and access-state handling when workspace seed
requests overlap.
- Added bounded export reads, a lighter preview path, deferred export
preparation, and lazy export-page loading.
- Matched loopback-bound runtime commands to their saved command
definitions.
- Added focused shared, server, and UI regression tests.

## Verification

- `pnpm exec vitest run <18 changed test files>`: 18 files and 256 tests
passed.
- `pnpm check:token-gates`: passed all four token gates.
- `pnpm -r typecheck`: passed for all workspace projects.
- `pnpm build`: passed for all workspace projects.
- `pnpm test:run`: tests ran without a reported failure, but the runner
did not close after the server handoff tests. The process closed with
status 0 after an interrupt.
- Focused latest-head route tests: 2 files and 4 tests passed.
- GitHub latest-head checks: all completed without failure.
- Greptile: 5/5 with no unresolved review threads.

## Risks

- Medium risk: settings routes and navigation changed across several
operator roles.
- Medium risk: bounded export concurrency increases simultaneous
database reads. The limits stay below the normal pool size.
- Low risk: runtime command matching accepts only the known Tailscale
HTTPS loopback transformation.
- No migrations are included.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex with a GPT-5-family coding model. The runtime does not
expose the exact deployed model ID or context-window size. Reasoning,
tool use, and local code execution were enabled.

## 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)
- [x] 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

Exception: This task requires the existing execution branch. The harness
does not permit a branch rename.
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-08-20 12:15:16 -05:00

213 lines
7.5 KiB
TypeScript

// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { InboxAgentPolicy } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { InboxAgentPolicyControl } from "./InboxAgentPolicyControl";
const mockAgentsApi = vi.hoisted(() => ({ list: vi.fn() }));
const mockInboxAgentPolicyApi = vi.hoisted(() => ({ getMine: vi.fn(), updateMine: vi.fn() }));
vi.mock("@/api/agents", () => ({ agentsApi: mockAgentsApi }));
vi.mock("@/api/inbox-agent-policy", () => ({ inboxAgentPolicyApi: mockInboxAgentPolicyApi }));
vi.mock("./AgentIconPicker", () => ({ AgentIcon: () => null }));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
async function act(callback: () => void | Promise<void>) {
let result: void | Promise<void> = undefined;
flushSync(() => {
result = callback();
});
await result;
}
async function flush() {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
}
async function waitForAssertion(assertion: () => void, attempts = 20) {
let lastError: unknown;
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
assertion();
return;
} catch (error) {
lastError = error;
await flush();
}
}
throw lastError;
}
function policy(overrides: Partial<InboxAgentPolicy> = {}): InboxAgentPolicy {
return {
companyId: "company-1",
userId: "user-1",
mode: "open",
allowedAgentIds: [],
materialized: false,
createdAt: null,
updatedAt: null,
...overrides,
};
}
function render(container: HTMLDivElement) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const root = createRoot(container);
act(() => {
root.render(
<QueryClientProvider client={queryClient}>
<InboxAgentPolicyControl companyId="company-1" />
</QueryClientProvider>,
);
});
return root;
}
function optionByTitle(container: HTMLElement, title: string) {
return Array.from(container.querySelectorAll('[role="radio"]'))
.find((node) => node.textContent?.includes(title)) as HTMLButtonElement | undefined;
}
describe("InboxAgentPolicyControl", () => {
let container: HTMLDivElement;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
mockAgentsApi.list.mockResolvedValue([
{ id: "agent-1", name: "Gardener", role: "gardener", status: "active", icon: null },
{ id: "agent-2", name: "Coder", role: "engineer", status: "active", icon: null },
{ id: "agent-3", name: "Retired", role: "engineer", status: "terminated", icon: null },
]);
mockInboxAgentPolicyApi.getMine.mockResolvedValue(policy());
mockInboxAgentPolicyApi.updateMine.mockImplementation((_companyId: string, input) =>
Promise.resolve(policy({ ...input, materialized: true })),
);
});
afterEach(() => {
document.body.innerHTML = "";
vi.clearAllMocks();
});
it("surfaces policy load failures instead of staying on loading", async () => {
mockInboxAgentPolicyApi.getMine.mockRejectedValue(new Error("Policy endpoint failed"));
const root = render(container);
await flush();
await waitForAssertion(() => {
expect(container.textContent).toContain("Policy endpoint failed");
expect(container.textContent).not.toContain("Loading inbox agent policy");
});
act(() => root.unmount());
});
it("renders all three policy states with the persisted mode selected", async () => {
mockInboxAgentPolicyApi.getMine.mockResolvedValue(policy({ mode: "disabled" }));
const root = render(container);
await flush();
await waitForAssertion(() => {
expect(optionByTitle(container, "Any of my agents")).toBeTruthy();
expect(optionByTitle(container, "Only chosen agents")).toBeTruthy();
expect(optionByTitle(container, "Off")).toBeTruthy();
expect(optionByTitle(container, "Off")?.getAttribute("aria-checked")).toBe("true");
expect(optionByTitle(container, "Any of my agents")?.getAttribute("aria-checked")).toBe("false");
});
act(() => root.unmount());
});
it("round-trips an allowlist selection through the PUT endpoint", async () => {
const root = render(container);
await flush();
// Save disabled until the draft diverges from the persisted policy.
await waitForAssertion(() => {
const save = Array.from(container.querySelectorAll("button")).find((b) => b.textContent?.includes("Save"));
expect(save?.disabled).toBe(true);
});
// Switch to allowlist — agents stay in the compact selector instead of a
// permanently expanded list.
await act(async () => optionByTitle(container, "Only chosen agents")!.click());
await flush();
await waitForAssertion(() => {
expect(container.textContent).toContain("Select agents");
expect(container.textContent).not.toContain("Gardener");
expect(container.textContent).not.toContain("Coder");
expect(container.textContent).not.toContain("Retired");
});
const selector = Array.from(container.querySelectorAll("button"))
.find((button) => button.textContent?.includes("Select agents"));
await act(async () => selector!.click());
await flush();
await waitForAssertion(() => {
expect(document.body.textContent).toContain("Gardener");
expect(document.body.textContent).toContain("Coder");
expect(document.body.textContent).not.toContain("Retired");
});
const gardenerCheckbox = document.body.querySelector<HTMLButtonElement>(
'button[aria-label="Allow Gardener"]',
);
expect(gardenerCheckbox).toBeTruthy();
await act(async () => gardenerCheckbox!.click());
await flush();
const saveButton = Array.from(container.querySelectorAll("button")).find((b) => b.textContent?.includes("Save"))!;
await waitForAssertion(() => expect(saveButton.disabled).toBe(false));
await act(async () => saveButton.click());
await flush();
expect(mockInboxAgentPolicyApi.updateMine).toHaveBeenCalledWith("company-1", {
mode: "allowlist",
allowedAgentIds: ["agent-1"],
});
await waitForAssertion(() => {
expect(container.textContent).toContain("Saved");
const save = Array.from(container.querySelectorAll("button")).find((b) => b.textContent?.includes("Save"));
expect(save?.disabled).toBe(true);
});
act(() => root.unmount());
});
it("clears the allowlist when switching to Off before saving", async () => {
mockInboxAgentPolicyApi.getMine.mockResolvedValue(policy({ mode: "allowlist", allowedAgentIds: ["agent-1"], materialized: true }));
const root = render(container);
await flush();
await waitForAssertion(() => {
expect(optionByTitle(container, "Only chosen agents")?.getAttribute("aria-checked")).toBe("true");
});
await act(async () => optionByTitle(container, "Off")!.click());
await flush();
const saveButton = Array.from(container.querySelectorAll("button")).find((b) => b.textContent?.includes("Save"))!;
await waitForAssertion(() => expect(saveButton.disabled).toBe(false));
await act(async () => saveButton.click());
await flush();
expect(mockInboxAgentPolicyApi.updateMine).toHaveBeenCalledWith("company-1", {
mode: "disabled",
allowedAgentIds: [],
});
act(() => root.unmount());
});
});