From 3bb36afcd9067b8b2db6509a7d92b1ef9412d1ed Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 6 Oct 2026 09:51:13 -0500 Subject: [PATCH] fix(connections): wire provider catalog setup and no-auth execution Keep the credential form and compatible personal-account picker with their catalog definitions. Add no-auth runtime preparation and abort-aware Claude code input. Move independent Grok and Gemini live-workflow fixes to the qualification follow-up. Co-Authored-By: Paperclip --- .../src/acpx-engine/execute.test.ts | 62 +-- .../adapter-utils/src/acpx-engine/execute.ts | 44 +- packages/adapters/gemini-local/src/index.ts | 4 - packages/adapters/grok-local/src/index.ts | 1 - .../grok-local/src/server/execute.test.ts | 12 - .../adapters/grok-local/src/server/execute.ts | 13 +- .../grok-local/src/server/grok-home.test.ts | 25 +- .../grok-local/src/server/grok-home.ts | 27 +- patches/acpx@0.12.0.patch | 16 +- server/src/__tests__/ai-connections.test.ts | 44 +- .../__tests__/file-delivery-bridges.test.ts | 4 +- server/src/services/ai-connection-runtime.ts | 33 +- .../services/local-ai-browser-login.test.ts | 17 + server/src/services/local-ai-browser-login.ts | 7 +- .../AiConnectionCredentialStep.tsx | 20 +- .../ai-connections/AiConnectionField.test.tsx | 39 +- .../ai-connections/AiConnectionField.tsx | 40 +- .../ai-connections/AiConnectionSelect.tsx | 192 +++++++ .../ai-connections/AiProviderSetup.test.tsx | 99 ++++ .../ai-connections/AiProviderSetup.tsx | 468 ++++++++++++++++++ ui/src/components/ui/select.tsx | 11 +- .../connections/ConnectionChoiceList.tsx | 5 +- .../connections/ConnectionSetupFlow.tsx | 1 + ui/src/pages/apps/AppsConnect.tsx | 26 +- 24 files changed, 945 insertions(+), 265 deletions(-) create mode 100644 ui/src/components/ai-connections/AiConnectionSelect.tsx create mode 100644 ui/src/components/ai-connections/AiProviderSetup.test.tsx create mode 100644 ui/src/components/ai-connections/AiProviderSetup.tsx diff --git a/packages/adapter-utils/src/acpx-engine/execute.test.ts b/packages/adapter-utils/src/acpx-engine/execute.test.ts index c56df4f70fa..4296a110e79 100644 --- a/packages/adapter-utils/src/acpx-engine/execute.test.ts +++ b/packages/adapter-utils/src/acpx-engine/execute.test.ts @@ -52,7 +52,6 @@ import { const tempRoots: string[] = []; -let defaultGeminiTestHome: string | undefined; async function makeTempRoot() { const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-skills-")); @@ -61,7 +60,6 @@ async function makeTempRoot() { } afterEach(async () => { - defaultGeminiTestHome = undefined; // A remote run stages a process-session bridge whose detached event writer can // still be flushing a trailing event file into `.../process-sessions//events` // when the run's own best-effort `client.remove(sessionDir)` (which production @@ -180,13 +178,6 @@ async function runExecutor( startupTraceContext?: AdapterExecutionContext["startupTraceContext"]; } = {}, ) { - // Skill reconciliation must never inspect or modify the developer's real - // Gemini home. Keep one private home across this test's resumed turns. - const configuredEnv = config.env as Record | undefined; - if (config.agent === "gemini" && !(typeof configuredEnv?.HOME === "string" && configuredEnv.HOME.trim())) { - defaultGeminiTestHome ??= await makeTempRoot(); - config = { ...config, env: { ...configuredEnv, HOME: defaultGeminiTestHome } }; - } const runtimeOptions: Record[] = []; const configOptions: Array<{ key: string; value: string }> = []; const sessionInputs: Record[] = []; @@ -612,7 +603,7 @@ describe("shared ACPX engine runtime behavior", () => { }); }); - it("sets Claude and Gemini models at startup without unsupported picker calls", async () => { + it("keeps Claude startup model handling and Gemini session config handling unchanged", async () => { const claude = await runExecutor({ agent: "claude", model: "claude-opus-4-7" }); expect((claude.meta[0]?.env as Record).ANTHROPIC_MODEL).toBe( "claude-opus-4-7", @@ -623,10 +614,9 @@ describe("shared ACPX engine runtime behavior", () => { agent: "gemini", model: "gemini-2.5-pro", thinkingEffort: "high", - env: { GEMINI_MODEL: "stale-model" }, }); - expect((gemini.meta[0]?.env as Record).GEMINI_MODEL).toBe("gemini-2.5-pro"); expect(gemini.configOptions).toEqual([ + { key: "model", value: "gemini-2.5-pro" }, { key: "effort", value: "high" }, ]); }); @@ -1594,29 +1584,6 @@ describe("shared ACPX engine runtime behavior", () => { expect(await pathExists(path.join(codexHome, "skills", operational.runtimeName, "SKILL.md"))).toBe(true); }); - it.each(["codex", "gemini"])("refreshes the %s skill root when a connection home changes between turns", async (agent) => { - const root = await makeTempRoot(); - const operational = { - ...await createSkill(path.join(root, "skills"), "paperclip"), - key: "paperclipai/paperclip/paperclip", - }; - const homes = [path.join(root, "first-home"), path.join(root, "next-home")]; - for (const home of homes) { - const { meta } = await runExecutor({ - agent, - stateDir: path.join(root, "state"), - env: agent === "codex" ? { CODEX_HOME: home } : { HOME: home }, - paperclipRuntimeSkills: [operational], - paperclipSkillSync: { desiredSkills: [] }, - }); - const skillsHome = agent === "codex" ? path.join(home, "skills") : path.join(home, ".gemini", "skills"); - expect(String(meta[0]?.prompt ?? "")).toContain(`Skill root for this run: ${skillsHome}`); - expect(String(meta[0]?.prompt ?? "")).toContain("Resolve referenced scripts and files relative to that skill"); - if (home === homes[1]) expect(String(meta[0]?.prompt ?? "")).not.toContain(homes[0]!); - await fs.rm(home, { recursive: true, force: true }); - } - }); - it.skipIf(process.platform === "win32")("removes legacy ACPX Codex skill symlinks when a skill is no longer desired", async () => { const root = await makeTempRoot(); const skillRoot = path.join(root, "skills"); @@ -2903,21 +2870,6 @@ describe("findAncestorBin", () => { }); describe("gemini ACP flag selection", () => { - it("uses the canonical local Gemini workspace for ACP filesystem requests", async () => { - const root = await makeTempRoot(); - const workspace = path.join(root, "workspace"); - const alias = path.join(root, "workspace-alias"); - await fs.mkdir(workspace); - await fs.symlink(workspace, alias, process.platform === "win32" ? "junction" : "dir"); - const { runtimeOptions, sessionInputs } = await runExecutor({ - agent: "gemini", agentCommand: "node ./fake-acp.js", cwd: alias, - stateDir: path.join(root, "state"), - }); - const canonical = await fs.realpath(workspace); - expect(runtimeOptions[0]!.cwd).toBe(canonical); - expect(sessionInputs[0]!.cwd).toBe(canonical); - }); - it("parses semantic version parts from gemini --version output", () => { expect(parseGeminiVersionParts("0.30.0")).toEqual([0, 30, 0]); expect(parseGeminiVersionParts("gemini-cli v1.2.3\n")).toEqual([1, 2, 3]); @@ -3574,16 +3526,6 @@ describe("ACPX engine remote sandbox staging seam (PR 1: workspace + cwd)", () = expect(sessionInputs[0]?.cwd).not.toBe(localCwd); }); - it("preserves Gemini's in-sandbox workspace without host canonicalization", async () => { - const { stateDir, localCwd, remoteCwd, executionTarget } = await setupRemoteSandbox(); - const { sessionInputs, runtimeOptions } = await runExecutor( - { agent: "gemini", agentCommand: "node ./fake-acp.js", stateDir, cwd: localCwd }, - { authToken: "real-run-jwt", executionTarget }, - ); - expect(runtimeOptions[0]?.cwd).toBe(remoteCwd); - expect(sessionInputs[0]?.cwd).toBe(remoteCwd); - }); - it("test_remote_warm_handle_reused_after_cwd_change", async () => { const { stateDir, localCwd, remoteCwd, executionTarget } = await setupRemoteSandbox(); const ensureInputs: Array> = []; diff --git a/packages/adapter-utils/src/acpx-engine/execute.ts b/packages/adapter-utils/src/acpx-engine/execute.ts index 6d49557057d..28e5b620259 100644 --- a/packages/adapter-utils/src/acpx-engine/execute.ts +++ b/packages/adapter-utils/src/acpx-engine/execute.ts @@ -2039,12 +2039,6 @@ async function buildRuntime(input: { if (requestedModel && acpxAgent === "claude" && !env.ANTHROPIC_MODEL) { env.ANTHROPIC_MODEL = requestedModel; } - // Gemini CLI reads GEMINI_MODEL when creating each ACP session. Its ACP - // implementation supports set_model, but not set_config_option; configure - // the selected model before startup without changing the transport. - if (requestedModel && acpxAgent === "gemini") { - env.GEMINI_MODEL = requestedModel; - } if (acpxAgent === "codex") { const codexStartupConfig = buildCodexStartupConfig({ existingConfig: env.CODEX_CONFIG, @@ -2190,9 +2184,8 @@ async function buildRuntime(input: { // (fingerprint, compat, persist, ensureSession, error) bind to THIS single // value so a warm/resumable session created with the in-sandbox cwd is reused // — not invalidated — on the next run. Remote runner-backed → the in-sandbox - // workspace dir; local and the runner-less fallback → the HOST cwd. - // Local Gemini resolves tool paths through realpath. Give its ACP filesystem - // client the same canonical root so workspace aliases stay within that root. + // workspace dir; local and the runner-less fallback → the HOST cwd, + // byte-identical to today. // // PR 3: the staging transport derives the in-sandbox workspace dir // deterministically from the target's `remoteCwd` (it is exactly `remoteCwd` @@ -2205,9 +2198,7 @@ async function buildRuntime(input: { const sessionCwd = useRemoteProcessSession && executionTarget?.kind === "remote" ? executionTarget.remoteCwd - : acpxAgent === "gemini" && !executionTargetIsRemote - ? await fs.realpath(cwd) - : cwd; + : cwd; // The 17 fields the session fingerprint hashes. Company, agent, and task // identifiers are NOT here; they scope the outer session key only (see // `keyIdentity`). The fingerprint builder accepts only this identity. @@ -2551,28 +2542,6 @@ async function buildRuntime(input: { await emitRunPhaseTiming(input.ctx, "start_transport", nowMs() - startTransportStart, "failed"); throw err; } - const currentSkillRoot = acpxAgent === "codex" && runtimeEnv.CODEX_HOME - ? path.join(runtimeEnv.CODEX_HOME, "skills") - : acpxAgent === "gemini" && !executionTargetIsRemote && typeof skillsIdentity.skillsHome === "string" - ? skillsIdentity.skillsHome - : null; - if (currentSkillRoot && Array.isArray(skillsIdentity.selectedSkills) && skillsIdentity.selectedSkills.length > 0) { - // Managed connection homes are disposable. A resumed conversation may - // remember a previous home's skill paths; supply the current root on every - // turn, after the remote launch environment has rebased CODEX_HOME. - skillPromptInstructions = [ - `Paperclip has materialized selected runtime skills for this ACPX ${acpxAgent === "codex" ? "Codex" : "Gemini"} run.`, - `Skill root for this run: ${currentSkillRoot}`, - `Selected skills: ${skillsIdentity.selectedSkills.join(", ")}`, - "When a task calls for one of these skills, read its SKILL.md from this root and follow it. Resolve referenced scripts and files relative to that skill. Use this run's root even when an earlier turn used a different path.", - ...(acpxAgent === "gemini" && skillsIdentity.selectedSkills.includes("paperclip") - ? [ - "Before calling Paperclip APIs or delivering task artifacts, read the selected paperclip skill's SKILL.md and its referenced artifact workflow. A completion comment does not upload an artifact or change task status.", - "Gemini's shell tool rejects command substitution. Write JSON request bodies to a workspace file and use curl --data-binary @file, or use the selected skill's helpers, instead of constructing a body with command substitution.", - ] - : []), - ].join("\n"); - } // The relay runs on the host with the sanitized remote launch environment. // Its /usr/bin/env node shebang cannot rely on that environment's PATH. const overrideCommand = processSessionBridge?.agentCommand @@ -2640,14 +2609,13 @@ async function buildRuntime(input: { function sessionConfigOptions(prepared: AcpxPreparedRuntime): Array<{ key: string; value: string }> { const options: Array<{ key: string; value: string }> = []; - // Claude, Codex and Gemini runtime config is pre-set via startup env vars; skip + // Claude and Codex runtime config is pre-set via startup env vars; skip // set_config_option to avoid ACP-server picker validation rejecting valid // backend model IDs that are not advertised by the local ACP server. if ( prepared.requestedModel && prepared.acpxAgent !== "claude" && - prepared.acpxAgent !== "codex" && - prepared.acpxAgent !== "gemini" + prepared.acpxAgent !== "codex" ) { options.push({ key: "model", value: prepared.requestedModel }); } @@ -4793,8 +4761,6 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) { ? `Requested ACPX model: ${prepared.requestedModel} (set via ANTHROPIC_MODEL env at startup).` : prepared.acpxAgent === "codex" ? `Requested ACPX model: ${prepared.requestedModel} (set via CODEX_CONFIG at startup).` - : prepared.acpxAgent === "gemini" - ? `Requested ACPX model: ${prepared.requestedModel} (set via GEMINI_MODEL at startup).` : `Requested ACPX model: ${prepared.requestedModel}.`, ] : []), diff --git a/packages/adapters/gemini-local/src/index.ts b/packages/adapters/gemini-local/src/index.ts index 4c21841190a..d71ce497e73 100644 --- a/packages/adapters/gemini-local/src/index.ts +++ b/packages/adapters/gemini-local/src/index.ts @@ -60,10 +60,6 @@ Operational fields: - graceSec (number, optional): SIGTERM grace period in seconds Notes: -- Explicit ACP models are set via \`GEMINI_MODEL\` before startup; this avoids unsupported \`session/set_config_option\` calls while preserving the ACP transport. Auto continues to use the installed CLI's model selection. -- Local turns include the current selected skill root and Paperclip artifact workflow guidance, including after a disposable connection home changes. -- Local ACP workspaces use their canonical directory so Gemini's resolved file paths match the client boundary. Missing files retain ACP resource-not-found semantics. Gemini CLI 0.58.0 still mishandles the plain error object during native new-file creation; the installed-CLI compatibility smoke documents this remaining limitation. -- Gemini shell commands may reject command substitution. Build JSON request bodies in workspace files and pass them with \`curl --data-binary @file\`, or use the selected skill's helpers. - Gemini ACP is the preferred auto lane when Node >=24.11.0 and the local Gemini CLI command is available. It runs Gemini CLI's native \`gemini --acp\` server through Paperclip's shared ACP engine, including selected skill links, Paperclip runtime prompt/env guidance, model config, and persistent ACP session state. Missing prerequisites fail both default and explicit ACP runs with an actionable setup error; the adapter never switches engines automatically. - Runs use --prompt for non-interactive execution, not stdin. - The adapter sets a headless-safe terminal/browser environment for Gemini CLI child processes so unattended runs do not wait on browser auth or 256-color terminal prompts. diff --git a/packages/adapters/grok-local/src/index.ts b/packages/adapters/grok-local/src/index.ts index 723937389fa..f296d574011 100644 --- a/packages/adapters/grok-local/src/index.ts +++ b/packages/adapters/grok-local/src/index.ts @@ -53,5 +53,4 @@ Notes: - Use \`grok models\` to inspect authentication and available models on the host. - Local subscription runs use the host \`grok login\` (\`~/.grok\`) until the company Grok home has a usable \`auth.json\` (sandbox device login). \`XAI_API_KEY\` authenticates without a home. Remote/sandbox runs never fall back to the host login. - Without a usable company login, local runs preserve an inherited or configured \`GROK_HOME\`. Managed AI connections keep their selected home. An explicit empty \`XAI_API_KEY\` clears an inherited key and selects subscription authentication. -- Managed local connections retain private session transcripts separately from disposable credentials, scoped to company, agent and connection identity. Missing local history starts a fresh task handoff without attempting remote subscription recovery. `; diff --git a/packages/adapters/grok-local/src/server/execute.test.ts b/packages/adapters/grok-local/src/server/execute.test.ts index acd6ad01f59..d7995cd8b60 100644 --- a/packages/adapters/grok-local/src/server/execute.test.ts +++ b/packages/adapters/grok-local/src/server/execute.test.ts @@ -163,18 +163,6 @@ async function makeCtx(runId: string, cwd: string): Promise { - it.each([false, true])("resumes a managed connection only when its isolated history exists (%s)", async present => { - const root = await makeTempRoot(); - const ctx = await makeCtx("managed-resume", root); - ctx.config.managedAiConnection = true; - ctx.config.env = { GROK_HOME: path.join(root, "home"), XAI_API_KEY: "fixture-key" }; - ctx.runtime.sessionParams = { sessionId: "fixture-session", cwd: root }; - if (present) await fs.mkdir(path.join(root, "home", "sessions", "encoded-cwd", "fixture-session"), { recursive: true }); - runProcessMock.mockResolvedValue(makeSuccessfulRunResult({ sessionId: "next-session" })); - const result = await execute(ctx); - expect((runProcessMock.mock.calls[0][3] as string[]).includes("--resume")).toBe(present); - expect(result.sessionParams?.sessionId).toBe("next-session"); - }); it("resumes the conversation while rotating runtime tool access", async () => { const root = await makeTempRoot(); runProcessMock.mockResolvedValue(makeSuccessfulRunResult({ sessionId: "existing-session" })); diff --git a/packages/adapters/grok-local/src/server/execute.ts b/packages/adapters/grok-local/src/server/execute.ts index db9be4f4a41..1170900e5fc 100644 --- a/packages/adapters/grok-local/src/server/execute.ts +++ b/packages/adapters/grok-local/src/server/execute.ts @@ -47,7 +47,7 @@ import { } from "@paperclipai/adapter-utils/server-utils"; import { DEFAULT_GROK_LOCAL_MODEL } from "../index.js"; import { copyBackGrokAuth } from "./grok-auth-copyback.js"; -import { grokHomeHasSession, grokHomeHasUsableAuth, resolveManagedGrokHomeDir, stageGrokHomeForSync } from "./grok-home.js"; +import { grokHomeHasUsableAuth, resolveManagedGrokHomeDir, stageGrokHomeForSync } from "./grok-home.js"; import { isGrokUnknownSessionError, parseGrokJsonl } from "./parse.js"; const __moduleDir = path.dirname(fileURLToPath(import.meta.url)); @@ -501,17 +501,12 @@ async function executeTurn(ctx: AdapterExecutionContext): Promise 0 && - !missingManagedSession && (runtimeSessionCwd.length === 0 || path.resolve(runtimeSessionCwd) === path.resolve(effectiveExecutionCwd)) && adapterExecutionTargetSessionMatches(runtimeRemoteExecution, runtimeExecutionTarget); const sessionId = canResumeSession ? runtimeSessionId : null; - if (missingManagedSession) { - await onLog("stdout", "[paperclip] Selected Grok session history is unavailable. Starting a fresh session with the task handoff instead of remote subscription recovery.\n"); - } else if (executionTargetIsRemote && runtimeSessionId && !canResumeSession) { + if (executionTargetIsRemote && runtimeSessionId && !canResumeSession) { await onLog( "stdout", `[paperclip] Grok session "${runtimeSessionId}" does not match the current remote execution identity and will not be resumed in "${effectiveExecutionCwd}". Starting a fresh remote session.\n`, @@ -658,7 +653,7 @@ async function executeTurn(ctx: AdapterExecutionContext): Promise { - it.skipIf(process.platform === "win32")("finds private linked history without following descendant links or accepting traversal", async () => { - const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-grok-history-")); - try { - const home = path.join(root, "home"); - const sessions = path.join(root, "private-sessions"); - const sessionId = "fixture-session"; - const session = path.join(sessions, "encoded-workspace", sessionId); - await fs.mkdir(home); - await fs.mkdir(session, { recursive: true }); - await fs.symlink(sessions, path.join(home, "sessions"), "dir"); - expect(await grokHomeHasSession(home, sessionId)).toBe(true); - expect(await grokHomeHasSession(home, "missing-session")).toBe(false); - expect(await grokHomeHasSession(home, "../../private-sessions")).toBe(false); - await fs.rm(session, { recursive: true }); - const outside = path.join(root, "outside", sessionId); - await fs.mkdir(outside, { recursive: true }); - await fs.symlink(path.dirname(outside), path.join(sessions, "outside-link"), "dir"); - expect(await grokHomeHasSession(home, sessionId)).toBe(false); - } finally { await fs.rm(root, { recursive: true, force: true }); } - }); -}); +import { GROK_SYNC_ALLOWLIST, stageGrokHomeForSync } from "./grok-home.js"; describe("GROK_SYNC_ALLOWLIST", () => { it("holds exactly one name: auth.json", () => { diff --git a/packages/adapters/grok-local/src/server/grok-home.ts b/packages/adapters/grok-local/src/server/grok-home.ts index fd5ba77f8bd..8a31e28f236 100644 --- a/packages/adapters/grok-local/src/server/grok-home.ts +++ b/packages/adapters/grok-local/src/server/grok-home.ts @@ -3,8 +3,8 @@ import os from "node:os"; import path from "node:path"; import { resolvePaperclipInstanceRootForAdapter } from "@paperclipai/adapter-utils/server-utils"; -// `GROK_HOME` replaces `~/.grok` and holds `auth.json` plus session history. -// Unlike Codex, a Grok `auth.json` has no fixed top-level key: it +// The Grok credential home. `GROK_HOME` replaces `~/.grok` and holds one file, +// `auth.json`. Unlike Codex, a Grok `auth.json` has no fixed top-level key: it // holds exactly one key, and that key is a composite `::` value. // This module resolves the company-scoped home path and reads its usable-auth // shape. It never writes to the managed home itself; {@link @@ -14,29 +14,6 @@ import { resolvePaperclipInstanceRootForAdapter } from "@paperclipai/adapter-uti const AUTH_FILE_NAME = "auth.json"; -/** Inspect only the selected private home, never Grok's remote registry. */ -export async function grokHomeHasSession(home: string, sessionId: string): Promise { - if (!home || !/^[a-zA-Z0-9_-]{1,128}$/.test(sessionId)) return false; - let remaining = 5000; - async function inspect(directory: string, depth: number): Promise { - let entries; - try { entries = await fs.opendir(directory); } - catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; - throw error; - } - for await (const entry of entries) { - if (--remaining < 0) throw new Error("Grok session history exceeds its lookup bound"); - if (entry.isSymbolicLink()) continue; - if ((entry.isFile() || entry.isDirectory()) && - (entry.name === sessionId || entry.name.startsWith(`${sessionId}.`))) return true; - if (entry.isDirectory() && depth > 0 && await inspect(path.join(directory, entry.name), depth - 1)) return true; - } - return false; - } - return inspect(path.join(home, "sessions"), 2); -} - /** * The allowlist of managed `GROK_HOME` entries that the grok-local adapter * stages into the sandbox `home` asset (see {@link stageGrokHomeForSync}). diff --git a/patches/acpx@0.12.0.patch b/patches/acpx@0.12.0.patch index 106815a9ef7..9cf65429fcd 100644 --- a/patches/acpx@0.12.0.patch +++ b/patches/acpx@0.12.0.patch @@ -1,5 +1,5 @@ diff --git a/dist/live-checkpoint-ClPCSdrW.js b/dist/live-checkpoint-ClPCSdrW.js -index 243c9d13bcba520923b63adfddad75cf2d94362d..b93d4b29edfce81c8eb3c769699712f490553506 100644 +index 243c9d13bcba520923b63adfddad75cf2d94362d..e2a254d4e57fb2e246ccb742f2e9de5a8a461d20 100644 --- a/dist/live-checkpoint-ClPCSdrW.js +++ b/dist/live-checkpoint-ClPCSdrW.js @@ -1532,7 +1532,7 @@ const ZED_TAG_KEYS = /* @__PURE__ */ new Set([ @@ -96,17 +96,7 @@ index 243c9d13bcba520923b63adfddad75cf2d94362d..b93d4b29edfce81c8eb3c769699712f4 }; } logAgentLaunch(plan) { -@@ -4729,6 +4749,9 @@ var AcpClient = class { - return await this.filesystem.readTextFile(params); - } catch (error) { - this.recordPermissionError(params.sessionId, error); -+ // Preserve missing-file semantics across JSON-RPC. Gemini checks for -+ // ENOENT before creating a new file; a generic Internal error hides it. -+ if (error && typeof error === "object" && error.code === "ENOENT") throw RequestError.resourceNotFound(params.path); - throw error; - } - } -@@ -6070,6 +6093,27 @@ async function withConnectedSession(options) { +@@ -6070,6 +6090,27 @@ async function withConnectedSession(options) { //#region src/runtime/engine/prompt-turn.ts const SESSION_REPLY_IDLE_MS = 1e3; const SESSION_REPLY_DRAIN_TIMEOUT_MS = 5e3; @@ -134,7 +124,7 @@ index 243c9d13bcba520923b63adfddad75cf2d94362d..b93d4b29edfce81c8eb3c769699712f4 async function runPromptTurn(params) { try { const promptPromise = params.client.prompt(params.sessionId, params.prompt); -@@ -6079,6 +6123,20 @@ async function runPromptTurn(params) { +@@ -6079,6 +6120,20 @@ async function runPromptTurn(params) { idleMs: SESSION_REPLY_IDLE_MS, timeoutMs: SESSION_REPLY_DRAIN_TIMEOUT_MS }).catch(() => {}); diff --git a/server/src/__tests__/ai-connections.test.ts b/server/src/__tests__/ai-connections.test.ts index 85178cffffc..b3404d6bc6e 100644 --- a/server/src/__tests__/ai-connections.test.ts +++ b/server/src/__tests__/ai-connections.test.ts @@ -4,7 +4,7 @@ import { issueRecoveryActionService } from "../services/issue-recovery-actions.j import * as localCredentials from "../services/local-ai-credentials.js"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { randomUUID } from "node:crypto"; -import { mkdtemp, realpath, rm, access, readFile, writeFile, stat, readlink, readdir } from "node:fs/promises"; +import { mkdtemp, realpath, rm, access, readFile, writeFile, stat } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { and, eq, sql } from "drizzle-orm"; @@ -50,29 +50,27 @@ beforeAll(async () => { afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); }); describe("managed AI connections", () => { - it("retains only Grok sessions across private runtime homes and isolates agents and accounts", async () => { - const save = (name: string) => service.save(companyId, "alice", { provider: "xai", method: "api_key", ownership: "personal", name, agentIds: [], allAgents: true }, `fixture-${name}`); - const account = await save("Grok history"); - const other = await save("Other Grok history"); - const runInput = { ...input, adapterType: "grok_local", responsibleUserId: "alice", config: {}, binding: { provider: "xai", method: "api_key", mode: "connection", connectionId: account.connectionId, grantId: account.grantId } as const }; - const first = await prepareManagedAiRuntime(db, runInput); - const sessions = await readlink(path.join(String(first.config.env.GROK_HOME), "sessions")); - await writeFile(path.join(sessions, "history.json"), '{"fixture":"history"}', { mode: 0o600 }); - await writeFile(path.join(String(first.config.env.GROK_HOME), "auth.json"), "disposable-auth", { mode: 0o600 }); - await first.cleanup(); - await expect(access(first.home!)).rejects.toThrow(); - expect(await readdir(sessions)).toEqual(["history.json"]); - expect((await stat(sessions)).mode & 0o777).toBe(0o700); - const resumed = await prepareManagedAiRuntime(db, runInput); - const otherAgent = await prepareManagedAiRuntime(db, { ...runInput, agentId: randomUUID() }); - const otherAccount = await prepareManagedAiRuntime(db, { ...runInput, binding: { ...runInput.binding, connectionId: other.connectionId, grantId: other.grantId } }); + it.each([ + ["openai", "codex_local", "responses"], + ["anthropic", "claude_local", "messages"], + ["openai", "opencode_local", "chat"], + ] as const)("prepares a no-auth %s endpoint without a vault secret", async (provider, adapterType, protocol) => { + const account = await service.save(companyId, "alice", { + provider, method: "api_key", ownership: "personal", name: `No-auth ${adapterType}`, + agentIds: [], allAgents: true, + routing: { kind: "local", protocol, baseUrl: "http://127.0.0.1:9000/v1", auth: "none", models: [] }, + }, ""); + const binding = { provider, method: "api_key", mode: "connection", connectionId: account.connectionId, grantId: account.grantId } as const; + const config = { model: "fixture-model", env: { OPENAI_API_KEY: "host-key", ANTHROPIC_API_KEY: "host-key" } }; + const first = await prepareManagedAiRuntime(db, { ...input, adapterType, responsibleUserId: "alice", binding, config }); + const second = await prepareManagedAiRuntime(db, { ...input, adapterType, responsibleUserId: "alice", binding, config }); try { - expect(resumed.home).not.toBe(first.home); - expect(await readlink(path.join(String(resumed.config.env.GROK_HOME), "sessions"))).toBe(sessions); - expect(await readlink(path.join(String(otherAgent.config.env.GROK_HOME), "sessions"))).not.toBe(sessions); - expect(await readlink(path.join(String(otherAccount.config.env.GROK_HOME), "sessions"))).not.toBe(sessions); - await expect(access(path.join(String(resumed.config.env.GROK_HOME), "auth.json"))).rejects.toThrow(); - } finally { await Promise.all([resumed.cleanup(), otherAgent.cleanup(), otherAccount.cleanup()]); } + expect(first.sessionIdentity).toBe(second.sessionIdentity); + expect(first.sessionIdentity).toContain("no-auth"); + expect(JSON.stringify(first.config)).not.toContain("host-key"); + const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, account.grantId)); + expect(grant.credentialSecretRefs).toEqual([]); + } finally { await Promise.all([first.cleanup(), second.cleanup()]); } }); it("authenticates local Gemini probes and runs with the saved key in an isolated home", async () => { const root = await mkdtemp(path.join(home, "gemini-auth-")); diff --git a/server/src/__tests__/file-delivery-bridges.test.ts b/server/src/__tests__/file-delivery-bridges.test.ts index c43f6ca4c3c..16ab0b6ad18 100644 --- a/server/src/__tests__/file-delivery-bridges.test.ts +++ b/server/src/__tests__/file-delivery-bridges.test.ts @@ -99,9 +99,9 @@ describe(`durable file delivery (${liveDaytona ? "Daytona" : "local processes"}) enableSandboxDuplexBridge: duplex, }); expect(bridge?.env.PAPERCLIP_API_BRIDGE_MODE).toBe(duplex ? "http2_v1" : "queue_v1"); - const env = { ...bridge!.env, TMPDIR: path.join(remote.workspace, ".unavailable-controller-temp"), PAPERCLIP_RUN_ID: fixture.runId, + const env = { ...bridge!.env, PAPERCLIP_RUN_ID: fixture.runId, PAPERCLIP_COMPANY_ID: fixture.companyId, PAPERCLIP_TASK_ID: fixture.issueId, - PAPERCLIP_WORKSPACE_CWD: remote.workspace }; + PAPERCLIP_HELPER_STATE_DIR: path.join(remote.workspace, ".helper-state") }; const headers = { authorization: `Bearer ${bridge!.env.PAPERCLIP_API_KEY}` }; const receipts: Array<{ attachment: { id: string; contentPath: string; downloadPath: string } }> = []; try { diff --git a/server/src/services/ai-connection-runtime.ts b/server/src/services/ai-connection-runtime.ts index 8d8abfe9bf6..bce54ad3d22 100644 --- a/server/src/services/ai-connection-runtime.ts +++ b/server/src/services/ai-connection-runtime.ts @@ -1,6 +1,6 @@ import { createHash } from "node:crypto"; import { HttpError, unprocessable } from "../errors.js"; -import { mkdtemp, mkdir, symlink, writeFile, readFile, rm } from "node:fs/promises"; +import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { and, eq } from "drizzle-orm"; @@ -17,7 +17,6 @@ import { decideCodexAuthMerge } from "@paperclipai/adapter-codex-local/server"; import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target"; import { runAdapterExecutionTargetProcess } from "@paperclipai/adapter-utils/execution-target"; import { decideGrokAuthMerge } from "@paperclipai/adapter-grok-local/server"; -import { resolvePaperclipInstanceRootForAdapter } from "@paperclipai/adapter-utils/server-utils"; export function isAiConnectionBusy(error: unknown): error is HttpError { return error instanceof HttpError && error.status === 422 && @@ -269,13 +268,15 @@ export async function prepareManagedAiRuntime( "The selected default changed. Retry this execution.", ); const credentialRef = selection.grant.credentialSecretRefs.find((ref) => ref.configPath === "ai.credential"); - if (!credentialRef) throw unprocessable("The selected AI credential is unavailable"); - const readFreshness = async () => (await db.select({ epoch: companySecrets.aiSessionEpoch, version: companySecrets.latestVersion }) - .from(companySecrets).where(and(eq(companySecrets.companyId, input.companyId), eq(companySecrets.id, credentialRef.secretId))).limit(1))[0]; - const freshness = await readFreshness(); - const value = await service.credential(selection); - const afterRead = await readFreshness(); - if (!freshness || freshness.version !== afterRead?.version || freshness.epoch !== afterRead.epoch) throw unprocessable("The AI credential changed during preparation; retry this execution"); + const routing = aiConnectionMetadataSchema.parse(selection.connection.config.ai).routing; + const noAuth = routing?.auth === "none"; + if (!noAuth && !credentialRef) throw unprocessable("The selected AI credential is unavailable"); + const readFreshness = async () => credentialRef ? (await db.select({ epoch: companySecrets.aiSessionEpoch, version: companySecrets.latestVersion }) + .from(companySecrets).where(and(eq(companySecrets.companyId, input.companyId), eq(companySecrets.id, credentialRef.secretId))).limit(1))[0] : undefined; + const freshness = noAuth ? undefined : await readFreshness(); + const value = noAuth ? "" : await service.credential(selection); + const afterRead = noAuth ? undefined : await readFreshness(); + if (!noAuth && (!freshness || freshness.version !== afterRead?.version || freshness.epoch !== afterRead.epoch)) throw unprocessable("The AI credential changed during preparation; retry this execution"); home = await mkdtemp( path.join( os.tmpdir(), @@ -289,7 +290,6 @@ export async function prepareManagedAiRuntime( ...Object.fromEntries(AI_AUTH_ENV_KEYS.map((key) => [key, ""])), ...managedAiHomeEnvironment(home), }; - const routing = aiConnectionMetadataSchema.parse(selection.connection.config.ai).routing; const capability = AI_CONNECTION_CAPABILITIES[input.binding.provider].methods[ selection.attribution.method @@ -339,18 +339,7 @@ export async function prepareManagedAiRuntime( .digest("hex") .slice(0, 16); const identity = `${selection.grant.id}:${input.responsibleUserId ?? "shared"}:${generation}`; - const sessionIdentity = `${selection.grant.id}:${input.responsibleUserId ?? "shared"}:${credentialRef.secretId}:${freshness.epoch}`; - if (input.adapterType === "grok_local") { - // Retain only transcripts across disposable credential homes. Scope them - // to the company, agent and credential identity, including rotations. - // Removing the runtime home removes the link, never its private target. - const scope = createHash("sha256") - .update(JSON.stringify([input.companyId, input.agentId, sessionIdentity])) - .digest("hex"); - const sessions = path.join(resolvePaperclipInstanceRootForAdapter(), "companies", input.companyId, "grok-sessions", scope); - await mkdir(sessions, { recursive: true, mode: 0o700 }); - await symlink(sessions, path.join(providerHome, "sessions"), "dir"); - } + const sessionIdentity = `${selection.grant.id}:${input.responsibleUserId ?? "shared"}:${noAuth ? "no-auth" : `${credentialRef!.secretId}:${freshness!.epoch}`}`; return { sessionIdentity, config: { diff --git a/server/src/services/local-ai-browser-login.test.ts b/server/src/services/local-ai-browser-login.test.ts index 1b102966ed8..0f8085314c7 100644 --- a/server/src/services/local-ai-browser-login.test.ts +++ b/server/src/services/local-ai-browser-login.test.ts @@ -65,6 +65,23 @@ describe.skipIf(process.platform === "win32")("local browser subscription login" await vi.waitFor(() => expect(() => process.kill(pid, 0)).toThrow()); }); + it("cancels Claude while waiting for its browser code and terminates the provider", async () => { + const home = await fakeCli("claude", [ + 'echo $$ > "$CLAUDE_CONFIG_DIR/login.pid"', + 'printf "Welcome to Claude Code\\nOpening browser to sign in…\\nBrowser didn\x27t open? Use the url below to sign in (c to copy)\\n"', + 'printf "https://claude.com/cai/oauth/authorize?client_id=cid&code=abcdefgh&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256&redirect_uri=https%%3A%%2F%%2Fplatform.claude.com%%2Foauth%%2Fcode%%2Fcallback&response_type=code&scope=user&state=0123456789abcdef\\n"', + 'printf "Paste code here if prompted >\\n"', + 'read -r entered', + ].join("\n")); + const login = startLocalBrowserLogin("anthropic", home); + await vi.waitFor(() => expect(login.authorizationUrl).toBeDefined()); + const pid = Number(await readFile(path.join(home, "login.pid"), "utf8")); + login.abort(); + await vi.waitFor(() => expect(login.outcome).toBe("failure")); + await vi.waitFor(() => expect(() => process.kill(pid, 0)).toThrow()); + await expect(readFile(path.join(home, ".credentials.json"))).rejects.toThrow(); + }); + it("returns a fixed failure without exposing provider error output", async () => { const home = await fakeCli("codex", 'echo "private-provider-error" >&2\nexit 1'); const login = startLocalBrowserLogin("openai", home); diff --git a/server/src/services/local-ai-browser-login.ts b/server/src/services/local-ai-browser-login.ts index d79a01555e9..ad3ee6dfe7a 100644 --- a/server/src/services/local-ai-browser-login.ts +++ b/server/src/services/local-ai-browser-login.ts @@ -80,7 +80,12 @@ export function startLocalBrowserLogin(provider: "anthropic" | "openai", home: s void runSetupTokenLogin(driver, { timeoutMs: 300_000, signal: controller.signal, onPrompt: (prompt) => { state.authorizationUrl = prompt.url; }, - provideCode: () => codeReady, + provideCode: (signal) => new Promise((resolve, reject) => { + const abort = () => reject(new Error("Local sign-in cancelled")); + if (signal.aborted) { abort(); return; } + signal.addEventListener("abort", abort, { once: true }); + codeReady.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort)); + }), onCredential: async (bytes) => { const file = await open(path.join(home, ".credentials.json"), constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); diff --git a/ui/src/components/ai-connections/AiConnectionCredentialStep.tsx b/ui/src/components/ai-connections/AiConnectionCredentialStep.tsx index ec151c4a75e..2043569e512 100644 --- a/ui/src/components/ai-connections/AiConnectionCredentialStep.tsx +++ b/ui/src/components/ai-connections/AiConnectionCredentialStep.tsx @@ -1,4 +1,4 @@ -import { useState } from "react"; +import { useState, type ReactNode } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { type AiProvider, type AiAuthMethod, type AiConnectionLoginIntent } from "@paperclipai/shared"; import { AgentProviderConnection } from "@/components/new-agent/AgentProviderConnection"; @@ -26,17 +26,19 @@ type Props = { agentIds: string[]; allAgents: boolean; environmentId?: string; + defaults?: ReactNode; + disabled?: boolean; onComplete: (result: { connectionId: string; grantId: string; method: AiAuthMethod }) => void; onCancel: () => void; }; /** Connections hosts the same provider step as agent setup, with its own save intent. */ export function AiConnectionCredentialStep(props: Props) { - if (props.provider === "openrouter") return ; + if (props.provider === "openrouter" || props.provider === "google") return ; return ; } -function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedMethod, connectionId, name: initialName, hideName, nameForMethod, ownership, agentIds, allAgents, environmentId: suppliedEnvironmentId, onComplete, onCancel }: Props) { +function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedMethod, connectionId, name: initialName, hideName, nameForMethod, ownership, agentIds, allAgents, environmentId: suppliedEnvironmentId, onComplete, onCancel, defaults, disabled }: Props) { const [name, setName] = useState(initialName); const [chosenEnvironment, setChosenEnvironment] = useState(); const client = useQueryClient(); @@ -82,6 +84,7 @@ function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedM {loginEnvironments.map((env) => {env.name})} } {error &&

{error}

} + {defaults} {loading ?

Preparing sign-in…

: {}} testConnection={async () => false} - managedAccount={{ intent, nameForMethod, initialMethod, fixedMethod: fixedMethod ?? Boolean(connectionId), disabled: loading || Boolean(error) || !name.trim(), onComplete: (result) => { void client.invalidateQueries({ queryKey: ["ai-connections", companyId] }); onComplete(result); } }} + managedAccount={{ intent, nameForMethod, initialMethod, fixedMethod: fixedMethod ?? Boolean(connectionId), disabled: disabled || loading || Boolean(error) || !name.trim(), onComplete: (result) => { void client.invalidateQueries({ queryKey: ["ai-connections", companyId] }); void client.invalidateQueries({ queryKey: ["tools"] }); onComplete(result); } }} />} ; } -function ApiKeyConnectionStep({ companyId, provider, connectionId, name: initialName, hideName, nameForMethod, ownership, agentIds, allAgents, onComplete, onCancel }: Props) { +function ApiKeyConnectionStep({ companyId, provider, connectionId, name: initialName, hideName, nameForMethod, ownership, agentIds, allAgents, onComplete, onCancel, defaults, disabled }: Props) { const [name, setName] = useState(initialName); const [apiKey, setApiKey] = useState(""); const client = useQueryClient(); const save = useMutation({ mutationFn: () => aiConnectionsApi.create(companyId, { provider, method: "api_key", name: connectionId ? name : nameForMethod?.("api_key") ?? name, ownership, agentIds, allAgents, connectionId, apiKey }), - onSuccess: (result) => { void client.invalidateQueries({ queryKey: ["ai-connections", companyId] }); onComplete({ ...result, method: "api_key" }); }, + onSuccess: (result) => { void client.invalidateQueries({ queryKey: ["ai-connections", companyId] }); void client.invalidateQueries({ queryKey: ["tools"] }); onComplete({ ...result, method: "api_key" }); }, onSettled: () => setApiKey(""), }); return
{!hideName && } {save.error &&

{save.error.message}

} - save.mutate()} disabled={save.isPending} placeholder="Enter API key here" autoFocus /> -
+ save.mutate()} disabled={disabled || save.isPending} placeholder="Enter API key here" autoFocus /> + {defaults} +
; } diff --git a/ui/src/components/ai-connections/AiConnectionField.test.tsx b/ui/src/components/ai-connections/AiConnectionField.test.tsx index 7ab32e4afe0..9603e6fd1f5 100644 --- a/ui/src/components/ai-connections/AiConnectionField.test.tsx +++ b/ui/src/components/ai-connections/AiConnectionField.test.tsx @@ -18,6 +18,7 @@ vi.mock("./AiConnectionCredentialStep", () => ({ }, })); vi.mock("./AiConnectionManagement", () => ({ AiConnectionLegacyNotice: () => null })); +vi.mock("./AiProviderSetup", () => ({ AiProviderSetup: () =>
Advanced provider setup
})); vi.mock("@/pages/apps/AppLogo", () => ({ AppLogo: () => null })); let root: Root; @@ -36,15 +37,26 @@ async function settle() { flushSync(() => {}); } } -async function mount(connections: AiManagedConnectionSummary[], canManageConnections = true) { +async function mount(connections: AiManagedConnectionSummary[], canManageConnections = true, preferAdvanced = false) { mocks.list.mockResolvedValue({ currentUserId: "owner", connections, canManageConnections }); flushSync(() => root.render( )); await settle(); } -function click(label: string) { +async function click(label: string) { + if (label === "Connect another account") { + const trigger = document.querySelector('[role="combobox"][aria-label="Connection"]')!; + flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }))); + await settle(); + const option = Array.from(document.querySelectorAll('[role="option"]')).find(item => item.textContent?.includes("Connect an account")); + expect(option).toBeDefined(); + flushSync(() => option!.click()); + await settle(); + return; + } const button = Array.from(document.querySelectorAll("button")).find(item => item.textContent === label); expect(button, `Missing button: ${label}`).toBeDefined(); flushSync(() => button!.click()); @@ -62,7 +74,7 @@ afterEach(() => { flushSync(() => root.unmount()); client.clear(); container.rem it("reconnects the unavailable personal default in place", async () => { await mount([account()]); - click("Reconnect account"); + await click("Reconnect account"); expect(credentialProps).toMatchObject({ connectionId: "old-connection", initialMethod: "subscription", fixedMethod: true }); credentialProps!.onComplete({ connectionId: "old-connection", grantId: "old-grant", method: "subscription" }); await settle(); @@ -70,9 +82,16 @@ it("reconnects the unavailable personal default in place", async () => { expect(onChange).toHaveBeenCalledWith({ provider: "anthropic", method: "subscription", mode: "responsible_user" }); }); +it("opens provider setup directly when connecting from the advanced mode", async () => { + await mount([], true, true); + await click("Connect another account"); + expect(document.body.textContent).toContain("Advanced provider setup"); + expect(credentialProps).toBeUndefined(); +}); + it("selects the returned new grant and actual method before adopting the personal default", async () => { await mount([account()]); - click("Connect another account"); + await click("Connect another account"); expect(document.body.textContent).toContain("default"); expect(credentialProps).toMatchObject({ connectionId: undefined, allAgents: true }); let resolveDefault!: () => void; @@ -88,7 +107,7 @@ it("selects the returned new grant and actual method before adopting the persona it("lets the owner limit a new personal connection to this agent", async () => { await mount([]); - click("Connect another account"); + await click("Connect another account"); const checkbox = document.querySelector('[role="checkbox"]')!; expect(checkbox).not.toBeNull(); expect(checkbox.getAttribute("aria-checked")).toBe("true"); @@ -98,13 +117,13 @@ it("lets the owner limit a new personal connection to this agent", async () => { it("keeps default-update failures visible and retries without another provider login", async () => { await mount([account()]); - click("Connect another account"); + await click("Connect another account"); mocks.setDefault.mockRejectedValueOnce(new Error("Default update failed")); credentialProps!.onComplete({ connectionId: "new-connection", grantId: "new-grant", method: "api_key" }); await settle(); expect(document.body.textContent).toContain("Default update failed"); expect(onChange).not.toHaveBeenCalled(); - click("Retry default selection"); + await click("Retry default selection"); await settle(); expect(mocks.setDefault).toHaveBeenCalledTimes(2); expect(onChange).toHaveBeenCalledWith({ provider: "anthropic", method: "api_key", mode: "responsible_user" }); @@ -117,12 +136,14 @@ it("does not offer reconnection for a healthy default or another owner's account it("keeps an ordinary member's new connection scoped to the current agent by default", async () => { await mount([], false); - click("Connect another account"); + expect(document.body.textContent).toContain("You have no default account"); + await click("Connect another account"); + expect(document.querySelector('[role="checkbox"]')!.disabled).toBe(true); expect(credentialProps).toMatchObject({ allAgents: false, agentIds: ["agent"] }); }); it("uses the server's connection-manager permission for company-wide access", async () => { await mount([], true); - click("Connect another account"); + await click("Connect another account"); expect(credentialProps).toMatchObject({ allAgents: true }); }); diff --git a/ui/src/components/ai-connections/AiConnectionField.tsx b/ui/src/components/ai-connections/AiConnectionField.tsx index 726cfa24f85..0af1ab54331 100644 --- a/ui/src/components/ai-connections/AiConnectionField.tsx +++ b/ui/src/components/ai-connections/AiConnectionField.tsx @@ -3,16 +3,17 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { aiConnectionBindingSchema, isAiConnectionCompatible, - type AiConnectionBinding, type AiRuntimeConnectionBinding, type AiAuthMethod, + type AiConnectionBinding, type AiProvider, type AiManagedConnectionSummary, } from "@paperclipai/shared"; import { aiConnectionsApi } from "@/api/ai-connections"; -import { AiConnectionPicker } from "./AiConnectionPicker"; -import { AiConnectionLegacyNotice } from "./AiConnectionManagement"; +import { AiConnectionSelect } from "./AiConnectionSelect"; +import { AiProviderSetup } from "./AiProviderSetup"; import { AiConnectionCredentialStep } from "./AiConnectionCredentialStep"; +import { AiConnectionLegacyNotice } from "./AiConnectionManagement"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { @@ -33,6 +34,8 @@ export function aiProviderForAdapter( codex_local: "openai", opencode_local: "openrouter", grok_local: "xai", + gemini_local: "google", + hermes_local: "openrouter", } as Record )[adapterType]; } @@ -47,6 +50,7 @@ export function AiConnectionField({ environmentId, legacy = false, readOnly = false, + preferAdvanced = false, routerAdapterType, }: { companyId: string; @@ -59,6 +63,7 @@ export function AiConnectionField({ environmentId?: string; legacy?: boolean; readOnly?: boolean; + preferAdvanced?: boolean; routerAdapterType?: string; }) { const provider = aiProviderForAdapter(adapterType); @@ -67,6 +72,7 @@ export function AiConnectionField({ const [adopting, setAdopting] = useState(false); const [pendingAdoption, setPendingAdoption] = useState(); const [connecting, setConnecting] = useState(false); + const [advancedSetup, setAdvancedSetup] = useState(false); const [reconnecting, setReconnecting] = useState(); const [allAgents, setAllAgents] = useState(true); const [savedAccount, setSavedAccount] = useState<{ connectionId: string; grantId: string; method: AiAuthMethod }>(); @@ -97,6 +103,7 @@ export function AiConnectionField({ const openConnection = (reconnect?: AiManagedConnectionSummary) => { returnFocus.current = document.activeElement as HTMLElement; setReconnecting(reconnect); + setAdvancedSetup(!reconnect && (preferAdvanced || provider === "openrouter")); setAllAgents(accounts.data?.canManageConnections ?? false); setSavedAccount(undefined); selectDefault.reset(); @@ -104,7 +111,7 @@ export function AiConnectionField({ }; const method: AiAuthMethod = (value && value.mode !== "router" && value.mode !== "responsible_user" ? value.method : undefined) ?? accounts.data?.connections.find((account) => account.provider === provider && account.isDefault)?.method - ?? (provider === "openrouter" ? "api_key" : "subscription"); + ?? (provider === "openrouter" || provider === "google" ? "api_key" : "subscription"); const compatiblePools = agentId ? accounts.data?.pools?.filter(pool => pool.enabled && pool.members.some(member => isAiConnectionCompatible(member.binding, routerAdapterType ?? adapterType, member.profile.model, member.profile.provider, member.profile.acpxAgent))) ?? [] : []; if (!provider) return null; if (legacy && !value && !adopting) @@ -134,7 +141,8 @@ export function AiConnectionField({ {value?.mode === "router" && New tasks rotate. Existing tasks keep their account.} } - {value?.mode !== "router" && {reconnecting ? "Reconnect account" : "Connect account"} - {reconnecting ? "Sign in again to repair your current default account. Its agent access stays the same." : "This account will become your default for this provider. Your tasks will use it; other users keep their own default."} + {advancedSetup ? "Choose a provider connection for this agent." : reconnecting ? "Sign in again to repair your current default account. Its agent access stays the same." : "This account will become your default for this provider. Your tasks will use it; other users keep their own default."} + {advancedSetup ? preferAdvanced ? setConnecting(false) : setAdvancedSetup(false)} + onComplete={binding => { + void client.invalidateQueries({ queryKey: ["ai-connections", companyId] }); + setConnecting(false); + changeBinding(binding); + }} + /> : <> {!reconnecting && !savedAccount && } {savedAccount ?
@@ -217,7 +236,7 @@ export function AiConnectionField({ initialMethod={reconnecting?.method ?? method} fixedMethod={Boolean(reconnecting)} connectionId={reconnecting?.id} - name={reconnecting?.name ?? `My ${provider === "anthropic" ? "Claude" : provider === "openai" ? "OpenAI" : provider === "xai" ? "Grok" : "OpenRouter"} ${method === "subscription" ? "subscription" : "API"}`} + name={reconnecting?.name ?? `My ${provider === "anthropic" ? "Claude" : provider === "openai" ? "OpenAI" : provider === "xai" ? "Grok" : provider === "google" ? "Gemini" : "OpenRouter"} ${method === "subscription" ? "subscription" : "API"}`} ownership="personal" agentIds={agentId ? [agentId] : []} allAgents={allAgents} @@ -228,6 +247,11 @@ export function AiConnectionField({ selectDefault.mutate(result); }} />} + {!reconnecting && !savedAccount &&
+ Advanced providers + +
} + }
diff --git a/ui/src/components/ai-connections/AiConnectionSelect.tsx b/ui/src/components/ai-connections/AiConnectionSelect.tsx new file mode 100644 index 00000000000..bb5fbbe04ec --- /dev/null +++ b/ui/src/components/ai-connections/AiConnectionSelect.tsx @@ -0,0 +1,192 @@ +import { useId } from "react"; +import { Plus, UserRound } from "lucide-react"; +import { + aiConnectionCatalogSlug, + isAiConnectionCompatible, + type AiConnectionBinding, +} from "@paperclipai/shared"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { AppLogo } from "@/pages/apps/AppLogo"; +import { Button } from "@/components/ui/button"; +import { aiConnectionProblem, personalAiDefault } from "./model"; +import type { AiConnectionPickerProps } from "./AiConnectionPicker"; +import type { AiConnectionSummary } from "./model"; + +function ConnectionLabel({ connection, label }: { connection: AiConnectionSummary; label?: string }) { + return ( + + + {label ?? connection.name} + + ); +} + +/** The same connection control on Create agent and Harness / Runtime. */ +export function AiConnectionSelect({ + requirement, + connections, + value, + currentUserId, + readOnly, + loading, + error, + onRetry, + onConnect, + onReconnect, + onChange, + adapterType, +}: AiConnectionPickerProps & { adapterType: string }) { + const selectId = useId(); + const personal = personalAiDefault(connections, requirement, currentUserId); + const selected = + value?.mode === "responsible_user" + ? personal + : connections.find( + (c) => c.id === value?.connectionId && c.grantId === value?.grantId, + ); + const compatible = connections + .filter( + (c) => + c.companyId === requirement.companyId && + isAiConnectionCompatible( + c, + adapterType, + c.provider === "openrouter" ? "openrouter/" : undefined, + ), + ) + .sort( + (a, b) => + Number(b.id === selected?.id) - Number(a.id === selected?.id) || + Number(Boolean(a.routing)) - Number(Boolean(b.routing)) || + a.name.localeCompare(b.name), + ); + const unavailable = Boolean( + value && + value.mode !== "responsible_user" && + !selected && + !loading && + !error, + ); + const canUseDefault = isAiConnectionCompatible( + { + provider: requirement.provider, + method: "api_key", + mode: "responsible_user", + }, + adapterType, + requirement.provider === "openrouter" ? "openrouter/" : undefined, + ); + const incompatible = + selected && !compatible.some((c) => c.id === selected.id); + const change = (id: string) => { + if (id === "connect") return onConnect(); + if (id === "responsible_user") + return onChange({ + provider: requirement.provider, + method: personal?.method ?? "api_key", + mode: "responsible_user", + }); + const connection = compatible.find((c) => c.id === id); + if (!connection) return; + onChange({ + provider: connection.provider, + method: connection.method, + mode: connection.ownership === "shared" ? "shared" : "delegated", + connectionId: connection.id, + grantId: connection.grantId, + } satisfies AiConnectionBinding); + }; + return ( +
+ + + {!readOnly && onReconnect && !loading && !error && ( + + )} + {error && ( +
+

+ {error} +

+ +
+ )} + {value?.mode === "responsible_user" && !personal && !loading && !error ? ( +

+ You have no default account for this provider. Connect an account or choose another connection. +

+ ) : unavailable ? ( +

+ This connection is unavailable. Choose another connection. +

+ ) : incompatible ? ( +

+ This connection does not support the selected harness. Choose a + compatible connection. +

+ ) : selected && aiConnectionProblem(selected) ? ( +

+ {aiConnectionProblem(selected)} +

+ ) : null} +
+ ); +} diff --git a/ui/src/components/ai-connections/AiProviderSetup.test.tsx b/ui/src/components/ai-connections/AiProviderSetup.test.tsx new file mode 100644 index 00000000000..eb60c665dad --- /dev/null +++ b/ui/src/components/ai-connections/AiProviderSetup.test.tsx @@ -0,0 +1,99 @@ +// @vitest-environment jsdom +import { act, type ComponentProps } from "react"; +import { createRoot } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { expect, it, vi } from "vitest"; +import { AiProviderSetup } from "./AiProviderSetup"; +import { aiConnectionsApi } from "@/api/ai-connections"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { aiProviderSetupPreset } from "@paperclipai/shared"; +import type { AiConnectionCredentialStep } from "./AiConnectionCredentialStep"; + +let credentialProps: ComponentProps | undefined; +vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: { create: vi.fn(async () => ({ connectionId: "connection", grantId: "grant" })), list: vi.fn(async () => ({ currentUserId: "owner", connections: [], canManageConnections: true })) } })); +vi.mock("@/api/agents", () => ({ agentsApi: { list: vi.fn(async () => []) } })); +vi.mock("./AiConnectionCredentialStep", () => ({ AiConnectionCredentialStep: (props: ComponentProps) => { credentialProps = props; return
Existing credential flow
; } })); + +it("reconnects an older OpenRouter account without adding routing metadata", async () => { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const container = document.createElement("div"); + const root = createRoot(container); + const onComplete = vi.fn(); + const account = { id: "connection", grantId: "grant", companyId: "company", provider: "openrouter", method: "api_key", name: "Existing OpenRouter", ownership: "personal", ownerUserId: "owner", isDefault: true, status: "needs_attention" } as const; + try { + await act(async () => root.render( {}} onComplete={onComplete} />)); + expect(container.textContent).toContain("Existing credential flow"); + expect(credentialProps).toMatchObject({ connectionId: account.id, provider: "openrouter", initialMethod: "api_key", fixedMethod: true }); + credentialProps!.onComplete({ connectionId: account.id, grantId: account.grantId, method: "api_key" }); + expect(onComplete).toHaveBeenCalledWith({ provider: "openrouter", method: "api_key", mode: "delegated", connectionId: account.id, grantId: account.grantId }); + } finally { + await act(async () => root.unmount()); + client.clear(); + } +}); + +const providerSources = ["openrouter", "bedrock", "responses-api", "messages-api", "chat-completions-api", "local"]; +it("shows advanced providers directly when entered from advanced connection mode", async () => { + const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } }); + client.setQueryData(["ai-connections", "company", undefined], { canManageConnections: true, connections: [] }); + client.setQueryData(["agents", "company", "provider-access"], []); + const container = document.createElement("div"); + const root = createRoot(container); + try { + await act(async () => root.render( {}} onComplete={() => {}} />)); + const choices = Array.from(container.querySelectorAll("button[aria-label]")).map(button => button.getAttribute("aria-label")); + expect(choices).toEqual(["OpenRouter", "Amazon Bedrock", "Custom gateway", "Local endpoint"]); + expect(container.querySelector("details")).toBeNull(); + } finally { + await act(async () => root.unmount()); client.clear(); + } +}); + +it.each(providerSources)("opens %s directly with shared access folded under Advanced", async source => { + const preset = aiProviderSetupPreset(source)!; + const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } }); + client.setQueryData(["ai-connections", "company", undefined], { canManageConnections: true, connections: [] }); + client.setQueryData(["agents", "company", "provider-access"], [{ id: "agent", name: "Nova" }]); + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + const onCancel = vi.fn(); + try { + await act(async () => root.render( {}} />)); + expect(container.textContent).not.toContain("Connect a model provider"); + expect(container.textContent).toContain("Connects for everyone in your organization, available to all agents."); + expect(container.querySelector('[role="radio"]')).toBeNull(); + const change = Array.from(container.querySelectorAll('button')).find(b => b.textContent === "Change")!; + expect(change.getAttribute("aria-expanded")).toBe("false"); + await act(async () => change.click()); + const radio = (text: string) => Array.from(container.querySelectorAll('[role="radio"]')).find(b => b.textContent?.includes(text)) as HTMLButtonElement; + expect(radio("Any human in the organization").getAttribute("aria-checked")).toBe("true"); + expect(radio("Any agent").getAttribute("aria-checked")).toBe("true"); + await act(async () => radio("Just me").click()); + expect(container.textContent).toContain("Connects as you, available to all agents."); + await act(async () => Array.from(container.querySelectorAll('button')).find(b => b.textContent === "Back")!.click()); + expect(onCancel).toHaveBeenCalledOnce(); + } finally { + await act(async () => root.unmount()); container.remove(); client.clear(); + } +}); + +it("saves the default organization grant and all-agent installation from the direct connect screen", async () => { + const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } }); + client.setQueryData(["ai-connections", "company", undefined], { canManageConnections: true, connections: [] }); + client.setQueryData(["agents", "company", "provider-access"], []); + const container = document.createElement("div"); + const root = createRoot(container); + try { + await act(async () => root.render( {}} onComplete={() => {}} />)); + const input = container.querySelector('input[aria-label="API key"]')!; + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "fixture-key"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + await act(async () => container.querySelector('form')!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }))); + expect(aiConnectionsApi.create).toHaveBeenCalledWith("company", expect.objectContaining({ ownership: "shared", allAgents: true, agentIds: [], apiKey: "fixture-key", routing: expect.objectContaining({ kind: "openrouter" }) })); + } finally { + await act(async () => root.unmount()); client.clear(); + } +}); diff --git a/ui/src/components/ai-connections/AiProviderSetup.tsx b/ui/src/components/ai-connections/AiProviderSetup.tsx new file mode 100644 index 00000000000..76dfc0388d5 --- /dev/null +++ b/ui/src/components/ai-connections/AiProviderSetup.tsx @@ -0,0 +1,468 @@ +import { useState } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Network, Monitor } from "lucide-react"; +import { + aiProviderRoutingSchema, + createAiConnectionSchema, + type AiProvider, + type AiProviderRouting, + type AiConnectionBinding, + type AiManagedConnectionSummary, +} from "@paperclipai/shared"; +import { aiConnectionsApi } from "@/api/ai-connections"; +import { agentsApi } from "@/api/agents"; +import { ConnectionChoiceList } from "@/features/connections/ConnectionChoiceList"; +import { ConnectionAccessDefaults, connectionDefaultSummarySentence } from "@/features/connections/ConnectionSetupFlow"; +import { AppLogo } from "@/pages/apps/AppLogo"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { AiConnectionCredentialStep } from "./AiConnectionCredentialStep"; + +const providers = [ + { + id: "openai", + name: "OpenAI", + description: "ChatGPT subscription or API key", + }, + { + id: "anthropic", + name: "Anthropic", + description: "Claude subscription or API key", + }, + { id: "google", name: "Google", description: "Gemini API key" }, + { id: "xai", name: "xAI", description: "Grok subscription or API key" }, + { + id: "openrouter", + name: "OpenRouter", + description: "Models through one API key", + advanced: true, + }, + { + id: "bedrock", + name: "Amazon Bedrock", + description: "Bedrock API key and AWS region", + advanced: true, + }, + { + id: "gateway", + name: "Custom gateway", + description: "Emissary or another compatible endpoint", + advanced: true, + }, + { + id: "local", + name: "Local endpoint", + description: "A model server in the agent’s environment", + advanced: true, + }, +] as const; +type ProviderChoice = (typeof providers)[number]["id"]; + +export function AiProviderSetup({ + companyId, + agentId, + environmentId, + initialProvider, + initialProtocol, + providerLabel, + advancedOnly = false, + reconnect, + onCancel, + onComplete, +}: { + companyId: string; + agentId?: string; + environmentId?: string; + initialProvider?: ProviderChoice; + initialProtocol?: AiProviderRouting["protocol"]; + providerLabel?: string; + advancedOnly?: boolean; + reconnect?: AiManagedConnectionSummary; + onCancel: () => void; + onComplete: ( + binding: Exclude, + ) => void; +}) { + const [provider, setProvider] = useState( + reconnect + ? reconnect.routing?.kind === "gateway" || + reconnect.routing?.kind === "local" || + reconnect.routing?.kind === "bedrock" + ? reconnect.routing.kind + : reconnect.provider + : initialProvider, + ); + const [step, setStep] = useState( + reconnect || initialProvider ? "connect" : "provider", + ); + const [ownershipChoice, setOwnership] = useState<"personal" | "shared">(); + const [allAgentsChoice, setAllAgents] = useState(); + const [agentIds, setAgentIds] = useState(new Set(agentId ? [agentId] : [])); + const [protocol, setProtocol] = useState( + reconnect?.routing?.protocol ?? initialProtocol ?? "responses", + ); + const [auth, setAuth] = useState( + reconnect?.routing?.auth ?? "bearer", + ); + const [baseUrl, setBaseUrl] = useState(reconnect?.routing?.baseUrl ?? ""); + const [region, setRegion] = useState( + reconnect?.routing?.region ?? "us-east-1", + ); + const [models, setModels] = useState( + reconnect?.routing?.models.map((m) => m.id).join(", ") ?? "", + ); + const [apiKey, setApiKey] = useState(""); + const client = useQueryClient(); + const accounts = useQuery({ + queryKey: ["ai-connections", companyId, agentId], + queryFn: () => aiConnectionsApi.list(companyId, agentId), + }); + const canManageConnections = accounts.data?.canManageConnections ?? false; + const ownership = reconnect?.ownership ?? ownershipChoice ?? (!agentId && canManageConnections ? "shared" : "personal"); + const allAgents = allAgentsChoice ?? (!agentId && canManageConnections); + const agents = useQuery({ + queryKey: ["agents", companyId, "provider-access"], + queryFn: () => agentsApi.list(companyId), + }); + const label = providerLabel ?? providers.find((p) => p.id === provider)?.name ?? "provider"; + const advanced = reconnect ? Boolean(reconnect.routing) : ["openrouter", "bedrock", "gateway", "local"].includes(provider ?? ""); + const nativeProvider: AiProvider = + provider === "bedrock" + ? "anthropic" + : provider === "gateway" || provider === "local" + ? protocol === "messages" + ? "anthropic" + : "openai" + : (provider ?? "openai"); + const name = + reconnect?.name ?? + `${ownership === "personal" ? "My" : "Company"} ${ + provider === "gateway" && baseUrl + ? (() => { + try { + return new URL(baseUrl).hostname; + } catch { + return label; + } + })() + : label + }`; + const complete = (result: { + connectionId: string; + grantId: string; + method?: "api_key" | "subscription"; + }) => { + void client.invalidateQueries({ queryKey: ["ai-connections", companyId] }); + void client.invalidateQueries({ queryKey: ["tools"] }); + onComplete({ + provider: nativeProvider, + method: result.method ?? "api_key", + mode: ownership === "shared" ? "shared" : "delegated", + ...result, + }); + }; + const save = useMutation({ + mutationFn: () => { + const routing = + reconnect?.routing ?? + aiProviderRoutingSchema.parse({ + kind: provider, + protocol: provider === "bedrock" ? "bedrock" : protocol, + auth: provider === "openrouter" ? "bearer" : auth, + ...(provider === "bedrock" + ? { region } + : provider === "gateway" || provider === "local" + ? { baseUrl } + : {}), + models: models + .split(",") + .map((id) => id.trim()) + .filter(Boolean) + .map((id) => ({ id })), + }); + return aiConnectionsApi.create( + companyId, + createAiConnectionSchema.parse({ + provider: nativeProvider, + method: "api_key", + name, + ownership, + allAgents, + agentIds: [...agentIds], + connectionId: reconnect?.id, + routing, + ...(auth !== "none" ? { apiKey } : {}), + }), + ); + }, + onSuccess: complete, + onSettled: () => { + setApiKey(""); + }, + }); + const choices = (advancedOnly: boolean) => ( + Boolean("advanced" in p && p.advanced) === advancedOnly) + .map((p) => ({ + ...p, + icon: + p.id === "gateway" || p.id === "local" ? ( + + {p.id === "gateway" ? ( + + ) : ( + + )} + + ) : ( + + ), + }))} + onSelect={(id) => { + setProvider(id as ProviderChoice); + setStep("connect"); + setApiKey(""); + setAuth("bearer"); + save.reset(); + }} + /> + ); + const modelSettings = ( + + ); + const accessDefaults = !reconnect ? ( + setOwnership(kind === "organization" ? "shared" : "personal")} + installChoice={allAgents ? "all" : "specific"} + setInstallChoice={choice => setAllAgents(choice === "all")} + installAgentIds={agentIds} + setInstallAgentIds={setAgentIds} + disabled={save.isPending} + notice={!canManageConnections ? ["Only a connection manager can share this credential with everyone or give every agent access."] : undefined} + /> + ) : undefined; + const cancel = () => reconnect || initialProvider ? onCancel() : setStep("provider"); + if (!reconnect && accounts.isPending) return

Loading connection permissions…

; + if (!reconnect && accounts.isError) return

Could not load connection permissions.

; + return ( +
event.stopPropagation()}> +
+

+ {step === "provider" + ? "Connect a model provider" + : `${reconnect ? "Reconnect" : "Connect"} ${label}`} +

+
+ {agents.isError &&

Could not load agents.

} + {step === "provider" ? ( + <> + {advancedOnly ? choices(true) : <> + {choices(false)} +
+ + Advanced providers + +
{choices(true)}
+
+ } + + + ) : !advanced ? ( + + ) : ( +
{ + e.preventDefault(); + save.mutate(); + }} + > + {(provider === "gateway" || provider === "local") && ( + <> + + + + )} + {provider === "bedrock" && ( + + )} + {provider !== "openrouter" && ( + + )} + { + auth !== "none" && ( + + ) + } + {reconnect &&
Model settings{modelSettings}
} +

+ Test the connection with your chosen model in the agent’s execution + environment after connecting. +

+ {save.error && ( +

+ {save.error instanceof Error && save.error.name === "ZodError" + ? "Check the URL, API format, and authentication fields." + : save.error.message} +

+ )} + {accessDefaults} +
+ + +
+
+ )} +
+ ); +} diff --git a/ui/src/components/ui/select.tsx b/ui/src/components/ui/select.tsx index fa2a98a1eb9..9c35a9b2409 100644 --- a/ui/src/components/ui/select.tsx +++ b/ui/src/components/ui/select.tsx @@ -4,6 +4,15 @@ import { Select as SelectPrimitive } from "radix-ui" import { cn } from "@/lib/utils" +export const nativeSelectClassName = "w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-sm leading-5 outline-none focus-visible:ring-2 focus-visible:ring-ring" + +export function NativeSelect({ className, ...props }: React.ComponentProps<"select">) { + return