Make harness choices deployment-configurable

Managed deployments need to control harness availability without changing Core policy. Add a generic environment contract and apply it across harness and model selectors, preserving saved supported profiles and validating import, team, and invite selections. Document deployment ownership in agent guidance.

Validation: focused local tests and typechecks passed; all applicable CI checks passed on the reviewed head. Greptile scored 5/5 with no unresolved comments.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-11-20 15:45:36 -08:00
1 parent 104f323bee
commit ae2afd525b
35 files changed
+822 -88

No files matched your search

+7
View File
@@ -99,6 +99,13 @@ preflight", "Start Dev", "Quick Health Checks", and "Database in Dev" in
4. **Keep behavior with its owning module.**
Provider protocols, payload parsing, and feature-specific sequencing belong to the module that owns them. Shared code uses narrow, normalized contracts. Explain any substantive change outside the owning module. See [`rules/module-boundaries.mdc`](rules/module-boundaries.mdc).
5. **Keep deployment policy out of Core.**
Do not hardcode Cloud allowlists, provider choices, or deployment-specific
defaults here. Core provides generic, documented configuration mechanisms;
the deployment repository supplies and owns its policy. Changing a Cloud
policy must not require a Core code change. See
[harness availability](doc/harness-availability.md) for an example contract.
## 6. Database Changes
Follow "Schema change workflow" in `doc/DATABASE.md`: edit the schema, run
+41
View File
@@ -0,0 +1,41 @@
# Deployment-configured harness availability
Core owns the mechanism for filtering harness choices. The deployment owns
the policy. Do not add a built-in Cloud provider allowlist to Core; change the
deployment's environment configuration when its supported harnesses change.
Managed deployments can set `PAPERCLIP_AVAILABLE_HARNESSES` to a JSON array of
canonical harness IDs, for example `["gemini_local"]`. The server publishes
the array as `cloud.availableHarnesses` on `/api/health`; every Cloud harness
selector uses that metadata. This includes creation and direct setup links,
agent configuration, issue and composer settings, bulk edits, imports, team
installs, and invites. Model catalogs for excluded harnesses are not fetched
by those controls.
- Unset: no additional deployment restriction. Existing adapter availability,
feature flags, and qualification rules still apply.
- `[]`: no harness choices.
- Invalid JSON, non-array values, invalid IDs, more than 128 entries, or a
value over 16 KiB: no choices, with a warning that omits the supplied value.
- IDs use lowercase letters, digits, `_`, `:`, and `-`, start with a letter,
and are at most 128 characters. Duplicates are removed. Syntactically valid
unknown IDs are accepted so configuration does not require a Core registry
update; they do not install or enable an adapter.
IDs follow `agentRuntimeSettingsHarness` in
`packages/shared/src/agent-runner.ts`. Native Runner profiles map to
their underlying harness (for example ACP Copilot is `copilot_runtime`), so
allowing the Runner adapter alone cannot bypass a profile restriction.
Existing agents can retain their stored configuration; selectors and import
or install submissions cannot select an excluded profile.
Change the environment value and restart/redeploy the tenant server. The UI
uses the shared health cache; reload the page after rollout to fetch the new
policy. The parser also reflects changed values on subsequent health requests
in runtimes that update their environment in place. No UI build is needed.
Without managed Cloud metadata this setting has no effect.
This is a UI availability policy, not an execution authorization boundary.
It does not revoke credentials, stop existing agents, or qualify experimental
harnesses. Operators must deploy a Core revision that supports this contract
before relying on it; older revisions ignore the variable.
@@ -0,0 +1,30 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { logger } from "../middleware/logger.js";
import { getAvailableHarnesses } from "../services/harness-availability.js";
describe("deployment harness availability", () => {
afterEach(() => vi.restoreAllMocks());
it("has no built-in deployment allowlist", () => {
expect(getAvailableHarnesses({})).toBeUndefined();
});
it("accepts deployment-chosen IDs and refreshes when configuration changes", () => {
const env = { PAPERCLIP_AVAILABLE_HARNESSES: '["gemini_local","plugin:example","gemini_local"]' };
expect(getAvailableHarnesses(env)).toEqual(["gemini_local", "plugin:example"]);
env.PAPERCLIP_AVAILABLE_HARNESSES = '["pi_local"]';
expect(getAvailableHarnesses(env)).toEqual(["pi_local"]);
env.PAPERCLIP_AVAILABLE_HARNESSES = "[]";
expect(getAvailableHarnesses(env)).toEqual([]);
expect(getAvailableHarnesses({})).toBeUndefined();
});
it.each(["", "claude_local", "{}", "null", '["valid",1]', '["Invalid"]', '["has space"]', JSON.stringify(["a".repeat(129)]), JSON.stringify(Array(129).fill("codex_local")), " ".repeat(16_385)])(
"fails closed for malformed configuration %# without logging its value", raw => {
getAvailableHarnesses({});
const warn = vi.spyOn(logger, "warn").mockImplementation(() => undefined);
expect(getAvailableHarnesses({ PAPERCLIP_AVAILABLE_HARNESSES: raw })).toEqual([]);
expect(warn).toHaveBeenCalledExactlyOnceWith("PAPERCLIP_AVAILABLE_HARNESSES is invalid; harness selection is disabled");
},
);
});
+14
View File
@@ -116,6 +116,20 @@ describe("GET /health", () => {
});
});
it("publishes deployment harness policy and reflects configuration updates", async () => {
const env = {
PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token",
PAPERCLIP_PRIMARY_HOST: "example.paperclip.app",
PAPERCLIP_AVAILABLE_HARNESSES: '["gemini_local","plugin:example"]',
};
const app = createApp(undefined, testServerInfo, undefined, env);
expect((await request(app).get("/health")).body.cloud.availableHarnesses).toEqual(["gemini_local", "plugin:example"]);
env.PAPERCLIP_AVAILABLE_HARNESSES = "[]";
expect((await request(app).get("/health")).body.cloud.availableHarnesses).toEqual([]);
env.PAPERCLIP_AVAILABLE_HARNESSES = "invalid";
expect((await request(app).get("/health")).body.cloud.availableHarnesses).toEqual([]);
});
it("lists operator-hidden settings and drops unknown keys", async () => {
const app = createApp(undefined, testServerInfo, undefined, {
PAPERCLIP_HIDDEN_SETTINGS: "instance.plugins,instance.adapters,instance.bogus",
+3
View File
@@ -20,6 +20,7 @@ import {
} from "../services/cloud-instance.js";
import { getCloudRuntimeIdentity } from "../services/cloud-runtime-identity.js";
import { getHiddenSettings } from "../services/settings-visibility.js";
import { getAvailableHarnesses } from "../services/harness-availability.js";
import {
inspectDatabaseBackupHealth,
type DatabaseBackupHealthStatus,
@@ -102,12 +103,14 @@ function getCloudHealthStatus(env: CloudInstanceEnv) {
const context = getCloudStackContext(env);
if (!context) return undefined;
const runtimeIdentity = env === process.env ? getCloudRuntimeIdentity() : null;
const availableHarnesses = getAvailableHarnesses(env);
return {
managed: true as const,
managedBy: "paperclip-cloud" as const,
stackSlug: context.stackSlug,
cloudBaseUrl: context.cloudOrigin,
...(availableHarnesses !== undefined ? { availableHarnesses } : {}),
...(runtimeIdentity ? {
runtimeIdentity: {
canonicalOrigin: runtimeIdentity.canonicalOrigin,
@@ -0,0 +1,28 @@
import { logger } from "../middleware/logger.js";
export const AVAILABLE_HARNESSES_ENV_KEY = "PAPERCLIP_AVAILABLE_HARNESSES";
const harnessId = /^[a-z][a-z0-9_:-]{0,127}$/;
let cache: { raw: string | undefined; available: string[] | undefined } | undefined;
/** Unset leaves existing choices intact; an empty array or invalid value allows none. */
export function getAvailableHarnesses(env: Record<string, string | undefined> = process.env): string[] | undefined {
const raw = env[AVAILABLE_HARNESSES_ENV_KEY];
if (cache && cache.raw === raw) return cache.available;
let available: string[] | undefined;
if (raw !== undefined) {
let entries: unknown;
try {
entries = raw.length <= 16_384 ? JSON.parse(raw) : null;
} catch {
entries = null;
}
if (!Array.isArray(entries) || entries.length > 128 || entries.some((entry) => typeof entry !== "string" || !harnessId.test(entry))) {
logger.warn(`${AVAILABLE_HARNESSES_ENV_KEY} is invalid; harness selection is disabled`);
available = [];
} else {
available = [...new Set(entries)];
}
}
cache = { raw, available };
return available;
}
@@ -9,6 +9,7 @@ import { beforeAll, describe, expect, it } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
import { sampleHarnesses } from "@/test-support/harness-availability";
import { CodexLocalConfigFields } from "./config-fields";
import { buildCodexRunnerConfig } from "./config-fields";
import { buildPaperclipRunnerConfig } from "@paperclipai/adapter-codex-local/ui";
@@ -17,22 +18,23 @@ import { resolveCodexLocalCliPolicy } from "@paperclipai/adapter-codex-local";
beforeAll(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); });
async function renderMarkup(node: ReactNode, expand?: string, inspect?: (container: HTMLElement) => void): Promise<string> {
async function renderMarkup(node: ReactNode, expand?: string, inspect?: (container: HTMLElement) => void | Promise<void>): Promise<string> {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => root.render(<QueryClientProvider client={new QueryClient()}>{node}</QueryClientProvider>));
const client = new QueryClient();
await act(async () => root.render(<QueryClientProvider client={client}>{node}</QueryClientProvider>));
if (expand) await act(async () => {
container.querySelector(`[aria-label="${expand}"]`)?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
});
inspect?.(container);
await inspect?.(container);
const html = container.innerHTML + Array.from(document.body.children).filter(child => child !== container).map(child => child.outerHTML).join("");
await act(async () => root.unmount());
container.remove();
return html;
}
async function renderRunner(config: Record<string, unknown>, expand?: string, inspectOrDot?: ((container: HTMLElement) => void) | boolean): Promise<string> {
async function renderRunner(config: Record<string, unknown>, expand?: string, inspectOrDot?: ((container: HTMLElement) => void) | boolean, cloud = false): Promise<string> {
const openAiDotEnabled = inspectOrDot === true;
const inspect = typeof inspectOrDot === "function" ? inspectOrDot : undefined;
return renderMarkup(
@@ -48,6 +50,7 @@ async function renderRunner(config: Record<string, unknown>, expand?: string, in
mark={() => undefined}
models={[]}
hideInstructionsFile
availableHarnesses={cloud ? sampleHarnesses : undefined}
openAiDotEnabled={openAiDotEnabled}
/>
</TooltipProvider>,
@@ -55,6 +58,37 @@ async function renderRunner(config: Record<string, unknown>, expand?: string, in
);
}
it("withholds unsupported Cloud Runner providers even for an existing native agent", async () => {
const html = await renderRunner({ provider: "codex" }, "Harness", undefined, true);
expect(html).toContain("Codex");
expect(html).toContain("OpenCode");
expect(html).toContain("Grok Build");
for (const label of ["Claude Managed", "AWS AgentCore", "Cursor Cloud", "Antigravity"]) expect(html).not.toContain(label);
});
it("offers only released ACP profiles on Cloud", async () => {
const html = await renderRunner({ provider: "acpx", acpxAgent: "claude" }, "ACP agent", undefined, true);
expect(html).toContain("Claude");
expect(html).toContain("Copilot");
for (const label of ["Antigravity", "Kimi", "Cursor", "qualification pending"]) expect(html).not.toContain(label);
});
it("selects an allowed ACP default when deployment configuration excludes Claude", async () => {
const changes: Record<string, unknown> = {};
await renderMarkup(<TooltipProvider><CodexLocalConfigFields mode="edit" isCreate={false}
adapterType="paperclip_runner" values={null} set={null} config={{ provider: "codex" }}
eff={(_group, _field, original) => original} mark={(_group, field, value) => { changes[field] = value; }}
models={[]} hideInstructionsFile availableHarnesses={["copilot_runtime"]} />
</TooltipProvider>, "Harness", async () => {
const option = [...document.querySelectorAll('[role="option"]')].find(element => element.textContent?.includes("ACP agents"));
expect(option).toBeDefined();
await act(async () => option!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));
expect(changes.provider).toBe("acpx");
expect(changes.acpxAgent).toBe("copilot");
expect(changes.model).toBe("");
});
});
async function selectField(container: HTMLElement, label: string, value: string) {
const picker = container.querySelector<HTMLButtonElement>(`[aria-label="${label}"]`)!;
await act(async () => {
+14 -5
View File
@@ -1,5 +1,7 @@
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, SelectPopover } from "../../components/ui/select";
import { AdapterMark } from "../../components/AdapterMark";
import { createCloudHarnessPolicy } from "@/lib/cloud-harness-policy";
import { useMemo } from "react";
import { MuseRunnerConnection } from "../../components/MuseRunnerConnection";
import { GrokBotConnection } from "../../components/GrokBotConnection";
import { DotRunnerConnection } from "../../components/DotRunnerConnection";
@@ -83,8 +85,12 @@ export function CodexLocalConfigFields({
models,
hideInstructionsFile,
managedSandboxOnly,
availableHarnesses,
hideRunnerHarness,
}: AdapterConfigFieldsProps) {
const harnessPolicy = useMemo(() => createCloudHarnessPolicy(availableHarnesses), [availableHarnesses]);
const allowedAcpxProfiles = PAPERCLIP_RUNNER_ACPX_PROFILES.filter(profile => profile.qualified && harnessPolicy.isCloudRunnerProviderAllowed("acpx", profile.value));
const defaultAcpxAgent = allowedAcpxProfiles.find(profile => profile.value === "claude")?.value ?? allowedAcpxProfiles[0]?.value ?? "claude";
const runnerManaged = adapterType === "paperclip_runner";
// The execution engine picks which binary runs on the execution host, and the
// ACP sub-fields below name host paths. The platform-managed environment owns
@@ -240,6 +246,7 @@ export function CodexLocalConfigFields({
value={runnerProvider === "acpx" && runnerSchemaValue("acpxAgent", "claude") === "grok" ? "grok" : runnerProvider}
onValueChange={(value) => {
const grok = value === "grok";
const acpxAgent = grok ? "grok" : defaultAcpxAgent;
const provider = grok ? "acpx" : isPaperclipRunnerProvider(value)
? value
: "codex";
@@ -254,7 +261,7 @@ export function CodexLocalConfigFields({
: provider === "aws_agentcore"
? defaultAwsAgentCoreModel
: provider === "acpx"
? grok ? "grok-4.7" : defaultAcpxClaudeModel
? grok ? "grok-4.7" : acpxAgent === "claude" ? defaultAcpxClaudeModel : ""
: provider === "cursor_cloud" ? ""
: DEFAULT_CODEX_LOCAL_MODEL;
if (isCreate) {
@@ -267,7 +274,7 @@ export function CodexLocalConfigFields({
acpxSessionMode: undefined,
piThinkingLevel: undefined,
...(provider === "cursor_cloud" ? { ...Object.fromEntries(cloudResetKeys.map(key => [key, undefined])), lifecycleMode: "per_turn" } : {}),
...(provider === "acpx" ? { acpxAgent: grok ? "grok" : "claude" } : {}),
...(provider === "acpx" ? { acpxAgent, acpxSessionMode: acpxAgent === "cursor" ? "agent" : undefined, piThinkingLevel: acpxAgent === "pi" ? "low" : undefined } : {}),
},
});
} else {
@@ -280,7 +287,9 @@ export function CodexLocalConfigFields({
for (const key of ["cwd", "env", "instructionsFilePath", "command", "extraArgs", "engine", "modelReasoningEffort", "workspaceStrategy", "workspaceRuntime", "idleTimeoutMs", "acpxAgent", "managedProfileId", "agentCoreProfileId"]) mark("adapterConfig", key, undefined);
}
if (provider === "acpx") {
mark("adapterConfig", "acpxAgent", grok ? "grok" : "claude");
mark("adapterConfig", "acpxAgent", acpxAgent);
mark("adapterConfig", "acpxSessionMode", acpxAgent === "cursor" ? "agent" : undefined);
mark("adapterConfig", "piThinkingLevel", acpxAgent === "pi" ? "low" : undefined);
}
if (provider === "cursor_cloud") {
mark("adapterConfig", "lifecycleMode", "per_turn");
@@ -292,7 +301,7 @@ export function CodexLocalConfigFields({
<SelectTrigger className="w-full" aria-label="Harness"><SelectValue /></SelectTrigger>
<SelectContent>
{!isPaperclipRunnerProvider(runnerProvider) && <SelectItem value={runnerProvider} disabled>{runnerProvider} (unknown provider)</SelectItem>}
{runnerHarnessOptions.map((option) => (
{runnerHarnessOptions.filter(option => option.value === "acpx" ? !harnessPolicy.restricted || allowedAcpxProfiles.length > 0 : harnessPolicy.isCloudRunnerProviderAllowed(option.value)).map((option) => (
<SelectItem key={option.value} value={option.value}>
<AdapterMark type={option.adapter} className="size-4" />
{option.label}
@@ -357,7 +366,7 @@ export function CodexLocalConfigFields({
}}>
<SelectTrigger className="w-full" aria-label="ACP agent"><SelectValue /></SelectTrigger>
<SelectContent>
{PAPERCLIP_RUNNER_ACPX_PROFILES.map(profile => (
{PAPERCLIP_RUNNER_ACPX_PROFILES.filter(profile => !harnessPolicy.restricted || (profile.qualified && harnessPolicy.isCloudRunnerProviderAllowed("acpx", profile.value))).map(profile => (
<SelectItem key={profile.value} value={profile.value} disabled={!profile.qualified}>
<AdapterMark type={profile.value === "cursor" ? "cursor" : `${profile.value}_local`} className="size-4" />
{profile.label}{profile.qualified ? "" : " — qualification pending"}
+2
View File
@@ -51,6 +51,8 @@ export interface AdapterConfigFieldsProps {
* so a stored path never flashes before the policy resolves.
*/
managedSandboxOnly?: boolean;
/** Operator-supplied selection policy; absent leaves existing choices intact. */
availableHarnesses?: readonly string[];
/** Show Dot for new selections only when its experimental prerequisites are enabled. */
openAiDotEnabled?: boolean;
/** Personal Muse is offered only with its own flag and the native Runner enabled. */
+2
View File
@@ -18,6 +18,8 @@ export type DevServerHealthStatus = {
};
export type CloudInstanceHealthStatus = {
/** Operator-supplied harness IDs. Absent means unrestricted; [] allows none. */
availableHarnesses?: string[];
managed: true;
managedBy: "paperclip-cloud";
stackSlug: string | null;
@@ -1,4 +1,5 @@
// @vitest-environment jsdom
import { sampleHarnesses } from "@/test-support/harness-availability";
import { useState } from "react";
import { MemoryRouter } from "react-router-dom";
@@ -332,6 +333,7 @@ async function renderForm(
onDirtyChange?: (dirty: boolean) => void;
onSaveActionChange?: (save: (() => void) | null) => void;
onCancelActionChange?: (cancel: (() => void) | null) => void;
cloud?: boolean;
} = {},
) {
mockEnvironmentsApi.list.mockResolvedValue(environments);
@@ -341,6 +343,7 @@ async function renderForm(
const root = createRoot(container);
const onSave = vi.fn();
const queryClient = createFormQueryClient();
if (options.cloud) queryClient.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses: sampleHarnesses } });
await act(async () => {
renderFormView(root, queryClient,
@@ -1461,6 +1464,20 @@ describe("AgentConfigForm environment selector", () => {
} finally { accounts.mockRestore(); }
});
it.each(["antigravity", "copilot"])("honors Cloud availability during saved %s model discovery", async acpxAgent => {
const result = await renderForm([], {
adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent, model: "source-model" },
}, { cloud: true });
roots.push(result.root);
await flushReact();
if (acpxAgent === "copilot") {
await vi.waitFor(() => expect(mockAgentsApi.adapterModels).toHaveBeenCalledWith("company-1", "paperclip_runner", expect.objectContaining({ provider: "acpx", acpxAgent })));
} else {
expect(result.container.querySelector('[aria-label="Model"]')).toBeNull();
expect(mockAgentsApi.adapterModels).not.toHaveBeenCalled();
}
});
it("refreshes Copilot models after reconnecting the same responsible-user account", async () => {
const binding = { mode: "responsible_user", provider: "github", method: "api_key" } as const;
const account = { id: "copilot-account", grantId: "copilot-grant", companyId: "company-1", provider: "github", method: "api_key", name: "My Copilot", ownership: "personal", ownerUserId: "you", isDefault: true, status: "needs_attention" } as const;
+16 -8
View File
@@ -95,6 +95,8 @@ import { useProposalReview } from "../pages/secrets/proposal-review";
import { AGENT_ACCESS_CONFIG_PATH_PREFIX } from "../lib/secret-delivery";
import { shouldShowLegacyWorkingDirectoryField } from "../lib/legacy-agent-config";
import { listAdapterOptions, listVisibleAdapterTypes } from "../adapters/metadata";
import { useCloudInstance } from "@/hooks/useCloudInstance";
import { useCloudHarnessPolicy } from "@/hooks/useCloudHarnessPolicy";
import { getAdapterDisplay, getAdapterLabel } from "../adapters/adapter-display-registry";
import { useDisabledAdaptersSync } from "../adapters/use-disabled-adapters";
import { buildAgentUpdatePatch, omitUndefinedEntries, type AgentConfigOverlay } from "../lib/agent-config-patch";
@@ -1048,10 +1050,13 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
).data?.provider === "openrouter" ? "openrouter" : runnerProvider;
const runnerAcpxAgent = adapterType === "paperclip_runner" && runnerProvider === "acpx"
? String(isCreate ? props.values.adapterSchemaValues?.acpxAgent ?? "claude" : eff("adapterConfig", "acpxAgent", config.acpxAgent ?? "claude")) : undefined;
const cloud = Boolean(useCloudInstance());
const harnessPolicy = useCloudHarnessPolicy();
const cloudHarnessAllowed = !cloud || harnessPolicy.isCloudHarnessAllowed(adapterType, { provider: runnerProvider, acpxAgent: runnerAcpxAgent });
const modelAiBinding = aiConnectionBindingSchema.safeParse((overlay.runtime.runtimeConfig as Record<string, unknown> | undefined)?.aiConnection ?? runtimeConfig.aiConnection).data;
const accountBoundCatalog = isAccountBoundAcpxAgent(runnerAcpxAgent);
const modelCacheIdentity = accountBoundCatalog ? `${modelProvider}:${runnerAcpxAgent}:${isCreate ? "new" : props.agent.id}:${JSON.stringify(modelAiBinding ?? null)}` : runnerAcpxAgent ? `${modelProvider}:${runnerAcpxAgent}` : modelProvider;
const connectionModels = useConnectionModels(isExternalRunner ? null : selectedCompanyId, isCreate ? undefined : modelAiBinding, aiRoutingHarness(adapterType, runnerProvider, runnerAcpxAgent));
const connectionModels = useConnectionModels(isExternalRunner || !cloudHarnessAllowed ? null : selectedCompanyId, isCreate ? undefined : modelAiBinding, aiRoutingHarness(adapterType, runnerProvider, runnerAcpxAgent));
// Fetch adapter models for the effective provider, including unsaved changes.
const modelAdapterType = accountBoundCatalog ? "paperclip_runner" : isRunnerHarness ? harnessType : adapterType;
const modelQueryKey = selectedCompanyId
@@ -1067,14 +1072,14 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
agentId: isCreate ? undefined : props.agent.id,
}),
...(accountBoundCatalog ? ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS : {}),
enabled: Boolean(selectedCompanyId) && !isExternalRunner && !connectionModels,
enabled: Boolean(selectedCompanyId) && cloudHarnessAllowed && !isExternalRunner && !connectionModels,
});
const { data: fetchedModels, error: fetchedModelsError, isLoading: fetchingModels, refetch: refreshConnectionModels } = fetchedModelsQuery;
const fetchedModelsView = useQueryView(fetchedModelsQuery);
const accountModelScope = accountBoundCatalog ? JSON.stringify(modelQueryKey) : null;
useEffect(() => {
if (accountModelScope && selectedCompanyId && !isExternalRunner && !connectionModels) void refreshConnectionModels();
}, [accountModelScope, selectedCompanyId, isExternalRunner, connectionModels, refreshConnectionModels]);
if (accountModelScope && selectedCompanyId && cloudHarnessAllowed && !isExternalRunner && !connectionModels) void refreshConnectionModels();
}, [accountModelScope, selectedCompanyId, cloudHarnessAllowed, isExternalRunner, connectionModels, refreshConnectionModels]);
const [refreshModelsError, setRefreshModelsError] = useState<string | null>(null);
const [refreshingModels, setRefreshingModels] = useState(false);
const models = connectionModels?.models ?? fetchedModels ?? externalModels ?? [];
@@ -1096,7 +1101,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
}
return agentsApi.detectModel(selectedCompanyId, adapterType);
},
enabled: Boolean(selectedCompanyId && isLocal && adapterType !== "opencode_local" && adapterType !== "paperclip_runner"),
enabled: Boolean(selectedCompanyId && cloudHarnessAllowed && isLocal && adapterType !== "opencode_local" && adapterType !== "paperclip_runner"),
});
const detectedModel = detectedModelData?.model ?? null;
const detectedModelCandidates = detectedModelData?.candidates ?? [];
@@ -1129,6 +1134,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
// every adapter without a per-adapter edit.
hideInstructionsFile: hideInstructionsFile || hideHostPaths || isExternalRunner,
managedSandboxOnly: hideHostPaths || isExternalRunner,
availableHarnesses: cloud ? harnessPolicy.availableHarnesses : undefined,
openAiDotEnabled: experimentalSettings?.enableOpenAiDot === true,
museEnabled: experimentalSettings?.enableMuse === true && experimentalSettings?.enableNativeRunner === true,
};
@@ -1971,7 +1977,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
)}
{renderAdapterFields("adapter")}
{isLocal && (<>
{isLocal && cloudHarnessAllowed && (<>
<ModelDropdown
models={models}
loadingModels={connectionModels?.isLoading ?? (fetchingModels || fetchedModelsView.kind === "reconnecting")}
@@ -4042,14 +4048,16 @@ export function AdapterTypeDropdown({
museEnabled?: boolean;
nativeRunnerEnabled?: boolean;
}) {
const cloud = Boolean(useCloudInstance());
const harnessPolicy = useCloudHarnessPolicy();
const selectedDisplay = getAdapterDisplay(value);
const adapterList = useMemo(() =>
[...listAdapterOptions(type => adapterLabels[type] ?? getAdapterLabel(type)),
...(openAiDotEnabled ? [{ value: "openai_dot", label: "OpenAI Dot", experimental: true, comingSoon: false }] : []),
...(museEnabled ? [{ value: "muse", label: "Muse — Personal agent", experimental: true, comingSoon: false }] : []),
].filter(item => !item.comingSoon && (item.value !== "paperclip_runner" || nativeRunnerEnabled) && !disabledTypes.has(item.value))
].filter(item => (!cloud || harnessPolicy.isCloudHarnessAllowed(item.value)) && !item.comingSoon && (item.value !== "paperclip_runner" || nativeRunnerEnabled) && !disabledTypes.has(item.value))
.sort((a, b) => Number(a.value === "paperclip_runner") - Number(b.value === "paperclip_runner")),
[disabledTypes, openAiDotEnabled, nativeRunnerEnabled, museEnabled]);
[cloud, harnessPolicy, disabledTypes, openAiDotEnabled, nativeRunnerEnabled, museEnabled]);
return <SelectPopover aria-label="Harness" value={value} onValueChange={onChange}
displayValue={<span className="inline-flex min-w-0 items-center gap-1.5">
<span aria-hidden="true" className="inline-flex shrink-0"><AdapterMark type={value} className="size-4" /></span>
@@ -0,0 +1,69 @@
// @vitest-environment jsdom
import { sampleHarnesses } from "@/test-support/harness-availability";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { beforeAll, describe, expect, it } from "vitest";
import { queryKeys } from "@/lib/queryKeys";
import { AdapterTypeDropdown } from "./AgentConfigForm";
import { TooltipProvider } from "./ui/tooltip";
beforeAll(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); });
describe("shared Cloud harness dropdown", () => {
it("updates choices from deployment health metadata without rebuilding", async () => {
const container = document.createElement("div");
document.body.append(container);
const root = createRoot(container);
const client = new QueryClient();
const update = (availableHarnesses?: string[]) => client.setQueryData(queryKeys.health,
{ status: "ok", cloud: { managed: true, availableHarnesses } });
update(["gemini_local"]);
try {
await act(async () => root.render(<QueryClientProvider client={client}><TooltipProvider>
<AdapterTypeDropdown value="gemini_local" onChange={() => {}} disabledTypes={new Set()} nativeRunnerEnabled />
</TooltipProvider></QueryClientProvider>));
await act(async () => container.querySelector('[aria-label="Harness"]')!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
const choices = () => [...document.querySelectorAll('[role="option"]')].map(option => option.getAttribute("data-value"));
expect(choices()).toEqual(["gemini_local"]);
await act(async () => { update(["pi_local"]); await new Promise(resolve => setTimeout(resolve, 0)); });
expect(choices()).toEqual(["pi_local"]);
await act(async () => { update([]); await new Promise(resolve => setTimeout(resolve, 0)); });
expect(choices()).toEqual([]);
await act(async () => { update(); await new Promise(resolve => setTimeout(resolve, 0)); });
expect(choices()).toContain("gemini_local");
expect(choices()).toContain("codex_local");
} finally {
await act(async () => root.unmount());
client.clear();
container.remove();
}
});
it.each([false, true])("filters Cloud choices without exposing experiments (cloud=%s)", async cloud => {
const container = document.createElement("div");
document.body.append(container);
const root = createRoot(container);
const client = new QueryClient();
client.setQueryData(queryKeys.health, { status: "ok", cloud: cloud ? { managed: true, availableHarnesses: sampleHarnesses } : null });
try {
await act(async () => root.render(<QueryClientProvider client={client}><TooltipProvider>
<AdapterTypeDropdown value="codex_local" onChange={() => {}} disabledTypes={new Set()}
openAiDotEnabled museEnabled nativeRunnerEnabled />
</TooltipProvider></QueryClientProvider>));
await act(async () => container.querySelector('[aria-label="Harness"]')!.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
const choices = [...document.querySelectorAll('[role="option"]')].map(option => option.getAttribute("data-value"));
if (cloud) {
expect(choices.sort()).toEqual(["claude_local", "codex_local", "grok_local", "opencode_local", "paperclip_runner"]);
} else {
expect(choices).toContain("gemini_local");
expect(choices).toContain("openai_dot");
expect(choices).toContain("muse");
}
} finally {
await act(async () => root.unmount());
client.clear();
container.remove();
}
});
});
+33 -17
View File
@@ -1,4 +1,5 @@
// @vitest-environment jsdom
import { sampleHarnesses } from "@/test-support/harness-availability";
import { act, createElement } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -218,29 +219,21 @@ it("offers one Codex harness without a runner/provider tile", async () => {
expect(document.querySelectorAll('input[value="codex_local"]')).toHaveLength(1);
expect(document.querySelector("select")).toBeNull();
});
it("opens native Cursor Cloud from the ordinary hosted adapter picker", async () => {
it("withholds Cursor Cloud from the hosted picker even when its native backend is available", async () => {
await act(async () => {
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true } });
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses: sampleHarnesses } });
cache.setQueryData(queryKeys.adapters.availability("company-1", null), [...state.adapters,
{ type: "cursor_cloud", loaded: true, supportedRunners: ["paperclip"], defaultRunner: "paperclip" }]);
});
await name();
const cursor = document.querySelector<HTMLInputElement>('input[value="cursor_cloud"]');
expect(cursor).not.toBeNull();
await act(async () => cursor!.click());
await click("Configure agent");
expect(agents.update).toHaveBeenCalledWith(agents.create.mock.calls[0][1].setupId, expect.objectContaining({
adapterType: "paperclip_runner", runner: "paperclip", adapterConfig: { provider: "cursor_cloud" },
}), "company-1");
const query = new URL(state.navigate.mock.calls[0][0], "http://local").searchParams;
expect(query.get("adapterType")).toBe("paperclip_runner");
expect(query.get("runnerProvider")).toBe("cursor_cloud");
expect(query.get("runner")).toBe("paperclip");
expect(cursor).toBeNull();
expect(agents.update).not.toHaveBeenCalled();
});
it("hides explicitly unsupported harnesses while keeping the qualified Cursor API card", async () => {
it.each([false, true])("withholds unavailable backends and limits Cloud to released harnesses (cloud=%s)", async cloud => {
await act(async () => {
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true } });
cache.setQueryData(queryKeys.health, { status: "ok", cloud: cloud ? { managed: true, availableHarnesses: sampleHarnesses } : null });
cache.setQueryData(queryKeys.adapters.availability("company-1", null), [
{ type: "codex_local", loaded: true, supportedRunners: [] },
{ type: "opencode_local", loaded: true, supportedRunners: [] },
@@ -253,12 +246,12 @@ it("hides explicitly unsupported harnesses while keeping the qualified Cursor AP
expect(document.querySelector('input[value="opencode_local"]')).toBeNull();
expect(document.querySelector('input[value="copilot_runtime"]')).toBeNull();
expect(document.querySelector('input[value="antigravity_runtime"]')).toBeNull();
expect(document.querySelector('input[value="cursor_cloud"]')).not.toBeNull();
expect(document.querySelector('input[value="cursor_cloud"]') !== null).toBe(!cloud);
});
it.each(["gate off", "native unavailable"])("keeps hosted Cursor Cloud hidden when %s", async reason => {
await act(async () => {
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true } });
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses: sampleHarnesses } });
if (reason === "gate off") cache.setQueryData(queryKeys.instance.experimentalSettings, { enableNativeRunner: false });
cache.setQueryData(queryKeys.adapters.availability("company-1", null), [...state.adapters,
{ type: "cursor_cloud", loaded: true, supportedRunners: reason === "native unavailable" ? ["legacy"] : ["paperclip"], defaultRunner: "legacy" }]);
@@ -306,6 +299,29 @@ it("hides Google Antigravity when the runtime adapter is disabled", async () =>
await name();
expect(document.querySelector('input[value="antigravity_runtime"]')).toBeNull();
});
it.each([
{ availableHarnesses: ["gemini_local"], expected: [] },
{ availableHarnesses: [], expected: [] },
{ availableHarnesses: ["grok_local"], expected: ["grok"] },
{ availableHarnesses: ["opencode_local"], expected: ["opencode"] },
])("filters Advanced native choices using the deployment policy ($availableHarnesses)", async ({ availableHarnesses, expected }) => {
await act(async () => {
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses } });
await new Promise(resolve => setTimeout(resolve, 0));
});
await name();
const picker = document.querySelector<HTMLButtonElement>('[aria-label="Experimental harness"]');
if (expected.length === 0) {
expect(picker).toBeNull();
expect(document.querySelector("summary")).toBeNull();
} else {
expect(picker).toBeTruthy();
await act(async () => (document.querySelector("summary") as HTMLElement).click());
await act(async () => picker!.click());
expect([...document.querySelectorAll('[role="option"]')].map(option => option.getAttribute("data-value"))).toEqual(expected);
}
});
it.each(["grok", "opencode"])("preserves explicit experimental %s creation in Advanced", async provider => {
await name();
await act(async () => (document.querySelector("summary") as HTMLElement).click());
@@ -432,7 +448,7 @@ it("waits for company approval before issuing a Dot capability", async () => {
it("allows the scoped Dot invitation on cloud when its prerequisites are enabled", async () => {
await act(async () => {
cache.setQueryData(queryKeys.instance.experimentalSettings, { enableOpenAiDot: true, enablePublicMcp: true });
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true } });
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses: sampleHarnesses } });
});
await click("Invite an external agent");
const dot = [...document.querySelectorAll("button")].find(b => b.textContent?.startsWith("Dot"))!;
+8 -4
View File
@@ -9,6 +9,8 @@ import { bindAccount } from "@/lib/account-scope";
import { aiConnectionsApi } from "@/api/ai-connections";
import { getAdapterLabel } from "@/adapters/adapter-display-registry";
import { bulkAgentDisabledReason, bulkAgentHarness } from "@/lib/bulk-agent-settings";
import { useCloudHarnessPolicy } from "@/hooks/useCloudHarnessPolicy";
import { useCloudInstance } from "@/hooks/useCloudInstance";
import { buildAgentRosterIndex } from "@/lib/agent-roster-filters";
import { AgentStatusBadge } from "@/components/StatusBadge";
import { Button } from "@/components/ui/button";
@@ -23,6 +25,8 @@ export function AgentBulkRoster({ companyId, agents, visibleAgents, renderAgent,
renderStatus?: (agent: Agent) => ReactNode;
}) {
const client = useQueryClient();
const cloud = Boolean(useCloudInstance());
const harnessPolicy = useCloudHarnessPolicy();
const openingRef = useRef(false);
const [opening, setOpening] = useState(false);
const [openError, setOpenError] = useState("");
@@ -37,8 +41,8 @@ export function AgentBulkRoster({ companyId, agents, visibleAgents, renderAgent,
const accounts = useQuery({ queryKey: ["ai-connections", companyId], queryFn: () => aiConnectionsApi.list(companyId) });
const visible = visibleAgents;
const rosterIndex = useMemo(() => buildAgentRosterIndex(agents, accounts.data), [agents, accounts.data]);
const selectable = visible.filter(a => !bulkAgentDisabledReason(a));
const selectedAgents = useMemo(() => agents.filter(a => selected.includes(a.id) && !bulkAgentDisabledReason(a)), [agents, selected]);
const selectable = visible.filter(a => !bulkAgentDisabledReason(a, cloud, harnessPolicy));
const selectedAgents = useMemo(() => agents.filter(a => selected.includes(a.id) && !bulkAgentDisabledReason(a, cloud, harnessPolicy)), [agents, selected, cloud, harnessPolicy]);
const [lastSelection, setLastSelection] = useState<Agent[]>([]);
useEffect(() => { if (selectedAgents.length) setLastSelection(selectedAgents); }, [selectedAgents]);
// Retain the card contents while it drops out, so its width does not collapse mid-animation.
@@ -62,7 +66,7 @@ export function AgentBulkRoster({ companyId, agents, visibleAgents, renderAgent,
if (!account.isCurrentAccount() || revision !== selectionRevision.current) return;
// The display cache excludes private runtime fields. Only complete,
// freshly authorized agents can become the editor's optimistic base.
if (complete.some(a => a.companyId !== companyId || bulkAgentHarness(a) !== harness || bulkAgentDisabledReason(a))) {
if (complete.some(a => a.companyId !== companyId || bulkAgentHarness(a) !== harness || bulkAgentDisabledReason(a, cloud, harnessPolicy))) {
setOpenError("The selected agents changed. Refresh the roster and select them again.");
return;
}
@@ -93,7 +97,7 @@ export function AgentBulkRoster({ companyId, agents, visibleAgents, renderAgent,
<tbody>{visible.map(agent => {
const metadata = rosterIndex.byAgentId.get(agent.id)!;
return <tr key={agent.id} data-state={selected.includes(agent.id) ? "selected" : undefined} className="group/agent-row border-t border-border data-[state=selected]:bg-accent/30 hover:bg-accent/50 focus-within:bg-accent/50 [&_td]:px-3 [&_td]:align-middle">
<td title={bulkAgentDisabledReason(agent)}><Checkbox aria-label={`Select ${agent.name}`} checked={selectedAgents.some(a => a.id === agent.id)} disabled={!!bulkAgentDisabledReason(agent)} onCheckedChange={value => changeSelection(value ? [...new Set([...selected, agent.id])] : selected.filter(id => id !== agent.id))} /></td>
<td title={bulkAgentDisabledReason(agent, cloud, harnessPolicy)}><Checkbox aria-label={`Select ${agent.name}`} checked={selectedAgents.some(a => a.id === agent.id)} disabled={!!bulkAgentDisabledReason(agent, cloud, harnessPolicy)} onCheckedChange={value => changeSelection(value ? [...new Set([...selected, agent.id])] : selected.filter(id => id !== agent.id))} /></td>
<td className="min-w-64 p-0">{renderAgent(agent)}</td>
{renderChat && <td>{renderChat(agent)}</td>}
<td>{renderStatus ? renderStatus(agent) : <AgentStatusBadge status={agent.status} />}</td>
@@ -39,6 +39,8 @@ import { queryKeys } from "../../lib/queryKeys";
import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS, nativeTaskModelCatalogOptions } from "../../lib/native-model-catalog";
import { buildCompanyUserInlineOptions, buildCompanyUserLabelMap, buildCompanyUserProfileMap, isAgentTaskTarget } from "../../lib/company-members";
import { ISSUE_OVERRIDE_ADAPTER_TYPES, type IssueModelLane } from "../../lib/issue-assignee-overrides";
import { useCloudInstance } from "@/hooks/useCloudInstance";
import { useCloudHarnessPolicy } from "@/hooks/useCloudHarnessPolicy";
import { useProjectOrder } from "../../hooks/useProjectOrder";
import {
getRecentAssigneeIds,
@@ -757,8 +759,11 @@ export function IssueProperties({
const assigneeAdapterType = assignee?.adapterType ?? null;
const assigneeAdapterOverrides = issue.assigneeAdapterOverrides ?? null;
const showAssigneeAdapterOptions = assigneeAdapterOverrides !== null;
const cloud = Boolean(useCloudInstance());
const harnessPolicy = useCloudHarnessPolicy();
const supportsAssigneeOverrides = Boolean(
assigneeAdapterType && (ISSUE_OVERRIDE_ADAPTER_TYPES.has(assigneeAdapterType) || nativeCatalog),
assigneeAdapterType && (!cloud || harnessPolicy.isCloudHarnessAllowed(assigneeAdapterType, assignee?.adapterConfig))
&& (ISSUE_OVERRIDE_ADAPTER_TYPES.has(assigneeAdapterType) || nativeCatalog),
);
const assigneeOverrideLane = overrideLane(assigneeAdapterOverrides);
const assigneeOverrideAdapterConfig = asRecord(assigneeAdapterOverrides?.adapterConfig);
@@ -12,6 +12,7 @@ import { ArrowLeft, ArrowRight, Check, ChevronRight } from "lucide-react";
import { adaptersApi } from "@/api/adapters";
import { instanceSettingsApi } from "@/api/instanceSettings";
import { useCloudInstance } from "@/hooks/useCloudInstance";
import { useCloudHarnessPolicy } from "@/hooks/useCloudHarnessPolicy";
import { isNewAgentAdapterAllowed } from "@/lib/new-agent-adapters";
import { queryKeys } from "@/lib/queryKeys";
import { getAdapterDisplay } from "@/adapters/adapter-display-registry";
@@ -71,6 +72,7 @@ export function AgentBasicsDialog({
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const cloud = Boolean(useCloudInstance());
const harnessPolicy = useCloudHarnessPolicy();
const experimental = useQuery({
queryKey: queryKeys.instance.experimentalSettings,
queryFn: instanceSettingsApi.getExperimental,
@@ -88,12 +90,12 @@ export function AgentBasicsDialog({
const adaptersView = useQueryView(adaptersQuery);
const adapters = adaptersView.data;
const nativeRunner = adapters?.find(adapter => adapter.type === "paperclip_runner" && adapter.loaded && !adapter.disabled && adapter.supportedRunners?.length !== 0);
const copilotAvailable = Boolean(nativeRunner) && PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "copilot" && profile.qualified);
const kimiAvailable = Boolean(nativeRunner) && experimental.data?.enableNativeRunner === true
const copilotAvailable = (!cloud || harnessPolicy.isCloudRunnerProviderAllowed("copilot")) && Boolean(nativeRunner) && PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "copilot" && profile.qualified);
const kimiAvailable = (!cloud || harnessPolicy.isCloudRunnerProviderAllowed("kimi")) && Boolean(nativeRunner) && experimental.data?.enableNativeRunner === true
&& PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "kimi" && profile.qualified);
const antigravityQualified = PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "antigravity" && profile.qualified);
const antigravityCandidate = nativeRunner?.candidateHarnesses?.some(candidate => candidate.agent === "antigravity");
const antigravityAvailable = Boolean(nativeRunner);
const antigravityAvailable = (!cloud || harnessPolicy.isCloudRunnerProviderAllowed("antigravity")) && Boolean(nativeRunner);
const choices = [...(adapters ?? []).filter(
(adapter) =>
adapter.loaded &&
@@ -102,6 +104,7 @@ export function AgentBasicsDialog({
adapter.type !== "paperclip_runner" &&
isNewAgentAdapterAllowed(adapter.type, {
cloud,
harnessPolicy,
nativeRunnerEnabled: experimental.data?.enableNativeRunner === true,
}) &&
(!cloud || adapter.type !== "cursor_cloud" || adapter.supportedRunners?.includes("paperclip")) &&
@@ -112,8 +115,13 @@ export function AgentBasicsDialog({
...(kimiAvailable ? [{ ...nativeRunner!, type: "kimi_runtime" }] : [])];
const experimentalRunnerAvailable = experimental.data?.enableNativeRunner === true
&& adapters?.some(adapter => adapter.type === "paperclip_runner" && adapter.loaded && !adapter.disabled && adapter.supportedRunners?.length !== 0);
const advancedRunnerOptions = [
{ value: "grok", label: "Grok Build (Paperclip Runner)" },
{ value: "opencode", label: "OpenCode (Paperclip Runner)" },
].filter(option => !cloud || harnessPolicy.isCloudRunnerProviderAllowed(option.value));
const validAdapter = choices.some((adapter) => adapter.type === adapterType)
|| (experimentalRunnerAvailable && adapterType === "paperclip_runner" && (runnerProvider !== "antigravity" || antigravityQualified));
|| (experimentalRunnerAvailable && adapterType === "paperclip_runner" && (runnerProvider !== "antigravity" || antigravityQualified)
&& isNewAgentAdapterAllowed(adapterType, { cloud, harnessPolicy, nativeRunnerEnabled: true, runnerProvider }));
async function submit() {
if (busy.current || !name.trim() || (step === "adapter" && !validAdapter)) return;
busy.current = true;
@@ -316,7 +324,7 @@ export function AgentBasicsDialog({
);
})}
</div>
{experimentalRunnerAvailable && <details className="space-y-3">
{experimentalRunnerAvailable && advancedRunnerOptions.length > 0 && <details className="space-y-3">
<summary className="cursor-pointer text-sm text-muted-foreground">Advanced</summary>
<div className="space-y-2">
<label className="text-sm text-muted-foreground">Experimental harness</label>
@@ -324,10 +332,7 @@ export function AgentBasicsDialog({
value={adapterType === "paperclip_runner" ? runnerProvider : ""}
placeholder="Choose a native harness…"
onValueChange={provider => { setRunnerProvider(provider); setAdapterType("paperclip_runner"); }}
options={[
{ value: "grok", label: "Grok Build (Paperclip Runner)" },
{ value: "opencode", label: "OpenCode (Paperclip Runner)" },
]} />
options={advancedRunnerOptions} />
</div>
</details>}
</fieldset>
+13 -2
View File
@@ -19,6 +19,7 @@ import { testAgentSetup } from "@/lib/test-agent-setup";
import { needsClaudeSetupQualification, qualifyClaudeSetup } from "@/lib/qualify-claude-setup";
import { useCloudInstance } from "@/hooks/useCloudInstance";
import { isNewAgentAdapterAllowed } from "@/lib/new-agent-adapters";
import { useCloudHarnessPolicy } from "@/hooks/useCloudHarnessPolicy";
import { pendingAgentSetupChoice } from "@/lib/agent-setup-choice";
import { useEffect, useRef, useState } from "react";
import { hashKey, useQuery, useQueryClient } from "@tanstack/react-query";
@@ -90,13 +91,15 @@ export function NewAgentSetup() {
const { selectedCompanyId } = useCompany();
const [params] = useSearchParams();
const navigate = useNavigate();
const cloud = Boolean(useCloudInstance());
const harnessPolicy = useCloudHarnessPolicy();
if (!selectedCompanyId)
return (
<p className="text-sm text-muted-foreground">
Select an organization to create an agent.
</p>
);
if (params.get("adapterType") === "muse" || params.get("runnerProvider") === "muse") return <ExternalAgentInviteDialog companyId={selectedCompanyId} initialPreset="muse" initialMuseName={params.get("name") ?? ""} onClose={() => navigate("/agents/all")} onBack={() => navigate("/agents/all")} />;
if ((!cloud || harnessPolicy.isCloudRunnerProviderAllowed("muse")) && (params.get("adapterType") === "muse" || params.get("runnerProvider") === "muse")) return <ExternalAgentInviteDialog companyId={selectedCompanyId} initialPreset="muse" initialMuseName={params.get("name") ?? ""} onClose={() => navigate("/agents/all")} onBack={() => navigate("/agents/all")} />;
return (
<Setup
key={`${selectedCompanyId}:${params.get("name")}:${params.get("adapterType")}:${params.get("runnerProvider") ?? "codex"}:${params.get("runner") ?? "auto"}`}
@@ -408,11 +411,13 @@ function Setup({
const usingKimiApi =
adapterType === "kimi_local" && Boolean(apiKey.trim() || selectedBinding);
const cloud = Boolean(useCloudInstance());
const harnessPolicy = useCloudHarnessPolicy();
const available =
(!nativeCursorCloud || experimental.data?.enableNativeRunner === true) &&
(!cloud || adapterType !== "cursor_cloud" || nativeCursorCloud) &&
isNewAgentAdapterAllowed(adapterType, {
cloud,
harnessPolicy,
nativeRunnerEnabled: experimental.data?.enableNativeRunner === true,
openAiDotEnabled: experimental.data?.enableOpenAiDot === true,
runnerProvider,
@@ -425,7 +430,7 @@ function Setup({
!adapter.disabled &&
!getAdapterDisplay(adapterType).comingSoon,
) && (requestAdapterType !== "paperclip_runner" || adapterType === "paperclip_runner" || adapterInventory.data?.some(adapter => adapter.type === "paperclip_runner" && adapter.loaded && !adapter.disabled));
const configurationAvailable = available || (pendingAntigravity && adapterInventory.data?.some(
const configurationAvailable = available || ((!cloud || harnessPolicy.isCloudRunnerProviderAllowed("antigravity")) && pendingAntigravity && adapterInventory.data?.some(
adapter => adapter.type === "paperclip_runner" && adapter.loaded && !adapter.disabled,
));
const connectionSettingsReady = Boolean(
@@ -888,6 +893,12 @@ function Setup({
}}
/>
);
if (cloud && !(adapterType === "paperclip_runner"
? harnessPolicy.isCloudRunnerProviderAllowed(runnerProvider)
: harnessPolicy.isCloudHarnessAllowed(adapterType))) return <div className="space-y-4">
<p role="alert">This adapter is unavailable. Choose an enabled adapter.</p>
<Button onClick={() => setChoosingAdapter(true)}>Change adapter</Button>
</div>;
if (!created && connectionSettingsReady && !pendingAntigravity) return <div className="space-y-4">
<p role={error ? "alert" : "status"}>{error ?? "Creating your agent…"}</p>
{error && <Button onClick={() => setCreationAttempt(value => value + 1)}>Retry</Button>}
@@ -1,4 +1,5 @@
// @vitest-environment jsdom
import { sampleHarnesses } from "@/test-support/harness-availability";
import { act, useState, type ComponentProps } from "react";
import { flushSync } from "react-dom";
@@ -8,6 +9,7 @@ import type { Agent } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { agentsApi } from "@/api/agents";
import { ComposerRunSettingsPicker } from "./ComposerRunSettingsPicker";
import { queryKeys } from "@/lib/queryKeys";
import type { ComposerRunSettings } from "./composer-run-settings";
import { getLastComposerEffort, rememberComposerEffort } from "@/lib/recent-composer-effort";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
@@ -61,6 +63,20 @@ afterEach(() => {
});
describe("composer assignee picker", () => {
it.each(["antigravity", "copilot"])("applies the Cloud allowlist to saved %s model settings", async acpxAgent => {
const selectedAgent = { ...agent, adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent, model: "saved-model" } } as Agent;
const client = render(vi.fn(), vi.fn(), false, { agents: new Map([[selectedAgent.id, selectedAgent]]) });
await act(async () => {
client.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses: sampleHarnesses } });
await new Promise(resolve => setTimeout(resolve, 0));
});
expect(document.querySelector('[aria-label="Select model and effort"]') !== null).toBe(acpxAgent === "copilot");
if (acpxAgent === "copilot") {
await click("Select model and effort");
expect(document.querySelector('[aria-label="Choose exact model"]')).not.toBeNull();
}
});
it.each([false, true])("allows model and effort changes with a fixed conversation agent (mobile: %s)", async (mobile) => {
const onAssigneeChange = vi.fn();
const onSettingsChange = vi.fn();
@@ -3,6 +3,8 @@ import { useQuery } from "@tanstack/react-query";
import { ArrowLeft, Check, ChevronDown, Plus, RotateCcw, Search, X, Zap } from "lucide-react";
import { aiRuntimeConnectionBindingSchema, agentHarnessType, type Agent, type IssueAssigneeAdapterOverrides } from "@paperclipai/shared";
import { agentsApi, type AdapterModel } from "@/api/agents";
import { useCloudInstance } from "@/hooks/useCloudInstance";
import { useCloudHarnessPolicy } from "@/hooks/useCloudHarnessPolicy";
import { queryKeys } from "@/lib/queryKeys";
import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS, nativeTaskModelCatalogOptions } from "@/lib/native-model-catalog";
import { cn } from "@/lib/utils";
@@ -106,7 +108,9 @@ export function ComposerRunSettingsPicker({
const mobileViewportStyle = useMobileEntityPickerViewportStyle();
const agentId = assigneeValue.startsWith("agent:") ? assigneeValue.slice(6) : "";
const agent = agents.get(agentId);
const modelSupported = supportsComposerModel(agent);
const cloud = Boolean(useCloudInstance());
const harnessPolicy = useCloudHarnessPolicy();
const modelSupported = supportsComposerModel(agent) && (!cloud || Boolean(agent && harnessPolicy.isCloudHarnessAllowed(agent.adapterType, agent.adapterConfig)));
const view = (requestedView === "models" && !modelSupported) || (requestedView === "agents" && !allowAssigneeChange)
? "settings"
: requestedView;
+8
View File
@@ -0,0 +1,8 @@
import { useMemo } from "react";
import { createCloudHarnessPolicy } from "@/lib/cloud-harness-policy";
import { useCloudInstance } from "./useCloudInstance";
export function useCloudHarnessPolicy() {
const availableHarnesses = useCloudInstance()?.availableHarnesses;
return useMemo(() => createCloudHarnessPolicy(availableHarnesses), [availableHarnesses]);
}
+9
View File
@@ -1,7 +1,16 @@
import { describe, expect, it } from "vitest";
import type { Agent } from "@paperclipai/shared";
import { createCloudHarnessPolicy } from "./cloud-harness-policy";
import { sampleHarnesses } from "@/test-support/harness-availability";
import { bulkAgentDisabledReason, mapBulkAgents, sameBinding } from "./bulk-agent-settings";
it("withholds Cloud bulk model edits for unsupported saved native profiles", () => {
const agent = { adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity" }, runtimeConfig: {}, status: "idle" } as unknown as Agent;
expect(bulkAgentDisabledReason(agent)).toBeUndefined();
expect(bulkAgentDisabledReason(agent, true, createCloudHarnessPolicy(sampleHarnesses))).toContain("not available on Paperclip Cloud");
expect(bulkAgentDisabledReason({ ...agent, adapterConfig: { provider: "acpx", acpxAgent: "copilot" } }, true, createCloudHarnessPolicy(sampleHarnesses))).toBeUndefined();
});
describe("bulk agent writes", () => {
it("allows Antigravity connection/model edits while preserving router-only editing", () => {
const agent = { adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity" }, runtimeConfig: {}, status: "active" } as unknown as Agent;
+3 -1
View File
@@ -1,4 +1,5 @@
import { agentRuntimeSettingsHarness, aiRuntimeConnectionBindingSchema, type Agent, type AiConnectionBinding, type AiConnectionList, type AiRuntimeConnectionBinding } from "@paperclipai/shared";
import { unrestrictedCloudHarnessPolicy, type CloudHarnessPolicy } from "./cloud-harness-policy";
export const bulkAgentHarness = (agent: Agent) => agentRuntimeSettingsHarness(agent.adapterType, agent.adapterConfig);
export const agentDefaultModel = (agent: Agent) => typeof agent.adapterConfig.model === "string" ? agent.adapterConfig.model.trim() || null : null;
@@ -8,7 +9,8 @@ export const sameBinding = (a: AiRuntimeConnectionBinding | undefined, b: AiRunt
return canonical(a) === canonical(b);
};
export function bulkAgentDisabledReason(agent: Agent): string | undefined {
export function bulkAgentDisabledReason(agent: Agent, cloud = false, harnessPolicy: CloudHarnessPolicy = unrestrictedCloudHarnessPolicy): string | undefined {
if (cloud && !harnessPolicy.isCloudHarnessAllowed(agent.adapterType, agent.adapterConfig)) return "This harness is not available on Paperclip Cloud";
if (["terminated", "pending_approval"].includes(agent.status)) return "This agent is not available for bulk edits";
if (agentConnection(agent)?.mode === "router") return "Edit connection pool members on the agent's configuration page";
if (!["codex_local", "claude_local", "gemini_local", "grok_local", "opencode_local", "hermes_local", "pi_local", "copilot_runtime", "antigravity_runtime", "cursor_local"].includes(bulkAgentHarness(agent))) return "Connection and model are managed externally";
+70
View File
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vitest";
import { createCloudHarnessPolicy } from "./cloud-harness-policy";
import { isNewAgentAdapterAllowed } from "./new-agent-adapters";
const harnessPolicy = createCloudHarnessPolicy(["claude_local", "codex_local", "grok_local", "opencode_local", "copilot_runtime"]);
const { isCloudHarnessAllowed, isCloudRunnerProviderAllowed } = harnessPolicy;
describe("configured Cloud harness choices", () => {
it("uses only the supplied policy, with no built-in Cloud list", () => {
const unrestricted = createCloudHarnessPolicy();
const changed = createCloudHarnessPolicy(["gemini_local", "pi_local", "antigravity_runtime", "plugin_harness"]);
for (const type of ["codex_local", "gemini_local", "plugin_harness"]) {
expect(unrestricted.isCloudHarnessAllowed(type)).toBe(true);
expect(createCloudHarnessPolicy([]).isCloudHarnessAllowed(type)).toBe(false);
}
expect(changed.isCloudHarnessAllowed("codex_local")).toBe(false);
expect(changed.isCloudHarnessAllowed("gemini_local")).toBe(true);
expect(changed.isCloudHarnessAllowed("plugin_harness")).toBe(true);
expect(changed.isCloudRunnerProviderAllowed("pi")).toBe(true);
expect(changed.isCloudRunnerProviderAllowed("antigravity")).toBe(true);
expect(changed.isCloudHarnessAllowed("paperclip_runner", { provider: "acpx", acpxAgent: "pi" })).toBe(true);
expect(changed.isCloudRunnerProviderAllowed("copilot")).toBe(false);
});
it("keeps qualification gates when the deployment allows a candidate", () => {
const policy = createCloudHarnessPolicy(["antigravity_runtime"]);
const options = { cloud: true, harnessPolicy: policy, nativeRunnerEnabled: true, runnerProvider: "antigravity" };
expect(isNewAgentAdapterAllowed("paperclip_runner", options)).toBe(false);
expect(isNewAgentAdapterAllowed("paperclip_runner", { ...options, candidateHarnesses: [{ agent: "antigravity", model: "candidate-model" }] })).toBe(true);
});
it.each(["claude_local", "codex_local", "grok_local", "opencode_local", "copilot_runtime"])("offers %s", type => {
expect(isCloudHarnessAllowed(type)).toBe(true);
});
it.each(["antigravity_runtime", "gemini_local", "kimi_local", "pi_local", "cursor", "cursor_cloud", "hermes_local", "openai_dot", "muse", "plugin_harness"])("withholds %s", type => {
expect(isCloudHarnessAllowed(type)).toBe(false);
expect(isNewAgentAdapterAllowed(type, { cloud: true, harnessPolicy, nativeRunnerEnabled: true, openAiDotEnabled: true, museEnabled: true })).toBe(false);
});
it.each(["claude", "codex", "grok", "opencode", "copilot"])("offers native %s", provider => {
expect(isCloudRunnerProviderAllowed(provider)).toBe(true);
expect(isNewAgentAdapterAllowed("paperclip_runner", { cloud: true, harnessPolicy, nativeRunnerEnabled: true, runnerProvider: provider })).toBe(true);
});
it.each(["antigravity", "kimi", "pi", "cursor", "cursor_cloud", "claude_managed", "aws_agentcore", "openai_dot", "muse", "grok_bot", "unknown"])("withholds native %s even with experiments and candidate access", runnerProvider => {
expect(isCloudRunnerProviderAllowed(runnerProvider)).toBe(false);
expect(isNewAgentAdapterAllowed("paperclip_runner", {
cloud: true, harnessPolicy, nativeRunnerEnabled: true, openAiDotEnabled: true, museEnabled: true, runnerProvider,
candidateHarnesses: [{ agent: "antigravity", model: "candidate-model" }],
})).toBe(false);
});
it("resolves saved Runner profiles by their harness", () => {
expect(isCloudHarnessAllowed("paperclip_runner")).toBe(true);
for (const acpxAgent of ["claude", "grok", "copilot"]) {
expect(isCloudHarnessAllowed("paperclip_runner", { provider: "acpx", acpxAgent })).toBe(true);
expect(isCloudRunnerProviderAllowed("acpx", acpxAgent)).toBe(true);
}
expect(isCloudHarnessAllowed("paperclip_runner", { provider: "acpx", acpxAgent: "antigravity" })).toBe(false);
expect(isCloudHarnessAllowed("paperclip_runner", { provider: "acpx", acpxAgent: "unknown" })).toBe(false);
});
it("preserves self-hosted experiments and Cloud's existing native gate", () => {
expect(isNewAgentAdapterAllowed("cursor_cloud", { cloud: false, nativeRunnerEnabled: true })).toBe(true);
expect(isNewAgentAdapterAllowed("paperclip_runner", { cloud: false, nativeRunnerEnabled: true, runnerProvider: "antigravity", candidateHarnesses: [{ agent: "antigravity", model: "candidate-model" }] })).toBe(true);
expect(isNewAgentAdapterAllowed("paperclip_runner", { cloud: true, harnessPolicy, nativeRunnerEnabled: false, runnerProvider: "codex" })).toBe(false);
expect(isNewAgentAdapterAllowed("paperclip_runner", { cloud: true, harnessPolicy, nativeRunnerEnabled: false, runnerProvider: "copilot" })).toBe(true);
});
});
+21
View File
@@ -0,0 +1,21 @@
import { agentRuntimeSettingsHarness } from "@paperclipai/shared";
import { PAPERCLIP_RUNNER_ACPX_PROFILES } from "@paperclipai/adapter-utils";
/** Deployment policy only restricts choices; adapter availability and qualification still apply. */
export function createCloudHarnessPolicy(availableHarnesses?: readonly string[]) {
const allowed = availableHarnesses === undefined ? undefined : new Set(availableHarnesses);
function isCloudHarnessAllowed(type: string, config: Record<string, unknown> = {}): boolean {
return allowed === undefined || allowed.has(agentRuntimeSettingsHarness(type, config));
}
function isCloudRunnerProviderAllowed(provider: string, acpxAgent?: string): boolean {
const profile = PAPERCLIP_RUNNER_ACPX_PROFILES.find(entry => entry.value === provider);
return isCloudHarnessAllowed("paperclip_runner", {
provider: profile ? "acpx" : provider,
acpxAgent: acpxAgent ?? profile?.value ?? (provider === "acpx" ? "claude" : provider),
});
}
return { availableHarnesses, restricted: allowed !== undefined, isCloudHarnessAllowed, isCloudRunnerProviderAllowed };
}
export type CloudHarnessPolicy = ReturnType<typeof createCloudHarnessPolicy>;
export const unrestrictedCloudHarnessPolicy = createCloudHarnessPolicy();
+6 -9
View File
@@ -1,24 +1,23 @@
import { PAPERCLIP_RUNNER_ACPX_PROFILES } from "@paperclipai/adapter-utils";
const CLOUD_ADAPTERS = new Set([
"claude_local",
"codex_local",
"opencode_local",
"grok_local",
]);
import { unrestrictedCloudHarnessPolicy, type CloudHarnessPolicy } from "./cloud-harness-policy";
/** Creation policy shared by the picker and direct setup links. */
export function isNewAgentAdapterAllowed(
type: string,
{
cloud,
harnessPolicy = unrestrictedCloudHarnessPolicy,
nativeRunnerEnabled,
openAiDotEnabled = false,
museEnabled = false,
runnerProvider,
candidateHarnesses,
}: { cloud: boolean; nativeRunnerEnabled: boolean; openAiDotEnabled?: boolean; museEnabled?: boolean; runnerProvider?: string;
}: { cloud: boolean; harnessPolicy?: CloudHarnessPolicy; nativeRunnerEnabled: boolean; openAiDotEnabled?: boolean; museEnabled?: boolean; runnerProvider?: string;
candidateHarnesses?: readonly { agent: "antigravity"; model: string }[] },
) {
if (cloud && !(type === "paperclip_runner"
? harnessPolicy.isCloudRunnerProviderAllowed(runnerProvider ?? "codex")
: harnessPolicy.isCloudHarnessAllowed(type))) return false;
if (type === "openai_dot" || (type === "paperclip_runner" && runnerProvider === "openai_dot")) {
return openAiDotEnabled;
}
@@ -26,7 +25,5 @@ export function isNewAgentAdapterAllowed(
if (type === "paperclip_runner" && runnerProvider === "antigravity") return PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "antigravity" && profile.qualified)
|| Boolean(candidateHarnesses?.some(candidate => candidate.agent === "antigravity" && candidate.model));
if (type === "paperclip_runner") return runnerProvider === "copilot" || nativeRunnerEnabled;
if (cloud && type === "cursor_cloud") return nativeRunnerEnabled;
if (cloud) return CLOUD_ADAPTERS.has(type);
return true;
}
+55 -1
View File
@@ -1,4 +1,5 @@
// @vitest-environment jsdom
import { sampleHarnesses } from "@/test-support/harness-availability";
import { webcrypto } from "node:crypto";
import type { ReactNode } from "react";
@@ -9,6 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ApiError } from "../api/client";
import type { CompanyImportJobAccepted } from "../api/companies";
import { CompanyImport } from "./CompanyImport";
import { queryKeys } from "@/lib/queryKeys";
// jsdom's crypto has no SubtleCrypto; the chunked transfer path hashes parts
// with WebCrypto, so back the global with Node's implementation.
@@ -334,9 +336,10 @@ describe("CompanyImport", () => {
await flushReact();
}
async function renderPage() {
async function renderPage(cloud = false) {
root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
if (cloud) queryClient.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses: sampleHarnesses } });
const currentRoot = root;
await act(async () => {
@@ -1067,6 +1070,57 @@ describe("CompanyImport", () => {
await clickButton((text) => text === "Preview import");
}
it("withholds unsupported Cloud import choices and requires a released harness for saved native profiles", async () => {
const preview = buildMixedAdapterPreviewResult();
preview.manifest.agents[0] = { ...preview.manifest.agents[0], adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity" } };
mockCompaniesApi.importPreview.mockResolvedValue(preview);
mockAdaptersApi.list.mockResolvedValue(["claude_local", "codex_local", "grok_local", "opencode_local", "paperclip_runner", "gemini_local", "kimi_local", "cursor_cloud"].map(type => ({ type, disabled: false })));
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableNativeRunner: true, enableOpenAiDot: true, enableMuse: true });
await renderPage(true);
await enterGithubUrl();
await clickButton(text => text === "Preview import");
const [source] = findAdapterSelects();
expect(source.value).toBe("");
expect([...source.options].filter(option => !option.disabled).map(option => option.value).sort()).toEqual([
"claude_local", "codex_local", "grok_local", "opencode_local", "paperclip_runner",
]);
const submit = [...container.querySelectorAll<HTMLButtonElement>("button")].find(button => button.textContent?.startsWith("Import 3 file"))!;
expect(submit.disabled).toBe(true);
const configure = [...container.querySelectorAll<HTMLButtonElement>("button")].find(button => button.textContent?.includes("configure adapter"))!;
expect(configure.disabled).toBe(true);
await act(async () => {
source.value = "codex_local";
source.dispatchEvent(new Event("change", { bubbles: true }));
});
await flushReact();
expect(submit.disabled).toBe(false);
});
it.each(["paperclip_runner", "codex_local"])("submits a fresh config when Cloud replaces Antigravity with %s", async adapterType => {
const preview = buildMixedAdapterPreviewResult();
preview.manifest.agents[0] = { ...preview.manifest.agents[0], adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "google-only-model" } };
mockCompaniesApi.importPreview.mockResolvedValue(preview);
mockAdaptersApi.list.mockResolvedValue(["claude_local", "codex_local", "paperclip_runner"].map(type => ({ type, disabled: false })));
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableNativeRunner: true });
await renderPage(true);
await enterGithubUrl();
await clickButton(text => text === "Preview import");
const [source] = findAdapterSelects();
await act(async () => {
source.value = adapterType;
source.dispatchEvent(new Event("change", { bubbles: true }));
});
await flushReact();
await clickButton(text => text.startsWith("Import 3 file"));
await settle();
const override = lastImportMeta().adapterOverrides?.coder;
expect(override?.adapterType).toBe(adapterType);
if (adapterType === "paperclip_runner") expect(override?.adapterConfig).toMatchObject({ provider: "codex" });
expect(override?.adapterConfig).toBeDefined();
expect(override?.adapterConfig).not.toHaveProperty("acpxAgent");
expect(override?.adapterConfig?.model).not.toBe("google-only-model");
});
function lastImportMeta() {
const call = mockCompaniesApi.importBundleAsync.mock.calls.at(-1);
expect(call).toBeTruthy();
+41 -12
View File
@@ -40,6 +40,8 @@ import {
import { GithubIcon } from "../components/icons/github-icon";
import { Field, adapterLabels } from "../components/agent-config-primitives";
import { getAdapterLabel } from "../adapters/adapter-display-registry";
import { useCloudInstance } from "@/hooks/useCloudInstance";
import { useCloudHarnessPolicy } from "@/hooks/useCloudHarnessPolicy";
import { defaultCreateValues } from "../components/agent-config-defaults";
import { getUIAdapter, listUIAdapters } from "../adapters";
import { isPaperclipRunnerProvider, PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES, type CreateConfigValues } from "@paperclipai/adapter-utils";
@@ -663,6 +665,8 @@ function AdapterPickerList({
onToggleExpand: (slug: string) => void;
onChangeConfig: (slug: string, patch: Partial<CreateConfigValues>) => void;
}) {
const cloud = Boolean(useCloudInstance());
const harnessPolicy = useCloudHarnessPolicy();
if (agents.length === 0) return null;
return (
@@ -679,6 +683,8 @@ function AdapterPickerList({
const selectedType =
adapterOverrides[agent.slug] ?? agent.fallbackAdapterType ?? agent.adapterChoice;
const isExpanded = expandedSlugs.has(agent.slug);
const allowed = !cloud || harnessPolicy.isCloudHarnessAllowed(selectedType,
configValues[agent.slug]?.adapterSchemaValues ?? (selectedType === agent.adapterChoice ? agent.adapterConfig : {}));
const vals = configValues[agent.slug] ?? importAdapterValues(
selectedType, selectedType === agent.adapterChoice ? agent.adapterConfig : undefined,
selectedType === agent.adapterChoice ? agent.adapterType : undefined,
@@ -700,7 +706,7 @@ function AdapterPickerList({
<ArrowRight className="h-3 w-3 shrink-0 text-muted-foreground" />
<select
className="min-w-0 flex-1 rounded-md border border-border bg-transparent px-2 py-1 text-xs outline-none focus:border-foreground"
value={selectedType}
value={allowed ? selectedType : ""}
onChange={(e) => onChangeAdapter(agent.slug, e.target.value)}
>
{adapterOptions.map((opt) => (
@@ -708,7 +714,8 @@ function AdapterPickerList({
{opt.label}
</option>
))}
{!adapterOptions.some((option) => option.value === selectedType) && (
{!allowed && <option value="" disabled>Choose an available harness</option>}
{allowed && !adapterOptions.some((option) => option.value === selectedType) && (
<option value={selectedType}>{agent.adapterChoice === "openai_dot" ? "OpenAI Dot (experimental)" : `${getAdapterLabel(selectedType)} (${agentHarnessType(agent.adapterType, agent.adapterConfig)})`}</option>
)}
</select>
@@ -721,6 +728,7 @@ function AdapterPickerList({
: "border-border text-muted-foreground hover:bg-accent/50",
)}
onClick={() => onToggleExpand(agent.slug)}
disabled={!allowed}
>
<ChevronRight className={cn("h-3 w-3 transition-transform", isExpanded && "rotate-90")} />
configure adapter
@@ -737,7 +745,7 @@ function AdapterPickerList({
{agent.availabilityWarning && selectedType === agent.adapterChoice && (
<p role="alert" className="mx-4 mb-2.5 text-xs text-destructive">{agent.availabilityWarning}</p>
)}
{isExpanded && (
{isExpanded && allowed && (
<div className="border-t border-border bg-accent/10 px-4 py-3 space-y-3">
<AgentConfigForm
mode="create"
@@ -1109,12 +1117,14 @@ export function CompanyImport() {
const nativeRunnerAvailable = runnerInstalled && experimentalSettings?.enableNativeRunner === true;
const dotAvailable = runnerInstalled && experimentalSettings?.enableOpenAiDot === true;
const museAvailable = nativeRunnerAvailable && experimentalSettings?.enableMuse === true;
const cloud = Boolean(useCloudInstance());
const harnessPolicy = useCloudHarnessPolicy();
const importAdapterOptions = useMemo(
() => IMPORT_ADAPTER_OPTIONS.filter((option) =>
option.value === "paperclip_runner" ? nativeRunnerAvailable
: option.value === "openai_dot" ? dotAvailable : option.value === "muse" ? museAvailable : true,
(!cloud || harnessPolicy.isCloudHarnessAllowed(option.value)) && (option.value === "paperclip_runner" ? nativeRunnerAvailable
: option.value === "openai_dot" ? dotAvailable : option.value === "muse" ? museAvailable : true),
),
[nativeRunnerAvailable, dotAvailable, museAvailable],
[cloud, harnessPolicy, nativeRunnerAvailable, dotAvailable, museAvailable],
);
const localZipHelpText =
@@ -1592,17 +1602,24 @@ export function CompanyImport() {
function handleAdapterChange(slug: string, adapterType: string) {
resetMutationState();
const source = adapterAgents.find(agent => agent.slug === slug);
const resetCloudProfile = cloud && source && !harnessPolicy.isCloudHarnessAllowed(source.adapterType, source.adapterConfig);
setAdapterOverrides((prev) => ({ ...prev, [slug]: adapterType }));
setAdapterConfigEditedSlugs(prev => {
const next = new Set(prev);
next.delete(slug);
// Selecting the generic Runner resets its provider, even when its API
// adapter type matches the manifest's unsupported native profile.
if (adapterType === "paperclip_runner" || resetCloudProfile) next.add(slug);
else next.delete(slug);
return next;
});
// Reset config values when adapter type changes
setAdapterConfigValues((prev) => {
const next = { ...prev };
if (adapterType === "openai_dot" || adapterType === "muse" || adapterType === "paperclip_runner") {
next[slug] = importAdapterValues(adapterType);
if (adapterType === "openai_dot" || adapterType === "muse" || adapterType === "paperclip_runner" || resetCloudProfile) {
next[slug] = { ...importAdapterValues(adapterType),
...(adapterType === "paperclip_runner" ? { adapterSchemaValues: { provider: "codex" } } : {}),
};
} else {
delete next[slug];
}
@@ -1702,7 +1719,7 @@ export function CompanyImport() {
// else any installed adapter, else null so the manifest adapter stands
// and the server's unknown-adapter rejection is the backstop.
const selectableTypes = [...availableAdapterTypes].filter((type) =>
type !== "paperclip_runner" || nativeRunnerAvailable,
(!cloud || harnessPolicy.isCloudHarnessAllowed(type)) && (type !== "paperclip_runner" || nativeRunnerAvailable),
);
fallbackAdapterType = selectableTypes.includes(ceoAdapterType)
? ceoAdapterType
@@ -1720,18 +1737,26 @@ export function CompanyImport() {
fallbackAdapterType,
};
});
}, [importPreview, availableAdapterTypes, ceoAdapterType, runnerInstalled, nativeRunnerAvailable, dotAvailable, museAvailable]);
}, [importPreview, availableAdapterTypes, ceoAdapterType, runnerInstalled, nativeRunnerAvailable, dotAvailable, museAvailable, cloud, harnessPolicy]);
/** The adapter type an imported agent will actually use: an explicit user pick, else the availability fallback, else the manifest adapter. */
function effectiveAdapterType(agent: AdapterPickerItem): string {
return adapterOverrides[agent.slug] ?? agent.fallbackAdapterType ?? agent.adapterChoice;
}
const selectedImportAgentSlugs = new Set(importPreview?.manifest.agents
.filter(agent => checkedFiles.has(agent.path) && !skippedSlugs.has(agent.slug)).map(agent => agent.slug));
const hasUnavailableCloudHarness = cloud && adapterAgents.some(agent => selectedImportAgentSlugs.has(agent.slug) && !harnessPolicy.isCloudHarnessAllowed(
effectiveAdapterType(agent), adapterConfigValues[agent.slug]?.adapterSchemaValues
?? (effectiveAdapterType(agent) === agent.adapterChoice ? agent.adapterConfig : {}),
));
// Build final adapterOverrides for import request. Only agents that diverge
// from the manifest adapter (a user pick or an availability fallback) or
// carry edited adapter config send an override — untouched agents flow
// through with none, so the manifest adapter survives the import.
function buildFinalAdapterOverrides(): Record<string, CompanyPortabilityAdapterOverride> | undefined {
if (hasUnavailableCloudHarness) throw new Error("Choose an available Cloud harness for each imported agent.");
const overrides: Record<string, CompanyPortabilityAdapterOverride> = {};
for (const agent of adapterAgents) {
const selectedType = effectiveAdapterType(agent);
@@ -1797,6 +1822,10 @@ export function CompanyImport() {
}
overrides[agent.slug] = override;
}
if (cloud && adapterAgents.some(agent => selectedImportAgentSlugs.has(agent.slug) && !harnessPolicy.isCloudHarnessAllowed(
overrides[agent.slug]?.adapterType ?? agent.adapterType,
overrides[agent.slug]?.adapterConfig ?? agent.adapterConfig,
))) throw new Error("Choose an available Cloud harness for each imported agent.");
return Object.keys(overrides).length > 0 ? overrides : undefined;
}
@@ -2258,7 +2287,7 @@ export function CompanyImport() {
<Button
size="sm"
onClick={() => importMutation.mutate({ previewForImport: importPreview, pauseAutomations })}
disabled={importMutation.isPending || hasErrors || selectedCount === 0}
disabled={importMutation.isPending || hasErrors || hasUnavailableCloudHarness || selectedCount === 0}
>
<Download className="mr-1.5 h-3.5 w-3.5" />
{importMutation.isPending
+46
View File
@@ -178,6 +178,52 @@ describe("InviteLandingPage", () => {
});
});
it.each([
{ availableHarnesses: ["gemini_local"] },
{ availableHarnesses: [] },
{ availableHarnesses: ["gemini_local"], nextHarnesses: ["codex_local"] },
{ availableHarnesses: ["gemini_local"], nextHarnesses: [] },
])("submits only the displayed allowed invite adapter (policy=$availableHarnesses, next=$nextHarnesses)", async ({ availableHarnesses, nextHarnesses }) => {
let policy = availableHarnesses;
getInviteMock.mockResolvedValue({ id: "invite-1", companyId: "company-1", companyName: "Example",
inviteType: "company_join", allowedJoinTypes: "agent" });
const health = { status: "ok", deploymentMode: "authenticated", cloud: { managed: true, availableHarnesses: policy } };
healthGetMock.mockResolvedValue(health);
acceptInviteMock.mockResolvedValue({ id: "request-1", requestType: "agent", status: "pending_approval" });
const root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
queryClient.setQueryData(queryKeys.health, health);
try {
await act(async () => renderInviteLanding(root, queryClient));
await flushReact();
await flushReact();
const input = container.querySelector("input")!;
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "Example agent");
input.dispatchEvent(new Event("input", { bubbles: true }));
});
if (nextHarnesses !== undefined) {
policy = nextHarnesses;
const updatedHealth = { ...health, cloud: { managed: true, availableHarnesses: policy } };
healthGetMock.mockResolvedValue(updatedHealth);
await act(async () => { queryClient.setQueryData(queryKeys.health, updatedHealth); });
await flushReact();
}
const select = container.querySelector("select")!;
expect(select.value).toBe(policy[0] ?? "");
const submit = [...container.querySelectorAll("button")].find(button => button.textContent?.includes("Submit"))!;
expect(submit).toBeTruthy();
expect(submit.disabled).toBe(policy.length === 0);
await act(async () => submit.click());
await flushReact();
if (policy.length) expect(acceptInviteMock).toHaveBeenCalledWith("pcp_invite_test", expect.objectContaining({ adapterType: policy[0] }));
else expect(acceptInviteMock).not.toHaveBeenCalled();
} finally {
await act(async () => root.unmount());
queryClient.clear();
}
});
it("defaults invite auth to account creation and guides existing users back to sign in", async () => {
signUpEmailMock.mockRejectedValue(
Object.assign(new Error("User already exists. Use another email."), {
+12 -4
View File
@@ -12,6 +12,7 @@ import { AuthApiError, authApi, authErrorServerMessage } from "../api/auth";
import { fetchCompanyListForCurrentAccount, useCompanyListQuery } from "../api/companies-query";
import { healthApi } from "../api/health";
import { getAdapterLabel } from "../adapters/adapter-display-registry";
import { useCloudHarnessPolicy } from "@/hooks/useCloudHarnessPolicy";
import { clearPendingInviteToken, rememberPendingInviteToken } from "../lib/invite-memory";
import { queryKeys } from "../lib/queryKeys";
import { cn, formatDate } from "../lib/utils";
@@ -214,6 +215,7 @@ function AwaitingJoinApprovalPanel({
}
export function InviteLandingPage() {
const harnessPolicy = useCloudHarnessPolicy();
const queryClient = useQueryClient();
const navigate = useNavigate();
const { setSelectedCompanyId } = useCompany();
@@ -236,6 +238,9 @@ export function InviteLandingPage() {
queryKey: queryKeys.health,
queryFn: () => healthApi.get(),
});
const availableJoinAdapterOptions = joinAdapterOptions.filter(type => !healthQuery.data?.cloud || harnessPolicy.isCloudHarnessAllowed(type));
const enabledJoinAdapterOptions = availableJoinAdapterOptions.filter(type => ENABLED_INVITE_ADAPTERS.has(type));
const selectedAdapterType = enabledJoinAdapterOptions.includes(adapterType) ? adapterType : enabledJoinAdapterOptions[0];
const sessionQuery = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
@@ -344,10 +349,11 @@ export function InviteLandingPage() {
if (invite.inviteType === "bootstrap_ceo" || invite.allowedJoinTypes !== "agent") {
return accessApi.acceptInvite(token, { requestType: "human" });
}
if (!selectedAdapterType) throw new Error("No adapters are available for this invite.");
return accessApi.acceptInvite(token, {
requestType: "agent",
agentName: agentName.trim(),
adapterType,
adapterType: selectedAdapterType,
capabilities: capabilities.trim() || null,
});
},
@@ -639,10 +645,12 @@ export function InviteLandingPage() {
<span className="mb-1 block text-zinc-400">Adapter type</span>
<select
className={fieldClassName}
value={adapterType}
value={selectedAdapterType ?? ""}
disabled={!selectedAdapterType}
onChange={(event) => setAdapterType(event.target.value as AgentAdapterType)}
>
{joinAdapterOptions.map((type) => (
{!selectedAdapterType && <option value="" disabled>No available adapter</option>}
{availableJoinAdapterOptions.map((type) => (
<option key={type} value={type} disabled={!ENABLED_INVITE_ADAPTERS.has(type)}>
{getAdapterLabel(type)}{!ENABLED_INVITE_ADAPTERS.has(type) ? " (Coming soon)" : ""}
</option>
@@ -661,7 +669,7 @@ export function InviteLandingPage() {
{error ? <p className="text-xs text-red-400">{error}</p> : null}
<Button
className="w-full rounded-none"
disabled={acceptMutation.isPending || agentName.trim().length === 0}
disabled={acceptMutation.isPending || agentName.trim().length === 0 || !selectedAdapterType}
onClick={() => acceptMutation.mutate()}
>
{acceptMutation.isPending ? "Working..." : joinButtonLabel}
@@ -0,0 +1,36 @@
// @vitest-environment jsdom
import { sampleHarnesses } from "@/test-support/harness-availability";
import { describe, expect, it } from "vitest";
import { queryKeys } from "@/lib/queryKeys";
import {
api, settings, state, cache, settle, render, renderCurrentParams, container,
} from "./NewAgent.test-support";
describe("Cloud agent harness choices", () => {
it("offers exactly the released harnesses even with experiments and candidate access", async () => {
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses: sampleHarnesses } });
settings.getExperimental.mockResolvedValue({ enableNativeRunner: true, enableOpenAiDot: true, enableMuse: true });
state.adapters = state.adapters.map((adapter: any) => adapter.type === "paperclip_runner"
? { ...adapter, candidateHarnesses: [{ agent: "antigravity", model: "candidate-model" }] }
: adapter);
const setupId = "00000000-0000-4000-8000-000000000094";
state.params = new URLSearchParams({ name: "Atlas", adapterType: "process", setupAgentId: setupId });
api.get.mockResolvedValue({ id: setupId, companyId: "company-1", name: "Atlas", adapterType: "process", adapterConfig: {}, runtimeConfig: {}, metadata: { setupAdapterPending: true }, pauseReason: "setup", status: "paused" });
await renderCurrentParams();
await settle();
expect([...document.querySelectorAll<HTMLInputElement>('input[name="new-agent-adapter"]')].map(input => input.value).sort()).toEqual([
"claude_local", "codex_local", "copilot_runtime", "grok_local", "opencode_local",
]);
expect(document.body.textContent).not.toContain("Google Antigravity");
});
it.each(["antigravity", "kimi", "pi", "cursor_cloud", "claude_managed", "aws_agentcore", "openai_dot", "muse"])("withholds native %s setup and model controls on direct links", async provider => {
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses: sampleHarnesses } });
settings.getExperimental.mockResolvedValue({ enableNativeRunner: true, enableOpenAiDot: true, enableMuse: true });
await render("paperclip_runner", provider);
expect(container.textContent).toContain("This adapter is unavailable");
expect(container.querySelector('[aria-label="Model"]')).toBeNull();
expect(api.testEnvironment).not.toHaveBeenCalled();
expect(api.hire).not.toHaveBeenCalled();
});
});
+5 -4
View File
@@ -1,4 +1,5 @@
// @vitest-environment jsdom
import { sampleHarnesses } from "@/test-support/harness-availability";
import { act } from "react";
import { PAPERCLIP_RUNNER_ACPX_PROFILES } from "@paperclipai/adapter-utils";
import { describe, expect, it, vi } from "vitest";
@@ -874,14 +875,14 @@ describe("New agent setup", () => {
expect(api.hire.mock.calls[0][1].defaultEnvironmentId).toBe("grok-sandbox");
});
it.each([false, true])("keeps other native setup links gated when the experiment is disabled (cloud=%s)", async (cloud) => {
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: cloud } });
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: cloud, availableHarnesses: cloud ? sampleHarnesses : undefined } });
settings.getExperimental.mockResolvedValue({ enableNativeRunner: false });
await render("paperclip_runner", "grok");
expect(container.textContent).toContain("This adapter is unavailable");
expect(api.hire).not.toHaveBeenCalled();
});
it.each([false, true])("restores native Claude setup intent and its connection flow with experiment=false (cloud=%s)", async cloud => {
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: cloud } });
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: cloud, availableHarnesses: cloud ? sampleHarnesses : undefined } });
settings.getExperimental.mockResolvedValue({ enableNativeRunner: false });
await render("paperclip_runner", "claude");
expect(container.textContent).not.toContain("This adapter is unavailable");
@@ -894,7 +895,7 @@ describe("New agent setup", () => {
it("blocks direct setup links for unsupported Cloud adapters", async () => {
cache.setQueryData(queryKeys.health, {
status: "ok",
cloud: { managed: true },
cloud: { managed: true, availableHarnesses: sampleHarnesses },
});
await render("pi_local");
expect(container.textContent).toContain("This adapter is unavailable");
@@ -906,7 +907,7 @@ describe("New agent setup", () => {
])("configures %s Grok on Cloud with an xAI %s connection", async (adapterType, method) => {
cache.setQueryData(queryKeys.health, {
status: "ok",
cloud: { managed: true },
cloud: { managed: true, availableHarnesses: sampleHarnesses },
});
envApi.list.mockResolvedValue([
{ id: "sandbox-1", name: "Paperclip Cloud", driver: "sandbox", config: { provider: "daytona" } },
+76 -1
View File
@@ -1,4 +1,6 @@
// @vitest-environment jsdom
import { createCloudHarnessPolicy } from "@/lib/cloud-harness-policy";
import { sampleHarnesses } from "@/test-support/harness-availability";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
@@ -16,6 +18,7 @@ import {
teamRoute,
} from "./TeamCatalog";
import { TooltipProvider } from "@/components/ui/tooltip";
import { queryKeys } from "@/lib/queryKeys";
const mockTeamCatalogApi = vi.hoisted(() => ({
catalogList: vi.fn(),
@@ -100,6 +103,11 @@ if (typeof Element !== "undefined" && !Element.prototype.scrollIntoView) {
}
describe("TeamCatalog routes", () => {
it("limits Cloud team installation choices to released harnesses", () => {
expect(listTeamInstallAdapterTypes(new Set(), true, true, createCloudHarnessPolicy(sampleHarnesses)).sort()).toEqual([
"claude_local", "codex_local", "grok_local", "opencode_local", "paperclip_runner",
]);
});
it("round-trips file paths containing literal tildes", () => {
const route = teamRoute("paperclipai/bundled/test/team", "agents/a~b/AGENTS.md");
@@ -124,6 +132,14 @@ describe("TeamCatalog routes", () => {
expect(resolveTeamInstallAdapterType("paperclip_runner", []))
.toBeNull();
});
it("preserves an allowed saved Runner only while its adapter is available", () => {
const harnessPolicy = createCloudHarnessPolicy(["copilot_runtime"]);
const options = { cloud: true, harnessPolicy, adapterConfig: { provider: "acpx", acpxAgent: "copilot" } };
expect(resolveTeamInstallAdapterType("paperclip_runner", [], { ...options, nativeRunnerAvailable: true })).toBe("paperclip_runner");
expect(resolveTeamInstallAdapterType("paperclip_runner", [], { ...options, nativeRunnerAvailable: false })).toBeNull();
expect(resolveTeamInstallAdapterType("paperclip_runner", [], { ...options, adapterConfig: {}, nativeRunnerAvailable: true })).toBeNull();
});
});
async function act(callback: () => void | Promise<void>) {
@@ -268,9 +284,10 @@ describe("TeamCatalog install preview path", () => {
vi.clearAllMocks();
});
async function renderPage() {
async function renderPage(cloud = false, availableHarnesses = sampleHarnesses) {
const root = createRoot(container);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
if (cloud) queryClient.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses } });
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
@@ -293,6 +310,64 @@ describe("TeamCatalog install preview path", () => {
expect(document.body.textContent).toContain("Projects");
});
it.each([
{ cloud: true, acpxAgent: "antigravity", chooseRunner: false, expected: "claude_local" },
{ cloud: true, acpxAgent: "antigravity", chooseRunner: false, expected: "paperclip_runner", onlyRunner: true },
{ cloud: true, acpxAgent: "antigravity", chooseRunner: true, expected: "paperclip_runner" },
{ cloud: true, acpxAgent: "copilot", chooseRunner: false, expected: undefined },
{ cloud: true, acpxAgent: "copilot", chooseRunner: false, expected: undefined, availableHarnesses: ["copilot_runtime"] },
{ cloud: true, acpxAgent: "copilot", chooseRunner: false, expected: undefined, availableHarnesses: ["claude_local", "copilot_runtime"] },
{ cloud: true, acpxAgent: "copilot", chooseRunner: true, expected: undefined, availableHarnesses: ["copilot_runtime"] },
{ cloud: true, acpxAgent: "copilot", chooseRunner: true, expected: undefined, availableHarnesses: ["claude_local", "copilot_runtime"], chooseLegacyFirst: true },
{ cloud: false, acpxAgent: "antigravity", chooseRunner: false, expected: undefined },
])("submits the selected native team profile (cloud=$cloud, source=$acpxAgent, reset=$chooseRunner, expected=$expected, policy=$availableHarnesses)", async ({ cloud, acpxAgent, chooseRunner, expected, onlyRunner, availableHarnesses, chooseLegacyFirst }) => {
mockAdapterAvailability.disabled = new Set(onlyRunner ? ["claude_local", "codex_local", "grok_local", "opencode_local"] : []);
const preview = makePreview();
preview.portabilityPreview.manifest.agents = [{
slug: "ceo", name: "CEO", path: "agents/ceo/AGENTS.md", skills: [], role: "ceo", title: null, icon: null,
capabilities: null, reportsToSlug: null, reportsToExistingAgentId: null, reportsToExistingAgentSlug: null,
adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent, model: "source-only-model" },
runtimeConfig: {}, permissions: {}, permissionGrants: [], budgetMonthlyCents: 0, metadata: null,
}];
mockTeamCatalogApi.preview.mockResolvedValue(preview);
const root = await renderPage(cloud, availableHarnesses);
await act(async () => findButton("Install team")!.click());
await flushReact();
if (chooseRunner) {
if (chooseLegacyFirst) {
const picker = [...document.querySelectorAll<HTMLButtonElement>('button[role="combobox"]')].find(button => /Paperclip Runner/.test(button.textContent ?? ""))!;
await act(async () => { picker.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); });
await flushReact();
const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(item => item.textContent?.trim() === "Claude Code");
expect(option).toBeDefined();
await act(async () => option!.click());
await flushReact();
}
const picker = [...document.querySelectorAll<HTMLButtonElement>('button[role="combobox"]')]
.find(button => /Claude Code|Paperclip Runner/.test(button.textContent ?? ""))!;
expect(picker).toBeTruthy();
await act(async () => { picker.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); });
await flushReact();
const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(item => item.textContent?.trim() === "Paperclip Runner");
expect(option).toBeDefined();
await act(async () => option!.click());
await flushReact();
}
const submit = [...document.querySelectorAll<HTMLButtonElement>("button")].filter(button => button.textContent?.includes("Install team")).at(-1)!;
expect(submit.disabled).toBe(false);
await act(async () => submit.click());
await flushReact();
const override = mockTeamCatalogApi.install.mock.calls[0]?.[2]?.adapterOverrides?.ceo;
if (expected) {
expect(override?.adapterType).toBe(expected);
expect(override?.adapterConfig).toEqual(expected === "paperclip_runner" ? { provider: "codex" } : {});
} else {
expect(mockTeamCatalogApi.install).toHaveBeenCalledTimes(1);
expect(override).toBeUndefined();
}
await act(async () => root.unmount());
});
it("opens the installer, fetches the preview, and submits the install", async () => {
await renderPage();
+56 -5
View File
@@ -22,6 +22,9 @@ import { AGENT_ADAPTER_TYPES } from "@paperclipai/shared";
import { teamCatalogApi } from "../api/teamCatalog";
import { agentsApi } from "../api/agents";
import { getAdapterLabel } from "../adapters/adapter-display-registry";
import { useCloudInstance } from "@/hooks/useCloudInstance";
import { useCloudHarnessPolicy } from "@/hooks/useCloudHarnessPolicy";
import { unrestrictedCloudHarnessPolicy, type CloudHarnessPolicy } from "@/lib/cloud-harness-policy";
import {
useAdapterRegistryLoaded,
useDisabledAdaptersSync,
@@ -125,9 +128,12 @@ const TEAM_INSTALL_FORBIDDEN_ADAPTER_TYPES = new Set(["process", "http"]);
export function listTeamInstallAdapterTypes(
disabledTypes: Set<string>,
adapterRegistryLoaded: boolean,
cloud = false,
harnessPolicy: CloudHarnessPolicy = unrestrictedCloudHarnessPolicy,
) {
return AGENT_ADAPTER_TYPES.filter(
(type) =>
(!cloud || harnessPolicy.isCloudHarnessAllowed(type)) &&
!TEAM_INSTALL_FORBIDDEN_ADAPTER_TYPES.has(type) &&
!disabledTypes.has(type) &&
(type !== "paperclip_runner" || adapterRegistryLoaded),
@@ -137,14 +143,31 @@ export function listTeamInstallAdapterTypes(
export function resolveTeamInstallAdapterType(
requestedType: string,
selectableAdapterTypes: readonly string[],
{ cloud = false, adapterConfig = {}, harnessPolicy = unrestrictedCloudHarnessPolicy, nativeRunnerAvailable = selectableAdapterTypes.includes("paperclip_runner") }: {
cloud?: boolean; adapterConfig?: Record<string, unknown>; harnessPolicy?: CloudHarnessPolicy; nativeRunnerAvailable?: boolean;
} = {},
) {
if (selectableAdapterTypes.includes(requestedType)) return requestedType;
const profileAllowed = !cloud || harnessPolicy.isCloudHarnessAllowed(requestedType, adapterConfig);
// A saved native profile can be allowed even when the default Codex profile
// is excluded. Keep that profile without adding an invalid generic fallback.
if (profileAllowed && (selectableAdapterTypes.includes(requestedType) || (requestedType === "paperclip_runner" && nativeRunnerAvailable))) return requestedType;
if (selectableAdapterTypes.includes(TEAM_INSTALL_FALLBACK_ADAPTER_TYPE)) {
return TEAM_INSTALL_FALLBACK_ADAPTER_TYPE;
}
return selectableAdapterTypes[0] ?? null;
}
function teamInstallSelectionConfig(
source: { adapterType: string; adapterConfig: Record<string, unknown> },
overrideType: string | undefined,
cloud: boolean,
harnessPolicy: CloudHarnessPolicy,
) {
const preserveSource = !overrideType || (overrideType === source.adapterType
&& (!cloud || harnessPolicy.isCloudHarnessAllowed(source.adapterType, source.adapterConfig)));
return preserveSource ? source.adapterConfig : {};
}
function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(() =>
typeof window !== "undefined" ? window.matchMedia(query).matches : false,
@@ -1089,9 +1112,12 @@ export function TeamInstallerDialog({
const [phase, setPhase] = useState<ApplyPhase>("form");
const disabledAdapterTypes = useDisabledAdaptersSync({ enabled: open });
const adapterRegistryLoaded = useAdapterRegistryLoaded({ enabled: open });
const nativeRunnerAvailable = adapterRegistryLoaded && !disabledAdapterTypes.has("paperclip_runner");
const cloud = Boolean(useCloudInstance());
const harnessPolicy = useCloudHarnessPolicy();
const selectableAdapterTypes = useMemo(
() => listTeamInstallAdapterTypes(disabledAdapterTypes, adapterRegistryLoaded),
[adapterRegistryLoaded, disabledAdapterTypes],
() => listTeamInstallAdapterTypes(disabledAdapterTypes, adapterRegistryLoaded, cloud, harnessPolicy),
[adapterRegistryLoaded, disabledAdapterTypes, cloud, harnessPolicy],
);
// Step 1 — target manager
@@ -1160,15 +1186,21 @@ export function TeamInstallerDialog({
const overrides: Record<string, CompanyPortabilityAdapterOverride> = {};
for (const [slug, adapterType] of Object.entries(adapterOverrides)) {
if (adapterType) {
const source = previewResult?.portabilityPreview.manifest.agents.find(agent => agent.slug === slug);
const adapterConfig = source ? teamInstallSelectionConfig(source, adapterType, cloud, harnessPolicy) : {};
const resolvedAdapterType = resolveTeamInstallAdapterType(
adapterType,
selectableAdapterTypes,
{ cloud, adapterConfig, harnessPolicy, nativeRunnerAvailable },
);
if (!resolvedAdapterType) {
throw new Error("Enable a legacy adapter before installing this team.");
}
if (cloud && source?.adapterType === "paperclip_runner" && resolvedAdapterType === source.adapterType
&& harnessPolicy.isCloudHarnessAllowed(source.adapterType, source.adapterConfig)) continue;
overrides[slug] = {
adapterType: resolvedAdapterType,
...(cloud ? { adapterConfig: resolvedAdapterType === "paperclip_runner" ? { provider: "codex" } : {} } : {}),
};
}
}
@@ -1177,12 +1209,15 @@ export function TeamInstallerDialog({
const adapterType = resolveTeamInstallAdapterType(
agent.adapterType,
selectableAdapterTypes,
{ cloud, adapterConfig: agent.adapterConfig, harnessPolicy, nativeRunnerAvailable },
);
if (!adapterType) {
throw new Error("Enable a legacy adapter before installing this team.");
}
if (adapterType !== agent.adapterType) {
overrides[agent.slug] = { adapterType };
if (adapterType !== agent.adapterType || (cloud && !harnessPolicy.isCloudHarnessAllowed(agent.adapterType, agent.adapterConfig))) {
overrides[agent.slug] = { adapterType,
...(cloud ? { adapterConfig: adapterType === "paperclip_runner" ? { provider: "codex" } : {} } : {}),
};
}
}
const enteredSecretValues = Object.fromEntries(
@@ -1258,6 +1293,7 @@ export function TeamInstallerDialog({
!resolveTeamInstallAdapterType(
adapterOverrides[agent.slug] ?? agent.adapterType,
selectableAdapterTypes,
{ cloud, adapterConfig: teamInstallSelectionConfig(agent, adapterOverrides[agent.slug], cloud, harnessPolicy), harnessPolicy, nativeRunnerAvailable },
),
),
);
@@ -1354,6 +1390,9 @@ export function TeamInstallerDialog({
onRename={(slug, name) => setNameOverrides((cur) => ({ ...cur, [slug]: name }))}
adapterOverrides={adapterOverrides}
selectableAdapterTypes={selectableAdapterTypes}
cloud={cloud}
harnessPolicy={harnessPolicy}
nativeRunnerAvailable={nativeRunnerAvailable}
onAdapterChange={(slug, adapterType) => setAdapterOverrides((cur) => ({ ...cur, [slug]: adapterType }))}
secretValues={secretValues}
visibleSecretKeys={visibleSecretKeys}
@@ -1778,6 +1817,9 @@ export function StepPreview({
onRename,
adapterOverrides,
selectableAdapterTypes,
cloud = false,
harnessPolicy = unrestrictedCloudHarnessPolicy,
nativeRunnerAvailable = selectableAdapterTypes.includes("paperclip_runner"),
onAdapterChange,
secretValues = {},
visibleSecretKeys = {},
@@ -1795,6 +1837,9 @@ export function StepPreview({
onRename: (slug: string, name: string) => void;
adapterOverrides: Record<string, string>;
selectableAdapterTypes: readonly string[];
cloud?: boolean;
harnessPolicy?: CloudHarnessPolicy;
nativeRunnerAvailable?: boolean;
onAdapterChange: (slug: string, adapterType: string) => void;
secretValues?: Record<string, string>;
visibleSecretKeys?: Record<string, boolean>;
@@ -1922,9 +1967,12 @@ export function StepPreview({
{manifestAgents.length > 0 && (
<PreviewSection title={`Adapter selection · ${manifestAgents.length}`}>
{manifestAgents.map((agent) => {
const savedRunnerSelectable = agent.adapterType === "paperclip_runner" && nativeRunnerAvailable
&& (!cloud || harnessPolicy.isCloudHarnessAllowed(agent.adapterType, agent.adapterConfig));
const selected = resolveTeamInstallAdapterType(
adapterOverrides[agent.slug] ?? agent.adapterType,
selectableAdapterTypes,
{ cloud, adapterConfig: teamInstallSelectionConfig(agent, adapterOverrides[agent.slug], cloud, harnessPolicy), harnessPolicy, nativeRunnerAvailable },
);
return (
<li key={agent.slug} className="flex items-center gap-2 px-3 py-2 text-sm">
@@ -1940,6 +1988,9 @@ export function StepPreview({
{selectableAdapterTypes.map((type) => (
<SelectItem key={type} value={type}>{getAdapterLabel(type)}</SelectItem>
))}
{savedRunnerSelectable && !selectableAdapterTypes.includes("paperclip_runner") && (
<SelectItem value="paperclip_runner">{getAdapterLabel("paperclip_runner")}</SelectItem>
)}
</SelectContent>
</Select>
) : (
@@ -0,0 +1,2 @@
// Example deployment configuration for tests. Core has no default allowlist.
export const sampleHarnesses = ["claude_local", "codex_local", "grok_local", "opencode_local", "copilot_runtime"];