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 <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-06 09:51:13 -05:00
1 parent fa9b3d22a1
commit 3bb36afcd9
24 files changed
+945 -265

No files matched your search

@@ -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/<id>/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<string, unknown> | undefined;
if (config.agent === "gemini" && !(typeof configuredEnv?.HOME === "string" && configuredEnv.HOME.trim())) {
defaultGeminiTestHome ??= await makeTempRoot();
config = { ...config, env: { ...configuredEnv, HOME: defaultGeminiTestHome } };
}
const runtimeOptions: Record<string, unknown>[] = [];
const configOptions: Array<{ key: string; value: string }> = [];
const sessionInputs: Record<string, unknown>[] = [];
@@ -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<string, string>).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<string, string>).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<Record<string, unknown>> = [];
@@ -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}.`,
]
: []),
@@ -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.
@@ -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.
`;
@@ -163,18 +163,6 @@ async function makeCtx(runId: string, cwd: string): Promise<AdapterExecutionCont
}
describe("grok_local execute", () => {
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" }));
@@ -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<AdapterExecuti
const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? "");
const runtimeSessionCwd = asString(runtimeSessionParams.cwd, "");
const runtimeRemoteExecution = parseObject(runtimeSessionParams.remoteExecution);
const missingManagedSession = !executionTargetIsRemote && Boolean(config.managedAiConnection) &&
Boolean(runtimeSessionId) && !await grokHomeHasSession(asString(env.GROK_HOME, ""), runtimeSessionId);
const canResumeSession =
runtimeSessionId.length > 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<AdapterExecuti
stderrLine ||
`Grok exited with code ${attempt.proc.exitCode ?? -1}`;
const canFallbackToRuntimeSession = !isRetry && !missingManagedSession;
const canFallbackToRuntimeSession = !isRetry;
const resolvedSessionId = attempt.parsed.sessionId
?? (canFallbackToRuntimeSession ? (runtimeSessionId ?? runtime.sessionId ?? null) : null);
const resolvedSessionParams = resolvedSessionId
@@ -727,7 +722,7 @@ async function executeTurn(ctx: AdapterExecutionContext): Promise<AdapterExecuti
return toResult(retry, true, true);
}
return toResult(initial, missingManagedSession);
return toResult(initial);
};
try {
@@ -3,30 +3,7 @@ import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { GROK_SYNC_ALLOWLIST, grokHomeHasSession, stageGrokHomeForSync } from "./grok-home.js";
describe("grokHomeHasSession", () => {
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", () => {
@@ -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 `<issuer>::<uuid>` 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<boolean> {
if (!home || !/^[a-zA-Z0-9_-]{1,128}$/.test(sessionId)) return false;
let remaining = 5000;
async function inspect(directory: string, depth: number): Promise<boolean> {
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}).
+3 -13
View File
@@ -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(() => {});
+21 -23
View File
@@ -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-"));
@@ -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 {
+11 -22
View File
@@ -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: {
@@ -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);
@@ -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<string>((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);
@@ -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 <ApiKeyConnectionStep {...props} />;
if (props.provider === "openrouter" || props.provider === "google") return <ApiKeyConnectionStep {...props} />;
return <SubscriptionConnectionStep {...props} />;
}
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<string>();
const client = useQueryClient();
@@ -82,6 +84,7 @@ function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedM
<SelectContent>{loginEnvironments.map((env) => <SelectItem key={env.id} value={env.id}>{env.name}</SelectItem>)}</SelectContent>
</Select>}
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
{defaults}
{loading ? <p role="status" className="text-sm text-muted-foreground">Preparing sign-in…</p> : <AgentProviderConnection
key={environmentId ?? "local"}
companyId={companyId}
@@ -92,24 +95,25 @@ function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedM
onBack={onCancel}
onConnected={() => {}}
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); } }}
/>}
</div>;
}
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 <div className="mx-auto w-full min-w-0 max-w-xl space-y-4">
{!hideName && <label className="block space-y-2 text-sm">Connection name<Input value={name} onChange={(event) => setName(event.target.value)} disabled={Boolean(connectionId)} /></label>}
{save.error && <p role="alert" className="text-sm text-destructive">{save.error.message}</p>}
<ProviderApiKeyCard providerName="OpenRouter" value={apiKey} onChange={setApiKey} onSubmit={() => save.mutate()} disabled={save.isPending} placeholder="Enter API key here" autoFocus />
<div className="flex justify-between gap-2"><Button variant="ghost" onClick={onCancel}>Cancel</Button><Button disabled={!name.trim() || !apiKey.trim() || save.isPending} onClick={() => save.mutate()}>{save.isPending ? "Connecting…" : "Connect"}</Button></div>
<ProviderApiKeyCard providerName={provider === "google" ? "Google" : "OpenRouter"} value={apiKey} onChange={setApiKey} onSubmit={() => save.mutate()} disabled={disabled || save.isPending} placeholder="Enter API key here" autoFocus />
{defaults}
<div className="flex justify-between gap-2"><Button variant="ghost" onClick={onCancel}>Cancel</Button><Button disabled={disabled || !name.trim() || !apiKey.trim() || save.isPending} onClick={() => save.mutate()}>{save.isPending ? "Connecting…" : "Connect"}</Button></div>
</div>;
}
@@ -18,6 +18,7 @@ vi.mock("./AiConnectionCredentialStep", () => ({
},
}));
vi.mock("./AiConnectionManagement", () => ({ AiConnectionLegacyNotice: () => null }));
vi.mock("./AiProviderSetup", () => ({ AiProviderSetup: () => <div>Advanced provider setup</div> }));
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(<QueryClientProvider client={client}>
<AiConnectionField companyId="company" agentId="agent" agentName="Nova" adapterType="claude_local"
preferAdvanced={preferAdvanced}
value={{ provider: "anthropic", method: "subscription", mode: "responsible_user" }} onChange={onChange} />
</QueryClientProvider>));
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<HTMLElement>('[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<HTMLButtonElement>('[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<HTMLButtonElement>('[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 });
});
@@ -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<string, AiProvider>
)[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<AiRuntimeConnectionBinding>();
const [connecting, setConnecting] = useState(false);
const [advancedSetup, setAdvancedSetup] = useState(false);
const [reconnecting, setReconnecting] = useState<AiManagedConnectionSummary>();
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({
</select>
{value?.mode === "router" && <span className="text-muted-foreground">New tasks rotate. Existing tasks keep their account.</span>}
</label>}
{value?.mode !== "router" && <AiConnectionPicker
{value?.mode !== "router" && <AiConnectionSelect
adapterType={adapterType}
requirement={{ companyId, provider }}
connections={accounts.data?.connections ?? []}
value={value}
@@ -198,11 +206,22 @@ export function AiConnectionField({
<DialogHeader>
<DialogTitle>{reconnecting ? "Reconnect account" : "Connect account"}</DialogTitle>
<DialogDescription>
{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."}
</DialogDescription>
</DialogHeader>
{advancedSetup ? <AiProviderSetup
companyId={companyId} agentId={agentId} environmentId={environmentId}
advancedOnly={preferAdvanced}
initialProtocol={adapterType === "claude_local" ? "messages" : adapterType === "codex_local" ? "responses" : "chat"}
onCancel={() => preferAdvanced ? setConnecting(false) : setAdvancedSetup(false)}
onComplete={binding => {
void client.invalidateQueries({ queryKey: ["ai-connections", companyId] });
setConnecting(false);
changeBinding(binding);
}}
/> : <>
{!reconnecting && !savedAccount && <label className="flex items-center gap-2 text-sm">
<Checkbox checked={allAgents} onCheckedChange={(checked) => setAllAgents(checked === true)} />
<Checkbox checked={allAgents} disabled={!accounts.data?.canManageConnections} onCheckedChange={(checked) => setAllAgents(checked === true)} />
Allow all agents in this company to use this account for my tasks
</label>}
{savedAccount ? <div className="space-y-4">
@@ -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 && <details>
<summary className="cursor-pointer text-sm text-muted-foreground">Advanced providers</summary>
<Button type="button" variant="ghost" onClick={() => setAdvancedSetup(true)}>Choose another provider or gateway</Button>
</details>}
</>}
</DialogContent>
</Dialog>
</div>
@@ -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 (
<span className="flex min-w-0 items-center gap-2">
<AppLogo name={connection.name} brandKey={aiConnectionCatalogSlug(connection.provider, connection.routing)} size={20} compact />
<span className="truncate">{label ?? connection.name}</span>
</span>
);
}
/** 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 (
<div className="space-y-2">
<label className="text-xs text-muted-foreground" htmlFor={selectId}>
Connection
</label>
<Select
value={
value?.mode === "responsible_user"
? "responsible_user"
: (value?.connectionId ?? "")
}
onValueChange={change}
disabled={readOnly || loading || Boolean(error)}
>
<SelectTrigger id={selectId} aria-label="Connection" className="w-full">
<SelectValue
placeholder={
loading ? "Loading connections…" : "Choose a connection"
}
>
{selected
? <ConnectionLabel connection={selected} label={value?.mode === "responsible_user" ? "Responsible user’s default" : undefined} />
: value?.mode === "responsible_user"
? "Responsible user’s default"
: value ? "Unavailable connection" : undefined}
</SelectValue>
</SelectTrigger>
<SelectContent>
{incompatible && selected && (
<SelectItem value={selected.id} disabled>
<ConnectionLabel connection={selected} label={`${selected.name} · Incompatible`} />
</SelectItem>
)}
{compatible.map((c) => (
<SelectItem
key={c.id}
value={c.id}
disabled={Boolean(aiConnectionProblem(c))}
>
<ConnectionLabel connection={c} label={`${c.name}${c.status !== "connected" ? " · Reconnect" : ""}`} />
</SelectItem>
))}
{(canUseDefault || value?.mode === "responsible_user") && (
<SelectItem value="responsible_user" disabled={!canUseDefault}>
<span className="flex size-5 shrink-0 items-center justify-center"><UserRound className="size-4" /></span>
Responsible user’s default
</SelectItem>
)}
<SelectItem value="connect">
<span className="flex size-5 shrink-0 items-center justify-center"><Plus className="size-4" /></span>
Connect an account…
</SelectItem>
</SelectContent>
</Select>
{!readOnly && onReconnect && !loading && !error && (
<Button type="button" variant="outline" onClick={onReconnect}>Reconnect account</Button>
)}
{error && (
<div className="space-y-2">
<p role="alert" className="text-sm text-destructive">
{error}
</p>
<Button type="button" variant="outline" onClick={onRetry}>
Retry connections
</Button>
</div>
)}
{value?.mode === "responsible_user" && !personal && !loading && !error ? (
<p role="alert" className="text-sm text-destructive">
You have no default account for this provider. Connect an account or choose another connection.
</p>
) : unavailable ? (
<p role="alert" className="text-sm text-destructive">
This connection is unavailable. Choose another connection.
</p>
) : incompatible ? (
<p role="alert" className="text-sm text-destructive">
This connection does not support the selected harness. Choose a
compatible connection.
</p>
) : selected && aiConnectionProblem(selected) ? (
<p role="alert" className="text-sm text-destructive">
{aiConnectionProblem(selected)}
</p>
) : null}
</div>
);
}
@@ -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<typeof AiConnectionCredentialStep> | 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<typeof AiConnectionCredentialStep>) => { credentialProps = props; return <div>Existing credential flow</div>; } }));
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(<QueryClientProvider client={client}><AiProviderSetup companyId="company" reconnect={account} onCancel={() => {}} onComplete={onComplete} /></QueryClientProvider>));
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(<QueryClientProvider client={client}><AiProviderSetup companyId="company" advancedOnly onCancel={() => {}} onComplete={() => {}} /></QueryClientProvider>));
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(<QueryClientProvider client={client}><TooltipProvider><AiProviderSetup companyId="company" initialProvider={preset.provider} initialProtocol={preset.protocol} providerLabel={preset.label} onCancel={onCancel} onComplete={() => {}} /></TooltipProvider></QueryClientProvider>));
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(<QueryClientProvider client={client}><AiProviderSetup companyId="company" initialProvider="openrouter" onCancel={() => {}} onComplete={() => {}} /></QueryClientProvider>));
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();
}
});
@@ -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<AiConnectionBinding, { mode: "responsible_user" }>,
) => void;
}) {
const [provider, setProvider] = useState<ProviderChoice | undefined>(
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<boolean>();
const [agentIds, setAgentIds] = useState(new Set(agentId ? [agentId] : []));
const [protocol, setProtocol] = useState<AiProviderRouting["protocol"]>(
reconnect?.routing?.protocol ?? initialProtocol ?? "responses",
);
const [auth, setAuth] = useState<AiProviderRouting["auth"]>(
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) => (
<ConnectionChoiceList
choices={providers
.filter((p) => Boolean("advanced" in p && p.advanced) === advancedOnly)
.map((p) => ({
...p,
icon:
p.id === "gateway" || p.id === "local" ? (
<span className="flex size-9 items-center justify-center rounded-lg bg-muted">
{p.id === "gateway" ? (
<Network className="size-5" />
) : (
<Monitor className="size-5" />
)}
</span>
) : (
<AppLogo name={p.name} brandKey={p.id} />
),
}))}
onSelect={(id) => {
setProvider(id as ProviderChoice);
setStep("connect");
setApiKey("");
setAuth("bearer");
save.reset();
}}
/>
);
const modelSettings = (
<label className="block space-y-2 text-xs text-muted-foreground">
Model IDs (comma separated)
<Input
aria-label="Model IDs"
value={models}
onChange={(e) => setModels(e.target.value)}
disabled={Boolean(reconnect)}
/>
<span className="block">
Use the provider’s model ID or your gateway’s alias. You can
also enter one on the agent.
</span>
</label>
);
const accessDefaults = !reconnect ? (
<ConnectionAccessDefaults
companyId={companyId}
extra={advanced ? modelSettings : undefined}
agents={agents.data ?? []}
sentence={connectionDefaultSummarySentence({ grantKind: ownership === "shared" ? "organization" : "user", authKind: auth === "none" ? "none" : "api_key", installChoice: allAgents ? "all" : "specific", installCount: agentIds.size })}
capabilities={{ canCreateOrganizationGrant: canManageConnections, canSetCompanyInstall: canManageConnections }}
authKind={auth === "none" ? "none" : "api_key"}
grantKind={ownership === "shared" ? "organization" : "user"}
grantKinds={["user", "organization"]}
setGrantKind={kind => 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 <p role="status">Loading connection permissions…</p>;
if (!reconnect && accounts.isError) return <p role="alert">Could not load connection permissions. <Button type="button" variant="ghost" onClick={() => void accounts.refetch()}>Retry</Button></p>;
return (
<div className="mx-auto w-full max-w-2xl space-y-6" onSubmit={(event) => event.stopPropagation()}>
<div className="space-y-2">
<h2 className="text-xl font-semibold">
{step === "provider"
? "Connect a model provider"
: `${reconnect ? "Reconnect" : "Connect"} ${label}`}
</h2>
</div>
{agents.isError && <p role="alert" className="text-sm text-destructive">Could not load agents. <Button type="button" variant="ghost" onClick={() => void agents.refetch()}>Retry</Button></p>}
{step === "provider" ? (
<>
{advancedOnly ? choices(true) : <>
{choices(false)}
<details>
<summary className="cursor-pointer text-sm text-muted-foreground">
Advanced providers
</summary>
<div className="pt-4">{choices(true)}</div>
</details>
</>}
<Button type="button" variant="ghost" onClick={onCancel}>
Cancel
</Button>
</>
) : !advanced ? (
<AiConnectionCredentialStep
companyId={companyId}
provider={nativeProvider}
connectionId={reconnect?.id}
initialMethod={reconnect?.method}
fixedMethod={Boolean(reconnect)}
name={name}
hideName
ownership={ownership}
allAgents={allAgents}
agentIds={[...agentIds]}
environmentId={environmentId}
onCancel={cancel}
defaults={accessDefaults}
disabled={!reconnect && !allAgents && agentIds.size === 0}
onComplete={complete}
/>
) : (
<form
className="space-y-5"
onSubmit={(e) => {
e.preventDefault();
save.mutate();
}}
>
{(provider === "gateway" || provider === "local") && (
<>
<label className="block space-y-2 text-xs text-muted-foreground">
Provider URL
<Input
aria-label="Provider URL"
placeholder={
provider === "local"
? "http://localhost:11434/v1"
: "https://gateway.example.com/v1"
}
value={baseUrl}
onChange={(e) => setBaseUrl(e.target.value)}
disabled={Boolean(reconnect)}
/>
</label>
<label className="block space-y-2 text-xs text-muted-foreground">
API format
<Select
value={protocol}
onValueChange={(v) => {
setProtocol(v as typeof protocol);
if (v !== "messages" && auth === "api_key")
setAuth("bearer");
}}
disabled={Boolean(reconnect) || Boolean(initialProtocol)}
>
<SelectTrigger aria-label="API format" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="responses">
OpenAI Responses · Codex
</SelectItem>
<SelectItem value="messages">
Anthropic Messages · Claude
</SelectItem>
<SelectItem value="chat">
Chat Completions · OpenCode, Hermes
</SelectItem>
</SelectContent>
</Select>
</label>
</>
)}
{provider === "bedrock" && (
<label className="block space-y-2 text-xs text-muted-foreground">
AWS region
<Input
aria-label="AWS region"
value={region}
onChange={(e) => setRegion(e.target.value)}
disabled={Boolean(reconnect)}
/>
</label>
)}
{provider !== "openrouter" && (
<label className="block space-y-2 text-xs text-muted-foreground">
Authentication
<Select
value={auth}
onValueChange={(v) => setAuth(v as typeof auth)}
disabled={Boolean(reconnect)}
>
<SelectTrigger aria-label="Authentication" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="bearer">
{provider === "bedrock"
? "Bedrock API key"
: "Bearer token"}
</SelectItem>
{provider !== "bedrock" && (
<>
{protocol === "messages" && (
<SelectItem value="api_key">
API key · x-api-key
</SelectItem>
)}
<SelectItem value="none">No authentication</SelectItem>
</>
)}
</SelectContent>
</Select>
</label>
)}
{
auth !== "none" && (
<label className="block space-y-2 text-xs text-muted-foreground">
API key
<Input
aria-label="API key"
type="password"
autoComplete="new-password"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
/>
</label>
)
}
{reconnect && <details><summary className="cursor-pointer text-sm text-muted-foreground">Model settings</summary>{modelSettings}</details>}
<p className="text-xs text-muted-foreground">
Test the connection with your chosen model in the agent’s execution
environment after connecting.
</p>
{save.error && (
<p role="alert" className="text-sm text-destructive">
{save.error instanceof Error && save.error.name === "ZodError"
? "Check the URL, API format, and authentication fields."
: save.error.message}
</p>
)}
{accessDefaults}
<div className="flex items-center justify-between gap-3">
<Button
type="button"
variant="ghost"
onClick={cancel}
disabled={save.isPending}
>
Back
</Button>
<Button
type="submit"
disabled={
save.isPending || accounts.isPending || accounts.isError ||
(!reconnect && !allAgents && agentIds.size === 0) ||
(auth !== "none" && !apiKey.trim())
}
>
{save.isPending
? "Connecting…"
: reconnect
? "Reconnect"
: "Connect"}
</Button>
</div>
</form>
)}
</div>
);
}
+10 -1
View File
@@ -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 <select {...props} className={cn(nativeSelectClassName, className)} />
}
// Shared with searchable picker triggers so their size and states match Select.
export const selectTriggerClassName = "border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-base md:text-sm whitespace-nowrap shadow-xs transition-(--tp-color-box-shadow) outline-none focus-visible:ring-(length:--rad-3) disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
@@ -35,7 +44,7 @@ function SelectTrigger({
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-base md:text-sm whitespace-nowrap shadow-xs transition-(--tp-color-box-shadow) outline-none focus-visible:ring-(length:--rad-3) disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
selectTriggerClassName,
className
)}
{...props}
@@ -3,7 +3,7 @@ import { Check, ChevronRight, Loader2 } from "lucide-react";
/** The account-reuse rows shared by connection setup and agent bindings. */
export function ConnectionChoiceList({ choices, selectedId, pendingId, disabled, onSelect }: {
choices: { id: string; name: string; description: ReactNode; disabled?: boolean }[];
choices: { id: string; name: string; description: ReactNode; icon?: ReactNode; disabled?: boolean }[];
selectedId?: string;
pendingId?: string | null;
disabled?: boolean;
@@ -19,7 +19,8 @@ export function ConnectionChoiceList({ choices, selectedId, pendingId, disabled,
disabled={disabled || Boolean(pendingId) || choice.disabled}
onClick={() => onSelect(choice.id)}
>
<span className="min-w-0">
{choice.icon && <span aria-hidden="true" className="shrink-0">{choice.icon}</span>}
<span className="min-w-0 flex-1">
<span className="block font-medium text-foreground">{choice.name}</span>
<span className="mt-1 block text-xs text-muted-foreground">{choice.description}</span>
</span>
@@ -2240,6 +2240,7 @@ function StandardConnectionSetupFlow({
const aiMethod = reconnectAiMethod ?? entry?.methods.find(method => method.key === connectionMethodKey)?.ai
?? (!connectionMethodKey && entry?.methods.every(method => method.ai) ? entry.methods[0]?.ai : undefined);
const credentialStep = entry ? renderCredentialStep?.({ app: entry, name: galleryName || entry.name, grantKind: effectiveGrantKind, agentIds: [...installAgentIds], allAgents: installChoice === "all", onBack: () => backToGallery() }) ?? (aiMethod && selectedCompanyId ? <><AiConnectionCredentialStep
defaults={reconnectConnection ? undefined : connectionDefaults}
companyId={selectedCompanyId} provider={aiMethod.provider} fixedMethod={Boolean(aiConnection && aiConnection.mode !== "responsible_user")} initialMethod={reconnectConnection?.connectionPurpose === "ai" ? (reconnectConnection.config?.ai as { method: "subscription" | "api_key" }).method : aiMethod.method}
connectionId={reconnectConnection?.connectionPurpose === "ai" ? reconnectConnection.id : undefined}
name={reconnectConnection?.connectionPurpose === "ai" ? reconnectConnection.name : galleryName || `My ${entry.name} ${aiMethod.method === "subscription" ? "subscription" : "API"}`}
+24 -2
View File
@@ -1,13 +1,15 @@
import { useQuery } from "@tanstack/react-query";
import { aiConnectionsApi } from "@/api/ai-connections";
import { AiProviderSetup } from "@/components/ai-connections/AiProviderSetup";
import { AiConnectionPoolConnector } from "@/components/ai-connections/AiConnectionPoolConnector";
import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { isRetiredComposioConnection } from "@paperclipai/shared";
import { findComposioCatalogApp } from "@paperclipai/shared/aggregator-app-catalog";
import { toolsApi } from "@/api/tools";
import { queryKeys } from "@/lib/queryKeys";
import { Button } from "@/components/ui/button";
import { ConnectionSetupFlow } from "@/features/connections/ConnectionSetupFlow";
import type { ToolConnectionCredentialSource } from "@paperclipai/shared";
import { aiProviderSetupPreset, type ToolConnectionCredentialSource } from "@paperclipai/shared";
import { useCompany } from "@/context/CompanyContext";
import { useNavigate, useParams, useSearchParams } from "@/lib/router";
import { consumeSkillSourceReturn, skillSourceReturnPath } from "@/lib/skill-source-connect-return";
@@ -24,6 +26,11 @@ export function AppsConnect({ byoOnly = false, credentialSource = "paperclip_vau
const [searchParams] = useSearchParams();
const { appKey } = useParams<{ appKey?: string }>();
const source = searchParams.get("source") ?? appKey ?? searchParams.get("appKey");
const reconnectId = searchParams.get("reconnect");
const preset = aiProviderSetupPreset(source);
const aiReconnectRequested = Boolean(reconnectId && (preset || ["openai", "anthropic", "xai"].includes(source ?? "")));
const aiAccounts = useQuery({ queryKey: ["ai-connections", selectedCompanyId], queryFn: () => aiConnectionsApi.list(selectedCompanyId!), enabled: Boolean(selectedCompanyId && aiReconnectRequested) });
const aiReconnect = aiAccounts.data?.connections.find(c => c.id === reconnectId);
const gallery = useQuery({ queryKey: queryKeys.apps.gallery(selectedCompanyId ?? "__none__"), queryFn: () => toolsApi.listGallery(selectedCompanyId!), enabled: !!selectedCompanyId && !!source?.startsWith("ai-router-") });
const router = gallery.data?.apps.find(app => app.slug === source)?.aiConnectionRouter;
const toolkit = searchParams.get("targetToolkit");
@@ -48,6 +55,21 @@ export function AppsConnect({ byoOnly = false, credentialSource = "paperclip_vau
const path = selectedCompanyId && consumeSkillSourceReturn(selectedCompanyId);
if (path) navigate(path);
}
if (aiReconnectRequested && aiAccounts.isPending) return <p role="status">Loading connection…</p>;
if (aiReconnectRequested && aiAccounts.isError) return <p role="alert">Could not load this connection. Refresh to try again.</p>;
if (aiReconnectRequested && !aiReconnect) return <p role="alert">This connection is unavailable. Return to Connectors to choose an account.</p>;
if (selectedCompanyId && (preset || aiReconnect?.routing)) return (
<AiProviderSetup
key={reconnectId ?? source}
companyId={selectedCompanyId}
reconnect={aiReconnect}
initialProvider={preset?.provider}
initialProtocol={preset?.protocol}
providerLabel={preset?.label}
onCancel={() => navigate("/apps")}
onComplete={binding => navigate(`/apps/${binding.connectionId}/permissions`)}
/>
);
if (source?.startsWith("ai-router-")) {
if (gallery.isPending) return <p role="status">Loading connector…</p>;
if (!router) return <p role="alert">{gallery.error?.message ?? "This connection pool plugin is unavailable. Enable it in Plugins."}</p>;