From 6e340a3f962c60e2723c780389db878ce7ff74c7 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Wed, 2 Dec 2026 16:47:58 -0800 Subject: [PATCH] Verify onboarding models and explain provider failures (#23563) Verify deployment-configured model preferences with the selected account. Preserve structured provider failures and show descriptive messages for known causes through the existing onboarding error display. Keep the existing failure buttons, account binding, and retry/sign-in behavior. Validation: UI typecheck, 38 focused tests, four browser journeys, all applicable CI checks, and Greptile 5/5 with no unresolved review comments. Co-Authored-By: Paperclip --- doc/onboarding-chat.md | 23 ++++ .../src/live/runnerd-codex-transport.test.ts | 29 +++++ .../src/live/runnerd-codex-transport.ts | 5 +- server/src/__tests__/health.test.ts | 8 ++ server/src/routes/health.ts | 4 + .../native-runtime/plugin-runner-probe.ts | 3 +- .../setup-probe-failure.test.ts | 18 +++ .../native-runtime/setup-probe-failure.ts | 22 ++++ .../native-runtime/setup-readiness.test.ts | 19 +++ .../native-runtime/setup-readiness.ts | 10 +- server/src/services/onboarding-models.test.ts | 16 +++ server/src/services/onboarding-models.ts | 14 +++ .../onboarding-subscription-models.spec.ts | 112 ++++++++++++++++++ ui/src/api/health.ts | 1 + ui/src/components/OnboardingWizard.tsx | 42 ++++--- ui/src/lib/onboarding-model-selection.test.ts | 62 ++++++++++ ui/src/lib/onboarding-model-selection.ts | 26 ++++ 17 files changed, 394 insertions(+), 20 deletions(-) create mode 100644 server/src/services/native-runtime/setup-probe-failure.test.ts create mode 100644 server/src/services/native-runtime/setup-probe-failure.ts create mode 100644 server/src/services/onboarding-models.test.ts create mode 100644 server/src/services/onboarding-models.ts create mode 100644 tests/e2e/onboarding-subscription-models.spec.ts create mode 100644 ui/src/lib/onboarding-model-selection.test.ts create mode 100644 ui/src/lib/onboarding-model-selection.ts diff --git a/doc/onboarding-chat.md b/doc/onboarding-chat.md index deaf5e791b7..0b6a74bb03b 100644 --- a/doc/onboarding-chat.md +++ b/doc/onboarding-chat.md @@ -30,3 +30,26 @@ Pasting a Claude authorization code submits it automatically and shows a finishi state; a rejected code offers a fresh sign-in immediately. Switching providers clears the previous provider's model so subscription verification uses a compatible model. + + +Automatic subscription setup uses `PAPERCLIP_ONBOARDING_MODELS`, when configured, +as a JSON object mapping harness IDs to up to three ordered model IDs. Core has +no deployment-specific preference list. Without the variable, the adapter's +normal default remains in use. The authenticated health response exposes valid +preferences as `onboardingModels`. + +For a new Claude or Codex subscription agent, onboarding verifies each preferred +model against the chosen saved account and environment. Only a structured model +refusal permits the next preference. Authentication, quota, permission, runtime +and cleanup failures stop the attempt. The existing shared connection deadline +bounds the complete operation; changing subscriptions or providers discards late +results. A passing model is saved in the configuration used to finish setup. +API/gateway selections and existing configured agents retain their explicit +model. The check consumes a small amount of the connected account's allowance. + +Failed setup keeps the existing error display, buttons and retry/sign-in flow. +When the provider reports a known cause, that display explains it: missing model +access, a failed sign-in, insufficient permission, exhausted usage, rate limiting, +a provider outage or a timeout. Unknown failures keep a generic error message. +No account chooser, connection-removal control or additional recovery action is +introduced during onboarding. diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts index 935e6bb3e0c..ad9fe13d2c3 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -4306,6 +4306,35 @@ it("recovers provider readiness from an already-committed journal without replay ).toEqual(persistedReady); }); +it("preserves a model refusal through the native hello turn and confirms cleanup", async () => { + const root = await mkdtemp(join(tmpdir(), "runnerd-model-access-probe-")); + const command = join(root, "provider.cjs"); + const cleanup = vi.fn(async () => {}); + await writeFile(command, ` + const { spawn } = require('node:child_process'); + const child = spawn(${JSON.stringify(fakeCodex)}, ${JSON.stringify(fakeCodexArgs(root, "--fail-turn-immediately"))}, { stdio: ['pipe', 'pipe', 'pipe'] }); + process.stdin.pipe(child.stdin); + child.stderr.pipe(process.stderr); + require('node:readline').createInterface({ input: child.stdout }).on('line', line => { + const event = JSON.parse(line); + if (event.params?.turn?.status === 'failed') event.params.turn.error = { + message: JSON.stringify({ error: { code: 'model_not_found', message: 'Fixture model is unavailable to this account' } }) + }; + process.stdout.write(JSON.stringify(event) + String.fromCharCode(10)); + }); + process.on('SIGTERM', () => child.kill('SIGTERM')); + child.on('exit', code => process.exit(code ?? 1)); + `); + try { + await expect(probeNativeRunnerEnvironment({ runtimeDirectory: root, provider: "codex", model: "gpt-test", + environment: { PATH: process.env.PATH, OPENAI_API_KEY: "inert-probe-key" }, timeoutMs: 10_000, + transportOptions: { runnerBinary: defaultCapabilityRunnerdBinary(), codexCommand: process.execPath, + codexArgs: [command], sourceCodexHome: "" }, onCleanupConfirmed: cleanup, + })).rejects.toMatchObject({ providerFailure: { category: "model_unavailable", providerCode: "model_not_found" } }); + expect(cleanup).toHaveBeenCalledOnce(); + } finally { await rm(root, { recursive: true, force: true }); } +}); + it("keeps the Copilot authentication launch requirements free of Codex search policy", async () => { const root = await mkdtemp(join(tmpdir(), "runnerd-copilot-probe-policy-")); let captured: RunnerProviderLaunchRequirements | undefined; diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 1ea69a75db6..10a58db55c1 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -9822,7 +9822,10 @@ export async function probeNativeRunnerEnvironment(options: { } if (event.eventType === "turn.failed" || event.eventType === "turn.interrupted" || event.eventType === "turn.cancelled") { const detail = record(event.payload.error).message; - throw new Error(typeof detail === "string" ? detail : "The native provider hello probe failed."); + const providerFailure = readProviderFailure(record(event.payload.error).providerFailure) + ?? readProviderFailure(event.payload.providerFailure); + throw Object.assign(new Error(typeof detail === "string" ? detail : "The native provider hello probe failed."), + providerFailure ? { providerFailure } : {}); } } throw new Error("The native provider hello probe ended without a successful turn."); diff --git a/server/src/__tests__/health.test.ts b/server/src/__tests__/health.test.ts index 5874e180c20..9af9bff006c 100644 --- a/server/src/__tests__/health.test.ts +++ b/server/src/__tests__/health.test.ts @@ -63,6 +63,14 @@ function createApp( } describe("GET /health", () => { + it("exposes only valid deployment model preferences to the onboarding client", async () => { + const app = createApp(undefined, testServerInfo, undefined, { + PAPERCLIP_ONBOARDING_MODELS: '{"example_local":["preferred","compatible"]}', + }); + const res = await request(app).get("/health"); + expect(res.body.onboardingModels).toEqual({ example_local: ["preferred", "compatible"] }); + }); + beforeEach(() => { vi.clearAllMocks(); mockReadPersistedDevServerStatus.mockReturnValue(undefined); diff --git a/server/src/routes/health.ts b/server/src/routes/health.ts index 6d1880ba5cd..d088514bd0c 100644 --- a/server/src/routes/health.ts +++ b/server/src/routes/health.ts @@ -1,6 +1,7 @@ import { supportsHostedGoogleAiLogin, supportsLocalAiLogin } from "../services/local-ai-login-policy.js"; import { randomUUID, timingSafeEqual } from "node:crypto"; import { Router } from "express"; +import { onboardingModels } from "../services/onboarding-models.js"; import type { Db } from "@paperclipai/db"; import { and, count, eq, gt, inArray, isNull, sql } from "drizzle-orm"; import { heartbeatRuns, instanceUserRoles, invites } from "@paperclipai/db"; @@ -244,6 +245,7 @@ export function healthRoutes( const healthStatus = startupRecovery.phase === "ready" ? "ok" : "starting"; const cloud = getCloudHealthStatus(runtimeEnv); + const preferredOnboardingModels = onboardingModels(runtimeEnv); // Operator-hidden settings ride every response (like `cloud`): the list // holds UI surface names only, and the settings nav needs it before any // fuller-detail fetch. Omitted entirely when nothing is hidden, so @@ -283,6 +285,7 @@ export function healthRoutes( serverVersion: serverVersion, commit, serverInfo, + ...(Object.keys(preferredOnboardingModels).length ? { onboardingModels: preferredOnboardingModels } : {}), ...(cloud ? { cloud } : {}), ...(hiddenSettings.length ? { hiddenSettings } : {}), } @@ -434,6 +437,7 @@ export function healthRoutes( res.json({ status: healthStatus, version: serverVersion, + ...(Object.keys(preferredOnboardingModels).length ? { onboardingModels: preferredOnboardingModels } : {}), serverVersion, commit, deploymentMode: opts.deploymentMode, diff --git a/server/src/services/native-runtime/plugin-runner-probe.ts b/server/src/services/native-runtime/plugin-runner-probe.ts index 3a37f7fa9a8..045d9dfcb46 100644 --- a/server/src/services/native-runtime/plugin-runner-probe.ts +++ b/server/src/services/native-runtime/plugin-runner-probe.ts @@ -14,6 +14,7 @@ import { resolveAcpxQualification } from "./acpx-qualification.js"; import { antigravityConnectionRefusal } from "./antigravity-connection-policy.js"; import { antigravityReleasePending } from "./antigravity-release.js"; import { isRunnerRevisionMismatch, runnerRevisionMismatchTestResult } from "../runner-revision-mismatch.js"; +import { setupProbeFailure } from "./setup-probe-failure.js"; /** Core verifies a real Runner; providers only implement their task API. */ export async function probePluginRunnerEnvironment(context: AdapterEnvironmentTestContext, @@ -101,7 +102,7 @@ export async function probePluginRunnerEnvironment(context: AdapterEnvironmentTe if (isRunnerRevisionMismatch(error)) return runnerRevisionMismatchTestResult("paperclip_runner", testedAt); // Provider failures may contain credentials or private addressing. return { adapterType: "paperclip_runner", status: "fail", testedAt, - checks: [{ code: "runner_hello_probe_failed", level: "error", message: "The selected plugin environment did not complete the Runner hello probe and confirmed cleanup. Check its runtime, account, and model access." }] }; + checks: [setupProbeFailure(error)] }; } finally { if (!probeStarted || cleanupConfirmed) rmSync(root, { recursive: true, force: true }); } diff --git a/server/src/services/native-runtime/setup-probe-failure.test.ts b/server/src/services/native-runtime/setup-probe-failure.test.ts new file mode 100644 index 00000000000..24ccac8db0c --- /dev/null +++ b/server/src/services/native-runtime/setup-probe-failure.test.ts @@ -0,0 +1,18 @@ +import { expect, it } from "vitest"; +import { setupProbeFailure } from "./setup-probe-failure.js"; + +it.each(["model_unavailable", "authentication", "permission", "quota_exhausted", "rate_limit", "overloaded", "timeout"])( + "preserves the actionable %s category without exposing provider diagnostics", category => { + const failure = { schema: "paperclip.provider-failure.v1", provider: "anthropic", phase: "turn", category, + retryability: "requires_action", message: "private account at https://internal.example credential=fixture-secret" }; + const error = Object.assign(new Error(failure.message), { providerFailure: failure }); + const check = setupProbeFailure(new Error("wrapped", { cause: error })); + expect(check).toMatchObject({ code: `runner_hello_probe_${category === "authentication" ? "auth_required" : category}`, level: "error" }); + expect(JSON.stringify(check)).not.toMatch(/internal\.example|fixture-secret|private account/); + expect(check.message).not.toMatch(/another subscription|change provider|reconnect|saved credentials/i); + }, +); +it("does not infer plan restrictions from arbitrary errors", () => { + expect(setupProbeFailure(new Error("model_not_found https://private.example"))) + .toMatchObject({ code: "runner_hello_probe_failed" }); +}); diff --git a/server/src/services/native-runtime/setup-probe-failure.ts b/server/src/services/native-runtime/setup-probe-failure.ts new file mode 100644 index 00000000000..cc10dc7fc53 --- /dev/null +++ b/server/src/services/native-runtime/setup-probe-failure.ts @@ -0,0 +1,22 @@ +import { providerFailureFromError } from "../../vendor/paperclip-runner/index.js"; +import type { AdapterEnvironmentCheck } from "@paperclipai/adapter-utils"; + +export function setupProbeFailure(error: unknown): AdapterEnvironmentCheck { + const failure = providerFailureFromError(error); + const messages = { + model_unavailable: "Your account does not have access to the selected model.", + authentication: "Your sign-in could not be verified. Please sign in again.", + permission: "Your account does not have permission to make this request.", + quota_exhausted: "Your account has no usage remaining. Check your plan's limits or available credits.", + rate_limit: "Your account is temporarily rate limited. Please wait before trying again.", + overloaded: "The provider is temporarily unavailable. Please try again shortly.", + timeout: "The provider did not respond in time. Please try again.", + }; + if (failure && failure.category in messages) { + const category = failure.category as keyof typeof messages; + return { code: `runner_hello_probe_${category === "authentication" ? "auth_required" : category}`, + level: "error", message: messages[category] }; + } + return { code: "runner_hello_probe_failed", level: "error", + message: "Paperclip could not verify your account. Please try again." }; +} diff --git a/server/src/services/native-runtime/setup-readiness.test.ts b/server/src/services/native-runtime/setup-readiness.test.ts index 5c807027d7e..b747d6ba975 100644 --- a/server/src/services/native-runtime/setup-readiness.test.ts +++ b/server/src/services/native-runtime/setup-readiness.test.ts @@ -457,6 +457,25 @@ describe("Codex selected native account verification", () => { expect(nativeProbe).toHaveBeenCalledOnce(); expect(execute).not.toHaveBeenCalled(); }); + it.each(["local", "ssh"].flatMap(transport => + ["model_unavailable", "authentication", "permission", "quota_exhausted"].map(category => [transport, category]), + ))("preserves structured %s probe failures for subscription recovery (%s)", async (transport, category) => { + const providerFailure = { schema: "paperclip.provider-failure.v1", provider: "codex", phase: "turn", category, + retryability: "requires_action", message: "private provider diagnostic bound-account" }; + nativeProbe.mockImplementation(async input => { + await input.onCleanupConfirmed(); + throw new Error("native probe failed", { cause: Object.assign(new Error(providerFailure.message), { providerFailure }) }); + }); + const selectedContext = transport === "ssh" ? sshContext : { companyId: "company", adapterType: "paperclip_runner", config: {} }; + const result = await testNativeRunnerAuthentication({ ...selectedContext, config: { env: { OPENAI_API_KEY: "bound-account" } } }, "codex", "gpt-6.1-sol"); + expect(result.status).toBe("fail"); + expect(result.checks[0]).toMatchObject({ code: `runner_hello_probe_${category === "authentication" ? "auth_required" : category}`, level: "error" }); + expect(result.checks.some(check => check.code === ADAPTER_AUTH_MISSING_CHECK_CODE)).toBe(category === "authentication"); + expect(JSON.stringify(result)).not.toMatch(/private provider diagnostic|bound-account/); + expect(nativeProbe).toHaveBeenCalledOnce(); + expect(transport === "ssh" ? selectedRemoteRunner : selectedRunner).toHaveBeenCalledOnce(); + await expect(stat(nativeProbeRuntimeDirectories[0]!)).rejects.toMatchObject({ code: "ENOENT" }); + }); it("names the ChatGPT retirement when the backend rejects a retired model", async () => { nativeProbe.mockRejectedValue(new Error(JSON.stringify({ type: "error", status: 400, error: { type: "invalid_request_error", message: "The 'gpt-5.5' model is not supported when using Codex with a ChatGPT account." } }))); diff --git a/server/src/services/native-runtime/setup-readiness.ts b/server/src/services/native-runtime/setup-readiness.ts index 285045c55a6..e9b6c51c489 100644 --- a/server/src/services/native-runtime/setup-readiness.ts +++ b/server/src/services/native-runtime/setup-readiness.ts @@ -13,6 +13,7 @@ import { readRemoteUserHome } from "./remote-user-home.js"; import { createNativeSshCommandRunner } from "./native-ssh-command-runner.js"; import { resolvePaperclipRunnerTransport } from "@paperclipai/adapter-utils/runner-connectivity"; import { createNativeRunnerExecutionDriver } from "./native-runner-execution-driver.js"; +import { setupProbeFailure } from "./setup-probe-failure.js"; const PROBE_TRANSPORT_ENV_KEYS = ["PATH", "LANG", "LANGUAGE", "TZ", "TMPDIR", "TEMP", "TMP", "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "no_proxy", "all_proxy"]; @@ -264,11 +265,14 @@ export async function testNativeRunnerAuthentication(context: AdapterEnvironment message: `The native ${provider} runtime verified the selected account and model in ${remote ? "the selected environment" : "the Paperclip host"}.` }] }; } catch (error) { if (error instanceof NativeEnvironmentProbeCleanupError) throw error; - const message = redactNativeProbeMessage(error instanceof Error ? error.message : "The selected native runtime could not verify this account.", { ...environment, ...(sourceAuthJson ? { [authKey]: sourceAuthJson } : {}) }); - const authentication = /(?:invalid (?:api[- ]?key|auth(?:entication)? token)|authentication (?:failed|required)|unauthenticated|unauthorized|not authenticated|please (?:log|sign) in|not logged in|\b(?:401|403)\b)/i.test(message); + const failure = setupProbeFailure(error); + const classified = failure.code !== "runner_hello_probe_failed"; + const message = classified ? failure.message : redactNativeProbeMessage(error instanceof Error ? error.message : "The selected native runtime could not verify this account.", { ...environment, ...(sourceAuthJson ? { [authKey]: sourceAuthJson } : {}) }); + const authentication = classified ? failure.code === "runner_hello_probe_auth_required" + : /(?:invalid (?:api[- ]?key|auth(?:entication)? token)|authentication (?:failed|required)|unauthenticated|unauthorized|not authenticated|please (?:log|sign) in|not logged in|\b(?:401|403)\b)/i.test(message); const rejectedModel = provider === "codex" ? CODEX_CHATGPT_MODEL_REJECTION_RE.exec(message)?.[1] : undefined; const retirementHint = rejectedModel ? codexChatGptRetirementHint(rejectedModel) : null; - return { adapterType: "paperclip_runner", status: "fail", testedAt: new Date().toISOString(), checks: [{ code: `${provider}_hello_probe_${authentication ? "auth_required" : /timed out/i.test(message) ? "timeout" : "failed"}`, level: "error", message, + return { adapterType: "paperclip_runner", status: "fail", testedAt: new Date().toISOString(), checks: [classified ? failure : { code: `${provider}_hello_probe_${authentication ? "auth_required" : /timed out/i.test(message) ? "timeout" : "failed"}`, level: "error", message, hint: retirementHint ?? "Check the selected account, model access, and native runtime prerequisites, then retry." }, ...(authentication && provider === "codex" ? [{ code: ADAPTER_AUTH_MISSING_CHECK_CODE, level: "error" as const, message: "The selected Codex account needs authentication.", diff --git a/server/src/services/onboarding-models.test.ts b/server/src/services/onboarding-models.test.ts new file mode 100644 index 00000000000..f940376d65f --- /dev/null +++ b/server/src/services/onboarding-models.test.ts @@ -0,0 +1,16 @@ +import { expect, it } from "vitest"; +import { onboardingModels } from "./onboarding-models.js"; + +it("leaves deployments without preferences on their normal adapter defaults", () => { + expect(onboardingModels({})).toEqual({}); +}); +it("reads fresh deployment preferences without provider or plan policy in Core", () => { + const env = { PAPERCLIP_ONBOARDING_MODELS: '{"example_local":["preferred","backup","preferred"]}' }; + expect(onboardingModels(env)).toEqual({ example_local: ["preferred", "backup"] }); + env.PAPERCLIP_ONBOARDING_MODELS = '{"example_local":["replacement"]}'; + expect(onboardingModels(env)).toEqual({ example_local: ["replacement"] }); +}); +it.each(["null", "[]", "invalid", '{"adapter":[]}', '{"adapter":[1]}', '{"adapter":["https://private.example"]}', + '{"adapter":["one","two","three","four"]}', " ".repeat(8193)])("rejects malformed or unbounded preferences %#", raw => { + expect(onboardingModels({ PAPERCLIP_ONBOARDING_MODELS: raw })).toEqual({}); +}); diff --git a/server/src/services/onboarding-models.ts b/server/src/services/onboarding-models.ts new file mode 100644 index 00000000000..95d916b4d86 --- /dev/null +++ b/server/src/services/onboarding-models.ts @@ -0,0 +1,14 @@ +export function onboardingModels(env: Record): Record { + const raw = env.PAPERCLIP_ONBOARDING_MODELS; + if (!raw || raw.length > 8_192) return {}; + try { + const value: unknown = JSON.parse(raw); + if (!value || typeof value !== "object" || Array.isArray(value)) return {}; + const entries = Object.entries(value); + if (entries.length > 16 || entries.some(([harness, models]) => + !/^[a-z][a-z0-9_]{0,63}$/.test(harness) || !Array.isArray(models) || !models.length || models.length > 3 + || models.some(model => typeof model !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._/\[\]-]{0,159}$/.test(model)), + )) return {}; + return Object.fromEntries(entries.map(([harness, models]) => [harness, [...new Set(models as string[])]])); + } catch { return {}; } +} diff --git a/tests/e2e/onboarding-subscription-models.spec.ts b/tests/e2e/onboarding-subscription-models.spec.ts new file mode 100644 index 00000000000..61f6c08d56f --- /dev/null +++ b/tests/e2e/onboarding-subscription-models.spec.ts @@ -0,0 +1,112 @@ +import { randomUUID } from "node:crypto"; +import { expect, test, type Page } from "@playwright/test"; + +type Outcome = "pass" | "fallback" | "quota_exhausted" | "auth_required" | "unknown"; +const genericError = "The environment test failed. Fix the reported checks before you hire this agent."; +const messages = { + quota_exhausted: "Your account has no usage remaining. Check your plan's limits or available credits.", + auth_required: "Your sign-in could not be verified. Please sign in again.", + model_unavailable: "Your account does not have access to the selected model.", + unknown: "", +}; + +async function setup(page: Page, provider: "Claude" | "OpenAI", initialOutcome: Outcome) { + const response = await page.request.post("/api/companies", { data: { name: `Model verification ${randomUUID()}` } }); + expect(response.ok()).toBe(true); + const company = await response.json(); + const accounts = ["anthropic", "openai"].map(provider => ({ + id: randomUUID(), grantId: randomUUID(), companyId: company.id, provider, + method: "subscription", name: "Personal account", ownership: "personal", ownerUserId: "local-board", status: "connected", isDefault: true, + })); + const candidates = { claude_local: ["claude-opus-5-5", "claude-sonnet-5-5"], codex_local: ["gpt-6.1-sol", "gpt-6-luna"] }; + const probes: Array<{ provider: string; model: string }> = []; + const hires: Array> = []; + const newSignIns: unknown[] = [], removals: string[] = []; + let agent: Record | undefined; + let outcome = initialOutcome; + await page.addInitScript(({ company }) => localStorage.setItem("paperclip-onboarding-state", JSON.stringify({ + step: 3, companyName: company.name, createdCompanyId: company.id, createdCompanyPrefix: company.issuePrefix, + agentName: "Recovery lead", agentRole: "general", + })), { company }); + await page.route("**/api/health", async route => { + const response = await route.fetch(); + await route.fulfill({ response, json: { ...await response.json(), onboardingModels: candidates } }); + }); + await page.route("**/api/adapters**", async route => { + const response = await route.fetch(); + const rows = await response.json(); + await route.fulfill({ response, json: rows.map((row: any) => ({ ...row, defaultRunner: "legacy", supportedRunners: ["legacy"] })) }); + }); + await page.route(`**/companies/${company.id}/ai-connections`, route => route.fulfill({ json: { + currentUserId: "local-board", canManageConnections: true, connections: accounts, + } })); + await page.route(`**/companies/${company.id}/ai-connections/default`, route => route.fulfill({ json: { ok: true } })); + await page.route("**/ai-connections/local/attempts", route => { + newSignIns.push(route.request().postDataJSON()); + return route.fulfill({ json: { sessionId: "unexpected-login", expiresAt: "2099-01-01T00:00:00Z" } }); + }); + await page.route("**/tool-connections/*", route => { + if (route.request().method() !== "DELETE") return route.continue(); + removals.push(route.request().url()); + return route.fulfill({ json: { removal: { providerAccess: "revoked" } } }); + }); + await page.route("**/api/agents/*", async route => { + if (!agent || !route.request().url().includes(agent.id)) return route.continue(); + if (route.request().method() === "PATCH") agent = { ...agent, ...route.request().postDataJSON() }; + await route.fulfill({ json: agent }); + }); + await page.route(`**/companies/${company.id}/agent-hires`, async route => { + hires.push(route.request().postDataJSON()); + await route.fulfill({ json: { agent: { ...agent, ...hires.at(-1), status: "idle" }, approval: null } }); + }); + await page.route("**/adapters/*/test-environment", async route => { + const request = route.request().postDataJSON(); + const adapter = route.request().url().includes("claude_local") ? "claude_local" : "codex_local"; + const model = request.adapterConfig.model; + probes.push({ provider: adapter, model }); + const reason = outcome === "fallback" ? model === candidates[adapter][0] ? "model_unavailable" : null + : outcome === "pass" ? null : outcome; + await route.fulfill({ json: { adapterType: "paperclip_runner", testedAt: "2099-01-01", status: reason ? "fail" : "pass", + checks: [{ code: reason ? `runner_hello_probe_${reason === "unknown" ? "failed" : reason}` : "runner_hello_probe_passed", + level: reason ? "error" : "info", message: reason ? messages[reason] : "Verified" }] } }); + }); + const created = page.waitForResponse(response => response.request().method() === "POST" + && response.url().endsWith(`/companies/${company.id}/agents`)); + await page.goto("/onboarding"); + await page.locator("#onboarding-agent-name").fill("Recovery lead"); + await page.getByRole("button", { name: "Next", exact: true }).click(); + agent = await (await created).json(); + await page.getByRole("radio", { name: new RegExp(provider) }).click(); + return { candidates, probes, hires, newSignIns, removals, setOutcome: (value: Outcome) => { outcome = value; } }; +} + +test("onboarding saves the model that passes the selected account's check", async ({ page }) => { + const fixture = await setup(page, "Claude", "fallback"); + await expect.poll(() => fixture.hires.length).toBe(1); + expect(fixture.probes).toEqual(fixture.candidates.claude_local.map(model => ({ provider: "claude_local", model }))); + expect(fixture.hires[0]).toMatchObject({ name: "Recovery lead", adapterConfig: { model: "claude-sonnet-5-5" } }); +}); + +for (const scenario of [ + { provider: "Claude", reason: "quota_exhausted", message: messages.quota_exhausted }, + { provider: "OpenAI", reason: "auth_required", message: messages.auth_required }, + { provider: "Claude", reason: "unknown", message: genericError }, +] as const) { + test(`${scenario.provider} ${scenario.reason} keeps existing failure controls and displays the available error`, async ({ page }) => { + const fixture = await setup(page, scenario.provider, scenario.reason); + await expect(page.getByText(scenario.message, { exact: true }).first()).toBeVisible(); + if (scenario.reason !== "unknown") await expect(page.getByText(genericError, { exact: true })).toHaveCount(0); + expect(fixture.probes).toHaveLength(1); + expect(fixture.hires).toHaveLength(0); + await expect(page.getByRole("button", { name: "Back", exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Connect", exact: true })).toBeEnabled(); + await expect(page.getByRole("button", { name: /Use another subscription|Remove this connection|Sign in to another account|Change provider/ })).toHaveCount(0); + fixture.setOutcome("pass"); + await page.getByRole("button", { name: "Connect", exact: true }).click(); + await expect.poll(() => fixture.hires.length).toBe(1); + expect(fixture.probes).toHaveLength(2); + expect(fixture.hires[0]).toMatchObject({ name: "Recovery lead" }); + expect(fixture.newSignIns).toHaveLength(0); + expect(fixture.removals).toHaveLength(0); + }); +} diff --git a/ui/src/api/health.ts b/ui/src/api/health.ts index 0863ca31204..5d1f63e48c0 100644 --- a/ui/src/api/health.ts +++ b/ui/src/api/health.ts @@ -30,6 +30,7 @@ export type CloudInstanceHealthStatus = { export type HealthStatus = { status: "ok" | "starting"; + onboardingModels?: Record; version?: string; /** Commit of the running server; null when build metadata is unavailable. */ commit?: string | null; diff --git a/ui/src/components/OnboardingWizard.tsx b/ui/src/components/OnboardingWizard.tsx index bdb0556ad28..221d1d505ed 100644 --- a/ui/src/components/OnboardingWizard.tsx +++ b/ui/src/components/OnboardingWizard.tsx @@ -1,5 +1,6 @@ import { ModelSourceMark } from "./onboarding/ModelSourceMark"; import { OnboardingSignInMark, OnboardingSignInRetry } from "./AdapterLoginChrome"; +import { selectOnboardingModel } from "../lib/onboarding-model-selection"; import type { AiConnectionLoginIntent } from "@paperclipai/shared"; import { cancelAdapterLoginSession, cancelPendingAdapterLogin, matchesAdapterLoginTarget } from "./useAdapterLoginCancellation"; import { useQueryView } from "@/components/QueryView"; @@ -2609,6 +2610,7 @@ function OnboardingWizardInner({ isCurrent = () => true, onQualifiedConfig?: (config: Record, adapters: AdapterInfo[], environmentId: string | null) => void, existingAgent?: Agent, + onTestedConfig?: (config: Record) => void, ): Promise { if (!runnerDiscoveryReady) return null; if (!createdCompanyId) { @@ -2734,18 +2736,28 @@ function OnboardingWizardInner({ }; onQualifiedConfig?.(testedConfig, qualified.adapters, environmentId); } - const result = await agentsApi.testEnvironment( - createdCompanyId, - adapterType, - { - adapterConfig: testedConfig, - ...(savedAgent?.companyId === createdCompanyId ? { agentId: savedAgent.id } : {}), - ...(["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && testRunner !== "auto" ? { runner: testRunner } : {}), - ...(managedBindingForStep() ? { aiConnection: managedBindingForStep() } : {}), - environmentId, + const automaticSubscription = credentialMode === "subscription" + && ["claude_local", "codex_local"].includes(adapterType); + const tested = await selectOnboardingModel({ + explicitModel: automaticSubscription && !createdAgentId ? undefined + : typeof testedConfig.model === "string" ? testedConfig.model : undefined, + candidates: automaticSubscription ? localLoginHealth.data?.onboardingModels?.[adapterType] : undefined, + signal, isCurrent: testIsCurrent, + probe: async selectedModel => { + const config = selectedModel ? { ...testedConfig, model: selectedModel } : testedConfig; + const result = await agentsApi.testEnvironment(createdCompanyId, adapterType, { + adapterConfig: config, + ...(savedAgent?.companyId === createdCompanyId ? { agentId: savedAgent.id } : {}), + ...(["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && testRunner !== "auto" ? { runner: testRunner } : {}), + ...(managedBindingForStep() ? { aiConnection: managedBindingForStep() } : {}), environmentId, + }, { signal }); + return result; }, - { signal }, - ); + }); + if (!tested || !testIsCurrent()) return null; + const result = tested.result; + if (tested.model) testedConfig = { ...testedConfig, model: tested.model }; + if (!blocksAgentCreate(result)) onTestedConfig?.(testedConfig); if (!testIsCurrent()) return null; if (blocksAgentCreate(result)) { captureOnboardingStepFailed({ @@ -2965,7 +2977,7 @@ function OnboardingWizardInner({ // stored login, would lock out a customer who has since fixed the // problem or signed in. const cachedUsable = - !needsClaudeSetupQualification({ adapterType, runner, savedAgentId: createdAgentId, environment: resolvedLoginEnvironment }) && adapterEnvResult && + credentialMode !== "subscription" && !needsClaudeSetupQualification({ adapterType, runner, savedAgentId: createdAgentId, environment: resolvedLoginEnvironment }) && adapterEnvResult && adapterEnvResultAppliedStoredLoginRef.current === shouldApplyStoredClaudeLogin && !blocksAgentCreate(adapterEnvResult) ? adapterEnvResult @@ -2973,16 +2985,16 @@ function OnboardingWizardInner({ const result = cachedUsable ?? (await runAdapterEnvironmentTest(hireAdapterConfig, shouldApplyStoredClaudeLogin, isCurrent, - (config, adapters, environmentId) => { hireAdapterConfig = config; qualifiedDiscovery = { adapters, environmentId }; }, existingAgent)); + (config, adapters, environmentId) => { hireAdapterConfig = config; qualifiedDiscovery = { adapters, environmentId }; }, existingAgent, config => { hireAdapterConfig = config; })); if (!result || !isCurrent()) return; // Block the hire on a failed environment test. Also block it on a // pass or a warn result that reports missing authentication — the // agent cannot run without one of those. if (blocksAgentCreate(result)) { - const nativeCodexError = adapterType === "codex_local" && result.adapterType === "paperclip_runner" + const nativeConnectionError = ["codex_local", "claude_local"].includes(adapterType) && result.adapterType === "paperclip_runner" ? result.checks.find(check => check.level === "error")?.message : undefined; setError( - nativeCodexError || (result.status === "fail" + nativeConnectionError || (result.status === "fail" ? cloudInstance ? "Paperclip couldn't finish connecting this agent. Try connecting again." : "The environment test failed. Fix the reported checks before you hire this agent." diff --git a/ui/src/lib/onboarding-model-selection.test.ts b/ui/src/lib/onboarding-model-selection.test.ts new file mode 100644 index 00000000000..d44d97bdd4c --- /dev/null +++ b/ui/src/lib/onboarding-model-selection.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it, vi } from "vitest"; +import type { AdapterEnvironmentTestResult } from "@paperclipai/shared"; +import { selectOnboardingModel } from "./onboarding-model-selection"; + +const pass: AdapterEnvironmentTestResult = { adapterType: "paperclip_runner", status: "pass", testedAt: "2099-01-01", + checks: [{ code: "runner_hello_probe_passed", level: "info", message: "Verified" }] }; +const failed = (reason: string): AdapterEnvironmentTestResult => ({ ...pass, status: "fail", + checks: [{ code: `runner_hello_probe_${reason}`, level: "error", message: "Refused" }] }); +const input = () => ({ candidates: ["preferred", "compatible"], signal: new AbortController().signal, isCurrent: () => true }); + +describe("automatic onboarding model selection", () => { + it("verifies the preferred model using the chosen account and stops after success", async () => { + const probe = vi.fn().mockResolvedValue(pass); + await expect(selectOnboardingModel({ ...input(), probe })).resolves.toEqual({ model: "preferred", result: pass }); + expect(probe.mock.calls).toEqual([["preferred"]]); + }); + it("uses the next deployment preference only after an explicit model refusal", async () => { + const probe = vi.fn().mockResolvedValueOnce(failed("model_unavailable")).mockResolvedValueOnce(pass); + await expect(selectOnboardingModel({ ...input(), probe })).resolves.toEqual({ model: "compatible", result: pass }); + expect(probe.mock.calls).toEqual([["preferred"], ["compatible"]]); + }); + it.each(["quota_exhausted", "rate_limit", "auth_required", "permission", "failed", "timeout"])("does not try more models for %s", async reason => { + const result = failed(reason); + const probe = vi.fn().mockResolvedValue(result); + await expect(selectOnboardingModel({ ...input(), probe })).resolves.toEqual({ model: "preferred", result }); + expect(probe).toHaveBeenCalledOnce(); + }); + it("does not hide a runtime error accompanying a model refusal", async () => { + const result = failed("model_unavailable"); + result.checks.push({ code: "cleanup_unconfirmed", level: "error", message: "Cleanup pending" }); + const probe = vi.fn().mockResolvedValue(result); + await selectOnboardingModel({ ...input(), probe }); + expect(probe).toHaveBeenCalledOnce(); + }); + it("preserves explicit saved models and the normal default when no policy is set", async () => { + const probe = vi.fn().mockResolvedValue(failed("model_unavailable")); + await selectOnboardingModel({ ...input(), explicitModel: "saved", probe }); + expect(probe.mock.calls).toEqual([["saved"]]); + probe.mockClear(); + await selectOnboardingModel({ ...input(), candidates: undefined, probe }); + expect(probe.mock.calls).toEqual([[""]]); + }); + it("bounds attempts and returns the final denial for subscription recovery", async () => { + const result = failed("model_unavailable"); + const probe = vi.fn().mockResolvedValue(result); + await expect(selectOnboardingModel({ ...input(), candidates: ["one", "two", "three", "four"], probe })) + .resolves.toEqual({ model: "three", result }); + expect(probe).toHaveBeenCalledTimes(3); + }); + it("discards late results when the subscription/provider changes", async () => { + let current = true; + const probe = vi.fn(async () => { current = false; return failed("model_unavailable"); }); + await expect(selectOnboardingModel({ ...input(), isCurrent: () => current, probe })).resolves.toBeNull(); + expect(probe).toHaveBeenCalledOnce(); + }); + it("does not start another model after the shared connection deadline", async () => { + const controller = new AbortController(); + const probe = vi.fn(async () => { controller.abort(); return failed("model_unavailable"); }); + await expect(selectOnboardingModel({ ...input(), signal: controller.signal, probe })).rejects.toThrow(); + expect(probe).toHaveBeenCalledOnce(); + }); +}); diff --git a/ui/src/lib/onboarding-model-selection.ts b/ui/src/lib/onboarding-model-selection.ts new file mode 100644 index 00000000000..96793fa6f90 --- /dev/null +++ b/ui/src/lib/onboarding-model-selection.ts @@ -0,0 +1,26 @@ +import type { AdapterEnvironmentTestResult } from "@paperclipai/shared"; + +export async function selectOnboardingModel(input: { + explicitModel?: string; + candidates?: string[]; + signal: AbortSignal; + isCurrent: () => boolean; + probe: (model: string) => Promise; +}): Promise<{ model: string; result: AdapterEnvironmentTestResult } | null> { + const explicit = input.explicitModel?.trim(); + const candidates = explicit ? [explicit] : [...new Set(input.candidates?.slice(0, 3) ?? [])]; + if (!candidates.length) candidates.push(""); + for (let index = 0; index < candidates.length; index++) { + input.signal.throwIfAborted(); + if (!input.isCurrent()) return null; + const model = candidates[index]!; + const result = await input.probe(model); + input.signal.throwIfAborted(); + if (!input.isCurrent()) return null; + const errors = result.checks.filter(check => check.level === "error"); + const modelRefused = result.status === "fail" && errors.length > 0 + && errors.every(check => /_hello_probe_model_unavailable$/.test(check.code)); + if (!modelRefused || index === candidates.length - 1) return { model, result }; + } + return null; +}