diff --git a/AGENTS.md b/AGENTS.md index 2df76c7e170..c76d48c0638 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/doc/harness-availability.md b/doc/harness-availability.md new file mode 100644 index 00000000000..cd5f2faaf43 --- /dev/null +++ b/doc/harness-availability.md @@ -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. diff --git a/server/src/__tests__/harness-availability.test.ts b/server/src/__tests__/harness-availability.test.ts new file mode 100644 index 00000000000..5a230516826 --- /dev/null +++ b/server/src/__tests__/harness-availability.test.ts @@ -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"); + }, + ); +}); diff --git a/server/src/__tests__/health.test.ts b/server/src/__tests__/health.test.ts index 31ec1d8bf26..8fb3d70c9eb 100644 --- a/server/src/__tests__/health.test.ts +++ b/server/src/__tests__/health.test.ts @@ -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", diff --git a/server/src/routes/health.ts b/server/src/routes/health.ts index b641a98ac82..ff146142ba9 100644 --- a/server/src/routes/health.ts +++ b/server/src/routes/health.ts @@ -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, diff --git a/server/src/services/harness-availability.ts b/server/src/services/harness-availability.ts new file mode 100644 index 00000000000..a54ac8e7a6b --- /dev/null +++ b/server/src/services/harness-availability.ts @@ -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 = 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; +} diff --git a/ui/src/adapters/codex-local/config-fields.test.tsx b/ui/src/adapters/codex-local/config-fields.test.tsx index 6b8da1ebccc..d57ef1c8c4c 100644 --- a/ui/src/adapters/codex-local/config-fields.test.tsx +++ b/ui/src/adapters/codex-local/config-fields.test.tsx @@ -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 { +async function renderMarkup(node: ReactNode, expand?: string, inspect?: (container: HTMLElement) => void | Promise): Promise { const container = document.createElement("div"); document.body.appendChild(container); const root = createRoot(container); - await act(async () => root.render({node})); + const client = new QueryClient(); + await act(async () => root.render({node})); 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, expand?: string, inspectOrDot?: ((container: HTMLElement) => void) | boolean): Promise { +async function renderRunner(config: Record, expand?: string, inspectOrDot?: ((container: HTMLElement) => void) | boolean, cloud = false): Promise { const openAiDotEnabled = inspectOrDot === true; const inspect = typeof inspectOrDot === "function" ? inspectOrDot : undefined; return renderMarkup( @@ -48,6 +50,7 @@ async function renderRunner(config: Record, expand?: string, in mark={() => undefined} models={[]} hideInstructionsFile + availableHarnesses={cloud ? sampleHarnesses : undefined} openAiDotEnabled={openAiDotEnabled} /> , @@ -55,6 +58,37 @@ async function renderRunner(config: Record, 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 = {}; + await renderMarkup( original} mark={(_group, field, value) => { changes[field] = value; }} + models={[]} hideInstructionsFile availableHarnesses={["copilot_runtime"]} /> + , "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(`[aria-label="${label}"]`)!; await act(async () => { diff --git a/ui/src/adapters/codex-local/config-fields.tsx b/ui/src/adapters/codex-local/config-fields.tsx index db2cc716b7d..c1e317b1673 100644 --- a/ui/src/adapters/codex-local/config-fields.tsx +++ b/ui/src/adapters/codex-local/config-fields.tsx @@ -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({ {!isPaperclipRunnerProvider(runnerProvider) && {runnerProvider} (unknown provider)} - {runnerHarnessOptions.map((option) => ( + {runnerHarnessOptions.filter(option => option.value === "acpx" ? !harnessPolicy.restricted || allowedAcpxProfiles.length > 0 : harnessPolicy.isCloudRunnerProviderAllowed(option.value)).map((option) => ( {option.label} @@ -357,7 +366,7 @@ export function CodexLocalConfigFields({ }}> - {PAPERCLIP_RUNNER_ACPX_PROFILES.map(profile => ( + {PAPERCLIP_RUNNER_ACPX_PROFILES.filter(profile => !harnessPolicy.restricted || (profile.qualified && harnessPolicy.isCloudRunnerProviderAllowed("acpx", profile.value))).map(profile => ( {profile.label}{profile.qualified ? "" : " — qualification pending"} diff --git a/ui/src/adapters/types.ts b/ui/src/adapters/types.ts index 4156ef13839..f7bfffe20fb 100644 --- a/ui/src/adapters/types.ts +++ b/ui/src/adapters/types.ts @@ -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. */ diff --git a/ui/src/api/health.ts b/ui/src/api/health.ts index ee38beb85fd..8edad1edc7e 100644 --- a/ui/src/api/health.ts +++ b/ui/src/api/health.ts @@ -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; diff --git a/ui/src/components/AgentConfigForm.render.test.tsx b/ui/src/components/AgentConfigForm.render.test.tsx index 7a617f27211..850b74ac44f 100644 --- a/ui/src/components/AgentConfigForm.render.test.tsx +++ b/ui/src/components/AgentConfigForm.render.test.tsx @@ -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; diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsx index 867bbaf209e..19c4207044c 100644 --- a/ui/src/components/AgentConfigForm.tsx +++ b/ui/src/components/AgentConfigForm.tsx @@ -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 | 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(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 && (<> [...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 diff --git a/ui/src/components/CloudHarnessSelectors.test.tsx b/ui/src/components/CloudHarnessSelectors.test.tsx new file mode 100644 index 00000000000..1d35ddf37ea --- /dev/null +++ b/ui/src/components/CloudHarnessSelectors.test.tsx @@ -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( + {}} disabledTypes={new Set()} nativeRunnerEnabled /> + )); + 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( + {}} disabledTypes={new Set()} + openAiDotEnabled museEnabled nativeRunnerEnabled /> + )); + 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(); + } + }); +}); diff --git a/ui/src/components/NewAgentDialog.test.tsx b/ui/src/components/NewAgentDialog.test.tsx index 35477a9139c..535c2043762 100644 --- a/ui/src/components/NewAgentDialog.test.tsx +++ b/ui/src/components/NewAgentDialog.test.tsx @@ -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('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('[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"))!; diff --git a/ui/src/components/agents/AgentBulkRoster.tsx b/ui/src/components/agents/AgentBulkRoster.tsx index f7cde6866d1..d0c73b2eeb2 100644 --- a/ui/src/components/agents/AgentBulkRoster.tsx +++ b/ui/src/components/agents/AgentBulkRoster.tsx @@ -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([]); 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, {visible.map(agent => { const metadata = rosterIndex.byAgentId.get(agent.id)!; return - a.id === agent.id)} disabled={!!bulkAgentDisabledReason(agent)} onCheckedChange={value => changeSelection(value ? [...new Set([...selected, agent.id])] : selected.filter(id => id !== agent.id))} /> + a.id === agent.id)} disabled={!!bulkAgentDisabledReason(agent, cloud, harnessPolicy)} onCheckedChange={value => changeSelection(value ? [...new Set([...selected, agent.id])] : selected.filter(id => id !== agent.id))} /> {renderAgent(agent)} {renderChat && {renderChat(agent)}} {renderStatus ? renderStatus(agent) : } diff --git a/ui/src/components/issue-properties/IssueProperties.tsx b/ui/src/components/issue-properties/IssueProperties.tsx index fbdaccece1b..86b1a97e246 100644 --- a/ui/src/components/issue-properties/IssueProperties.tsx +++ b/ui/src/components/issue-properties/IssueProperties.tsx @@ -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); diff --git a/ui/src/components/new-agent/AgentBasicsDialog.tsx b/ui/src/components/new-agent/AgentBasicsDialog.tsx index df1cc6f5601..d20a70d28d6 100644 --- a/ui/src/components/new-agent/AgentBasicsDialog.tsx +++ b/ui/src/components/new-agent/AgentBasicsDialog.tsx @@ -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(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({ ); })} - {experimentalRunnerAvailable &&
+ {experimentalRunnerAvailable && advancedRunnerOptions.length > 0 &&
Advanced
@@ -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} />
} diff --git a/ui/src/components/new-agent/NewAgentSetup.tsx b/ui/src/components/new-agent/NewAgentSetup.tsx index d06f3ff3313..3b6824fbb5c 100644 --- a/ui/src/components/new-agent/NewAgentSetup.tsx +++ b/ui/src/components/new-agent/NewAgentSetup.tsx @@ -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 (

Select an organization to create an agent.

); - if (params.get("adapterType") === "muse" || params.get("runnerProvider") === "muse") return navigate("/agents/all")} onBack={() => navigate("/agents/all")} />; + if ((!cloud || harnessPolicy.isCloudRunnerProviderAllowed("muse")) && (params.get("adapterType") === "muse" || params.get("runnerProvider") === "muse")) return navigate("/agents/all")} onBack={() => navigate("/agents/all")} />; return ( 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
+

This adapter is unavailable. Choose an enabled adapter.

+ +
; if (!created && connectionSettingsReady && !pendingAntigravity) return

{error ?? "Creating your agent…"}

{error && } diff --git a/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx b/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx index 18ba8546c74..2f89c34dfd4 100644 --- a/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx +++ b/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx @@ -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(); diff --git a/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx b/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx index b25a2370a3c..2ffa0c54ad2 100644 --- a/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx +++ b/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx @@ -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; diff --git a/ui/src/hooks/useCloudHarnessPolicy.ts b/ui/src/hooks/useCloudHarnessPolicy.ts new file mode 100644 index 00000000000..b59c6867cd5 --- /dev/null +++ b/ui/src/hooks/useCloudHarnessPolicy.ts @@ -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]); +} diff --git a/ui/src/lib/bulk-agent-settings.test.ts b/ui/src/lib/bulk-agent-settings.test.ts index a00707f41cd..b6601c61d0a 100644 --- a/ui/src/lib/bulk-agent-settings.test.ts +++ b/ui/src/lib/bulk-agent-settings.test.ts @@ -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; diff --git a/ui/src/lib/bulk-agent-settings.ts b/ui/src/lib/bulk-agent-settings.ts index 5e45b4287e1..3571d8b0fac 100644 --- a/ui/src/lib/bulk-agent-settings.ts +++ b/ui/src/lib/bulk-agent-settings.ts @@ -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"; diff --git a/ui/src/lib/cloud-harness-policy.test.ts b/ui/src/lib/cloud-harness-policy.test.ts new file mode 100644 index 00000000000..f18f0f5e708 --- /dev/null +++ b/ui/src/lib/cloud-harness-policy.test.ts @@ -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); + }); +}); diff --git a/ui/src/lib/cloud-harness-policy.ts b/ui/src/lib/cloud-harness-policy.ts new file mode 100644 index 00000000000..d4d461a1928 --- /dev/null +++ b/ui/src/lib/cloud-harness-policy.ts @@ -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 = {}): 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; +export const unrestrictedCloudHarnessPolicy = createCloudHarnessPolicy(); diff --git a/ui/src/lib/new-agent-adapters.ts b/ui/src/lib/new-agent-adapters.ts index 1d44ef9b862..2f92658c401 100644 --- a/ui/src/lib/new-agent-adapters.ts +++ b/ui/src/lib/new-agent-adapters.ts @@ -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; } diff --git a/ui/src/pages/CompanyImport.test.tsx b/ui/src/pages/CompanyImport.test.tsx index ef09cd5e51a..f6a852c62c0 100644 --- a/ui/src/pages/CompanyImport.test.tsx +++ b/ui/src/pages/CompanyImport.test.tsx @@ -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("button")].find(button => button.textContent?.startsWith("Import 3 file"))!; + expect(submit.disabled).toBe(true); + const configure = [...container.querySelectorAll("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(); diff --git a/ui/src/pages/CompanyImport.tsx b/ui/src/pages/CompanyImport.tsx index 11db214522e..33ed5812bd7 100644 --- a/ui/src/pages/CompanyImport.tsx +++ b/ui/src/pages/CompanyImport.tsx @@ -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) => 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({ @@ -721,6 +728,7 @@ function AdapterPickerList({ : "border-border text-muted-foreground hover:bg-accent/50", )} onClick={() => onToggleExpand(agent.slug)} + disabled={!allowed} > configure adapter @@ -737,7 +745,7 @@ function AdapterPickerList({ {agent.availabilityWarning && selectedType === agent.adapterChoice && (

{agent.availabilityWarning}

)} - {isExpanded && ( + {isExpanded && allowed && (
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 | undefined { + if (hasUnavailableCloudHarness) throw new Error("Choose an available Cloud harness for each imported agent."); const overrides: Record = {}; 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() {