feat: operator-configurable settings visibility via PAPERCLIP_HIDDEN_SETTINGS (#11823)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The instance settings surface (Access, Plugins, Adapters, General,
Experimental) assumes the person at the keyboard operates the whole
instance
> - Operators who host Paperclip for others — a managed cloud or an
internal shared server — expose settings pages and toggles that do not
apply to their deployment, and the related mutation APIs stay open
> - A hosted tenant can open Plugins or Adapters, try an action, and hit
a confusing failure, because only a few hardcoded platform floors exist
> - This pull request adds a generic, operator-configured visibility
mechanism: one env var hides declared settings surfaces in the UI and
floors their mutation routes with a stable 403 code
> - The benefit is a clean hosted-tenant settings surface for any
operator, with zero behavior change for normal self-hosted instances

## Linked Issues or Issue Description

**Subsystem affected**

Instance settings (server routes and UI), the shared settings registry
in `packages/shared`, and the `/api/health` bootstrap payload.

**Problem or motivation**

An operator who hosts Paperclip for other people cannot hide settings
surfaces that the platform manages. Tenants see Access, Plugins, and
Adapters pages, backup retention, and host-level experimental toggles
that do nothing useful for them. The mutation APIs behind these surfaces
also stay open, so a tenant admin can attempt actions the platform must
control. ROADMAP.md names a cleaner shared deployment story as a goal
("Teams should be able to run the same product in hosted or semi-hosted
environments without changing the mental model").

**Proposed solution**

Add a declarative registry of hideable settings surfaces and one env
var, `PAPERCLIP_HIDDEN_SETTINGS`. The server parses the list at boot,
reports it on `/api/health`, and rejects value-changing writes to hidden
surfaces with a stable `settings_operator_managed` 403 code. The UI
reads the list from the health payload and removes the hidden pages,
sections, and toggles from navigation, routes, and page content. Unknown
keys warn and are ignored, so one list can roll across a fleet with
mixed app versions. With the variable unset, behavior is byte-identical
to today.

**Alternatives considered**

- Hardcode the hidden set for cloud instances in this repo: rejected,
because each hosting operator needs a different policy, and policy does
not belong in shared code.
- Deliver the hidden set through the managed-config document: rejected,
because that channel is cloud-specific and fail-closed on unknown
fields; a plain env var works for any operator, including self-hosted
shared servers.
- Lock the controls with a badge instead of hiding them: rejected for
these surfaces, because they are meaningless to tenants, not merely
platform-controlled; the existing managed-overlay lock stays the right
tool for controlled flags.

**Roadmap alignment**

Supports the "shared deployment story" item in ROADMAP.md: hosted and
semi-hosted deployments keep the same product with a settings surface
that matches what the tenant can actually do.

## What Changed

- New `packages/shared/src/settings-visibility.ts`: registry of hideable
surfaces (every instance settings page — profile, environments, access,
heartbeats, experimental, plugins, adapters; every Instance → General
section; every experimental flag as `instance.experimental.<key>`), the
`PAPERCLIP_HIDDEN_SETTINGS` parser, and the `settings_operator_managed`
error code. The General page stays visible as the settings root and
redirect target.
- New `server/src/services/settings-visibility.ts`: parse-once accessor;
unknown keys log one warning and are ignored.
- `/api/health` reports `hiddenSettings` on every response shape; the
field is omitted when nothing is hidden.
- Server floors on hidden surfaces, with same-value echo tolerance (the
`executionMode` precedent): field-backed general sections and
experimental keys reject value-changing PATCHes, and hiding the whole
Experimental page floors every toggle; plugin lifecycle and config
writes, adapter management writes, and the Access admin routes (reads
included) return 403 `settings_operator_managed`. Reads the app itself
needs (plugin `ui-contributions`, adapter metadata, plugin job trigger)
stay open. Pages without instance-scoped mutation routes are hidden in
the UI only.
- UI: new `useHiddenSettings` hook and `HiddenSettingsPageGate` route
gate (hidden pages redirect to the settings root); the settings sidebar
and tab bar drop hidden entries; remembered settings paths remap to the
default page; `InstanceGeneralSettings` skips hidden sections; every
`ExperimentalToggleCard` now carries its flag key and renders nothing
when hidden.
- Removed the dead `InstanceSidebar` component (referenced only by its
own test).
- Docs: `docs/deploy/environment-variables.md` documents the variable
and the key registry.

## Verification

- `pnpm vitest run` over the new and extended suites: shared registry
and parser, representative floor tests per route class (changed-value
403, same-value echo 200, unset env 200, page-level Experimental
hiding), the health field, the route gate, nav filtering, and
section/card hiding with one hidden example per surface kind — 168 tests
pass.
- Full root `pnpm typecheck` passes.
- Manual: booted a server with the variable set. `/api/health` lists the
keys; an unknown key logs one warning and the server boots; hidden pages
redirect; hidden sections and cards do not render; hidden-field PATCH
returns 403 with `details.code = "settings_operator_managed"`; a
same-value echo returns 200. Unset the variable: the full settings
surface returns and responses are byte-identical to master.

## Risks

- Low risk for self-hosted instances: with the variable unset, the
hidden set is empty, the health field is omitted, and no floor
activates.
- Flooring plugin config writes assumes hosted deployments configure
plugins through the platform. If a future bundled plugin needs
tenant-entered config, the floor needs a narrow carve-out.
- Hidden-key floors tolerate same-value echoes, so API clients that
round-trip full GET responses keep working.
- Hiding a toggle does not change its value; operators pair hiding with
the desired default where the value matters.

## Model Used

Claude Fable 5 (Anthropic, `claude-fable-5`) with extended thinking and
agentic tool use, driven through the Claude Code CLI (file edits, test
execution, and live-server verification loops).

## 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)
- [x] 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
- [x] 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
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Devin Foley authored and GitHub committed 2026-08-20 17:54:44 -07:00
1 parent 0fa318b8da
commit db4defdfbf
32 files changed
+1328 -414

No files matched your search

@@ -3,6 +3,7 @@
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { queryKeys } from "@/lib/queryKeys";
import { CompanySettingsSidebar } from "./CompanySettingsSidebar";
const sidebarNavItemMock = vi.hoisted(() => vi.fn());
@@ -353,3 +354,64 @@ describe("CompanySettingsSidebar", () => {
});
});
});
describe("CompanySettingsSidebar operator-hidden entries", () => {
let container: HTMLDivElement;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
mockSidebarBadgesApi.get.mockResolvedValue({
inbox: 0,
approvals: 0,
failedRuns: 0,
joinRequests: 0,
});
mockPluginsApi.list.mockResolvedValue([]);
mockUsePluginSlots.mockReturnValue({ slots: [], isLoading: false, errorMessage: null });
});
afterEach(() => {
container.remove();
document.body.innerHTML = "";
vi.clearAllMocks();
});
async function renderSidebar(hiddenSettings?: string[]) {
const root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
queryClient.setQueryData(queryKeys.health, {
status: "ok",
...(hiddenSettings ? { hiddenSettings } : {}),
});
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<CompanySettingsSidebar />
</QueryClientProvider>,
);
});
await flushReact();
}
it("skips operator-hidden pages and their queries", async () => {
await renderSidebar(["instance.plugins", "instance.heartbeats"]);
expect(container.textContent).not.toContain("Plugins");
expect(container.textContent).not.toContain("Heartbeats");
expect(container.textContent).toContain("General");
expect(container.textContent).toContain("Adapters");
expect(container.textContent).toContain("Access");
expect(mockPluginsApi.list).not.toHaveBeenCalled();
});
it("keeps every entry when nothing is hidden", async () => {
await renderSidebar();
expect(container.textContent).toContain("Access");
expect(container.textContent).toContain("Plugins");
expect(container.textContent).toContain("Heartbeats");
expect(container.textContent).toContain("Adapters");
expect(mockPluginsApi.list).toHaveBeenCalled();
});
});
+61 -40
View File
@@ -25,6 +25,7 @@ import { SIDEBAR_SCROLL_RESET_STATE } from "@/lib/navigation-scroll";
import { queryKeys } from "@/lib/queryKeys";
import { useCompany } from "@/context/CompanyContext";
import { useSidebar } from "@/context/SidebarContext";
import { useHiddenSettings } from "@/hooks/useHiddenSettings";
import { usePluginSlots } from "@/plugins/slots";
import { SidebarNavItem } from "./SidebarNavItem";
@@ -43,6 +44,9 @@ function isSandboxProviderOnly(plugin: PluginRecord): boolean {
export function CompanySettingsSidebar() {
const { selectedCompany, selectedCompanyId } = useCompany();
const { isMobile, setSidebarOpen } = useSidebar();
const { hidden: hiddenSettings } = useHiddenSettings();
const showPage = (pageKey: string) => !hiddenSettings.has(pageKey);
const showPlugins = showPage("instance.plugins");
const { slots: companySettingsPluginSlots } = usePluginSlots({
slotTypes: ["companySettingsPage"],
companyId: selectedCompanyId,
@@ -69,6 +73,9 @@ export function CompanySettingsSidebar() {
const { data: plugins } = useQuery({
queryKey: queryKeys.plugins.all,
queryFn: () => pluginsApi.list(),
// The listing only feeds the per-plugin subtree below; skip it when the
// operator hides the Plugins surface.
enabled: showPlugins,
});
const sidebarPlugins = (plugins ?? []).filter((plugin) => !isSandboxProviderOnly(plugin));
@@ -90,12 +97,14 @@ export function CompanySettingsSidebar() {
<nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2">
<div className="flex flex-col gap-0.5">
<SidebarNavItem to="/company/settings" label="General" icon={SlidersHorizontal} end />
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/profile`}
label="Profile"
icon={UserRoundPen}
end
/>
{showPage("instance.profile") && (
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/profile`}
label="Profile"
icon={UserRoundPen}
end
/>
)}
<SidebarNavItem
to="/company/settings/members"
label="Members"
@@ -116,37 +125,47 @@ export function CompanySettingsSidebar() {
))}
<SidebarNavItem to="/company/settings/invites" label="Invites" icon={MailPlus} end />
<SidebarNavItem to="/company/settings/secrets" label="Secrets" icon={KeyRound} end />
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/environments`}
label="Environments"
icon={MonitorCog}
end
/>
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/access`}
label="Access"
icon={Shield}
end
/>
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/heartbeats`}
label="Heartbeats"
icon={Clock3}
end
/>
{showPage("instance.environments") && (
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/environments`}
label="Environments"
icon={MonitorCog}
end
/>
)}
{showPage("instance.access") && (
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/access`}
label="Access"
icon={Shield}
end
/>
)}
{showPage("instance.heartbeats") && (
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/heartbeats`}
label="Heartbeats"
icon={Clock3}
end
/>
)}
<SidebarNavItem to="/company/export" label="Export" icon={Download} />
<SidebarNavItem to="/company/import" label="Import" icon={Upload} end />
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/experimental`}
label="Experimental"
icon={FlaskConical}
/>
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/plugins`}
label="Plugins"
icon={Puzzle}
/>
{sidebarPlugins.length > 0 ? (
{showPage("instance.experimental") && (
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/experimental`}
label="Experimental"
icon={FlaskConical}
/>
)}
{showPlugins && (
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/plugins`}
label="Plugins"
icon={Puzzle}
/>
)}
{showPlugins && sidebarPlugins.length > 0 ? (
<div className="ml-4 mt-1 flex flex-col gap-0.5 border-l border-border/70 pl-3">
{sidebarPlugins.map((plugin) => (
<NavLink
@@ -167,11 +186,13 @@ export function CompanySettingsSidebar() {
))}
</div>
) : null}
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/adapters`}
label="Adapters"
icon={Cpu}
/>
{showPage("instance.adapters") && (
<SidebarNavItem
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/adapters`}
label="Adapters"
icon={Cpu}
/>
)}
</div>
</nav>
</aside>
@@ -0,0 +1,88 @@
// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { queryKeys } from "@/lib/queryKeys";
import { HiddenSettingsPageGate } from "./HiddenSettingsPageGate";
vi.mock("@/lib/router", () => ({
Navigate: ({ to, replace }: { to: string; replace?: boolean }) => (
<div data-testid="navigate" data-to={to} data-replace={String(replace)} />
),
Outlet: () => <div data-testid="page-content">Page content</div>,
}));
async function flushReact() {
for (let index = 0; index < 5; index += 1) {
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
}
flushSync(() => {});
}
describe("HiddenSettingsPageGate", () => {
let container: HTMLDivElement;
let root: Root | null = null;
async function renderGate(pageKey: string, health?: Record<string, unknown>) {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
if (health !== undefined) {
queryClient.setQueryData(queryKeys.health, health);
}
flushSync(() => {
root!.render(
<QueryClientProvider client={queryClient}>
<HiddenSettingsPageGate pageKey={pageKey} />
</QueryClientProvider>,
);
});
await flushReact();
}
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
afterEach(() => {
flushSync(() => root?.unmount());
root = null;
container.remove();
vi.clearAllMocks();
});
it("redirects to the settings root when the page is operator-hidden", async () => {
await renderGate("instance.plugins", {
status: "ok",
hiddenSettings: ["instance.plugins", "instance.adapters"],
});
expect(container.querySelector('[data-testid="navigate"]')?.getAttribute("data-to")).toBe(
"/company/settings",
);
expect(container.querySelector('[data-testid="page-content"]')).toBeNull();
});
it("renders the page when it is not hidden", async () => {
await renderGate("instance.plugins", { status: "ok", hiddenSettings: ["instance.access"] });
expect(container.querySelector('[data-testid="page-content"]')).not.toBeNull();
expect(container.querySelector('[data-testid="navigate"]')).toBeNull();
});
it("renders the page when nothing is hidden at all", async () => {
await renderGate("instance.adapters", { status: "ok" });
expect(container.querySelector('[data-testid="page-content"]')).not.toBeNull();
});
it("renders nothing until health is cached", async () => {
await renderGate("instance.plugins");
expect(container.querySelector('[data-testid="page-content"]')).toBeNull();
expect(container.querySelector('[data-testid="navigate"]')).toBeNull();
});
});
@@ -0,0 +1,17 @@
import { Navigate, Outlet } from "@/lib/router";
import { useHiddenSettings } from "@/hooks/useHiddenSettings";
/**
* Route gate for instance-settings pages the hosting operator can hide
* (`instance.access`, `instance.plugins`, `instance.adapters`). Hidden pages
* redirect to the settings root instead of rendering; until health is cached
* nothing renders, so a hidden page never flashes. Under CloudAccessGate the
* health response is always cached before board routes mount.
*/
export function HiddenSettingsPageGate({ pageKey }: { pageKey: string }) {
const { hidden, loaded } = useHiddenSettings();
if (!loaded) return null;
if (hidden.has(pageKey)) return <Navigate to="/company/settings" replace />;
return <Outlet />;
}
-288
View File
@@ -1,288 +0,0 @@
// @vitest-environment jsdom
import type { ReactNode } 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 type { PluginRecord } from "@paperclipai/shared";
const mockPluginsApi = vi.hoisted(() => ({
list: vi.fn(),
}));
vi.mock("@/api/plugins", () => ({
pluginsApi: mockPluginsApi,
}));
vi.mock("@/lib/router", () => ({
NavLink: ({
children,
to,
className,
}: {
children: ReactNode | ((arg: { isActive: boolean }) => ReactNode);
to: string;
state?: unknown;
end?: boolean;
onClick?: () => void;
className?: string | ((arg: { isActive: boolean }) => string);
}) => {
const resolvedClass =
typeof className === "function" ? className({ isActive: false }) : className;
const content = typeof children === "function" ? children({ isActive: false }) : children;
return (
<a href={to} className={resolvedClass}>
{content}
</a>
);
},
}));
vi.mock("../context/SidebarContext", () => ({
useSidebar: () => ({ isMobile: false, setSidebarOpen: vi.fn() }),
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
import { InstanceSidebar } from "./InstanceSidebar";
async function act(callback: () => void | Promise<void>) {
await callback();
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
}
function makePlugin(overrides: Partial<PluginRecord> & { manifestJson: PluginRecord["manifestJson"] }): PluginRecord {
return {
id: overrides.id ?? "plugin-id",
pluginKey: overrides.pluginKey ?? "plugin-key",
packageName: overrides.packageName ?? "@scope/pkg",
version: overrides.version ?? "1.0.0",
apiVersion: overrides.apiVersion ?? 1,
categories: overrides.categories ?? [],
manifestJson: overrides.manifestJson,
status: overrides.status ?? "ready",
installOrder: overrides.installOrder ?? 0,
packagePath: overrides.packagePath ?? null,
lastError: overrides.lastError ?? null,
installedAt: overrides.installedAt ?? new Date(0),
updatedAt: overrides.updatedAt ?? new Date(0),
};
}
async function flushReact() {
await act(async () => {
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
});
}
async function findPluginLinks(container: HTMLElement, expectedCount: number) {
await act(async () => {
await vi.waitFor(() => {
expect(container.querySelectorAll('a[href^="/company/settings/instance/plugins/"]')).toHaveLength(expectedCount);
});
});
return Array.from(container.querySelectorAll<HTMLAnchorElement>('a[href^="/company/settings/instance/plugins/"]'));
}
function renderSidebar(container: HTMLElement) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0 } },
});
const root = createRoot(container);
act(() => {
root.render(
<QueryClientProvider client={queryClient}>
<InstanceSidebar />
</QueryClientProvider>,
);
});
return { root, queryClient };
}
describe("InstanceSidebar", () => {
let container: HTMLDivElement;
let root: ReturnType<typeof createRoot> | null;
let queryClient: QueryClient | null;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = null;
queryClient = null;
mockPluginsApi.list.mockReset();
});
afterEach(async () => {
if (root) {
const currentRoot = root;
await act(async () => {
currentRoot.unmount();
});
}
queryClient?.clear();
container.remove();
document.body.innerHTML = "";
vi.clearAllMocks();
});
it("filters out sandbox-provider-only plugins from the sidebar", async () => {
const sandboxPlugin = makePlugin({
id: "e2b",
packageName: "@paperclipai/plugin-e2b",
manifestJson: {
id: "e2b",
name: "E2B Sandbox Provider",
displayName: "E2B Sandbox Provider",
version: "1.0.0",
apiVersion: 1,
environmentDrivers: [
{
driverKey: "e2b",
kind: "sandbox_provider",
displayName: "E2B",
configSchema: { type: "object" },
},
],
} as unknown as PluginRecord["manifestJson"],
});
const regularPlugin = makePlugin({
id: "linear",
packageName: "@paperclipai/plugin-linear",
manifestJson: {
id: "linear",
name: "Linear",
displayName: "Linear",
version: "1.0.0",
apiVersion: 1,
} as unknown as PluginRecord["manifestJson"],
});
mockPluginsApi.list.mockResolvedValue([sandboxPlugin, regularPlugin]);
const rendered = renderSidebar(container);
root = rendered.root;
queryClient = rendered.queryClient;
await flushReact();
const pluginLinks = await findPluginLinks(container, 1);
expect(pluginLinks[0]?.getAttribute("href")).toBe("/company/settings/instance/plugins/linear");
expect(pluginLinks[0]?.textContent).toBe("Linear");
expect(container.textContent).not.toContain("Access");
expect(container.textContent).not.toContain("Heartbeats");
});
it("keeps plugins that mix sandbox-provider with other contributions", async () => {
const hybridPlugin = makePlugin({
id: "hybrid",
packageName: "@example/plugin-hybrid",
manifestJson: {
id: "hybrid",
name: "Hybrid",
displayName: "Hybrid",
version: "1.0.0",
apiVersion: 1,
environmentDrivers: [
{
driverKey: "sb",
kind: "sandbox_provider",
displayName: "SB",
configSchema: { type: "object" },
},
{
driverKey: "env",
kind: "environment_driver",
displayName: "Env",
configSchema: { type: "object" },
},
],
} as unknown as PluginRecord["manifestJson"],
});
mockPluginsApi.list.mockResolvedValue([hybridPlugin]);
const rendered = renderSidebar(container);
root = rendered.root;
queryClient = rendered.queryClient;
await flushReact();
const pluginLinks = await findPluginLinks(container, 1);
expect(pluginLinks[0]?.getAttribute("href")).toBe("/company/settings/instance/plugins/hybrid");
});
it("renders the indented plugin list between the Plugins and Adapters rows", async () => {
mockPluginsApi.list.mockResolvedValue([
makePlugin({
id: "linear",
packageName: "@paperclipai/plugin-linear",
manifestJson: {
id: "linear",
name: "Linear",
displayName: "Linear",
version: "1.0.0",
apiVersion: 1,
} as unknown as PluginRecord["manifestJson"],
}),
]);
const rendered = renderSidebar(container);
root = rendered.root;
queryClient = rendered.queryClient;
await flushReact();
await findPluginLinks(container, 1);
await vi.waitFor(() => {
const links = Array.from(
container.querySelectorAll<HTMLAnchorElement>('a[href^="/company/settings/instance/"]'),
);
expect(links.some((a) => a.getAttribute("href") === "/company/settings/instance/plugins/linear")).toBe(true);
});
const topLevelLinks = Array.from(container.querySelectorAll<HTMLAnchorElement>('a[href^="/company/settings/instance/"]'));
const hrefs = topLevelLinks.map((a) => a.getAttribute("href"));
const pluginsIndex = hrefs.indexOf("/company/settings/instance/plugins");
const adaptersIndex = hrefs.indexOf("/company/settings/instance/adapters");
const linearIndex = hrefs.indexOf("/company/settings/instance/plugins/linear");
expect(pluginsIndex).toBeGreaterThanOrEqual(0);
expect(adaptersIndex).toBeGreaterThan(pluginsIndex);
expect(linearIndex).toBeGreaterThan(pluginsIndex);
expect(linearIndex).toBeLessThan(adaptersIndex);
});
it("does not render the indented group when every plugin is filtered out", async () => {
mockPluginsApi.list.mockResolvedValue([
makePlugin({
id: "e2b",
packageName: "@paperclipai/plugin-e2b",
manifestJson: {
id: "e2b",
name: "E2B",
displayName: "E2B",
version: "1.0.0",
apiVersion: 1,
environmentDrivers: [
{
driverKey: "e2b",
kind: "sandbox_provider",
displayName: "E2B",
configSchema: { type: "object" },
},
],
} as unknown as PluginRecord["manifestJson"],
}),
]);
const rendered = renderSidebar(container);
root = rendered.root;
queryClient = rendered.queryClient;
await flushReact();
await vi.waitFor(() => {
expect(mockPluginsApi.list).toHaveBeenCalled();
});
const pluginLinks = Array.from(container.querySelectorAll('a[href^="/company/settings/instance/plugins/"]'));
expect(pluginLinks).toHaveLength(0);
});
});
-66
View File
@@ -1,66 +0,0 @@
import { useQuery } from "@tanstack/react-query";
import { Cpu, FlaskConical, MonitorCog, Puzzle, SlidersHorizontal, UserRoundPen } from "lucide-react";
import type { PluginRecord } from "@paperclipai/shared";
import { NavLink } from "@/lib/router";
import { pluginsApi } from "@/api/plugins";
import { INSTANCE_SETTINGS_PATH_PREFIX } from "@/lib/instance-settings";
import { queryKeys } from "@/lib/queryKeys";
import { SIDEBAR_SCROLL_RESET_STATE } from "@/lib/navigation-scroll";
import { SidebarNavItem } from "./SidebarNavItem";
/**
* Sandbox-provider-only plugins (e.g. E2B, exe.dev, Modal) have no per-plugin
* settings page — `PluginSettings` redirects them to the Environments page —
* so a sidebar entry would lead nowhere useful. Filter them out here. Plugins
* that mix a sandbox provider with other contributions still appear.
*/
function isSandboxProviderOnly(plugin: PluginRecord): boolean {
const drivers = plugin.manifestJson.environmentDrivers ?? [];
if (drivers.length === 0) return false;
return drivers.every((d) => d.kind === "sandbox_provider");
}
export function InstanceSidebar() {
const { data: plugins } = useQuery({
queryKey: queryKeys.plugins.all,
queryFn: () => pluginsApi.list(),
});
const sidebarPlugins = (plugins ?? []).filter((p) => !isSandboxProviderOnly(p));
return (
<aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">
<nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide flex flex-col gap-4 px-3 py-2">
<div className="flex flex-col gap-0.5">
<SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/profile`} label="Profile" icon={UserRoundPen} end />
<SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/general`} label="General" icon={SlidersHorizontal} end />
<SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/environments`} label="Environments" icon={MonitorCog} end />
<SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/experimental`} label="Experimental" icon={FlaskConical} />
<SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/plugins`} label="Plugins" icon={Puzzle} />
{sidebarPlugins.length > 0 ? (
<div className="ml-4 mt-1 flex flex-col gap-0.5 border-l border-border/70 pl-3">
{sidebarPlugins.map((plugin) => (
<NavLink
key={plugin.id}
to={`${INSTANCE_SETTINGS_PATH_PREFIX}/plugins/${plugin.id}`}
state={SIDEBAR_SCROLL_RESET_STATE}
className={({ isActive }) =>
[
"rounded-md px-2 py-1.5 text-xs transition-colors",
isActive
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground",
].join(" ")
}
>
{plugin.manifestJson.displayName ?? plugin.packageName}
</NavLink>
))}
</div>
) : null}
<SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/adapters`} label="Adapters" icon={Cpu} />
</div>
</nav>
</aside>
);
}
@@ -2,7 +2,9 @@
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { queryKeys } from "@/lib/queryKeys";
import { CompanySettingsNav, getCompanySettingsTab } from "./CompanySettingsNav";
let currentPathname = "/company/settings";
@@ -89,12 +91,25 @@ describe("CompanySettingsNav", () => {
expect(getCompanySettingsTab("/company/settings/instance/adapters")).toBe("instance-adapters");
});
function renderNav(root: ReturnType<typeof createRoot>, hiddenSettings?: string[]) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
queryClient.setQueryData(queryKeys.health, {
status: "ok",
...(hiddenSettings ? { hiddenSettings } : {}),
});
root.render(
<QueryClientProvider client={queryClient}>
<CompanySettingsNav />
</QueryClientProvider>,
);
}
it("renders the active tab and navigates when a different tab is selected", async () => {
currentPathname = "/PAP/company/settings/members";
const root = createRoot(container);
await act(async () => {
root.render(<CompanySettingsNav />);
renderNav(root);
});
expect(container.textContent).toContain("members");
@@ -132,4 +147,34 @@ describe("CompanySettingsNav", () => {
root.unmount();
});
});
it("filters operator-hidden tabs out of the tab bar", async () => {
currentPathname = "/PAP/company/settings/members";
const root = createRoot(container);
await act(async () => {
renderNav(root, ["instance.plugins", "instance.heartbeats"]);
});
const renderedValues = pageTabBarMock.mock.calls.at(-1)?.[0]?.items?.map(
(item: { value: string }) => item.value,
);
expect(renderedValues).toEqual([
"general",
"export",
"import",
"members",
"invites",
"secrets",
"instance-profile",
"instance-environments",
"instance-access",
"instance-experimental",
"instance-adapters",
]);
await act(async () => {
root.unmount();
});
});
});
@@ -1,5 +1,6 @@
import { PageTabBar } from "@/components/PageTabBar";
import { Tabs } from "@/components/ui/tabs";
import { useHiddenSettings } from "@/hooks/useHiddenSettings";
import { INSTANCE_SETTINGS_PATH_PREFIX } from "@/lib/instance-settings";
import { useLocation, useNavigate } from "@/lib/router";
@@ -21,6 +22,17 @@ const items = [
type CompanySettingsTab = (typeof items)[number]["value"];
/** Tab values suppressed when their page is operator-hidden. */
const hiddenSettingKeyByTab: Partial<Record<CompanySettingsTab, string>> = {
"instance-profile": "instance.profile",
"instance-environments": "instance.environments",
"instance-access": "instance.access",
"instance-heartbeats": "instance.heartbeats",
"instance-experimental": "instance.experimental",
"instance-plugins": "instance.plugins",
"instance-adapters": "instance.adapters",
};
export function getCompanySettingsTab(pathname: string): CompanySettingsTab {
if (pathname.includes(`${INSTANCE_SETTINGS_PATH_PREFIX}/profile`)) {
return "instance-profile";
@@ -84,10 +96,15 @@ export function getCompanySettingsTab(pathname: string): CompanySettingsTab {
export function CompanySettingsNav() {
const location = useLocation();
const navigate = useNavigate();
const { hidden: hiddenSettings } = useHiddenSettings();
const activeTab = getCompanySettingsTab(location.pathname);
const visibleItems = items.filter((item) => {
const hiddenKey = hiddenSettingKeyByTab[item.value];
return !hiddenKey || !hiddenSettings.has(hiddenKey);
});
function handleTabChange(value: string) {
const nextTab = items.find((item) => item.value === value);
const nextTab = visibleItems.find((item) => item.value === value);
if (!nextTab || nextTab.value === activeTab) return;
navigate(nextTab.href);
}
@@ -95,7 +112,7 @@ export function CompanySettingsNav() {
return (
<Tabs value={activeTab} onValueChange={handleTabChange}>
<PageTabBar
items={items.map(({ value, label }) => ({ value, label }))}
items={visibleItems.map(({ value, label }) => ({ value, label }))}
value={activeTab}
onValueChange={handleTabChange}
align="start"